blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d1825afd10ce13925171fa81cefb8541c16b7378 | anvartdinovtimurlinux/ADPY-12 | /1.2/generator.py | 367 | 3.5625 | 4 | import hashlib
def md5_generator_from_file(path_to_file,):
with open(path_to_file, 'r', encoding='utf-8') as f:
for line in f:
result = hashlib.md5(line.encode())
yield result.hexdigest()
if __name__ == '__main__':
for i, line in enumerate(md5_generator_from_file('result.txt'), 1):
print('{}) {}'.format(i, line))
|
1532177b8dafbe4192f883cc294ad5622dae5532 | jaramir/AoC2018 | /day9/part1.py | 1,391 | 3.734375 | 4 | class Node:
def __init__(self, value, prev=None, next=None):
self.value = value
self.next = self if next is None else next
self.prev = self if prev is None else prev
def insert(self, value):
node = Node(value, self, self.next)
self.next.prev = node
self.next = node
return node
def remove(self):
self.prev.next = self.next
self.next.prev = self.prev
return self.next
class Game:
def __init__(self, players=1):
self.marbles = Node(0)
self.last = 0
self.points = [0] * players
def turn(self):
value = self.last + 1
if value % 23 == 0:
self.marbles = self.marbles.prev.prev.prev.prev.prev.prev.prev
player = (value - 1) % len(self.points)
self.points[player] += value + self.marbles.value
self.marbles = self.marbles.remove()
else:
self.marbles = self.marbles.next.insert(value)
self.last = value
def play_until(self, value):
while self.last < value:
self.turn()
return self
def get_marbles(self):
n = self.marbles
yield n.value
n = n.next
while n != self.marbles:
yield n.value
n = n.next
if __name__ == '__main__':
print max(Game(players=476).play_until(71431).points)
|
dc010a904846d5df1f68cb5895206cf5032acc84 | jaramir/AoC2018 | /day6/part1.py | 1,547 | 3.625 | 4 | def neighbours(cell):
x, y = cell
return {(x + 1, y),
(x - 1, y),
(x, y + 1),
(x, y - 1)}
def contested(point, cells):
for neighbour in neighbours(point):
if neighbour in cells:
return True
else:
return False
def step(families):
new_families = []
for index, cells in enumerate(families):
next = set()
others = set(cell
for family in families
for cell in family
if families.index(family) != index)
for cell in cells:
next.add(cell)
spawns = neighbours(cell)
for spawn in spawns:
if spawn in cells:
continue
if spawn in next:
continue
if not contested(spawn, others):
next.add(spawn)
new_families.append(next)
return new_families
def draw(families):
cells = [cell for family in families for cell in family]
for y in range(300):
for x in range(300):
if (x, y) in cells:
print '#',
else:
print ' ',
print
print '-' * 500
def stat(families):
for family in families:
print len(family)
print '-' * 100
if __name__ == '__main__':
families = [
[tuple(map(int, line.strip().split(", ")))]
for line in open("input")
]
for i in range(200):
draw(families)
stat(families)
families = step(families)
|
41af103a812a599e376b79251c7f1c76a01fe914 | KevinOluoch/Andela-Labs | /missing_number_lab.py | 787 | 4.4375 | 4 | def find_missing( list1, list2 ):
"""When presented with two arrays, all containing positive integers,
with one of the arrays having one extra number, it returns the extra number
as shown in examples below:
[1,2,3] and [1,2,3,4] will return 4
[4,66,7] and [66,77,7,4] will return 77
"""
#The lists are checked to ensure none of them is empty and if they are equal
if list1 == list2 or not (list1 or list2):
return 0
#If list1 is the larger one, the process of checking for the extra number is reversed
if len(list1) > len (list2):
return [ x for x in list1 if x not in list2 ][0]
return [ x for x in list2 if x not in list1 ][0]
print find_missing ( [66,77,7,4], [4,66,7] )
print find_missing ( [1,2,3], [1,2,3,4] ) |
f21f3a0a880d6b17fb8d99257c0b1a7d5b56d5ec | siamang/weather | /weather.py | 629 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# weather.py
#
# display temperature
import urllib2
import json
city = raw_input("City: ")
state = raw_input("State: ")
with open("key.txt") as key:
APIkey = key.readline().strip()
http = "http://api.wunderground.com/api/" + APIkey + "/geolookup/conditions/q/" + state + "/" + city + ".json"
f = urllib2.urlopen(http)
json_string = f.read()
parsed = json.loads(json_string)
try:
location = parsed['location']['city']
temperature = parsed['current_observation']['temp_f']
print "Current Temperature in %s is %s" % (location, temperature)
except KeyError:
print "City not found"
f.close()
|
d8edaa78416dd7379814a590c3492415f20bd4b7 | haden-liu/streamlit | /app.py | 685 | 3.765625 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
DATA_URL = (
"Jan_2020_ontime.csv"
)
st.title("Flight Delay Analysis Jan 2020")
st.markdown("This application is a Streamlit dashboard that"
"to analyze flight delay in US Cities")
@st.cache(persist=True)
def load_data(nrows):
data = pd.read_csv(DATA_URL, nrows=nrows)
data.dropna(inplace=True)
return data
data = load_data(150000)
st.header("How many flight occur during a day of month?")
dayMonth = st.selectbox("Day to look at", range(1,32),1)
data = data[data['DAY_OF_MONTH'] == dayMonth]
if st.checkbox("Show Raw Data", False):
st.subheader("Raw Data")
st.write(data) |
b1f2fa7118378dea5df54f6957cc0a00a33fb88d | Lakshya7312/c131 | /131.py | 867 | 3.625 | 4 | import csv
import pandas as pd
df = pd.read_csv(r"C:\Users\Lenovo\Desktop\Python Projects\Stardata.csv")
# kg = 1.989e+30
finaldata = df.dropna()
finaldata.isnull().sum()
finaldata
#print(finaldata)
#print(df)
finaldata
mass = finaldata["Mass"].tolist()
radius = finaldata["Radius"].tolist()
gravity = []
# print(radius)
def convertToSI(radius, mass):
for i in range(0, len(radius)-1):
radius[i] = radius[i] * 6.957e+8
mass[i] = mass[i] * 1.989e+30
convertToSI(radius, mass)
def calculateGravity(radius, mass):
# print(len(mass))
G = 6.674e-11
for i in range(0,len(mass)-1):
try:
print(radius[i])
g = (mass[i] * G) / ((radius[i]) ** 2)
gravity.append(g)
except:
pass
calculateGravity(radius, mass)
df["Gravity"] = gravity |
b2875d7737c5fd6cc06a5299f9f8c888c93bebb8 | byhay1/Practice-Python | /Repl.it-Practice/forloops.py | 1,856 | 4.71875 | 5 | #--------
#Lets do for loops
#used to iterate through an object, list, etc.
# syntax
# my_iterable = [1,2,3]
# for item_name in my_iterable
# print(item_name)
# KEY WORDS: for, in
#--------
#first for loop example
mylist = [1,2,3,4,5,6,7,8,9,10]
#for then variable, you chose the variable
print('\n')
for num in mylist:
print(num)
#or you can print whatever you want, flexible
print('\n')
for num in mylist:
print ('Hi')
#ctrl flow with for loops
print('\n')
for num in mylist:
if num % 2 == 0:
print (num, 'even')
else:
print (num, 'odd future')
#get the sum of everything using loop
listsum = 0
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#show all by putting it in the for loop through indentation
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#do for strings
print('\n')
mystring = 'Hello World'
for letter in mystring:
print (letter)
#can use the underscore when you are not assigning variables '_'
print('\n')
for _ in mystring:
print("don't you dare look at me")
#tuple stuffs, tuple unpacking
print('\n')
mylist2 = [(1,2),(3,4),(5,6),(7,8)]
print(len(mylist2))
#return tuples back using a for loop
for item in mylist2:
print(item)
#Or you can do the following
#(a,b) does not need '()'
print('\n', 'unpacking the tuples!')
for (a,b) in mylist2:
print(a)
print(b)
#------------
#iterating through a dictionary
#------------
d = {'k1':1,'k2':2,'k3':3}
#only iterating the Key... not the value
#if you want only the value use .values()
print('\n')
for item in d:
print(item)
#------------
#If you want to iterate the value use the .items()
#This will give you the full item tuple set.
#------------
for item in d.items():
print(item)
#use unpacking to get the dictionary values
for key, value in d.items():
print(key, '=', value)
|
29d08b7acb73e2baeb8a2daf67be103e1ad302fc | byhay1/Practice-Python | /Repl.it-Practice/tuples.py | 828 | 4.1875 | 4 | #------------
#tuples are immutable and similar to list
#FORMAT of a tuple == (1,2,3)
#------------
# create a tuple similar to a list but use '()' instead of '[]'
#define tuple
t = (1,2,3)
t2 = ('a','a','b')
mylist = [1,2,3]
#want to find the class type use the typle function type(PUTinVAR)
print('',"Find the type of the var 't' by using type(t): ", type(t), '\n', "Find the other type using type(mylist): ", type(mylist),'\n')
#can use other identifiers like a len(PUTinVar) and splice it how you want VAR[start:stop:step]
#find how many times a value occurs in a tuple or list
#do so by using the .count method
print('','There are only two methods you can use to get the count and the index position \n',"So t2.count('a') = ")
print(t2.count('a'))
#get the index num
print("and t2.index('b') = ")
print(t2.index('b'))
|
4f3e7af26400a2f4c309cffa69d5a6f874819731 | byhay1/Practice-Python | /Repl.it-Practice/OOPattributeClass.py | 2,069 | 4.5 | 4 | #----------
# Introduction to OOP:
# Attributes and Class Keywords
#
#----------
import math
mylist = [1,2,3]
myset = set()
#built in objects
type(myset)
type(list)
#######
#define a user defined object
#Classes follow CamelCasing
#######
#Do nothing sample class
class Sample():
pass
#set variable to class
my_sample = Sample()
#see type using built-in object
type(my_sample)
#######
#Give a class attributes
#######
#do something Dog class
class Dog():
def __init__(self,breed,name,spots):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
#Expect boolean True/False
self.spots = spots
#because attribute is used, must pass expected attribute or it will return an error
my_dog = Dog(breed='Mutt',name='Ruby',spots=False)
#Check to see type=instance of the dog class.
my_dog.breed
my_dog.name
my_dog.spots
#######PART TWO#######
#######
#Using Class object attribute and more...
#Using Methods within class
#######
######################
class Doggy():
# CLASS OBJECT ATTRIBUTE
# SAME FOR ANY INSTANCE OF A CLASS
clss = 'mammal'
# USER DEFINED ATTRIBUTE
def __init__(self,breed,name):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
# OPERATIONS/Actions ---> Methods
def bark(self, number):
print("WOOF! My name is {} and I am {} years old".format(self.name, number))
#because attribute is used, must pass expected attribute or it will return an error
my_dog2 = Doggy(breed='whtMutt',name='Rita')
#Methods need to be executed so they need '(' ')'
my_dog2.bark(2)
#######
#Create a new class called 'Circle'
#######
class Circle():
# CLASS OBJECT ATTRIBUTE
pi = math.pi
def __init__(self, radius=1):
self.radius = radius
self.area = radius*radius*Circle.pi
# METHOD
def get_circumference(self):
return self.radius*2*Circle.pi
my_circle = Circle(33)
print(my_circle.get_circumference)
print(my_circle.area)
print(my_circle.pi)
|
6ca35f085ec691266a89ebbe24479424bb7f11ce | sowmyadavuluri/Learnings | /cr_list_tuple_from_arr.py | 206 | 3.984375 | 4 | # lists and tuples from input
a = int(input("enter first number: "))
b = int(input("enter second number: "))
c = int(input("enter third number: "))
list = [a,b,c]
print(list)
tuple = (a,b,c)
print(tuple)
|
eef86cb4c54bf7d0b38ced84acff83220b0304e3 | jongwlee17/teampak | /Python Assignment/Assignment 5.py | 988 | 4.34375 | 4 | """ Exercise 5: Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
Extras:
1. Randomly generate two lists to test this
2. Write this in one line of Python (don't worry if you can't figure this out at this point - we'll get to it soon)
"""
import random
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# random_a = range(1, random.randint(1,30))
# random_b = range(1, random.randint(1,40))
print("Random_a list consists of: ", random_a)
print("Random_b list consists of: ", random_b)
def findCommonValues(a, b):
final_list = []
for num in a:
if num in b:
if num not in final_list:
final_list.append(num)
return final_list
print(findCommonValues(a, b)) |
78bc59ffaf91ff24bc23fb87439767e4ac7ce0bf | jongwlee17/teampak | /Python Assignment/Assignment 8.py | 2,139 | 4 | 4 | """ Exercise 8: Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to
the winner, and ask if the players want to start a new game)
Remember the rules:
- Rock beats scissors
- Scissors beats paper
- Paper beats rock
"""
first_player = input("Please enter from the following: Rock, Paper, or Scissors. Type quit when you want to exit the program.\n").strip().lower()
second_player = input("Please enter from the following: Rock, Paper, or Scissors. Type quit when you want to exit the program.\n").strip().lower()
def determineWinner(first_player, second_player):
if first_player == "rock":
if second_player == "rock":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nIt's a tie!")
if second_player == "paper":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 2 wins!")
if second_player == "scissors":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 1 wins!")
elif first_player == "paper":
if second_player == "rock":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 1 wins!")
if second_player == "paper":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nIt's a tie!")
if second_player == "scissors":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 2 wins!")
elif first_player == "scissors":
if second_player == "rock":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 2 wins!")
if second_player == "paper":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nPlayer 1 wins!")
if second_player == "rock":
print("Player 1 has played " + first_player + "\nPlayer 2 has played " + second_player + "\nIt's a tie!")
while first_player != "quit" or second_player != "quit":
determineWinner(first_player, second_player)
|
8dc7d1a00f7a0083ca99da898165a5ba1163f166 | heymayras/atividades_python | /asd.py | 200 | 4 | 4 | if ((not False and True) and (True or False or False)):
print("Verdadeiro")
else:
print("Falso")
if (not (5 == 5) and (not (Ture or False))):
print("Verdadeiro")
else:
print("Falso")
|
ee885f888260cf82625a0658de0c8f7718b7b28a | UWMRO/ScienceCamera | /evora/common/logging/my_logger.py | 1,911 | 3.609375 | 4 | #!/usr/bin/env python2
from __future__ import division, print_function
import os
import logging
from datetime import date
def myLogger(loggerName, fileName=None):
"""
This returns a custom python logger.
This initializes the logger characteristics. Passing in a file name
will send logging output, not only to console, but to a file.
"""
LOGGER = logging.getLogger(loggerName) # get logger named for this module
LOGGER.setLevel(logging.DEBUG) # set logger level to debug
# create formatter
LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
LOG_FORMAT = ('\n[%(levelname)s/%(name)s:%(lineno)d] %(asctime)s ' + '(%(processName)s/%(threadName)s)\n> %(message)s')
FORMATTER = logging.Formatter(LOG_FORMAT, datefmt=LOG_DATEFMT)
CH = logging.StreamHandler() # create console handler
CH.setLevel(logging.DEBUG) # set handler level to debug
CH.setFormatter(FORMATTER) # add formatter to ch
LOGGER.addHandler(CH) # add console handler to logger
if fileName is not None:
# Get local gregorian date in YYYYMMDD format
d = date.today().strftime("%Y%m%d")
# Get path of log directory relative to this file
log_directory = os.path.join(os.path.dirname(__file__), "logs/")
# Construct log file name from fileName passed and date
log_file_name = "{}_{}.log".format(fileName, d)
log_file = os.path.join(log_directory, log_file_name)
try:
FH = logging.FileHandler(log_file) # create file handler
FH.setLevel(logging.DEBUG) # set handler level to debug
FH.setFormatter(FORMATTER) # add formatter to fh
LOGGER.addHandler(FH) # add file handler to logger
return LOGGER
except IOError:
print("Could not open logs, make sure you are running from the evora directory.")
print("Exiting...")
quit()
|
987c9e3ff8225d1666e907ce2857379229bc8048 | akhilbommu/July_LeetCode_Challenge | /Day16-Pow(x,n).py | 191 | 3.578125 | 4 | class Power:
def myPow(self, x: float, n: int) -> float:
return pow(x, n)
obj = Power()
print(obj.myPow(2.00000, 10))
print(obj.myPow(2.10000, 3))
print(obj.myPow(2.00000, -2))
|
0cf699ef7a6372fdb4c251a2ed9653b6a873d4c1 | akhilbommu/July_LeetCode_Challenge | /Day14-AngleBetweenHandsOfClock.py | 399 | 3.765625 | 4 | class AngleBetweenHandsOfClock:
def angleClock(self, hrs: int, mins: int) -> float:
hrs %= 12
hours = hrs*30 + mins/2
mins = 6 * mins
return min(abs(hours-mins), 360-abs(mins-hours))
obj = AngleBetweenHandsOfClock()
print(obj.angleClock(12, 30))
print(obj.angleClock(3, 30))
print(obj.angleClock(3, 15))
print(obj.angleClock(4, 50))
print(obj.angleClock(12, 0)) |
1d3b02a7b85a002a205ca90445a9df981007a27d | Artem7898/-Python-client-server-applications | /Python_lesson_7_client_app/service.py | 687 | 3.609375 | 4 | import socket
# Задаем адрес сервера
SERVER_ADDRESS = ('localhost', 8888)
# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(10)
print('сервер работает, пожалуйста, нажмите ctrl + c для остановки')
# Слушаем запросы
while True:
connection, address = server_socket.accept()
print("new connection from {address}".format(address=address))
data = connection.recv(1024)
print(str(data))
connection.send(bytes('Привет я сервер!', encoding='UTF-8'))
connection.close()
|
3f6665eb79095563cbc774af8fb87c24d398455e | fossabot/bhandar | /convertbase.py | 593 | 3.5 | 4 | #!/usr/bin/env python
import sys
import string
def convert(no, ibase, obase):
newno = int(no, ibase)
if obase == 10:
return str(newno)
data = dict(enumerate(string.digits+string.ascii_uppercase))
ret = []
while newno:
ret.insert(0, str(data[newno % obase]))
newno = int(newno / obase)
return ''.join(ret)
if len(sys.argv) != 4:
print("Invalid number of parameters passed")
print("Usage:")
print(sys.argv[0] + " <number> <input_base> <output_base>")
sys.exit(1)
print(convert(sys.argv[1], int(sys.argv[2]), int(sys.argv[3])))
|
07b7c56ffaa62eef2841fb04a8ade3413e14cb41 | sebastianslupinski/python-OOP-battleship- | /game.py | 4,059 | 3.859375 | 4 | import os
from player import Player
from ocean import Ocean
from square import Square
from ship import Ship
import random
import time
class PlayBattleships():
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
def placement_validation(self, ship_list, player, player_ship, ship):
if not player.validate_if_ship_is_near(player_ship):
os.system('clear')
return False
else:
player_ship.change_squares_to_ship()
player.warships.append(player_ship)
ship_list.remove(ship)
def create_player_ships(self, player):
os.system('clear')
ship_list = [("Destroyer", '2'), ("Submarine", '3'), ("Cruiser", '3'), ('Battleship', '4'), ('Carrier', '5')]
os.system('clear')
for ship in reversed(ship_list):
while True:
os.system('clear')
player.print_boards()
if ship_list:
ship_cord = input("Where do you want to place {})? ".format(" (".join(ship)))
ship_orient = input("Do you want to place {}) horizontally or vertically ? Press h or v. ".format(" (".join(ship)))
if ship_orient in ["H", "h"]:
try:
player_ship = player.get_ship_coordinates(ship[0], ship_cord.upper(), False)
if self.placement_validation(ship_list, player, player_ship, ship) is False:
print('>>>>> Wrong input <<<<<')
continue
except IndexError or ValueError:
print('>>>>> Wrong input <<<<<')
continue
break
elif ship_orient in ["V", "v"]:
try:
player_ship = player.get_ship_coordinates(ship[0], ship_cord.upper(), True)
if self.placement_validation(ship_list, player, player_ship, ship) is False:
print('>>>>> Wrong input <<<<<')
continue
except IndexError or ValueError:
print('>>>>> Wrong input <<<<<')
continue
break
else:
continue
break
def change_ships_to_hidden(self, player1, player2):
for ship in player1.warships:
list_of_cords = ship.coordinates
for square in list_of_cords:
square = player2.view.find_object(square.name)
square.hidden_ship = True
def boards_setup(self):
ready_check = input('{} press Enter if youre ready '.format(self.player1.name))
self.create_player_ships(self.player1)
self.change_ships_to_hidden(self.player1, self.player2)
ready_check = input('{} press Enter if youre ready '.format(self.player2.name))
self.create_player_ships(self.player2)
self.change_ships_to_hidden(self.player2, self.player1)
def turn_mechanics(self, player1, player2):
os.system('clear')
player1.print_boards()
print('{} it is your turn!' .format(player1.name))
time.sleep(1)
player_shoot = input('Where you want to shoot ? ')
player1.shoot_to_ship(player_shoot.upper())
player2.get_hit(player_shoot.upper())
for ship in player2.warships:
ship.check_if_sunk()
if ship.is_sunk is True:
player2.warships.remove(ship)
player1.print_boards()
def player_victory(self, player):
os.system('clear')
player.highscore.append(player.name)
player.highscore.append(len(player.warships))
print('{} YOU WON!!! '.format(player.name))
def check_if_warships_alive(self, player2):
if not player2.warships:
return True
|
16a1ced785b92534c788b76216f5d7a261e03de3 | yannikinniger/draughts-game | /src/model/pieces/AbstractPiece.py | 891 | 3.609375 | 4 | import abc
from model.pieces.InvalidMoveException import InvalidMoveException
class AbstractPiece:
def __init__(self, owner, location, direction):
self.owner = owner
self.location = location
self.direction = direction
def move(self, location):
"""
Moves the piece to a different location on the board. This method has to check if the new location is valid.
:param location: Location of to move to.
:raises: InvalidMoveException when an invalid move is attempted.
"""
if self._is_move_permitted(location):
self.location = location
else:
raise InvalidMoveException
@abc.abstractmethod
def _is_move_permitted(self, location):
"""
Returns an array of points consisting the available positions to move to.
"""
raise NotImplementedError()
|
0790e92f564be4ce7329f600d37c04cc11baea91 | TheodoreNestel/Theo-Capstone-One | /models.py | 3,208 | 3.546875 | 4 | from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
#setups to allow Bcrypt and sqlalchemy to function
bcrypt = Bcrypt()
db = SQLAlchemy()
# Model ###############
class User(db.Model):
__tablename__ = 'users'
#we start with a unique id for each user being incremented automatically
id = db.Column(db.Integer , primary_key = True , autoincrement = True)
#each user needs and email and it must be unique
email = db.Column(db.Text, nullable = False, unique = True)
#this will be used to grab their LoL profile when they log in
username = db.Column(db.Text, nullable = False)
#this is where we will store the password once its hashed
password = db.Column(db.Text,nullable = False)
#we need to store a user's region so we know which api to call
region = db.Column(db.Text,nullable = False)
#######Functions#########
#a function that will return info on the object
def __repr__(self):
return f"<User #{self.id}: {self.username}, {self.email}>"
#######class Functions###
@classmethod
def signup(cls, username, email, password,region): # a method for signing up users
"""Sign up user.
Hashes password and adds user to system.
"""
hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8') #we grab their password input and hash it
user = User( #then we grab the info passed in and slap it into a new User object
username=username,
email=email,
password=hashed_pwd,
region=region
)
db.session.add(user) #add if to our db.session
return user #then we return the user back to app.py
@classmethod
#wowow the bigbois this is the method used to let a user into their account if they provide the correct login details
def authenticate(cls, email, password): #it takes in the class its in username and then a password
"""Find user with `email` and `password`.
This is a class method (call it on the class, not an individual user.) #this is important you call this on class since
#we dont know who we're login in yet
It searches for a user whose password hash matches this password
and, if it finds such a user, returns that user object.
If can't find matching user (or if password is wrong), returns False.
"""
user = cls.query.filter_by(email=email).first() #filter our db by username and find the first match
if user:
is_auth = bcrypt.check_password_hash(user.password, password) #do the password match for this user?
if is_auth:
return user #if its a match return the user
return False #otherwise False
#Finally the logic to connect to our database
def connect_db(app):
"""Connect this database to provided Flask app.
You should call this in your Flask app.
"""
db.app = app
db.init_app(app)
#a helper function to help us update a user's password
def change_password(password):
new_hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8')
return new_hashed_pwd
|
968efa71c64032cb0fde2fcd03f347bdf3c95e5d | yunussalta/pg1926odevleri | /ödevdir/python ödev3.py | 255 | 3.671875 | 4 | #python 3
def diz(d):
sifir = []
kalanlar = list()
for i in d :
if i == 0 :
sifir.append(i)
else :
kalanlar.append(i)
sonuc = sifir + kalanlar
return (sonuc)
test = [0,2,5,8,6,0,0,7]
d = diz(test)
print(d) |
331477627dd5cb9e6b13f3cea75fcde810995f99 | chuymtz/python_scripts | /projects/dice/dice.py | 653 | 4 | 4 | #from random import randint
import random
def roll_dice(n):
random_number = random.randint(1,6)
print("\nYou have rolled a {}.\n".format(random_number))
main_menu()
def dice_menu():
print('\nEnter the number of dice.\n')
num_dice = int(input('> '))
roll_dice(num_dice)
def main_menu():
print('Type \'q\' to quit.')
print('Type \'n\' to select the number of dice.\n')
ans = input('> ')
check = True
while check == True:
if ans == 'q':
#check = False
quit()
elif ans == 'n':
dice_menu()
else:
main_menu()
def main():
print('\n Welcome to my 1st Dice Similator!\n')
main_menu()
if __name__ == "__main__": main()
|
840a3f299777461bebbeb0a1951ab7a119ad7a26 | chuymtz/python_scripts | /spyder_scripts/jan_workshop/so3.py | 3,672 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Python Workshop 01/30/2015
Exercise 3
Execute the first line of code, which generates a variable "seq", which is
a DNA sequence
1. Count the number of 'C's in the sequence and print it out
2. Calculate its 'GC-content' and print it out
GC-content = (#G + #C) / sequence length
3. Print out its conplementary chain sequence
(A to T, T to A, C to G, G to T)
* Transcribe the sequence to mRNA (T to U) and then translate it to protein
** Stop translating at 'STOP' codon or
** Neglect all 'STOP' codons
@author: yuanwang
"""
seq = 'AGTTTTGAGAAACCTAGAGATCCATCGTGACCTGCCCCGGTTTTACAAGCCCCTCCATATACATTGGCCGATTAAAAGTCCACCCCATTGGCTTCCGCTGGATAGTCGTTAGAACCTGGATAAAAGCCGACTAGCTCTAAGCGCTCGCCGGCAACACGGAAGTGGCATTCCTGGTACGCGACGATTAGGACCACCGGAGCAGTCTACAGTTGCGCGCGCATGTACGGCAATGCGATTGAATTAGCAGTGTGTAATAAACAATATGAGGAGTTCTTGCCGACGAGTTTCCCTTATTTGTGTCTCGGCTAGCGTTCAACACGATCACGTTCGATGTACTAGGAGGGTTAGGTTTATCTGGGCTTGTCGAGACTCAATTTGCGATTGTTCGTTAACATTTAGCCAAAGGCCCCGCAAAATGCGGAGCGTCCGGGGTTACAGCCGCGTGTGTCCTGGTTTCTGCAATCGCCAGACGGCCAAAAAAAGAATACTTGGGTTAGCTTCAGGTGAAGGCAAATATAATTGAACGTTGGTTATGATTCGGTCATTGATCGCATGCCCCTCATCCCATTGAGAGGTGGAATCTTAATAATCAGTCAAAACATCGCGAGGAAGCTATCAGGCAACACGGGCTGCGCTCGCGAGGAATATACTCGATCCGGCTTAAAGGACAACATCAGGACTGATCGACTCGCTGCAGTGACGATGTAGTCCTTGTCCAACGCTGGGCACAATGACGAGTGAAAGTCATAAACTGGTGTCTCGTCGAGAAATGTAGTCTACACGTCCCCACTGCCCTAGACAATAAGGACTGTTGTCGGGAACAAGATCCGGATCGGCTCGGATTCACCGCTCGGAGCAAGTCTGCTCAACGAATATCCATCGGCGCATTAG'
#######question 1################
numC = 0
for i in seq:
if i == 'C':
numC += 1
print 'The number of C is %d' % numC
#######question 2################
numCG = 0
for i in seq:
if i == 'C' or i == 'G':
numCG += 1
GCcontent = float(numCG)/len(seq)
print 'GC-content : %.2f' %GCcontent
#######question 3################
newSeq = ''
for i in seq:
if i == 'A':
newSeq = newSeq + 'T'
elif i == 'T':
newSeq = newSeq + 'A'
elif i == 'C':
newSeq = newSeq + 'G'
else:
newSeq = newSeq + 'C'
print '------Conplementary Sequence----'
print newSeq
##### ********** ################
CodonTable = {"UUU":"F", "UUC":"F", "UUA":"L", "UUG":"L",
"UCU":"S", "UCC":"S", "UCA":"S", "UCG":"S",
"UAU":"Y", "UAC":"Y", "UAG":"STOP", "UAA":"STOP",
"UGU":"C", "UGC":"C", "UGA":"STOP", "UGG":"W",
"CUU":"L", "CUC":"L", "CUA":"L", "CUG":"L",
"CCU":"P", "CCC":"P", "CCA":"P", "CCG":"P",
"CAU":"H", "CAC":"H", "CAA":"Q", "CAG":"Q",
"CGU":"R", "CGC":"R", "CGA":"R", "CGG":"R",
"AUU":"I", "AUC":"I", "AUA":"I", "AUG":"M",
"ACU":"T", "ACC":"T", "ACA":"T", "ACG":"T",
"AAU":"N", "AAC":"N", "AAA":"K", "AAG":"K",
"AGU":"S", "AGC":"S", "AGA":"R", "AGG":"R",
"GUU":"V", "GUC":"V", "GUA":"V", "GUG":"V",
"GCU":"A", "GCC":"A", "GCA":"A", "GCG":"A",
"GAU":"D", "GAC":"D", "GAA":"E", "GAG":"E",
"GGU":"G", "GGC":"G", "GGA":"G", "GGG":"G"}
mRNA = seq.replace('T', 'U')
translation1 = ''
translation2 = ''
for i in range(0,len(mRNA),3):
if CodonTable[mRNA[i:i+3]] == 'STOP':
break
else:
translation1 = translation1 + CodonTable[mRNA[i:i+3]]
print '-' * 20
print translation1
for i in range(0,len(mRNA),3):
if CodonTable[mRNA[i:i+3]] == 'STOP':
continue
else:
translation2 = translation2 + CodonTable[mRNA[i:i+3]]
print '-' * 20
print translation2
print '-' * 20
|
6473549df86b8ce3c0f09603cf4e97346bddae14 | viticlick/adventofcode | /2020/day_07/day_07_02.py | 691 | 3.578125 | 4 | #! /usr/bin/env python3
import re, sys
def bags(colorset, color):
if colorset.get(color) == []:
print(color, ' has no bags inside')
return 1
print(color, ' contains:')
counter = 0
for n, c in colorset[color]:
counter = counter + int(n) * bags(colorset,c)
print(n, ' of ', c, ' bags')
return counter + 1
counter = 0
with open('input', 'r') as f:
colorset = dict()
for line in f.readlines():
base_color = re.findall(r'(\w+ \w+) bags contain', line)[0]
colors = re.findall(r'(\d+) (\w+ \w+)',line)
colorset[base_color] = colors
print(colorset)
print(bags(colorset, 'shiny gold') - 1)
|
c36cca80b50214006b35ce064e0a0756942482cc | viticlick/adventofcode | /2020/day_12/day_12.py | 1,015 | 3.890625 | 4 | #! /usr/bin/env python3
import re
class Ship():
def __init__(self):
self.compass = ['N','E','S','W']
self.facing_to = 1
self.position = {
"N" : 0,
"S" : 0,
"E" : 0,
"W" : 0
}
def move(self, action, value):
if action in self.position:
self.position[action] += value
elif action == 'F':
self.position[self.compass[self.facing_to]] += value
elif action == 'R':
self.facing_to = int((self.facing_to + value/90) % 4)
elif action == 'L':
self.facing_to = int((self.facing_to - value/90) % 4)
def manhattan(self):
return abs(self.position['E'] - self.position['W']) + abs(self.position['N'] - self.position['S'])
ship = Ship()
f = open('input', 'r')
actions = [ re.findall(r'([NSEWLRF])(\d+)', line)[0] for line in f.readlines()]
[ship.move(action, int(value)) for action, value in actions]
print('distance: ',ship.manhattan())
|
b6dc70544dbe6a2e3b7021d04355016b31d8bb9d | robertwuss/PythonCodeClass | /is5.py | 94 | 3.828125 | 4 |
msg = input()
a = msg
if a == 5:
print('this is 5')
else:
print ('this is not 5')
|
c2eb7abdf2b4313193163c0cfdaaa365dbb393cf | nightwatch92/HackBulgaria-Programming101-exercises | /week0/number_to_list/solution.py | 134 | 3.53125 | 4 | def number_to_list(n):
n = abs(n)
n = str(n)
list = []
for digit in n:
list.append(int(digit))
return list |
bafe4c604c5539a31dcb02c6a32b82c9889ab17c | nightwatch92/HackBulgaria-Programming101-exercises | /week0/number_balanced/solution.py | 693 | 3.65625 | 4 | def is_number_balanced(n):
to_str = str(n)
lenght = len(to_str)
first_part = to_str[:len(to_str)//2]
second_part = to_str[len(to_str)//2:]
# print(first_part, second_part, third_part)
left_part = 0
for x in first_part:
left_part += int(x)
# print(left_part)
right_part = 0
for y in second_part:
right_part += int(y)
if lenght % 2 == 1:
third_part = to_str[len(to_str)//2]
final = right_part - int(third_part)
if final == left_part:
return True
else:
return False
else:
if left_part == right_part:
return True
else:
return False |
1dfcf6225ea686ebf66f46d924731b1843663e23 | nightwatch92/HackBulgaria-Programming101-exercises | /week0/sum_of_divisors/solution.py | 350 | 3.78125 | 4 | def sum_of_divisors(n):
index = 1
result = 0
while index <= abs(n):
if n % index == 0 :
result = result + index
index = index + 1
return result
def main():
print(sum_of_divisors(8))
print(sum_of_divisors(3))
print(sum_of_divisors(1))
print(sum_of_divisors(1000))
print(sum_of_divisors(7))
if __name__ == '__main__':
main() |
b29b31927a4973b2413236b24fb5ba41f5bd6542 | nightwatch92/HackBulgaria-Programming101-exercises | /week0/biggest_difference/test.py | 936 | 3.515625 | 4 | import unittest
import solution
class BiggestDifferenceTest(unittest.TestCase):
"""docstring for VowelsTest"""
def test_biggest_difference(self):
self.assertEqual(-99,solution.biggest_diffarance(range(100)))
self.assertEqual(0,solution.biggest_diffarance([1,1,1,1]))
self.assertEqual(0,solution.biggest_diffarance([3,3,3,3]))
self.assertEqual(0,solution.biggest_diffarance([0,0,0,0,0]))
def test_biggest_diffarance_negative(self):
self.assertEqual(-9,solution.biggest_diffarance([-10, -9, -1]))
self.assertEqual(-42,solution.biggest_diffarance([-3, -45, -22]))
self.assertEqual(-18,solution.biggest_diffarance([-13, -23, -31]))
self.assertEqual(-88,solution.biggest_diffarance([-50, -91, -3]))
# def test_consonants_upper_case(self):
# self.assertEqual(3311,solution.biggest_diffarance([3,3,1,1]))
if __name__ == '__main__':
unittest.main() |
c6df0cd4a9ef708fee71ed7da66569f64b339e02 | nightwatch92/HackBulgaria-Programming101-exercises | /week0/is_int_palindrom/test.py | 1,259 | 3.515625 | 4 | import unittest
import solution
class IsIntPalindrom(unittest.TestCase):
"""docstring for SumOfDivisorsTest"""
def test_is_palindrom(self):
self.assertEqual(False, solution.is_int_palindrom(889))
self.assertEqual(True, solution.is_int_palindrom(101))
def test_zero_palindrom(self):
self.assertEqual(True, solution.is_int_palindrom(0))
def test_negative_number(self):
self.assertEqual(True, solution.is_int_palindrom(-101))
self.assertEqual(True, solution.is_int_palindrom(-123321))
self.assertEqual(False,solution.is_int_palindrom(-3134))
# # self.assertEqual(2340, solution.is_int_palindrom(1000))
# def test_zero(self):
# self.assertEqual(0, solution.is_int_palindrom(0))
if __name__ == '__main__':
unittest.main()
# def is_int_palindrom(n):
# digits = n
# rev = 0
# while n!=0:
# rev = n%10+rev*10
# n = n//10
# # print(rev)
# # print(n)
# # print(digits)
# if digits == rev:
# print True
# else:
# print False
# def main():
# print(is_int_palindrom(101))
# print(is_int_palindrom(1221))
# print(is_int_palindrom(12334))
# print(is_int_palindrom(1))
# print(is_int_palindrom(100001))
|
95e2755f031e25873023a3ddef573d4375da9fef | nightwatch92/HackBulgaria-Programming101-exercises | /week0/prime_factorization/solution.py | 884 | 3.578125 | 4 | def prime_factorization(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
f = [primfac.count(el) for el in primfac]
if len(primfac) == 1:
first_value1 = primfac.pop(0)
first_value_stepen1 = f.pop(0)
f = ([(first_value1,first_value_stepen1)])
return f
else:
first_value = primfac.pop(0)
first_value_stepen = f.pop(0)
second_value = primfac.pop()
second_value_stepen = f.pop()
b = ([(first_value,first_value_stepen),(second_value, second_value_stepen)])
return b
# print(prime_factorization(24))
# print(prime_factorization(10))
# print(prime_factorization(14))
# print(prime_factorization(10432420))
# print(prime_factorization(89)) |
a2a917cc460652648c7d1a1e63acea8bc3a87725 | ChrisToumanian/wave-fitter | /combine.py | 432 | 3.640625 | 4 | #! /usr/local/bin/python3
import sys
import math
def main():
pairs = {}
# combine
for i in range(1, len(sys.argv)):
f = open(sys.argv[i], 'r')
lines = f.readlines()
for line in lines:
x = float(line.split(' ')[0])
y = float(line.split(' ')[1])
if str(x) in pairs:
pairs[str(x)] += float(pairs[str(x)]) + y
else:
pairs[str(x)] = y
# print
for pair in pairs:
print(pair, pairs[pair])
main()
|
45c58c6fe36db189aae6da06ae0d76e648a589cd | lianbo2006/Project | /test/python/Day 1: Data Types.py | 506 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
# Read and save an integer, double, and String to your variables.
n=int(input())
o=float(input())
s1=input().strip()
# Print the sum of both integer variables on a new line.
print(i+n)
# Print the sum of the double variables on a new line.
print(d+o)
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s+s1) |
bfeff7606be263b858c5ff1881f3831b4b8b7664 | andersonwillsam/Will_OS | /Will_OS_Files/WillGames/Baseball/Functions.py | 1,615 | 3.578125 | 4 | import time
import math
def wait(): # Change both wait times to 0 for game to complete immediately
time.sleep(2) # default 2
def wait_short():
time.sleep(.5) # default .5
def batting_team(half_inning):
if half_inning % 2 == 0:
return "home"
else:
return "away"
def pitching_team(half_inning):
if half_inning % 2 == 0:
return "away"
else:
return "home"
def format_batting_average(avg):
avg_string = str(avg)
# Remove leading 0
avg_string = avg_string[1:]
# Add trailing 0s if necessary
if len(avg_string) == 2:
avg_string = avg_string + "00"
elif len(avg_string) == 3:
avg_string = avg_string + "0"
return avg_string
def format_era(era):
era_string = str(era)
# Add trailing 0 if necessary
if len(era_string) == 3:
era_string = era_string + "0"
return era_string
def ball_in_play_animation():
# flush=True makes sure time.sleep instances do not occur all at once
print("\033[1;97;100mBall in play!\033[0m", end="", flush=True)
for x in range(0, 6):
wait_short()
print("\033[1;97;100m .\033[0m", end="", flush=True)
print("")
def pitching_animation(pitch_count, half_inning, current_pitcher, redo_pitch_loops):
# flush=True makes sure time.sleep instances do not occur all at once
print("\033[1;30;40mPitch " + str(pitch_count[pitching_team(half_inning)]) + " (" + current_pitcher[pitching_team(half_inning)][0] + ") \033[0m", end = "", flush=True)
for x in range(0, 3):
wait_short()
print("\033[1;30;40m. \033[0m", end="", flush=True)
for x in range(0, redo_pitch_loops):
wait_short()
print("\033[1;30;40m. \033[0m", end="", flush=True)
print("") |
2f9b70942f1005798c09f0a3f4e95bc6ea681c0e | bourov/translator | /Problems (10)/What day is it/main.py | 140 | 3.59375 | 4 | offset = int(input())
if offset + 10.5 >= 24:
print('Wednesday')
elif offset + 10.5 < 0:
print('Monday')
else:
print('Tuesday')
|
c72386586f7fb7b7d66a281485e43b050f82bfd2 | bourov/translator | /Problems (30)/Plurals/main.py | 123 | 3.984375 | 4 | number = int(input())
word = input()
# write a condition for plurals
print(number, word if number == 1 else word + 's')
|
72145292859d6d1fb0d8f84e0c0adf4550966733 | voidnologo/coursera | /principles_of_computing_1/2048/cli_2048_main.py | 1,850 | 3.703125 | 4 | import cmd
from cli_2048 import Game
class GameLoop(cmd.Cmd):
welcome = "Command Line 2048 "
prompt = '>>> '
def preloop(self):
print(self.welcome)
self.initialize_game()
def initialize_game(self):
default = (4, 4)
size = input('What size of game board do you want? \nFormat: x, y Example: 2, 3\n(press Enter for default of 4x4) >>')
x, y = [int(q.strip()) for q in size.split(',')] if size else default
self.game = Game(width=x, height=y)
amount = int(x * y / 3) or 1
for _ in range(amount):
empty = self.game.find_empty()
self.game.add_new_tile(empty)
self.display_board()
def display_board(self):
print(self.game.display_board())
def do_h(self, args):
'Shift tiles left'
self.game.take_turn('left')
def do_left(self, args):
self.do_h(args)
def do_l(self, args):
'Shift tiles right'
self.game.take_turn('right')
def do_right(self, args):
self.do_l(args)
def do_j(self, args):
'Shift tiles up'
self.game.take_turn('up')
def do_up(self, args):
self.do_j(args)
def do_k(self, args):
'Shift tiles down'
self.game.take_turn('down')
def do_down(self, args):
self.do_k(args)
def do_q(self, args):
return True
def do_quit(self, args):
return True
def postcmd(self, stop, line):
if line in ('q', 'quit'):
return True
empty = self.game.find_empty()
if not empty:
return self.lose_game()
self.game.add_new_tile(empty)
self.display_board()
return stop
def lose_game(self):
print('You have failed!!! ')
return True
if __name__ == '__main__':
GameLoop().cmdloop()
|
7c8a0bd5accb2abec67a3501e521ec330efa17cf | littlew/CellPAD | /CellPAD/pipeline/filter.py | 11,260 | 3.90625 | 4 | # Copyright (c) 2017 Wu Jun (littlewj187@gmail.com)
import numpy as np
class DropAnomalyFilter:
def __init__(self, rule='gauss', coef=2.5):
"""
DropAnomalyFilter is a class for measuring the drop degree.
DropAnomalyFilter implements three anomaly detection methods,
- gauss: based on gauss distribution assumption, which filters the outliers with high drop ratios as anomalies.
- threshold: the operator could set a threshold of drop ratio by his or her domain knowledge.
- proportion: the operator could set an assumed proportion of anomalies.
:param rule: str | the approach to detect and filter out anomalies.
:param coef: float | the coefficient for a specific approach(rule).
"""
if rule == 'gauss':
self.rule = rule
self.sigma = coef
if rule == 'threshold':
self.rule = rule
self.threshold = coef
if rule == 'proportion':
self.rule = rule
self.proportion = coef
return
def detect_anomaly(self, predicted_series, practical_series):
"""
It calculates the drop ratio of each point by comparing the predicted value and practical value.
Then it runs filter_anomaly() function to filter out the anomalies by the parameter "rule".
:param predicted_series: the predicted values of a KPI series
:param practical_series: the practical values of a KPI series
:return: drop_ratios, drop_labels and drop_scores
"""
drop_ratios = []
for i in range(len(practical_series)):
dp = (practical_series[i] - predicted_series[i]) / (predicted_series[i] + 1e-7)
drop_ratios.append(dp)
drop_scores = []
for r in drop_ratios:
if r < 0:
drop_scores.append(-r)
else:
drop_scores.append(0.0)
drop_labels = self.filter_anomaly(drop_ratios)
return drop_ratios, drop_labels, drop_scores
def filter_by_threshold(self, drop_scores, threshold):
"""
It judges whether a point is an anomaly by comparing its drop score and the threshold.
:param drop_scores: list<float> | a measure of predicted drop anomaly degree.
:param threshold: float | the threshold to filter out anomalies.
:return: list<bool> | a list of labels where a point with a "true" label is an anomaly.
"""
drop_labels = []
for r in drop_scores:
if r < threshold:
drop_labels.append(True)
else:
drop_labels.append(False)
return drop_labels
def filter_anomaly(self, drop_ratios):
"""
It calculates the threshold for different approach(rule) and then calls filter_by_threshold().
- gauss: threshold = mean - self.sigma * std
- threshold: the given threshold variable
- proportion: threshold = sort_scores[threshold_index]
:param drop_ratios: list<float> | a measure of predicted drop anomaly degree
:return: list<bool> | the drop labels
"""
if self.rule == 'gauss':
mean = np.mean(drop_ratios)
std = np.std(drop_ratios)
threshold = mean - self.sigma * std
drop_labels = self.filter_by_threshold(drop_ratios, threshold)
return drop_labels
if self.rule == "threshold":
threshold = self.threshold
drop_labels = self.filter_by_threshold(drop_ratios, threshold)
return drop_labels
if self.rule == "proportion":
sort_scores = sorted(np.array(drop_ratios))
threshold_index = int(len(drop_ratios) * self.proportion)
threshold = sort_scores[threshold_index]
drop_labels = self.filter_by_threshold(drop_ratios, threshold)
return drop_labels
class ChangeAnomalyFilter:
def __init__(self, rule='gauss', coef=3.0):
"""
ChangeAnomalyFilter is a class for measuring the change degree.
ChangeAnomalyFilter implements three anomaly detection methods,
- gauss: based on gauss distribution assumption, which filters the outliers with high change ratios as anomalies.
- threshold: the operator could set a threshold of change ratio by his or her domain knowledge.
- proportion: the operator could set an assumed proportion of anomalies.
:param rule: str | the approach to detect and filter out anomalies.
:param coef: float | the coefficient for a specific approach(rule).
"""
if rule == 'gauss':
self.rule = rule
self.sigma = coef
if rule == 'threshold':
self.rule = rule
self.threshold = coef
if rule == 'proportion':
self.rule = rule
self.proportion = coef
return
def detect_anomaly_lcs(self, lcs_scores):
"""
It detects the anomalies which are measured by local correlation tracking method.
- gauss: threshold = 0.0 + self.sigma * std
- threshold: the given threshold variable
- proportion: threshold = sort_scores[threshold_index]
:param lcs_scores: list<float> | the list of local correlation scores
:return:
"""
if self.rule == "gauss":
mean = 0.0
std = np.std(lcs_scores)
threshold = mean + self.sigma * std
change_labels = []
for lcs in range(len(lcs_scores)):
if lcs > threshold:
change_labels.append(True)
else:
change_labels.append(False)
return change_labels, lcs_scores
if self.rule == "threshold":
threshold = self.threshold
change_labels = []
for lcs in range(len(lcs_scores)):
if lcs > threshold:
change_labels.append(True)
else:
change_labels.append(False)
return change_labels, lcs_scores
if self.rule == "proportion":
sort_scores = sorted(np.array(lcs_scores))
threshold_index = int(len(lcs_scores) * (1.0 - self.proportion))
threshold = sort_scores[threshold_index]
change_labels = []
for lcs in range(len(lcs_scores)):
if lcs > threshold:
change_labels.append(True)
else:
change_labels.append(False)
return change_labels, lcs_scores
def detect_anomaly_regression(self, predicted_series1, practical_series1, predicted_series2, practical_series2):
"""
It calculates the drop ratio of each point by comparing the predicted value and practical value.
Then it runs filter_anomaly() function to filter out the anomalies by the parameter "rule".
:param predicted_series1: list<float> | the predicted values of the KPI series 1.
:param practical_series1: list<float> | the practical values of the KPI series 1.
:param predicted_series2: list<float> | the predicted values of the KPI series 2.
:param practical_series2: list<float> | the practical values of the KPI series 2.
:return:
"""
change_ratios1 = []
change_ratios2 = []
change_scores = []
for i in range(len(practical_series1)):
c1 = (practical_series1[i] - predicted_series1[i]) / (predicted_series1[i] + 1e-7)
c2 = (practical_series2[i] - predicted_series2[i]) / (predicted_series2[i] + 1e-7)
change_ratios1.append(c1)
change_ratios2.append(c2)
s = (abs(c1) + abs(c2)) / 2.0
change_scores.append(s)
change_labels = self.filter_anomaly(change_ratios1, change_ratios2, change_scores)
return change_ratios1, change_ratios2, change_labels, change_scores
def filter_by_threshold(self, change_ratios, threshold1, threshold2):
"""
It filter out the too deviated points as anomalies.
:param change_ratios: list<float> | the change ratios.
:param threshold1: float | the negative threshold standing for a drop deviation.
:param threshold2: float | the positive threshold standing for a rise deviation.
:return: list<bool> | the list of the labels where "True" stands for an anomaly.
"""
change_labels = []
for r in change_ratios:
if r < threshold1 or r > threshold2:
change_labels.append(True)
else:
change_labels.append(False)
return change_labels
def filter_anomaly(self, change_ratios1, change_ratios2, change_scores):
"""
It detects the anomalies which are measured by regression method.
- gauss: threshold1 = mean - self.sigma * std, threshold2 = mean + self.sigma * std
- threshold: the given threshold variable
- proportion: threshold = sort_scores[threshold_index]
:param change_ratios1: list<float> | the change ratios of the KPI1.
:param change_ratios2: list<float> | the change ratios of the KPI2.
:param change_scores: list<float> | the average of the change anomaly degree of the two change ratios.
:return: list<bool> | the list of the labels where "True" stands for an anomaly.
"""
if self.rule == 'gauss':
mean = np.mean(change_ratios1)
std = np.std(change_ratios1)
threshold1 = mean - self.sigma * std
threshold2 = mean + self.sigma * std
change_labels1 = self.filter_by_threshold(change_ratios1, threshold1, threshold2)
mean = np.mean(change_ratios2)
std = np.std(change_ratios2)
threshold1 = mean - self.sigma * std
threshold2 = mean + self.sigma * std
change_labels2 = self.filter_by_threshold(change_ratios2, threshold1, threshold2)
change_labels = list(np.array(change_labels1) + np.array(change_labels2))
return change_labels
if self.rule == "threshold":
threshold = self.threshold
change_labels1 = self.filter_by_threshold(change_ratios1, -threshold, threshold)
change_labels2 = self.filter_by_threshold(change_ratios2, -threshold, threshold)
change_labels = list(np.array(change_labels1) + np.array(change_labels2))
return change_labels
if self.rule == "proportion":
sort_scores = sorted(np.array(change_scores))
threshold_index = int(len(change_scores) * (1.0 - self.proportion))
threshold = sort_scores[threshold_index]
change_labels = []
for i in range(len(change_scores)):
if change_scores[i] > threshold:
change_labels.append(True)
else:
change_labels.append(False)
return change_labels
|
f453d9cf5dce7a5cf043d16c53fb4e0c75914463 | HaithamAsaad/Python-V2 | /Part A TempConv/temperature converter.py | 779 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 23 13:48:31 2018
@author: haithama
"""
Fflg=0; Cflg=0;
x = int(input("input temerature mode 1 for C to F and 2 for F to C "))
T = int(input("input temerature "))
if x==1:
Fflg=1;
F = ((T + 40)* 9/5) - 40
print("temperature in F is ",F)
elif x==2:
Cflg=1;
C = ((T + 40)* 5/9) - 40
print("temperature in C is ",C)
else:print("wrong temperature mode selection, please re enter your choice")
if ((F<=32 and Fflg==1) or (C<=0 and Cflg==1)):
print("very cold")
elif ((32<F<=50 and Fflg==1) or (0<C<=20 and Cflg==1)):
print("cold")
elif ((50<F<=75 and Fflg==1) or (20<C<=38 and Cflg==1)):
print("worm")
elif ((75<F and Fflg==1) or (38<C and Cflg==1)):
print("hot")
|
b5bde237775df9410b4778b58235a56007c55427 | sgriffith3/try2Go | /class_link.py | 394 | 3.546875 | 4 |
def class_html():
course_name = input("Course Name: ")
labs = input("Number of Labs: ")
low_student_number = input("Lowest Student ID Number: ")
high_student_number = input("Highest Student ID Number: ")
print("Your Class Link is http://alta3.com/graphs?={}&={}&={}&={}".format(
course_name, labs, low_student_number, high_student_number)
class_html()
|
c86e7a38823aefed6fee9ba5f180c30ea35157d8 | 6895mahfuzgit/Calculus_for_Machine_Learning | /delta_method_practise.py | 427 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 1 22:59:11 2021
@author: Mahfuz_Shazol
"""
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-10,10,1000)
#function y=x^2+2x+2
def f(x):
x=x**2+2*x+2
return x
x_delta=0.000001
x=-1
#find the slop of x=-1
y=f(x)
print('y:',y)
#the point P is (-1,1)
x2=x+x_delta
print('x2 :',x2)
y2=f(x2)
print('y2 :',y2)
m=(y2-y)/(x2-x)
print('m :',m)
|
6f2f358e0f5ce0f1e9ceb33e63d1da37adbb731b | cog/Shuffle-Tracker | /shuffle_tracker/shuffle_tracker.py | 1,222 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""Track cards through shuffles and cuts"""
CARDS = ['AH', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '10H', 'JH', 'QH', 'KH',
'AC', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '10C', 'JC', 'QC', 'KC',
'KD', 'QD', 'JD', '10D', '9D', '8D', '7D', '6D', '5D', '4D', '3D', '2D', 'AD',
'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S', 'AS']
class Deck(object):
"""decks of cards: shuffles and cuts"""
def __init__(self):
self.deck = CARDS
def riffle_shuffle(self):
"""riffle shuffles a deck"""
return self.deck
def faro(self):
"""faro shuffles a deck"""
return self.deck
def cut(self):
"""cuts a deck"""
return self.deck
def find(self):
"""finds a card by its position or by its name"""
return self.deck
def distance(self):
"""finds the distance between two cards"""
return self.deck
def find_card_before(self):
"""finds the card immediately before another card"""
return self.deck
def find_card_after(self):
"""finds the card immediately after another card"""
return self.deck
|
da8f3be8b7da919b7ea537bbc55817439fc6d700 | ankitoct/Core-Python-Code | /1. Variable and Operators/10. isNotOperator.py | 66 | 3.71875 | 4 | a = 10
b = 10
print(a is not b)
a = 10
b = '10'
print(a is not b) |
3061d9515b321d746e69674f44b9550ae0e6f151 | ankitoct/Core-Python-Code | /40. List/6. AppendMethod.py | 222 | 4.125 | 4 | # Append Method
a = [10, 20, -50, 21.3, 'Geekyshows']
print("Before Appending:")
for element in a:
print (element)
# Appending an element
a.append(100)
print()
print("After Appending")
for element in a:
print (element) |
52ffb75abd2f29ecbedc9835433a3b441243d6a4 | ankitoct/Core-Python-Code | /1. Variable and Operators/8. notInOperator.py | 164 | 3.515625 | 4 | st1 = "Welcome to geekyshows"
print("subs" not in st1)
st2 = "Welcome to geekyshows"
print("to" not in st2)
st3 = "Welcome top geekyshows"
print("to" not in st3)
|
749d22c7b3be00f25f1f604928937450ecf873d6 | ankitoct/Core-Python-Code | /58. Important Function/8. dictFunction.py | 149 | 3.515625 | 4 | # dict() Function
a = [(101, 'Rahul'), (102, 'Raj'), (103, 'Sonam')]
print(a)
print(type(a))
new_a = dict(a)
print(new_a)
print(type(new_a))
print()
|
e7902135af7f4199590e50467ebecb9b6aa82685 | ankitoct/Core-Python-Code | /29. Numpy Two D ones Function/1. TwoDOnesFunction.py | 634 | 4.03125 | 4 | # 2D Array using ones Function Numpy
from numpy import *
a = ones((3,2), dtype=int)
print("**** Accessing Individual Elements ****")
print(a[0][0])
print(a[0][1])
print(a[1][0])
print(a[1][1])
print(a[2][0])
print(a[2][1])
print()
print("**** Accessing by For Loop ****")
for r in a:
for c in r:
print(c)
print()
print("**** Accessing by For Loop with Index ****")
n = len(a)
for i in range(n):
for j in range(len(a[i])):
print('index',i,j,"=",a[i][j])
print()
print("**** Accessing by While Loop ****")
n = len(a)
i = 0
while i < n :
j = 0
while j < len(a[i]):
print('index',i,j,"=",a[i][j])
j+=1
i+=1
print()
|
bd44616f212df95e3ac53792dc0c506dca28d64d | ankitoct/Core-Python-Code | /10. While Loop/2. whileElseLoop.py | 138 | 4 | 4 | # While Else Loop
a = 1
while a<=10:
print(a)
a+=1
else:
print("While Condition FALSE So Else Part Executed")
print("Rest of the Code") |
0a064e70245373690e15b0a00b36ee1f2ba76c8d | ankitoct/Core-Python-Code | /45. Tuple/6. tupleModification.py | 585 | 4.125 | 4 | # Modifying Tuple
a = (10, 20, -50, 21.3, 'GeekyShows')
print(a)
print()
# Not Possible to Modify like below line
#a[1] = 40 # Show TypeError
# It is not possible to modify a tuple but we can concate or slice
# to achieve desired tuple
# By concatenation
print("Modification by Concatenation")
b = (40, 50)
tup1 = a + b
print(tup1)
print()
# By Slicing
print("Modification by Slicing")
tup2 = a[0:3]
print(tup2)
print()
# By Concatenation and Slicing
print("Modification by Concatenation and Slicing")
c = (101, 102)
s1 = a[0:2]
s2 = a[3:]
tup3 = s1+c+s2
print(tup3)
print()
|
0bd0d5d36b1b20c75b521a6fa1b77bfd32931af0 | ankitoct/Core-Python-Code | /26. Numpy Input From User 1D Array/2. gettingInputFromUser1DArrayWhileLoop.py | 291 | 3.765625 | 4 | # Getting Input from user in 1D Array using While Loop Numpy
from numpy import *
n = int(input("Enter Number of Elements: "))
a = zeros(n, dtype=int)
u = len(a)
i = 0
j = 0
while(i<u):
x = int(input("Enter Element: "))
a[i] = x
i+=1
while(j<(len(a))):
print(a[j])
j+=1
print(type(a)) |
54051160251db27cf67af23632cac19a82b6c411 | ankitoct/Core-Python-Code | /40. List/5. DeletionList.py | 257 | 3.75 | 4 | a = [10, 20, -50, 21.3, 'Geekyshows']
print("Before Deletion: ")
print(a)
print()
# Deleting single element of List
print("After Deletion:")
del a[2]
print(a)
print()
# Deleting entire List
del a
print(a) # It will show error as List a has been deleted
|
771338ef5b59bece23ddf67331ac5824bbcc0cde | ankitoct/Core-Python-Code | /16. Numpy One D Array Function/1. arrayfunction.py | 1,576 | 4 | 4 | # 1D Array using array Function Numpy Example 1
import numpy
stu_roll = numpy.array([101, 102, 103, 104, 105])
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
# 1D Array with Float Number using array Function Numpy Example 2
import numpy
stu_roll = numpy.array([101, 102, 103, 104, 105], dtype=float)
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
# 1D Array with Implicit Float Conversion using array Function Numpy Example 3
import numpy
stu_roll = numpy.array([101, 102, 103, 104, 10.5])
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
# 1D Array with Character using array Function Numpy Exmaple 4
import numpy
stu_roll = numpy.array(['a', 'b', 'c', 'd', 'e'])
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
# 1D Array with string using array Function Numpy Example 5
import numpy
stu_roll = numpy.array(['Rahul', 'Sonam', 'Raj', 'Rani', 'Sumit'])
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
# 1D Array using array Function Numpy Example 6
from numpy import *
stu_roll = array([101, 102, 103, 104, 105])
print(stu_roll)
print(stu_roll.dtype)
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4]) |
a673f44d42f7a6ee67fa74814afac52099634358 | ankitoct/Core-Python-Code | /38. Function/28. TwoDecoratorFunction.py | 642 | 4.1875 | 4 | # Two Decorator Function to same function
# Example 1
def decor(fun):
def inner():
a = fun()
add = a + 5
return add
return inner
def decor1(fun):
def inner():
b = fun()
multi = b * 5
return multi
return inner
def num():
return 10
result_fun = decor(decor1(num))
print(result_fun())
# Example 2
def decor(fun):
def inner():
a = fun()
add = a + 5
return add
return inner
def decor1(fun):
def inner():
b = fun()
multi = b * 5
return multi
return inner
@decor
@decor1
def num():
return 10
# result_fun = decor(decor1(num))
# print(result_fun()) instead of this directly call num function
print(num())
|
5137a5b00a1198a7ff7878824fda595e36ce314e | ankitoct/Core-Python-Code | /52. Dictionary/2. ModifyingDict.py | 223 | 3.671875 | 4 | # Modifying Dictionary
stu = {101: 'Rahul', 102: 'Raj', 103: 'Sonam' }
print("Before Modification:")
print(stu)
print(id(stu))
print()
stu[102] = 'Python'
print("After Modification:")
print(stu)
print(id(stu))
print()
|
4a5c283937a23193f3f0cf9e9a3eb11994c7b3c3 | ankitoct/Core-Python-Code | /40. List/9. insertMethod.py | 156 | 3.796875 | 4 | #insert() Method
a = [10, 20, 30, 10, 90, 'Geekyshows']
print("Before:",a)
a.insert(3, 'Subscribe')
print("After:",a)
for element in a:
print (element) |
f341356d382ea355f3402d2f1e2be8960b9cd081 | ankitoct/Core-Python-Code | /15. Array/5. insertMethod.py | 278 | 3.59375 | 4 | # Insert
from array import *
stu_roll = array('i', [101, 102, 103, 104, 105])
n = len(stu_roll)
i = 0
while(i<n):
print(stu_roll[i])
i+=1
print("Array After Insert")
stu_roll.insert(1, 106)
stu_roll.insert(3, 107)
n = len(stu_roll)
i = 0
while(i<n):
print(stu_roll[i])
i+=1 |
74b872c0cdaec66aa6e378aed100b87079b91f6d | ankitoct/Core-Python-Code | /54. Nested Dictionary/3. AccessNestedDict1.py | 375 | 4.40625 | 4 | # Accessing Nested Dictionary using For loop
a = {1: {'course': 'Python', 'fees':15000},
2: {'course': 'JavaScript', 'fees': 10000 } }
# Accessing ID
print("ID:")
for id in a:
print(id)
print()
# Accessing each id keys
for id in a:
for k in a[id]:
print(k)
print()
# Accessing each id keys -- value
for id in a:
for k in a[id]:
print(id,'=',k,'=',a[id][k])
|
fba5066edb3916f2d8eec8ca5ab564335c6cdbf9 | ankitoct/Core-Python-Code | /58. Important Function/7. setFunction.py | 425 | 3.703125 | 4 | # set() Function
a = [10,20,30]
print(a)
print(type(a))
new_a = set(a)
print(new_a)
print(type(new_a))
print()
b = (10,20,30)
print(b)
print(type(b))
new_b = set(b)
print(new_b)
print(type(new_b))
print()
c = "GeekyShows"
print(c)
print(type(c))
new_c = set(c)
print(new_c)
print(type(new_c))
print()
d = {101:'Rahul', 102:'Raj', 103:'Sonam'}
print(d)
print(type(d))
new_d = set(d)
print(new_d)
print(type(new_d))
print()
|
bbf0d85066f85fae9f77a1a91d43237aaa3a1f57 | ankitoct/Core-Python-Code | /9. if elif else Statement/1. ifelifelseStatement.py | 472 | 4.40625 | 4 | # If elif else Statement
day = "Tuesday"
if (day == "Monday"):
print("Today is Monday")
elif (day == "Tuesday"):
print("Today is Tuesday")
elif (day == "Wednesday"):
print("Today is Wednesday")
else:
print("Today is Holiday")
# If elif else with User Input
day = input("Enter Day: ")
if day == "Monday":
print("Today is Monday")
elif day == "Tuesday":
print("Today is Tuesday")
elif day == "Wednesday":
print("Today is Wednesday")
else:
print("Today is Holiday") |
ec9e9c5652c7abebb904349d0f33c50e058ca9a0 | ankitoct/Core-Python-Code | /37. String Functions/7. Example7.py | 221 | 3.78125 | 4 | print("****** startswith Function ******")
name = "Hi How are you"
str1 = name.startswith('Hi')
print(name)
print(str1)
print("****** endswith Function ******")
name = "Thank you Bye"
str1 = name.endswith('Bye')
print(name)
print(str1) |
7457008cab91ec66f819dcaec3f2b4bd4e69c627 | ankitoct/Core-Python-Code | /36. Formatting String/7. FStringExample3.py | 897 | 4.125 | 4 | # Thousand Separator
price = 1234567890
print(f"{price:,}")
print(f"{price:_}")
#Variable
name = "Rahul"
age= 62
print(f"My name is {name} and age {age}")
# Expression
print(f"{10*8}")
# Expressing a Percentage
a = 50
b = 3
print(f"{a/b:.2%}")
# Accessing arguments items
value = (10, 20)
print(f"{value[0]} {value[1]}")
# Format with Dict
data = {'rahul': 2000, 'sonam': 3000}
print(f"{data['rahul']:d} {data['sonam']:d}")
# Calling Function
name= "GeekyShows"
print(f"{name}")
print(f"{name.upper()}")
# Using object created from class
#print(f"{obj.name}")
# Curly Braces
print(f"{10}")
print(f"{{10}}")
# Date and Time
from datetime import datetime
today = datetime(2019, 10, 5)
print(f"{today}")
print(f"{today:%d-%b-%Y}")
print(f"{today:%d/%b/%Y}")
print(f"{today:%b/%d/%Y}")
# Datetime Directive https://docs.python.org/3.7/library/datetime.html#strftime-and-strptime-behavior
|
9e3c71a9e4df068f7e4982ec9d335abb08f0d796 | ankitoct/Core-Python-Code | /40. List/10. popMethod.py | 148 | 3.84375 | 4 | #pop() method
a = [10, 20, 30, 10, 90, 'Geekyshows']
print("Before POP:", a)
a.pop()
print("After POP:", a)
for element in a:
print(element)
|
d6a56cdb7c1ced567dce8514c33969fb00559086 | ankitoct/Core-Python-Code | /55. List Comprehension/3. ListCompNestedConditional.py | 252 | 4.03125 | 4 | # List Comprehension
# Without List Comprehension (Conditional)
lst1 =[]
for i in range(20):
if(i%2==0):
if(i%3==0):
lst1.append(i)
print(lst1)
# With List Comprehension (Conditional)
lst2 =[i for i in range(20) if i%2==0 if i%3==0]
print(lst2) |
50e73325ec725a44435d6436bddcda31b9a40578 | renatodjurdjevic/petlje | /while-petlja-primjer.py | 414 | 3.578125 | 4 | # while petlja
import random # importamo random library
secret = random.randint(1,30)
while True:
guess = int(input("Pogodi jedan broj izmedju 1 i 30: "))
if guess == secret:
print("Bravo! Traženi broj je bio: " + str(secret))
break
elif guess > secret:
print("Fulao si, probaj s manjim brojem.")
elif guess < secret:
print("Fulao si, probaj s većim brojem.") |
3a3484608d9f4df11ef21c158fb0b2021f36c069 | PaliwalSparsh/Attendance-Project | /func.py | 1,626 | 3.515625 | 4 | #!usr/env/bin/python2.7
import sqlite3
import datetime
def take_attendance(strength,course,conn_obj):
today = str(datetime.date.today())
print ("Attendance for %s" %today)
try:
conn_obj.execute("ALTER TABLE %s ADD COLUMN '%s' 'char'" %(course,today))
except sqlite3.OperationalError:
print "Attendance for the date already taken"
return
print "Enter p | a | m for Present | Absent | Manual_entry"
for x in range(1,strength):
print ("%d." %x)
att = raw_input("").lower()
while(1):
if att =='p' :
print "present"
conn_obj.execute("UPDATE %s SET '%s'='P' WHERE 'roll'=%d" %(course,today,x))
break
elif att == 'a' :
print "absent"
conn_obj.execute("UPDATE %s SET '%s'='A' WHERE 'roll'=%d" %(course,today,x))
break
elif att == 'm' :
man = int(raw_input("Enter the roll call\n"))
man_att = raw_input("Enter p | a for Present | Absent\n").lower()
if man_att == 'p' :
print "present"
conn_obj.execute("UPDATE %s SET '%s'='P' WHERE 'roll'=%d" %(course,today,man))
elif man_att == 'a' :
print "absent"
conn_obj.execute("UPDATE %s SET '%s'='A' WHERE 'roll'=%d" %(course,today,man))
break
else:
print "Enter a valid input"
continue
def course_exist(course,conn_obj):
for x in conn_obj.execute("SELECT name from courses;"):
if (x[0].lower()) == (course.lower()):
return True
return False
def create_course(course,strength,conn_obj):
conn_obj.execute('CREATE TABLE %s(roll int);' %course)
for x in range(1,strength):
conn_obj.execute("INSERT INTO %s VALUES(%d);" %(course,x))
if __name__ == "__main__":main()
|
7db324b896ba06a565b38640bcc16512f23ee7c0 | HarshPraharaj/LeetcodePractice | /Easy/1365_HowManyNumbersAreSmallerThantheCurrentNumber.py | 331 | 3.59375 | 4 | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
dict1 = {}
n = nums[:]
nums.sort()
for i in range(len(nums)):
if i == 0 or nums[i-1] < nums[i]:
dict1[nums[i]] = i
return [dict1[num] for num in n]
|
a60165af0986981ea6097e34278a844d9b9b2f70 | MirandaTowne/Python-Projects | /grade_list.py | 754 | 4.46875 | 4 | # Name: Miranda Towne
# Description: Creating a menu that gives user 3 choices
# Empty list
grade = []
done = False
new_grade = ''
# Menu options
menu = """
Grade Book
0: Exit
1: Display a sorted list of grades
2: Add a grade to the list
"""
# Display menu at start of a while loop
while not done:
print(menu)
# Ask for users choice
option = int(input('\nPlease enter an option: '))
# Respond to users choice
if option == 0:
done = True
print("Good bye!")
elif option == 1:
grade.sort
print(grade)
elif option == 2:
new_grade = input('\nPlease add a new grade to the list: ')
grade.append(new_grade)
print("\nGrade added to the list")
print(grade)
|
b58755aca2047658a8d56dfcb65258e2789d4f26 | PashaKlybik/Python | /lab2/z4.py | 3,498 | 3.625 | 4 | __author__ = 'pasha'
class Vector():
def __init__(self,n=1):
self.vec = [0 for _ in range(n)]
def __len__(self):
return len(self.vec)
def __getitem__(self, item):
if 0<=item<len(self.vec):
return self.vec[item]
return None
def __setitem__(self, key, value):
if 0<=key<len(self.vec):
self.vec[key]=value
def __str__(self):
return str(self.vec)
def __eq__(self, other):
if type(self)==type(other) and (len(self.vec)==len(other.vec)):
return True
return False
def __iadd__(self, other):
if type(other)==type(self):
if len(self)==len(other):
for i in range(len(self)):
self.vec[i]+=other.vec[i]
return self
else:
print ("different length vectors")
return self
elif type(other)==type(self.vec[0]):
for i in range(len(self)):
self.vec[i]+=other
return self
else:
print("Type error")
return self
def __add__(self, other):
if type(other)==type(self):
if len(self)==len(other):
temp = Vector(len(self))
for i in range(len(self)):
temp.vec[i]=self.vec[i]+other.vec[i]
return temp
else:
print ("different length vectors")
return 0
elif type(other)==type(self.vec[0]):
temp = Vector(len(self))
for i in range(len(self)):
temp.vec[i]=self.vec[i]+other
return temp
else:
print("Type error")
return 0
def __isub__(self, other):
if type(other)==type(self):
if len(self)==len(other):
for i in range(len(self)):
self.vec[i]-=other.vec[i]
return self
else:
print ("different length vectors")
return self
elif type(other)==type(self.vec[0]):
for i in range(len(self)):
self.vec[i]-=other
return self
else:
print("Type error")
return self
def __sub__(self, other):
if type(other)==type(self):
if len(self)==len(other):
temp = Vector(len(self))
for i in range(len(self)):
temp.vec[i]=self.vec[i]-other.vec[i]
return temp
else:
print ("different length vectors")
return 0
elif type(other)==type(self.vec[0]):
temp = Vector(len(self))
for i in range(len(self)):
temp.vec[i]=self.vec[i]-other
return temp
else:
print("Type error")
return 0
def __mul__(self, other):
if type(self)==type(other):
if len(self)==len(other):
scalar = 0
for vec1, vec2 in zip(self.vec, other.vec):
scalar += vec1+vec2
return scalar
else:
print("different length vectors")
elif type(other)==type(self.vec[0]):
temp = Vector(len(self))
for i in range(len(temp)):
temp.vec[i] = self.vec[i]*other
return temp
else:
print("Type error")
return 0
|
c44a238b0c36f6f4d1e74ec2b3de0fe7d18b0d3f | Inerial/leetcode | /8_30/2.py | 670 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
root = head = ListNode(0)
extra = 0
while l1 or l2 or extra:
mysum = 0
if l1:
mysum += l1.val
l1 = l1.next
if l2:
mysum += l2.val
l2 = l2.next
extra, mysum = divmod(mysum + extra, 10)
head.next = ListNode(mysum)
head = head.next
return root.next |
37d959edf740464ebade95b257fdc78945b2a1d9 | shubhamgg1997/pyspark | /excersise/list.py | 262 | 3.546875 | 4 | '''Write a program which take a list of list and give result of
# all list'''
from pyspark import SparkContext
sc = SparkContext("local", "list app")
list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=sc.parallelize(list1)
list3=list2.reduce(lambda x,y: x+y)
print(list3)
|
11720d7839d3f1452e70e42a73a1a2e508b4b56e | AurelienCaille/ProjetGraphes | /CarteDestination.py | 461 | 3.9375 | 4 | class CarteDestination(object):
""" Class representant une carte destination du jeu """
def __init__(self, depart, arrive, point):
"""
:attribut self.depart: def self.depart to depart
:attribut self.arrive: def self.depart to arrive
"""
self.depart = depart
self.arrive = arrive
self.point = point
def __repr__(self):
return (self.depart + "--->" + self.arrive + " : " + self.point)
|
7a64cd8c0aca172f6f0fe660c19bcf62451000be | kimalaacer/Head-First-Learn-to-Code | /chapter 4/thing1.py | 266 | 3.5625 | 4 | characters=['a','m','a','n','a','p','l','a','n','a','c']
output=''
length=len(characters)
i=0
while(i<length):
output=output+characters[i]
i=i+1
length=length * -1
i=-2
while(i>=length):
output=output+characters[i]
i=i-1
print(output)
|
ec40f68419b2a7c639bb9614cf1447f02927f529 | kimalaacer/Head-First-Learn-to-Code | /chapter 12/dog4.py | 1,205 | 4.34375 | 4 | # this is an introduction to object oriented programming OOP
# dog class has some attributes (state) such as name, age, weight,and behavior ( or method) bark
class Dog:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def bark(self):
if self.weight > 29:
print(self.name, 'says "WOOF WOOF"')
else:
print(self.name, 'says "woof woof')
def human_years(self):
human_age = self.age * 7
return human_age
def __str__(self):
return "I'm a dog named " + self.name
def print_dog(dog):
print(dog.name+"'s",'age is', dog.age,'and weight is', dog.weight)
# all ServiceDog objects are Dog objects
#not all Dogs are Service Dogs.
class ServiceDog(Dog):
def __init__(self, name, age, weight, handler):
Dog.__init__(self, name, age, weight)
self.handler = handler
def walk(self):
print(self.name,'is helping its handler', self.handler, 'walk')
codie = Dog('Codie', 12, 38)
jackson = Dog('Jackson', 9, 12)
rody = ServiceDog('Rody', 8, 38, 'Joseph')
print(codie)
print(jackson)
print(rody)
|
78f5290978cd8434f697f538acf29cab1797430d | kimalaacer/Head-First-Learn-to-Code | /chapter 9/crazy_sys_argv.py | 1,946 | 3.765625 | 4 | # this code is for a game crazy lib
import sys
def make_crazy_lib(filename):
try:
file=open(filename, 'r')
text=''
for line in file:
text=text+process_line(line)
file.close()
return text
except FileNotFoundError:
print("Sorry, Couldn't find:", filename + '.')
except IsADirectoryError:
print("Sorry", filename, 'is a directory.')
except:
print('Sorry, could not read', filename) # value None will get returned
# a simple solution is to add 'Noun,' to placeholders. it does not encompass all the punctuations but it is fast.
# placeholders=['NOUN','ADJECTIVE','VERB_ING', 'VERB', 'NOUN,']
# I tested it and it worked.
placeholders=['NOUN','ADJECTIVE','VERB_ING', 'VERB']
def process_line(line):
global placeholders
processed_line=''
words=line.split()
for word in words:
stripped=word.strip('.,;?!') # this will strip all punctuations
if stripped in placeholders:
answer = input('Enter a '+ stripped + ":")
processed_line=processed_line + answer
if word[-1] in '.,;?!':
processed_line=processed_line +word[-1] +' ' # this code is to put the punctuation back at the end of the word
else:
processed_line=processed_line + ' '
else:
processed_line=processed_line + word + ' '
return processed_line+ '\n'
def save_crazy_lib(filename,text):
file=open(filename, 'w')
file.write(text)
file.close()
def main():
if len(sys.argv) !=2:
print("crazy_sys_argv.py need to be followed by the text you need to run. i.e: crazy_sys_argv.py lib.txt")
else:
filename=sys.argv[1]
lib=make_crazy_lib(filename)
if (lib!= None):
save_crazy_lib('crazy_'+filename, lib)
if __name__=='__main__':
main()
|
ba44dedf1532fe9b0242830580ad7cf930354e50 | kimalaacer/Head-First-Learn-to-Code | /chapter 11/blastoff.py | 367 | 3.671875 | 4 | # using tkinter to update root at 1000 ms
from tkinter import *
root = Tk()
count = 10
def countdown():
global root, count
if count > 0:
print (count)
count = count -1
root.after(1000, countdown) # this is using the after module in tkinter to autoupdate
else:
print('Blastoff')
countdown()
mainloop()
|
d1ea9bede4e582981025d41bfb63994aa3bee27d | kimalaacer/Head-First-Learn-to-Code | /chapter 5/compute.py | 160 | 3.71875 | 4 | def compute(x,y):
total= x+y
if total>10:
total=10
return total
test1=compute(2,3)
test2=compute(11,3)
print(test1)
print(test2)
|
c88afb04db70df72b71e62a667d5734b502679e2 | kimalaacer/Head-First-Learn-to-Code | /chapter 6/readability.py | 2,729 | 4.03125 | 4 | # this code is to check the readability of ch1 text
#f=open('ch6.txt','r')
#contents=f.read()
#print(contents)
import ch1_text
def count_syllables(words):
count =0
for word in words:
word_count=count_syllables_in_word(word)
count=count+word_count
return count
def count_syllables_in_word(word):
count=0
endings='.,;!?:'
last_char=word[-1]
if last_char in endings:
processed_word=word[0:-1]
else:
processed_word=word
if len(processed_word)<=3:
return 1
if processed_word[-1] in 'eE':
processed_word=processed_word[0:-1]
vowels='aeiouAEIOU'
prev_char_was_vowel=False
for char in processed_word:
if char in vowels:
if not prev_char_was_vowel:
count=count+1
prev_char_was_vowel=True
else:
prev_char_was_vowel=False
if processed_word[-1] in 'yY':
count=count+1
return count
def count_sentences(text):
count=0
# for char in text:
# if char== '.' or char=='?' or char=='!' or char== ';' or char== ':':
# count=count+1
# else:
# count=count
# return(count)
terminals='.;?!'
for char in text:
if char in terminals:
count=count+1
return count
count_sentences(ch1_text.text)
def output_results(score):
if score>=90:
print('Reading level of 5th grade. Easily understood by an average 11-year-old student.')
elif score>=80:
print('Reading level of 6th grade. Conversational English for consumers.')
elif score>=70:
print('Reading level of 7th grade.')
elif score>=60:
print('Reading level of 8th & 9th grade. Plain English. Easily understood by 13- to 15-year-old students.')
elif score>=50:
print('Reading level of 10th to 12th grade. Fairly difficult to read.')
elif score>=30:
print('Reading level of College. Difficult to read.')
else:
print('Reading level of College graduate. Very difficult to read. Best understood by university graduates.')
def readability(text):
total_words=0
total_sentences=0
total_syllables=0
score=0
words=text.split()
total_words=len(words)
total_sentences=count_sentences(text)
total_syllables=count_syllables(words)
score=(206.835 - 1.015*(total_words/total_sentences) - 84.6 * (total_syllables/total_words) )
print(total_words, 'words')
print(total_sentences, 'sentences')
print(total_syllables, 'syllables')
print(score,'reading ease score')
output_results(score)
readability(ch1_text.text)
|
a1888d6249afb09d877a7dead579d416487cbe57 | oomintrixx/EC500-hackthon | /sqlite_database/serverTable3_db.py | 2,364 | 4 | 4 | import sqlite3
#server table three: table used for store online_users
#primary ID, username(string), ip address(string), port(int), public key(string)
def server_database3():
conn = sqlite3.connect('server_table3.db') #Opens Connection to SQLite database file.
conn.cursor().execute('''CREATE TABLE server_table3
(PRIMARY_ID INTEGER,
USERNAME TEXT,
IP_ADDRESS TEXT,
PORT INTEGER,
PUBLIC_KEY TEXT
);''')
conn.commit()
conn.close()
#create server table 3 with primary id, username, ip address, port, and public key
def create_svtable3(primaryid, username, ipaddress, port, publickey):
conn = sqlite3.connect('server_table3.db')
cursor = conn.cursor()
params = (primaryid, username, ipaddress, port, publickey)
cursor.execute("INSERT INTO server_table3 VALUES (?,?,?,?,?)",params)
conn.commit()
#print('User Creation Successful')
conn.close()
#retrieve all information stored inside server table 3
def retrieve_all():
conn = sqlite3.connect('server_table3.db')
cur = conn.cursor()
cur.execute("SELECT * FROM server_table3")
return (cur.fetchall())
#return all information associated with this primary id
def retrieve_specific(primaryid):
conn = sqlite3.connect('server_table3.db')
cur = conn.cursor()
cur.execute("SELECT * FROM server_table3 WHERE PRIMARY_ID =:PRIMARY_ID",{'PRIMARY_ID':primaryid})
return (cur.fetchall())
#delete all information related to this username from the database
def delete_userFromUsername(username):
conn = sqlite3.connect('server_table3.db')
cur = conn.cursor()
cur.execute("""DELETE FROM server_table3 WHERE USERNAME =:USERNAME """,{'USERNAME':username})
conn.commit()
conn.close()
#delete all information related to this primary from the database
def delete_userFromID(primaryid):
conn = sqlite3.connect('server_table3.db')
cur = conn.cursor()
cur.execute("""DELETE FROM server_table3 WHERE PRIMARY_ID =:PRIMARY_ID """,{'PRIMARY_ID':primaryid})
conn.commit()
conn.close()
#delete all information from database
def delete_all():
conn = sqlite3.connect('server_table3.db')
cur = conn.cursor()
cur.execute("""DELETE FROM server_table3""")
conn.commit()
conn.close()
|
644c69d138019c8b1230cba53f6368508a250e8f | mmilett14/project-euler | /8-largest-product-in-a-series.py | 404 | 3.515625 | 4 | # Use sliding Window
# Solved problem
window_max = 0
i = 0
for i in range(0, len(num)-12):
window_prod = int(num[i]) * int(num[i+1]) * int(num[i+2]) * int(num[i+3]) * int(num[i+4]) * int(num[i+5]) * int(num[i+6]) * int(num[i+7]) * int(num[i+8]) * int(num[i+9]) * int(num[i+10]) * int(num[i+11]) * int(num[i+12])
if window_prod > window_max:
window_max = window_prod
print(window_max)
|
a2812dfad727e073118a0a5fac2df8d4d771618c | alem-classroom/student-python-introduction-AubakirovArman | /sets/sets.py | 436 | 3.75 | 4 | def size_of_set(set):
return len(set)
def is_elem_in_set(set, elem):
return elem in set
def are_sets_equal(first_set, second_set):
return first_set==second_set
def add_elem_to_set(set, elem):
set.add(elem)
return set
def remove_elem_if_exists(set, elem):
if elem in set:
set.remove(elem)
return set
else:
return set
def delete_first_element(set):
set.pop()
return set
|
6e7d6ba858aabbe11f058f94ca79ed004191a036 | sarsaparel/lesson2 | /Documents/projects/lesson2/if1.py | 354 | 4 | 4 | age = int(input('Сколько тебе лет? '))
if age < 5:
print ('Кушай манную кашу с комочками')
elif 5 <= age <= 16:
print ('Заполни дневник, играй в CS')
elif 16 < age <= 21:
print ('Пиши курсовую')
elif age > 21 :
print ('Ешь печеньки, получай зарплату') |
bf779d5b46eb8ec609bc3f5159b40364cfc85c20 | sychaichangkun/Udacity_Courses | /CS212:Design of Computer Programs/Lesson4/Csuccessors.py | 2,586 | 3.859375 | 4 | # -----------------
# User Instructions
#
# Write a function, csuccessors, that takes a state (as defined below)
# as input and returns a dictionary of {state:action} pairs.
#
# A state is a tuple with six entries: (M1, C1, B1, M2, C2, B2), where
# M1 means 'number of missionaries on the left side.'
#
# An action is one of the following ten strings:
#
# 'MM->', 'MC->', 'CC->', 'M->', 'C->', '<-MM', '<-MC', '<-M', '<-C', '<-CC'
# where 'MM->' means two missionaries travel to the right side.
#
# We should generate successor states that include more cannibals than
# missionaries, but such a state should generate no successors.
def csuccessors(state):
"""Find successors (including those that result in dining) to this
state. But a state where the cannibals can dine has no successors."""
M1, C1, B1, M2, C2, B2 = state
# your code here
res = {}
if (M1 < C1 and M1>0) or (M2 < C2 and M2 >0):#cannibals can dine
return res
if B1 == 1:
if M1:
res[(M1-1, C1, 0, M2+1, C2, 1)] = 'M->'
if M1 >= 2:
res[(M1-2, C1, 0, M2+2, C2, 1)] = 'MM->'
if C1:
res[(M1, C1-1, 0, M2, C2+1 ,1)] = 'C->'
if C1 >= 2:
res[(M1, C1-2, 0, M2, C2+2 ,1)] = 'CC->'
if C1 and M1:
res[(M1-1, C1-1, 0, M2+1, C2+1 ,1)] = 'MC->'
elif B2 == 1:
if M2:
res[(M1+1, C1, 1, M2-1, C2, 0)] = '<-M'
if M2 >= 2:
res[(M1+2, C1, 1, M2-2, C2, 0)] = '<-MM'
if C2:
res[(M1, C1+1, 1, M2, C2-1, 0)] = '<-C'
if C2 >= 2:
res[(M1, C1+2, 1, M2, C2-2, 0)] = '<-CC'
if C2 and M2:
res[(M1+1, C1+1, 1, M2-1, C2-1, 0)] = '<-MC'
return res
def test():
assert csuccessors((2, 2, 1, 0, 0, 0)) == {(2, 1, 0, 0, 1, 1): 'C->',
(1, 2, 0, 1, 0, 1): 'M->',
(0, 2, 0, 2, 0, 1): 'MM->',
(1, 1, 0, 1, 1, 1): 'MC->',
(2, 0, 0, 0, 2, 1): 'CC->'}
assert csuccessors((1, 1, 0, 4, 3, 1)) == {(1, 2, 1, 4, 2, 0): '<-C',
(2, 1, 1, 3, 3, 0): '<-M',
(3, 1, 1, 2, 3, 0): '<-MM',
(1, 3, 1, 4, 1, 0): '<-CC',
(2, 2, 1, 3, 2, 0): '<-MC'}
assert csuccessors((1, 4, 1, 2, 2, 0)) == {}
return 'tests pass'
print test()
|
0c0ee41359c913d08ad4c33914a13e99f85a054a | Silentsoul04/2020-02-24-full-stack-night | /1 Python/solutions/random_password.py | 1,114 | 3.875 | 4 | import random
import string
def get_lowercase_letters(n_letters, password):
for i in range(0, n_letters):
password.append(random.choice(string.ascii_lowercase))
def get_uppercase_letters(n_letters, password):
for i in range(0, n_letters):
password.append(random.choice(string.ascii_uppercase))
def get_numbers(n_numbers, password):
for i in range(0, n_numbers):
password.append(random.choice(string.digits))
def get_specials(n_specials, password):
for i in range(0, n_specials):
password.append(random.choice(string.punctuation))
def main():
password = []
n_lowers = int(input('\nhow many lowercase? '))
n_uppers = int(input('how many uppercase? '))
n_numbers = int(input('how many numbers? '))
n_specials = int(input('how many \'specials\'? '))
get_lowercase_letters(n_lowers, password)
get_uppercase_letters(n_uppers, password)
get_numbers(n_numbers, password)
get_specials(n_specials, password)
# print(f'{"".join(password)}')
print(f'\n{"".join(random.sample(password, k=len(password)))}\n')
main()
|
bffb8076b777e4962c687e0f9c790b5fafc93041 | Silentsoul04/2020-02-24-full-stack-night | /1 Python/solutions/unit_converter.py | 697 | 4.25 | 4 | def convert_units(data):
conversion_factors = {
'ft': 0.3048,
'mi': 1609.34,
'm': 1,
'km': 1000,
'yd': 0.9144,
'in': 0.0254,
}
value, unit_from, unit_to = data
converted_m = conversion_factors[unit_from] * value
return round(converted_m / conversion_factors[unit_to], 2)
def main():
user_input = input('\nenter the distance: ')
convert_to_unit = input('\nenter units to convert to: ')
user_input_split = user_input.split(" ")
value = float(user_input_split[0])
unit = user_input_split[1]
print(f'\n{value} {unit} is {convert_units((value, unit, convert_to_unit))} {convert_to_unit}.\n')
main() |
f9bd9368cf0fbb371e9549eed41bfe1ece94a20b | vxrnxk/python-brasil-exercicios-estrutura-de-decisao | /L02-E06.py | 794 | 4.0625 | 4 | # Lista 02 - Exercício 06
# Faça um Programa que leia três números e mostre o maior deles.
primeiro_numero = int(input("Digite o primeiro número "))
segundo_numero = int(input("Digite o segundo número "))
terceiro_numero = int(input("Digite o terceiro número "))
maior_numero = 0
if primeiro_numero > segundo_numero:
if primeiro_numero > terceiro_numero:
maior_numero = primeiro_numero
if primeiro_numero < terceiro_numero:
maior_numero = terceiro_numero
if segundo_numero > primeiro_numero:
if segundo_numero > terceiro_numero:
maior = segundo_numero
if segundo_numero < terceiro_numero:
maior_numero = terceiro_numero
print(f"O Maior número de [{ primeiro_numero }, { segundo_numero }, { terceiro_numero }] é: { maior_numero }")
|
4522bc7692b2ae528cdc1a18b1c7d00c47ca808c | sagarwani/simple_Programs | /MovingAverage.py | 1,558 | 4.0625 | 4 | #Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
#
#Example:
#
#MovingAverage m = new MovingAverage(3);
#m.next(1) = 1
#m.next(10) = (1 + 10) / 2
#m.next(3) = (1 + 10 + 3) / 3
#m.next(5) = (10 + 3 + 5) / 3
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.size = size
self.queue = [None] * size
self.tail = -1
self.pos = 0
def isEmpty(self):
if self.tail == -1:
return True
def next(self, val):
"""
:type val: int
:rtype: float
"""
sumTotal1, sumTotal2 = 0,0
self.flag = 0
if self.isEmpty():
self.queue[0] = val
self.tail = 0
self.pos += 1
else:
self.tail = (self.tail + 1) % self.size
self.queue[self.tail] = val
self.pos += 1
#Calculate average
if self.pos >= self.size:
for i in range(self.size):
sumTotal1 += self.queue[i]
average = float(sumTotal1) / self.size
return average
else:
for i in range(self.pos):
sumTotal2 += self.queue[i]
average = float(sumTotal2) / self.pos
return average
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
|
7960c0c29c9870b0edae9256f45e6cd8c22d0336 | wilmtang/PythonBasicKnowledge | /尾递归的阶乘.py | 176 | 3.875 | 4 | def fact(n):
return fact_iter(n, 1)
def fact_iter(n, product):
if n==1:
return product
else:
return fact_iter(n-1, product*n)
n=7
print('fact(%d) =%d' % (n, fact(n)) ) |
268877ac74d3f32b7e8a49dba2228bf29fdf9742 | Mukul-12/tuple | /tuple4.py | 94 | 3.6875 | 4 | t=eval(input('enter your list : '))
m=eval(tuple(input('enter your list : ')))
a=t+m
print(a)
|
d17ae00557886fec698e222a49805cce5af9ffa4 | hirangoly/PythonExercises | /lcm.py | 176 | 3.640625 | 4 | from sys import argv
def lcm(x,y):
tmp=x
while (tmp%y)!=0:
tmp+=x
return tmp
def lcmm(*args):
return reduce(lcm,args)
args=map(int,argv[1:])
print lcmm(*args)
|
3adafc3efa2519a2d272a00013c70b0aa3983fb3 | CS-Cowboy/HRSolutions | /dp_ksack/solve_equal_subset_partition.py | 1,435 | 3.65625 | 4 | import sys
from typing import Dict
targetVal = 0
nums = list()
def solve_equal_subset_partition(memo, sums, n, i):
K = i + 1
if i == len(nums) or sums[K] == targetVal:
return memo[i]
# print("new call-> ", memo, sums, n, i, '\n')
for N in nums:
if N == n:
continue
if sums[K] + N <= targetVal:
memo[K].append(N)
sums[K] += N
# print('MEMO->\t\t\t', memo, "\n")
if sums[K] == targetVal:
for F in memo[K]:
nums.remove(F)
return nums, memo[K]
else:
return solve_equal_subset_partition(memo, sums, nums[i], K)
if __name__ == "__main__":
sum = 0
if len(sys.argv) > 1:
numList = str(sys.argv[1]).split()
for n in numList:
sum += int(n)
nums.append(int(n))
if sum % 2 == 0:
targetVal = int(sum / 2)
print("Target (must be whole number) -> ", targetVal)
memo = dict()
sums = dict()
j = 0
for j in range(len(nums)):
memo.update({nums[j]: list()})
sums.update({nums[j]: 0})
print("Partition Solution -> ", solve_equal_subset_partition(memo, sums, nums[0], 0), " Both partitions now add to: ", targetVal, ' =^_^=')
else:
print("Impossible!")
else:
print('Please supply argument: <number list>')
|
ac41db90b8f4c9bc50a0d9ca61e772cde263941f | AmotzL/Spotify_Recommendation | /spotify_crawler.py | 6,070 | 3.546875 | 4 |
import spotipy
import json
from spotipy.oauth2 import SpotifyClientCredentials
from globs import *
TRACKS_LIMIT = 500
client_credentials_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
def playlists_by_word(search_word):
"""
A method to search playlists in Spotify by word.
:param search_word: The given word.
:return: List of playlists with total TRACKS_LIMIT number if tracks. (maybe more)
"""
list_playlist = list()
result_search = sp.search(search_word, type='playlist', limit=50)
num_songs = 0
while result_search:
for playlist in result_search['playlists']['items']:
num_songs += playlist['tracks']['total']
list_playlist.append(playlist['id'])
# tracks_playlist = sp.user_playlist('spotify', playlist['id'], fields="tracks,next")
# analyze_playlist(tracks_playlist['tracks'])
if num_songs > TRACKS_LIMIT:
return list_playlist
if result_search['playlists']['next']:
result_search = sp.next(result_search['playlists'])
else:
result_search = None
def analyze_playlists(playlists):
"""
A method that goes over a given list of playlists ids. (to do something with it).
:param playlists: A list of ids of playlist in spotify.
:return: List of tracks ids.
"""
list_tracks_id = list()
for playlist_id in playlists:
# get the playlist by id from spotify.
result = sp.user_playlist('spotify', playlist_id, fields="tracks,next")
# from result we take the tracks.
playlist = result['tracks']
# now we go over the tracks(songs).
while playlist:
for track in playlist['items']:
# track is some dictionary, we need the track id.
list_tracks_id.append(track['track']['id'])
if playlist['next']:
playlist = sp.next(playlist)
else:
playlist = None
return list_tracks_id
def filter_happy_songs(tracks):
"""
A method to filter the songs to get the most "happy" ones.
:param tracks: The tracks we want to analyze.
:return: List of songs, with their features.
"""
data = dict()
data['songs'] = list()
for track_id in tracks:
# next line get the feature.
result = sp.audio_features(track_id)
data['songs'].append({'song_name': track_id, 'song_features': result[0]})
return data
def filter_sad_songs(tracks):
"""
A method to filter the songs to get the most "sad" ones.
:param tracks: The tracks we want to analyze.
:return: List of songs, with their features.
"""
data = dict()
data['songs'] = list()
for track_id in tracks:
# next line get the feature.
result = sp.audio_features(track_id)
if result[0]['valence'] < 0.21:
data['songs'].append({'song_name': track_id, 'song_features': result[0]})
return data
def filter_angry_songs(tracks):
"""
A method to filter the songs to get the most "angry" ones.
:param tracks: The tracks we want to analyze.
:return: List of songs, with their features.
"""
data = dict()
data['songs'] = list()
for track_id in tracks:
# next line get the feature.
result = sp.audio_features(track_id)
if result[0]['energy'] > 0.7 and result[0]['loudness'] > -10:
data['songs'].append({'song_name': track_id, 'song_features': result[0]})
return data
def no_filter_songs(tracks):
"""
A method to put the tracks in a list of features.
:param tracks: The tracks we want to analyze.
:return: List of songs, with their features.
"""
data = dict()
data['songs'] = list()
for track_id in tracks:
# next line get the feature.
result = sp.audio_features(track_id)
data['songs'].append({'song_name': track_id, 'song_features': result[0]})
return data
def get_playlist_by_keys(key_words):
"""
A method to search for playlists in mood category of spotify.
:param key_words: A list of key words we search in the name of playlists.
:return: A list of playlists with the key words in their names.
"""
list_playlist = list()
categories = sp.categories()['categories']['items']
for category in categories:
if category['name'] == 'Mood':
result = sp.category_playlists(category_id=category['id'], country='US', limit=50)['playlists']
for i in range(2):
mood_playlists = result['items']
for playlist in mood_playlists:
playlist_name = playlist['name']
for happy_key in key_words:
if happy_key in playlist_name:
list_playlist.append(playlist['id'])
break
if result['next']:
result = sp.next(result)['playlists']
return list_playlist
def build_data_songs_from_spotify(key_words, filename, filter_feature_func):
"""
A method to build the "data.txt" files for each mode.
:param key_words: The words we search in playlist name.
:param filename: The name of the file we save.
:param filter_feature_func: A method to filter the songs we have.
:return:
"""
playlists_ids = get_playlist_by_keys(key_words)
tracks_ids = analyze_playlists(playlists_ids)
data = filter_feature_func(tracks_ids)
# now you have list of "vectors"
with open(filename, 'w') as outfile:
json.dump(data, outfile)
outfile.close()
def main():
build_data_songs_from_spotify(KEY_HAPPY_WORDS, HAPPY_SONGS_FILE_SET, filter_happy_songs)
build_data_songs_from_spotify(KEY_SAD_WORDS, SAD_SONGS_FILE_SET, filter_sad_songs)
build_data_songs_from_spotify(KEY_ANGRY_WORDS, ANGRY_SONGS_FILE_SET, filter_angry_songs)
if __name__ == '__main__':
main()
|
18e87e4ac3bb3ee0793687214fac727e1fa5a2e8 | tditrani/ChallengeProject | /twitter_search.py | 575 | 3.75 | 4 | #!/usr/bin/env python
import twitter
#Get the term to search for
search_term = raw_input("Term to search for: ")
#Initilize the Api with the necisary info
api = twitter.Api(consumer_key='uNzYbptRPxMLQnoZ73daQuPHw',
consumer_secret='NExhIi50MBCkt6bkTTK62MEAbcZcUyvBir9wK81vcCwMBen15y',
access_token_key='2776231794-RluWf6txQBnDUDWB6Uq5TEbOwZ9dNnajBBQa5b2',
access_token_secret='s4kjjSfykRDunrd6S2eptmqFdSrspJh7dpUYZZ5kkKJWm'
)
#Search twitter
result = api.GetSearch(term=search_term)
text_array = []
#Put the text from the related tweets into one array
for u in result:
text_array.append(u.text)
print(text_array)
|
a055c9d02f04d0f83f37f1f0f6a6fbc52d070b42 | IvanDimitrov2002/school | /tp/hw2/homework2_tests.py | 5,945 | 3.75 | 4 | import unittest
from solution import TicTacToeBoard
class TestTicTacToe(unittest.TestCase):
def setUp(self):
self.board = TicTacToeBoard()
# # column tests
def test_left_column_with_x_win(self):
self.board["A1"] = "X"
self.board["B2"] = "O"
self.board["A2"] = "X"
self.board["B3"] = "O"
self.board["A3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
def test_middle_column_with_x_win(self):
self.board["B1"] = "X"
self.board["A1"] = "O"
self.board["B2"] = "X"
self.board["A2"] = "O"
self.board["B3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
def test_right_column_with_x_win(self):
self.board["C1"] = "X"
self.board["A1"] = "O"
self.board["C2"] = "X"
self.board["B2"] = "O"
self.board["C3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
# # row tests
def test_low_row_with_x_win(self):
self.board["A1"] = "X"
self.board["A3"] = "O"
self.board["B1"] = "X"
self.board["B2"] = "O"
self.board["C1"] = "X"
self.assertEqual("X wins!", self.board.game_status())
def test_middle_row_with_x_win(self):
self.board["A2"] = "X"
self.board["A1"] = "O"
self.board["B2"] = "X"
self.board["B3"] = "O"
self.board["C2"] = "X"
self.assertEqual("X wins!", self.board.game_status())
def test_top_row_with_x_win(self):
self.board["A3"] = "X"
self.board["A2"] = "O"
self.board["B3"] = "X"
self.board["B2"] = "O"
self.board["C3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
# # diagonal tests
def test_main_diagonal_with_x_win(self):
self.board["A1"] = "X"
self.board["A2"] = "O"
self.board["B2"] = "X"
self.board["B3"] = "O"
self.board["C3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
def test_main_diagonal_with_x_win(self):
self.board["C1"] = "X"
self.board["A2"] = "O"
self.board["B2"] = "X"
self.board["B3"] = "O"
self.board["A3"] = "X"
self.assertEqual("X wins!", self.board.game_status())
# # column tests
def test_left_column_with_o_win(self):
self.board["A1"] = "O"
self.board["B1"] = "X"
self.board["A2"] = "O"
self.board["B2"] = "X"
self.board["A3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_middle_column_with_o_win(self):
self.board["B1"] = "O"
self.board["A1"] = "X"
self.board["B2"] = "O"
self.board["A2"] = "X"
self.board["B3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_right_column_with_o_win(self):
self.board["C1"] = "O"
self.board["A1"] = "X"
self.board["C2"] = "O"
self.board["A3"] = "X"
self.board["C3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
# # row tests
def test_low_row_with_o_win(self):
self.board["A1"] = "O"
self.board["B2"] = "X"
self.board["B1"] = "O"
self.board["C2"] = "X"
self.board["C1"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_middle_row_with_o_win(self):
self.board["A2"] = "O"
self.board["A1"] = "X"
self.board["B2"] = "O"
self.board["C3"] = "X"
self.board["C2"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_top_row_with_o_win(self):
self.board["A3"] = "O"
self.board["A1"] = "X"
self.board["B3"] = "O"
self.board["B2"] = "X"
self.board["C3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
# # diagonal tests
def test_main_diagonal_with_o_win(self):
self.board["A1"] = "O"
self.board["A2"] = "X"
self.board["B2"] = "O"
self.board["B3"] = "X"
self.board["C3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_main_diagonal_with_o_win(self):
self.board["C1"] = "O"
self.board["A2"] = "X"
self.board["B2"] = "O"
self.board["B3"] = "X"
self.board["A3"] = "O"
self.assertEqual("O wins!", self.board.game_status())
def test_draw(self):
self.board["B1"] = "O"
self.board["A1"] = "X"
self.board["A2"] = "O"
self.board["B2"] = "X"
self.board["C3"] = "O"
self.board["C2"] = "X"
self.board["A3"] = "O"
self.board["B3"] = "X"
self.board["C1"] = "O"
self.assertEqual("Draw!", self.board.game_status())
def test_game_in_progress(self):
self.board["A1"] = "X"
self.board["A2"] = "O"
self.assertEqual("Game in progress.", self.board.game_status())
# test __str__() method
def test_print_empty_board(self):
board_string = "\n -------------\n\
3 | | | |\n\
-------------\n\
2 | | | |\n\
-------------\n\
1 | | | |\n\
-------------\n\
A B C \n"
self.assertEqual(board_string, self.board.__str__())
def test_print_full_board(self):
self.board["B1"] = "O"
self.board["A1"] = "X"
self.board["A2"] = "O"
self.board["B2"] = "X"
self.board["C3"] = "O"
self.board["C2"] = "X"
self.board["A3"] = "O"
self.board["B3"] = "X"
self.board["C1"] = "O"
board_string = "\n -------------\n\
3 | O | X | O |\n\
-------------\n\
2 | O | X | X |\n\
-------------\n\
1 | X | O | O |\n\
-------------\n\
A B C \n"
self.assertEqual(board_string, self.board.__str__())
if __name__ == "__main__":
unittest.main()
|
bc6cfcaf8c2aa0d71f6afdb2b22d5200b30778da | jamesbusbee/train_script | /main.py | 2,273 | 3.5625 | 4 | #!/usr/bin/env python3
from bs4 import BeautifulSoup; # for web scraping
import requests;
import urllib.request;
from urllib.request import urlopen;
import re;
import sys;
# sets the destination URL and returns parsed webpage as BeautifulSoup object
# to be used in other functions
def choose_vehicle_class(choice):
url = "https://www.hitachi-rail.com/delivery/rail_vehicles/{}/index.html".format(choice)
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
return soup
# prints delivery speed record data scraped from Hitachi website
def print_speed_records(choice):
"""pulls train delivery speed records and prints based on user selection"""
soup = choose_vehicle_class(choice)
counter = 0 # counter to track when a table has been iterated over
train_tables = soup.find_all('table', {'class':'TableStyle3'}) # grab all tables of trains with style class TableStyle3...
for tr in train_tables: # ... for each <tr> train tables...
rows = tr.find_all('tr') # find all <tr> and assign to var rows
if counter == 0:
for td in rows: # ... for each <td> found in <tr>...
removed_tags = td.get_text() # ... format HTML tags out, print, and update counter
print(removed_tags)
counter = 1
else:
print("------------------------------------------") # ... else print table delimiter and update counter
counter = 0
def main():
running = True
while running:
print(
"TYPE: High Speed Trains KEY: 'high_speed'\nTYPE: Intercity Trains KEY: 'intercity'\nTYPE: Commuter/Metro Trains KEY: 'commuter'\nTYPE: High Speed Lightweight Bolsterless Bogie Trains KEY: 'bogie'\n")
print("To exit program type '0'")
user_choice = input("To see delivery records for desired train class please type key value and press Enter: ")
if user_choice == 0: # regardless if 0 is entered program is terminating on any input other than defined KEYS
running = False
break
else:
print_speed_records(user_choice)
if __name__ == "__main__":
main()
|
be5b38013b9ec0fd33d940636a846def635e1bc3 | wangzitiansky/Learning | /src/book-notes/effective-python/ch01/code/10.py | 531 | 3.953125 | 4 | # 用enumerate取代range
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
for i in range(len(flavor_list)):
flavor = flavor_list[i]
print('%d %s' % (i + 1, flavor))
for i, flavor in enumerate(flavor_list, 1):
print('%d %s' % (i, flavor))
'''
输出均是:
1 vanilla
2 chocolate
3 pecan
4 strawberry
'''
# 也可以用来生成包含元组的列表
enumerate_list = list(enumerate(flavor_list))
print(enumerate_list)
'''
输出:
[(0, 'vanilla'), (1, 'chocolate'), (2, 'pecan'), (3, 'strawberry')]
''' |
e23acb78551656296d8c490bac569ae20dd1fa53 | Dauflo/4AIT-Chatbot | /fake_data_generation.py | 2,255 | 3.796875 | 4 | import datetime
import json
import random
def check_city(city, data):
for data_city in data:
if city.lower() == data_city.lower():
return True
return False
# Use to generate coherent fake data, in prodcution env, this would be an API call to a booking API
def create_fake_data(city='', number_of_person=0, place='', date='', duration=0):
data = None
with open('data.json', encoding='utf-8') as json_file:
data = json.load(json_file)
number_of_result = random.randint(3, 8)
travel_results = []
for i in range(number_of_result):
travel = {}
# SETUP CITY, if not exist, then take a random one from data
if city and check_city(city, data['city']):
travel['city'] = city.capitalize()
else:
travel['city'] = random.choice(data['city'])
# SETUP PLACE, if not exist, then take a random one from data
if place and place.lower() in data['place']:
travel['place'] = place
else:
travel['place'] = random.choice(data['place'])
# SETUP NUMBER OF PERSON, if equal 0, then generate a random number of person
if number_of_person != 0:
travel['numberOfPerson'] = random.randint(number_of_person - 1, number_of_person + 1)
else:
travel['numberOfPerson'] = random.randint(1, 5)
# SETUP DURATION, if equal 0, then generate a random one
# Unit : day
if duration != 0 and duration != '':
travel['duration'] = duration
else:
travel['duration'] = random.randint(7, 30)
# SETUP DATE, if not exist, then generate a random one
if date:
date = date.split('T')[0]
date_infos = date.split('-')
final_date = datetime.datetime(int(date_infos[0]), int(date_infos[1]), int(date_infos[2]))
final_date += datetime.timedelta(days=random.randint(-5, 5))
travel['date'] = final_date.strftime('%d-%m-%Y')
else:
final_date = datetime.datetime.today() + datetime.timedelta(days=random.randint(0, 30))
travel['date'] = final_date.strftime('%d-%m-%Y')
travel_results.append(travel)
return travel_results |
7abefc2fa401d166bc0fef096992dc4cc90ae999 | QMIND-Team/Modern-OT | /wavProcessing.py | 10,873 | 3.5625 | 4 | # This file is no longer needed for our project, but it might be useful to keep
# TODO: Consider deleting this file
from pyAudioAnalysis import audioFeatureExtraction
import matplotlib.pyplot as plt
import os
import numpy
from pydub import AudioSegment
def readAudioFile(path):
"""Reads an audio file located at specified path and returns a numpy array of audio samples
NOTE: This entire function was ripped from pyAudioAnalysis.audioBasicIO.py
All credits to the original author, Theodoros Giannakopoulos.
The existing audioBasicIO.py relies on broken dependencies, so it is much more reliable to rip the only function
we need to process WAV files
Paramters
----------
path : str
The path to a given audio file
Returns
----------
Fs : int
Sample rate of audio file
x : numpy array
Data points of the audio file"""
extension = os.path.splitext(path)[1]
try:
# Commented below, as we don't need this
# #if extension.lower() == '.wav':
# #[Fs, x] = wavfile.read(path)
# if extension.lower() == '.aif' or extension.lower() == '.aiff':
# s = aifc.open(path, 'r')
# nframes = s.getnframes()
# strsig = s.readframes(nframes)
# x = numpy.fromstring(strsig, numpy.short).byteswap()
# Fs = s.getframerate()
if extension.lower() == '.mp3' or extension.lower() == '.wav' or extension.lower() == '.au' or extension.lower() == '.ogg':
try:
audiofile = AudioSegment.from_file(path)
except:
print("Error: file not found or other I/O error. "
"(DECODING FAILED)")
return -1 ,-1
if audiofile.sample_width == 2:
data = numpy.fromstring(audiofile._data, numpy.int16)
elif audiofile.sample_width == 4:
data = numpy.fromstring(audiofile._data, numpy.int32)
else:
return -1, -1
Fs = audiofile.frame_rate
x = numpy.array(data[0::audiofile.channels]).T
else:
print("Error in readAudioFile(): Unknown file type!")
return -1, -1
except IOError:
print("Error: file not found or other I/O error.")
return -1, -1
if x.ndim == 2:
if x.shape[1] == 2:
x = x.flatten()
return Fs, x
def get_sig(filename):
"""Gets a signal from an audio file
Parameters
----------
filename : string
Name of the WAV audio file, including extension
Returns
----------
rate : int
Sample rate of the audio file
signal : numpy array
NumPy array containing all sample points in the audio file.
The NumPy dtype in the array depends on the format of the WAV file."""
(rate, data) = readAudioFile(filename)
return rate, data
def get_st_features(signal, rate, window_step=0.025, window_length=0.05):
"""Computes all 34 features for each window in a given signal
Parameters
----------
signal : numpy array
All sample points for the audio signal
Can be any type of number
rate : int
Sample rate of the audio signal, in Hz
window_step : float
Time step between each successive window, in seconds
Default: 0.025 (25 ms)
window_length : float
Length of each window, in seconds
Should generally be greater than windowStep to allow for overlap between frames
Default: 0.05 (50 ms)
Returns
----------
features : numpy array
NumPy array of size (number of windows) * 34
Each row in mfcc_features contains all the features for a single frame
feature_names : [str]
Names of each feature located at specified index"""
sample_step = int(rate*window_step)
sample_length = int(rate*window_length)
(features, feature_names) = audioFeatureExtraction.stFeatureExtraction(signal, rate, sample_length, sample_step)
return features, feature_names
def relevant_indexes(data, min_threshold):
"""Finds first and last index where data > min_threshold
To find the start and end indexes of the frames where there is some noise
Could be useful to take many audio clips and find the lowest start index and highest end index common between
all audio clips. This would be useful if the ML code must take a fixed # of input layer data points
Parameters
----------
data : numpy array
Energy levels of multiple frames
min_threshold : float
Minimum threshold value that each data is compared to
Returns
----------
start_index : int
First index in data with a value greater than min_threshold
end_index : int
Last index in data with a value greater than min_threshold"""
start_index = 1
end_index = len(data) - 1
for i in range(len(data)):
if data[i] > min_threshold:
start_index = i
break
for i in range(len(data)):
if data[::-1][i] > min_threshold:
end_index = i
break
return start_index, end_index
def make_line_plot(data, x_label="Data", y_label="Data Point"):
"""Creates a line plot of data, where each point on the plot is (i, data[i])
Parameters
----------
data : numpy array
Any type of homogeneous numerical data
x_label : str
The label to put on the independent axis
y_label : str
The label to put on the dependent axis
Returns
----------
None"""
y = data
x = range(len(y))
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.plot(x, y)
plt.show()
def get_trimmed_features(words, num_recordings, base_path="", energy_threshold=0.001):
"""Calculates features for a list of words, returning trimmed data based on a frame energy threshold
Assumes all audio recordings are in the same directory base_path, and all recordings are WAV format.
Calculates features for every recording and returns them in a hierarchical array to be fed into a neural network.
The number of frames for each word type is the same for all recordings of that word type, as determined by
the energy threshold for each frame.
Parameters
----------
words : [str]
A list of distinct words
It is assumed that audio files will have path base_path/(word)(num).wav
Where word is one of the words in the words parameter
num_recordings : [int]
A list of integers >= 1
List must have same length as words
For word words[i], there should be num_recordings[i] distinct recordings/files of that word
It is assumed that audio files will have path base_path/(word)(num).wav
Where num is in the range of 1 to num_recordings
base_path : str
The base path that will be appended to all audio file paths as a prefix
This is where the directory of audio files would be specified
energy_threshold : float
Minimum energy for a given frame to be considered relevant
i.e. if a frame is loud enough or contains enough information to impact the data set
Returns
----------
features_by_word : numpy array
Cell array of same length as words
Ordering of cells is determined by the order of the words in words parameter
The ith cell has num_recordings[i] elements
Each element in a cell is an array of equal lengths, with each element in said array containing all relevant
frames
Within each frame are the 34 features extracted by pyAudioAnalysis"""
features_by_word = []
for i in range(len(words)):
indexes = []
feature_array = []
for j in range(1, num_recordings[i] + 1):
# Determine the path
path = base_path + words[i] + str(j) + ".wav"
(rate, data) = get_sig(path)
# features is all the audio features for a given file
features = get_st_features(data, rate)[0]
# features[1] is total frame energies
# energy threshold of 0.001 is arbitrary
indexes.append(relevant_indexes(features[1], energy_threshold))
# Add features for this specific audio file to the feature array for this word
feature_array.append(features)
# Finds the minimum index of all start indexes
min_index = sorted(indexes, key=lambda x: x[0])[0][0]
# Finds the max index of all end indexes
max_index = sorted(indexes, key=lambda x: x[1])[::-1][0][1]
# Debug print statements commented out
# print("min, max index for word", words[i])
# print(min_index, max_index)
# Only take the frames between min index and max index for each sample word
# Note: Potential for a bug; if maxIndex is outside the length of its frame array
# To fix, need to pad the shorter recordings with extra data
features_by_word.append([x[0:34, min_index:max_index].transpose() for x in feature_array])
# print(numpy.shape(features_by_word[i]))
# features_by_word is an array of len(words) cells
# Each cell has num_recordings[i] elements corresponding to the number of recordings of each word words[i]
# Each recording has the same number of frames for a given word, as determined by minIndex and maxIndex
# for a given word.
# Finally, each frame contains the 34 features from that frame's raw data samples
return features_by_word
# word_list = ["light", "off", "on", "slack", "tv"]
# # Could change this to numbers between 1 and 30 to see how it handles more or less data
# nums = [30, 30, 30, 30, 30]
# # The base_directory might be different for windows users
# base_directory = "ModernOTData/"
# output = get_trimmed_features(word_list, nums, base_directory)
#
# # energy_values is a sequential list of all energy values over all recordings
# energy_values = []
#
# # Should print 5
# print("There are", len(output), "different words")
# for word_num in range(len(output)):
# # Should print 30
# print("There are", len(output[word_num]), "different recordings for word", word_list[word_num])
# for recording_num in range(len(output[word_num])):
# # Print number of frames for each recording
# # Should be equal for all words
# print("# frames:", len(output[word_num][recording_num]), "in recording #", str(recording_num+1), "for word",
# word_list[word_num])
# for frame in output[word_num][recording_num]:
# # Should be 34 features for each frame
# # print(len(frame))
# # frame[1] is the energy for that frame
# energy_values.append(frame[1])
#
# # Sample plot of energies across every recording
# make_line_plot(energy_values, "Frame Number", "Energy") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.