blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
89fe3f0295ebf82b45fd715b5386857dc5394ba6
Python
josiah-bennett/mp3p
/mp3p/time_manipulation.py
UTF-8
1,686
3.484375
3
[ "MIT" ]
permissive
from mp3p.time_util import TimeUtil def goto_help(cmd): """display the help screen for the goto method.""" print('The goto command takes a timestamp and jumps to that location in the audio.') print('Syntax: goto timestamp') print('timestamp: hour:minutes:seconds') print(' minutes:seconds') print(' seconds \n') print('the current location is: ' + str(current_location(cmd)) + 'ms') def goto(cmd, timestamp): """Specify a timestamp in the audio to jump to.""" time_array = timestamp.split(':') # convert the timestamp to milliseconds time = TimeUtil(time_array).time_to_ms() if time < cmd.icp.get_length(): cmd.icp.pause() cmd.icp.set_time(time) cmd.icp.play() else: print('*** Warning: The given timestamp exceeds the length of the audio.') def jump_help(cmd): """display the help screen for the jump method""" print('The jump commend takes a interval in seconds and jumps according to the symbol forwards or backwards.') print('Syntax: jump +/-interval \n') print('The current location is: ' + str(current_location(cmd)) + 'ms') def jump(cmd, interval): """Jump forward or backward in the audio by the specified time interval.""" symbols = ['+', '-'] for i in symbols: if interval.startswith(i): interval = interval.strip(i) print(interval) if interval.isdigit(): cmd.icp.pause() time = 'cmd.icp.get_time() ' + i + ' int(interval) * 1000' cmd.icp.set_time(eval(time)) cmd.icp.play() return print('*** The time interval specified is not a valid number.') # TODO implement a better location method def current_location(cmd): """return the current playback location""" return cmd.icp.get_time()
true
ffd58bc32ac7880558cdd9405c1737dee465feb4
Python
pvigier/lpc-scripts
/apply_palette.py
UTF-8
753
2.9375
3
[ "MIT" ]
permissive
import sys import time import numpy as np from PIL import Image def color_image(indices, palette): print(indices.shape, palette.shape) return Image.fromarray(palette[0,indices], mode='RGBA') if __name__ == '__main__': if len(sys.argv) < 3: print('Too few arguments: a greyscale image and a palette are expected') exit() indices_path = sys.argv[1] palette_path = sys.argv[2] start = time.time() indices = Image.open(indices_path) palette = Image.open(palette_path) image = color_image(np.asarray(indices), np.asarray(palette)) image_path = indices_path[indices_path.rfind('/')+1:indices_path.rfind('.')] + '_colored.png' image.save(image_path, compress_level=9) print(time.time() - start)
true
12cbad83d2bbc01d506131d4db5f9120fa4c0abd
Python
Wanqianxn/refugees-say
/helpers.py
UTF-8
4,671
2.890625
3
[]
no_license
import random import pandas as pd import numpy as np class MatchingAlgo: def __init__(self, cases, sites): self.cases = cases self.sites = sites # Takes community's details (city, state) and returns dict of relevant info. def communityInfo(self, city, state): comDf = self.sites[(self.sites['city'] == city) & (self.sites['state'] == state)] if comDf.empty: return None return comDf.iloc[0].to_dict() # Return all communities in a *dict dict*. def dictOfCommunities(self): comD = dict() for i in range(len(self.sites.index)): key = self.sites.iloc[i]['city'] + ", " + self.sites.iloc[i]['state'] comD[key] = self.communityInfo(self.sites.iloc[i]['city'], self.sites.iloc[i]['state']) return comD # Takes refugee group's name and returns dict of relevant info. def refugeesInfo(self): pass # Return all refugees from a particular community in a *dict dict*. def dictOfRefugees(self): pass # Get rid of spaces in string. def noSpace(string): words = string.strip().split() all_words = "" for word in words: all_words = all_words + word return all_words.lower() def getToolTip(key): abbreviations={'cap':'Capacity', 'nats':'Nationalities supported', 'slang':'Staff languages', 'clang':'Community languages', 'lfs':'Large family support', 'sps':'Single parent support', 'num':'Number in family', 'nat':'Nationality', 'lang':'Languages spoken', 'sp':'Single Parent', 'score':'Community fit score'} return abbreviations[key] # Randomly assigns cases to sites. def randomize(cases, sites): randDictbyName, randDictbySite = dict(), dict() for city in sites['city']: key = (city, sites[sites['city'] == city].iloc[0]['state']) randDictbySite[key] = dict() for name in cases['name']: city = random.choice(sites['city']) randDictbyName[name] = city key = (city, sites[sites['city'] == city].iloc[0]['state']) randDictbySite[key][name] = None return randDictbyName, randDictbySite # Placeholder for algorithm that provides real score def randScore(groupName, groupComm): return random.randint(0, 100) # Random score def randScore(): return random.randint(0, 100) class RandomAlgo(MatchingAlgo): def __init__(self, cases, sites): MatchingAlgo.__init__(self, cases, sites) self.randDictbyName, self.randDictbySite = randomize(self.cases, self.sites) def refugeesInfo(self, groupName): refDf = self.cases[self.cases['name'] == groupName] if refDf.empty: return None refugeesInfo = refDf.iloc[0].to_dict() languages = refDf.iloc[0]['lang'] refugeesInfo['lang'] = languages.replace(" ", "").split(",") #refugeesInfo['community'] = self.randDictbyName[groupName] refugeesInfo['score'] = randScore() return refugeesInfo def dictOfRefugees(self, city): key = (city, self.sites[self.sites['city'] == city].iloc[0]['state']) if key in self.randDictbySite: for name in self.randDictbySite[key]: self.randDictbySite[key][name] = self.refugeesInfo(name) return self.randDictbySite[key] else: return dict() class CSVAlgo(MatchingAlgo): def __init__(self, cases, sites, output): MatchingAlgo.__init__(self, cases, sites) self.output = output def refugeesInfo(self, groupName): refDf = self.cases[self.cases['name'] == groupName] if refDf.empty: return None refugeesInfo = refDf.iloc[0].to_dict() languages = refDf.iloc[0]['lang'] refugeesInfo['lang'] = languages.replace(" ", "").split(",") #for i in range(len(self.output.index)): #if self.output.iloc[i, 0] == groupName: #for j in range(len(self.output.columns)): #if self.output.iloc[i, j] == 1: #refugeesInfo['community'] = self.output.columns[j] return refugeesInfo def dictOfRefugees(self, city): refD = dict() #for name in self.cases['name']: #if self.refugeesInfo(name)['community'] == city: #refD[name] = self.refugeesInfo(name) return refD # For testing. def main(): sites1 = pd.read_csv('data/sites.csv') cases1 = pd.read_csv('data/cases.csv') output1 = pd.read_csv('data/output.csv') csv = RandomAlgo(cases1, sites1) print(csv.dictOfRefugees("Los Gatos")) if __name__ == '__main__': main()
true
03ebcf5ea77d0c9a8f5670c8d744f8a22a8be0d0
Python
loveAlakazam/Homeworks2019
/ProgramTraining/SW_Expert_Academy/1284/수도요금경쟁.py
UTF-8
283
2.84375
3
[]
no_license
#13분14초 T=int(input()) for t in range(1,T+1): P,Q,R,S,W= map(int, input().split()) A= W*P #A사: 1리터당 P원, W리터당=> P*W원 #B사: (W<=R) Q원 (W>R) Q+(W-R)*S B=Q if(W>R): B+=S*(W-R) result=min(A,B) print('#{} {}'.format(t, result))
true
0775c1cbf181f32510c4ecdc0c17d1ab0c6f247b
Python
reddyonlinenow/codebreakers-solutions
/leetcode/142/142.py
UTF-8
1,045
3.796875
4
[]
no_license
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: # check to see if head is None or of length 1 if not head or not head.next: return None # use 2 pointers to find if there's a cycle slow = head.next fast = head.next.next while fast and fast.next: slow = slow.next fast = fast.next.next # cycle found if slow == fast: break # there's no cycle if they don't equal each other if slow != fast: return None # move one of the nodes to the head of the list, then # increment the two pointers one at a time and when they meet again # we've found the start of the cycle slow = head while slow != fast: slow = slow.next fast = fast.next return slow
true
214029d2049d7faddad3649690b541b973cb5fa1
Python
Lukdes/ATM-project
/main.py
UTF-8
1,213
3.25
3
[]
no_license
from Banksystem import Bank Luke = Bank("Luke", "1234" , "4321" ) go = Luke.Login() while go: #once acess is granted, you need to choose one of the seven choices and then hit enter. If something else is typed you are told to choose a number from 1 to 7 print "__________________________________________________" print "1) View Checkings Balance" print "2) View Savings Balance" print "3) Withdraw Cash" print "4) Desposit Cash" print "5) Transfer Money" print "6) View Summary" print "7) End session" print "__________________________________________________" question = raw_input("What would you like to do? ") print "__________________________________________________" if question == "1": Luke.ViewCheckingsBalance() elif question == "2": Luke.ViewSavingsBalance() elif question == "3": Luke.WithdrawCash() elif question == "4": Luke.DepositCashIntoChecking() elif question == "5": Luke.TransferFundsFromAccounts() elif question == "6": Luke.ViewSummaryofAccount() elif question == "7": count = 1 go = Luke.TerminateSession() else: print "Please choose a number from 1 to 7"
true
1a170e0fe6fa3a81f2c9159275d4af16c9aa1caf
Python
pawelczapla/gameofcheckers
/checkers/constants.py
UTF-8
543
2.921875
3
[]
no_license
import pygame # Dimensions WIDTH, HEIGHT = 800, 800 ROWS, COLS = 8, 8 square_size = 100 # Colors RED = (255, 0, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (0, 0, 255) GREY = (128, 128, 128) # Assets circle = pygame.image.load('assets/circle.png') background = pygame.image.load('assets/black.jpg') tile = pygame.image.load('assets/white.png') white_man = pygame.image.load('assets/white_man.png') black_man = pygame.image.load('assets/black_man.png') crown = pygame.transform.scale(pygame.image.load('assets/crown.png'), (62, 62))
true
ece28d6043f3c38ab3f403232d87dd06648f0ea6
Python
PyrosCoffee/KBA-iot-portfolio
/monitor_ii/db.py
UTF-8
1,154
2.5625
3
[]
no_license
""" Edited the db.py that was in the base components to suit the needs of the project """ import os from sqlalchemy import Column, DateTime, Float, Integer, String from sqlalchemy.ext.declarative import declarative_base from datetime import datetime # data folder doesnt get things added to it, fix later db_folder = "./data/" db_name = "enviromon.db" if not os.path.isdir(db_folder): os.makedirs(db_folder) print(f"Created {db_folder} folder") Base = declarative_base() # class for storing environment details class EnvironmentTPH(Base): __tablename__ = "tph_storage" id = Column(Integer, primary_key=True, autoincrement="auto") device_name = Column(String) device_mac = Column(String) device_serial = Column(String) temperature = Column(Float) pressure = Column(Float) humidity = Column(Float) created_at = Column(DateTime) def __init__(self): self.device_name = "UNKNOWN" self.device_mac = "ZZ:ZZ:ZZ:ZZ:ZZ:ZZ" self.device_serial = "UNKNOWN" self.temperature = None self.pressure = None self.humidity = None self.created_at = datetime.now()
true
fe29ea0ad32892dc9f3b87d211a9622e0900befd
Python
TheHa1fBloodPrince/formautofill
/FormAutoFill.py
UTF-8
2,208
3.3125
3
[]
no_license
#Created by: TheHalfBloodPrince from selenium import webdriver import pyautogui from datetime import datetime from threading import Timer print ('Executing Order 66...') option = webdriver.ChromeOptions() browser = webdriver .Chrome('/usr/bin/chromedriver') browser.get ("Insert form link") #Function that makes script run at the right time - example, this is set to run tommorow @8:55 am x=datetime.today() y=x.replace(day=x.day+1, hour=8, minute=55, second=0, microsecond=0) delta_t=y-x secs=delta_t.seconds+1 def auto_sign_in(): #import datetime again so it fills out the correct day in the form and not the day the scirpt was run, see last question from datetime import datetime current_time = datetime.now() #This section is if you need to sign in to your organizations emaill account to get access like I do, so you may be able to comment this whole section out... #school email sign in pyautogui.write('email address') pyautogui.press('enter', interval=4.00) #login pyautogui.press('tab', interval=0.25) pyautogui.write('username') pyautogui.press('tab', interval=0.25) pyautogui.write('password') pyautogui.press('tab', interval=0.25) pyautogui.press('enter', interval=4.00) #confirm this account belongs to you: pyautogui.press('tab', interval=0.25) pyautogui.press('enter', interval=4.00) #Questions #full name? pyautogui.press('tab', interval=0.25) pyautogui.press('tab', interval=0.25) pyautogui.write('name', interval=0.25) #Are you here? (Radio button) pyautogui.press('tab', interval=0.25) pyautogui.press('space', interval=0.25) #you understand the work? (Radio button) pyautogui.press('tab', interval=0.25) pyautogui.press('space', interval=0.25) #input date #DD pyautogui.press('tab', interval=0.25) pyautogui.write(current_time.strftime('%d')) #MM pyautogui.write(current_time.strftime('%m')) #yyyy pyautogui.write(current_time.strftime('20%y')) #submit pyautogui.press('tab') pyautogui.press('enter') t = Timer(secs, auto_sign_in) t.start() print ('Finished')
true
fc4d345dc456d380ced074d053837d533651f082
Python
adarshsingh994/Practice
/Python/MaximisingXor.py
UTF-8
382
3.03125
3
[]
no_license
#!/bin/python3 import math import os import random import re import sys # Complete the maximizingXor function below. def maximizingXor(l, r): maxXor = 0 for i in range(l, r + 1): for j in range(i, r + 1): curXor = i ^ j if curXor > maxXor: maxXor = curXor print(maxXor) if __name__ == '__main__': l = int(input()) r = int(input()) maximizingXor(l, r)
true
639d69e2e9b3e5c77a1cc63ee40c45db6cdb8c3a
Python
songcq/mammoth
/tube_wrap.py
UTF-8
2,285
2.796875
3
[]
no_license
import solid as sc import math from solid.utils import Point2 import utils def f(x): l = x a = x p = Point2(math.cos(a), math.sin(a)) p.set_length(l) return p points = [f(i * 0.3) for i in range(100)] # d = _sp.catmull_rom_polygon(points, subdivisions=10) d = sc.text("hi", halign="center", valign="center") def wrap_tube(objects, radius, hstep, vstep): tilt_angle = utils.point_angle(Point2(hstep, vstep)) def create(i): obj = objects[i] obj = sc.rotate((0, 0, tilt_angle))(obj) obj = sc.rotate((90, 0, 0))(obj) facing_angle = math.degrees(i * hstep / radius) obj = sc.rotate(facing_angle + 90)(obj) hpos = utils.unit_point2(facing_angle) * radius pos = (*hpos, i * vstep) obj = sc.translate(pos)(obj) return obj return sc.union()([create(i) for i in range(len(objects))]) def create_tube(text): def create(char): return sc.linear_extrude(0.1)(sc.text(char, size=1, font="Monaco", segments=100)) objects = [create(char) for char in text] wrap = wrap_tube(objects, 10, 0.7, 0.02) wrap = sc.translate((0, 0, 0.5))(wrap) return wrap text = "I met a traveller from an antique land, Who said — Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away." def create_cup(): height = 27.5 cup = sc.cylinder(10, height, center=True, segments=200) cup = sc.translate((0, 0, height / 2))(cup) cutter = sc.cylinder(9.5, height, center=True, segments=200) cutter = sc.translate((0, 0, 1 + height / 2))(cutter) cup = cup - cutter return cup tube = create_tube(text + " " + text) cup = create_cup() d = sc.color("gold")(tube) + sc.color("blue")(cup) sc.scad_render_to_file(d, "/tmp/output.scad")
true
e8603fb188666256208b4440113f0f39d83671ba
Python
durbanie/ProjectEuler
/src/P1/Problem25.py
UTF-8
2,036
4.125
4
[]
no_license
''' Problem: Find the index of the first 1000 digit fibonacci number. Strategy: Brute-force & Mathematical Notes: Implementing this as an array with each digit as an entry in the array. In Python, this is actually not necessary (python allows an arbitrary number of digits in an integer), but in other languages like C or Java, the number of digits is limited. Therefore, this array implementation is meant to be valid in other languages. The mathematical strategy involves an approximation to binet's formula, where to find the nth fibonacci number F(n): F(n) = Phi^n / sqrt(5) where Phi is the golden ratio, Phi = 1.61803398875... To find the number of digits, take log_10 of F(n) and add 1 Ndigits(F(n)) = n log10(Phi) - log10(sqrt(5)) + 1 Solving for n gives: n = (Ndigits(F(n)) - 1 + log10(sqrt(5))) / log10(Phi) Run-time: Brute-force: 1435 ms, mathematical: <1us ''' from math import log10 from Common.stopwatch import StopWatch def add(l1, l2): l3 = [] r = 0 l1l = len(l1) l2l = len(l2) ml = max(l1l, l2l) for i in range(ml): #print i, l1, l2 l1v, l2v = 0, 0 if (i < len(l1)): l1v = l1[i] if (i < len(l2)): l2v = l2[i] #print l1v, l2v, r r, v = divmod(l1v+l2v+r, 10) l3.append(v) if r > 0: #print r l3.append(r) return l3 def fibonacci_brute_force(): i = [1] j = [1] counter = 1 while len(j) < 1000: counter += 1 t = j j = add(i, j) i = t print len(j) print counter+1 root5 = 2.236068 Phi = 1.618034 def fibonacci_math(ndigits): #n = (Ndigits(F(n)) + log10(sqrt(5))) / log10(Phi) return int(round((ndigits - 1 + log10(root5)) / log10(Phi))) def main(): StopWatch.start() fibonacci_brute_force() StopWatch.print_time() StopWatch.start() print fibonacci_math(1000) StopWatch.print_time() if __name__ == '__main__': main()
true
8af18bb462c1a194394b1126f32ebe170d827b73
Python
guptaabhishekknp/algorithms_project-graphs
/allcode/Map.py
UTF-8
28,498
3.125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import math import sys # In[2]: #functions for heap data structure #adjacency lists are implemented as python dictionaries def PARENT(i,D): n = len(D) if i>0: return math.floor((i-1)/2) else: return -1 def LCHILD(i,D): n = len(D) if ((2*i)+1) < n: return (2*i)+1 else: return -1 def RCHILD(i,D): n = len(D) if ((2*i)+2) < n: return (2*i)+2 else: return -1 def RSIB(i,D): n = len(D) if i<(n-1) and i%2 == 1: return i+1 else: return -1 def PERC_UP(i,D): while i>0 and D[i][1]<D[PARENT(i,D)][1]: p = D[i] D[i] = D[PARENT(i,D)] D[PARENT(i,D)] = p i = PARENT(i,D) return D def INSERT(v,D): n = len(D) D.insert(n,v) PERC_UP(n,D) return D def PERCDOWN(i,D): while (RCHILD(i,D)!=-1 and D[i][1]>D[RCHILD(i,D)][1]) or (LCHILD(i,D)!=-1 and D[i][1]>D[LCHILD(i,D)][1]): if RCHILD(i,D)==-1: j = LCHILD(i,D) elif LCHILD(i,D)==-1: j = RCHILD(i,D) else: j = RCHILD(i,D) if D[LCHILD(i,D)][1]<D[RCHILD(i,D)][1]: j = LCHILD(i,D) p = D[i] D[i] = D[j] D[j] = p i = j return D def DELETEMIN(D): n = len(D)-1 smallest = D[0] D[0]=D[n] del D[n] D = PERCDOWN(0,D) return D, smallest def DECREASE(i,new_value,D): D[i] = (D[i][0],new_value) D = PERC_UP(i,D) return D # In[3]: def initialize_D(start_vertex, graph): infty = float("inf") #infinity value, change this to 10,000 before submitting the code vertices = [key for key in graph] start_vertex_ngbrs = graph[start_vertex] D = [(start_vertex,0)] vertices.remove(start_vertex) #if you want to uncomment the 3 lines below, the back pointer must be initialized #so that vertices adjacent to the starting vertex point to the starting vertex #for nghbr in start_vertex_ngbrs: # D = INSERT((nghbr[0],nghbr[1]),D) # vertices.remove(nghbr[0]) for v in vertices: D = INSERT((v,infty),D) return D def index_in_list(vert_indx,D): i = 0 for v in D: if v[0] == vert_indx: return i i+=1 return -1 def print_paths(graph, start_vertex, back_pointer): for key in graph: l = [] k = key while k != back_pointer[k]: l.append(k) k = back_pointer[k] l.append(start_vertex) l = l[::-1] print('path from {} to {} is given by:'.format(start_vertex,key),l) print('total cost of this path is:',find_path_length(l,graph)) return def find_path_length(l,graph): length = 0 for i in range(len(l)-1): idx = index_in_list(l[i+1],graph[l[i]]) length+= graph[l[i]][idx][1] return length def run_Dijkstras(start_vertex, graph): back_pointer = {key:key for key in graph} mark = {key:0 for key in graph} #0 for unmarked, 1 for marked D = initialize_D(start_vertex, graph) #for strt_nbrs in graph[start_vertex]: # back_pointer[strt_nbrs[0]] = start_vertex while 0 in list(mark.values()): D, v = DELETEMIN(D) current_vertex = v[0] mark[current_vertex] = 1 for adj_vert in graph[current_vertex]: adj_indx = adj_vert[0] adj_cost = adj_vert[1] j = index_in_list(adj_indx,D) if mark[adj_indx] == 0 and D[j][1]>v[1]+adj_cost: D = DECREASE(j,v[1]+adj_cost,D) back_pointer[adj_indx] = current_vertex return back_pointer def words_in_name(lst): new_list = [] for piece in lst: word = piece.rstrip('&"\/').lstrip('&"\/').split('-') if len(word[0]) > 0: new_list = new_list+word return new_list def create_vertex_data(): vertex_data = read_from_file("MapDataVertices.txt") for element in vertex_data: element[2] = int(element[2]) element[3] = int(element[3]) #element[4] = element[4]#.split()#words_in_name(element[4].split()) return vertex_data #returns a list of tuples: #(vertex_id,label,x-coordinate,y-coordinate,name,list of words in the name) def read_from_file(filename): data = [] with open(filename) as f: for line in f: fields = line.split('"')[0].split() if fields!=[] and fields[0][0]!='/': name = line.split('"')[1] data.append([int(fields[0])]+fields[1:]+[name]) return data def create_edge_data(): edge_data = read_from_file("MapDataEdges.txt") for element in edge_data: element[3] = int(element[3]) element[4] = int(element[4]) element[5] = int(element[5]) element[6] = int(element[6]) element[8] = element[8].strip('()') return edge_data def construct_graph(vertex_data, edge_data, has_skateboard, minimize_time): graph = {vertex[0]:[] for vertex in vertex_data} for edge in edge_data: if minimize_time: cost = calculate_time(edge[5],has_skateboard,edge[8]) else: cost = edge[5] graph[edge[3]].append( (edge[4], cost, edge[0] ) ) return graph def make_path(graph, start_vertex, end_vertex, back_pointer, edge_data, has_skateboard): l = [] while end_vertex != back_pointer[end_vertex]: l.append(end_vertex) end_vertex = back_pointer[end_vertex] l.append(start_vertex) l = l[::-1] return l def create_output(l, graph, edge_data, has_skateboard): time = 0 distance = 0 legs = 0 path_list = [] for i in range(len(l)-1): v = l[i] j = index_in_list(l[i+1],graph[l[i]]) edge_indx = graph[l[i]][j][2] dist_for_leg = edge_data[find_index_in_edge_data(edge_indx,edge_data)][5] time_for_leg = calculate_time(dist_for_leg,has_skateboard,edge_data[find_index_in_edge_data(edge_indx,edge_data)][8]) time += time_for_leg distance += dist_for_leg legs += 1 path_list.append('FROM: ({}) {}\n'.format(vertex_data[l[i]][1],vertex_data[l[i]][-1])) path_list.append('ON: {}\n'.format(edge_data[find_index_in_edge_data(edge_indx,edge_data)][-1])) path_list.append('Travel {} feet in direction {} degrees {}\n'.format(dist_for_leg,edge_data[find_index_in_edge_data(edge_indx,edge_data)][-4],edge_data[find_index_in_edge_data(edge_indx,edge_data)][-3])) path_list.append('TO: ({}) {}\n'.format(vertex_data[l[i+1]][1],vertex_data[l[i+1]][-1])) path_list.append('({} seconds)\n\n'.format(time_for_leg)) path_list.append('legs = {}, distance = {} feet, time = {} seconds\n'.format(legs,distance,time)) return ''.join(path_list) def calculate_time(edge_length, has_skateboard, C): WalkSpeed = 272 #ft/min = (3.1 miles/hr) * (5280 ft/mile) / (60 mins/hr) WalkFactorU = 0.9 #Multiply walk speed by this for walk up. WalkFactorD = 1.1 #Multiply walk speed by this for walk down. SkateFactorU = 1.1 #Multiply walk speed by this for skateboard up. SkateFactorF = 2.0 #Multiply walk speed by this for skateboard flat. SkateFactorD = 5.0 #Multiply walk speed by this for skateboard down. StepFactorU = 0.5 #Multiply walk speed by this for walk up steps. StepFactorD = 0.9 #Multiply walk speed by this for walk down steps. BridgeFactor = 1.0 #Multiply walk speed by this for walking on a bridge. div_factor = { 'f': 1, 'x': (int(has_skateboard)*SkateFactorF + (int(not has_skateboard))*1), 'F': int(has_skateboard)*SkateFactorF + (int(not has_skateboard))*1, 'u': WalkFactorU, 'U': int(has_skateboard)*SkateFactorU + (int(not has_skateboard))*WalkFactorU, 'd': WalkFactorD, 'D': int(has_skateboard)*SkateFactorD + (int(not has_skateboard))*WalkFactorD, 's': StepFactorU, 't': StepFactorD, 'b': BridgeFactor } t = int(60*float(edge_length)/float(WalkSpeed) + 0.5) t /= div_factor[C] return int(t) def create_route_file(l, vertex_data): MapWidthFeet = 5521 MapHeightFeet = 4369 MapWidthPixels = 2528 MapHeightPixels = 2000 CropLeft = 150 CropDown = 125 file = open(r"Route.txt","w+") file_cropped = open(r"RouteCropped.txt","w+") for i in range(len(l)-1): v = vertex_data[find_index_in_edge_data(l[i],vertex_data)][2] w = vertex_data[find_index_in_edge_data(l[i],vertex_data)][3] x = vertex_data[find_index_in_edge_data(l[i+1],vertex_data)][2] y = vertex_data[find_index_in_edge_data(l[i+1],vertex_data)][3] a = int(v * MapHeightPixels / MapHeightFeet) b = int(w * MapWidthPixels / MapWidthFeet) c = int(x * MapHeightPixels / MapHeightFeet) d = int(y * MapWidthPixels / MapWidthFeet) file.write('{} {} {} {}\n'.format(a,b,c,d)) a = a - CropLeft b = b - CropDown c = c - CropLeft d = d - CropDown file_cropped.write('{} {} {} {}\n'.format(a,b,c,d)) file.close() file_cropped.close() return def plot_on_map(): from PIL import Image, ImageDraw img = Image.open('BrandeisMapLabeled.jpg') drawing = ImageDraw.Draw(img) with open('Route.txt') as f: for line in f: coords = line.split() a, b, c, d = int(coords[0]), int(coords[1]), int(coords[2]), int(coords[3]) drawing.line([(a,b),(c,d)],fill='pink',width=15) img.show() return def print_list(l): for i in l: print('*',i) return def get_vertex_id(s, vertex_data): #get vertex id from the input string s l = [] for data in vertex_data: if s.lower() == data[1].lower(): return data[0] if s.lower() == data[4].lower(): return data[0] if s.lower() in data[4].lower(): l.append(data[0]) if len(l)==1: return l[0] if len(l)>1: print('Ambigous name. Following multiple matches found.\n') print_list([vertex_data[i][4] for i in l]) print('\nPlease enter a substring that uniquely identifies the place.\n') return 0 if len(l)==0: print('Place not found. Try again.') return 0 #the string entered should be either the map location, for example L24 etc, or, a substring of a unique name #so either the full name or a word that uniquely identifies the location for example 'farber', 'Farber l', 'Farber lib' #are all substrings of unique location 'Farber Library' #not case sensitive so more flexible # return -1 #location not found, try again # return -2 #more than one location for example 'schwartz will give two locations', 'Hassenfeld Lot will give two locations' #maybe just return a single location error and try again- NO!!! the #first check if it matches map location #then check if it is exactly the name of a place #then check if it is substring # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 # # Part 2 def is_undirected(graph): #checks if every edge - reverse-edge pair has the same weight, #so that the graph represented by adjacency list can be interpreted as undirected result = True for key in graph: for vert in graph[key]: vertex_indx = vert[0] edge_wt = vert[1] j = index_in_list(key, graph[vertex_indx]) reverse_edge_wt = graph[vertex_indx][j][1] if edge_wt!=reverse_edge_wt: print(key,vertex_indx,edge_wt,j,reverse_edge_wt) result = False return result def just_one(a, b, l): return ((a in l) and (b not in l)) or ((a not in l) and (b in l)) def find_index_in_edge_data(idx,edge_data): l = [x[0] for x in edge_data] return l.index(idx) def min_span_tree(graph, start_vertex, edge_data): T = set() to_put_back = [] vertices_in_T = set() vertices_in_T.add(start_vertex) edge_cost_pairs = set() for key in graph: for element in graph[key]: edge_cost_pairs.add((element[2],element[1])) heap = [] for x in list(edge_cost_pairs): heap = INSERT(x,heap) num_vertices = len(graph) while len(T)<num_vertices-1: heap, smallest = DELETEMIN(heap) smallest = smallest[0] indx_sm_edge_data = find_index_in_edge_data(smallest,edge_data) while not just_one(edge_data[indx_sm_edge_data][3],edge_data[indx_sm_edge_data][4],vertices_in_T): #loop until there is a edge with exactly one to_put_back.append(smallest) #print(heap) #print(len(vertices_in_T)) heap, smallest = DELETEMIN(heap) smallest = smallest[0] indx_sm_edge_data = find_index_in_edge_data(smallest,edge_data) T.add(smallest) vertices_in_T.add(edge_data[indx_sm_edge_data][3]) vertices_in_T.add(edge_data[indx_sm_edge_data][4]) for edg in to_put_back: heap = INSERT((edg,edge_data[find_index_in_edge_data(edg,edge_data)][5]),heap) to_put_back = [] return T def plot_edges(edge_list, edge_data, vertex_data):#needs to be changed!!!!!!!! MapWidthFeet = 5521 MapHeightFeet = 4369 MapWidthPixels = 2528 MapHeightPixels = 2000 img = Image.open('BrandeisMapLabeled.jpg') drawing = ImageDraw.Draw(img) for edg in edge_list: v_1 = edge_data[edg][3] v_2 = edge_data[edg][4] v = vertex_data[v_1][2] w = vertex_data[v_1][3] x = vertex_data[v_2][2] y = vertex_data[v_2][3] a = int(v * MapHeightPixels / MapHeightFeet) b = int(w * MapWidthPixels / MapWidthFeet) c = int(x * MapHeightPixels / MapHeightFeet) d = int(y * MapWidthPixels / MapWidthFeet) drawing.line([(a,b),(c,d)],fill='pink',width=10) img.show() return def plotting_cordinates_from_edges(edge_list, edge_data, vertex_data): MapWidthFeet = 5521 MapHeightFeet = 4369 MapWidthPixels = 2528 MapHeightPixels = 2000 coords = [] for edg in edge_list: v_1 = edge_data[find_index_in_edge_data(edg,edge_data)][3] v_2 = edge_data[find_index_in_edge_data(edg,edge_data)][4] v = vertex_data[v_1][2] w = vertex_data[v_1][3] x = vertex_data[v_2][2] y = vertex_data[v_2][3] a = int(v * MapHeightPixels / MapHeightFeet) b = int(w * MapWidthPixels / MapWidthFeet) c = int(x * MapHeightPixels / MapHeightFeet) d = int(y * MapWidthPixels / MapWidthFeet) coords.append(str(a)+' '+str(b)+' '+str(c)+' '+str(d)) return '\n'.join(coords) def tree_from_edges(edges, vertex_data, edge_data): tree = {key[0]: set() for key in vertex_data} for edge in edges: edge_idx = find_index_in_edge_data(edge,edge_data) v1 = edge_data[edge_idx][3] v2 = edge_data[edge_idx][4] tree[v1].add((v2,0))#0 is a dummy coordinate in the tuple tree[v2].add((v1,0))#0 is a dummy coordinate in the tuple for key in tree: tree[key] = list(tree[key]) return tree def plot_traversal(traversal, vertex_data):#needs to be changed!!!!!!!! from PIL import Image, ImageDraw MapWidthFeet = 5521 MapHeightFeet = 4369 MapWidthPixels = 2528 MapHeightPixels = 2000 img = Image.open('BrandeisMapLabeled.jpg') drawing = ImageDraw.Draw(img) visited = [] for i in range(len(traversal)-1): v_1 = traversal[i] v_2 = traversal[i+1] visited.append(v_1) v = vertex_data[v_1][2] w = vertex_data[v_1][3] x = vertex_data[v_2][2] y = vertex_data[v_2][3] a = int(v * MapHeightPixels / MapHeightFeet) b = int(w * MapWidthPixels / MapWidthFeet) c = int(x * MapHeightPixels / MapHeightFeet) d = int(y * MapWidthPixels / MapWidthFeet) drawing.line([(a,b),(c,d)],fill='pink',width=10) if v_2 in visited: drawing.line([(a,b),(c,d)],fill='red',width=2) else: drawing.line([(a,b),(c,d)],fill='pink',width=10) img.show() return def pre_order_trvsl(tree, root_key, vistd_vrtx_list):#returns a list of vertices in the order in which they are traversed vistd_vrtx_list.append(root_key) for nghbr in tree[root_key]: if nghbr[0] not in vistd_vrtx_list: vistd_vrtx_list = pre_order_trvsl(tree,nghbr[0],vistd_vrtx_list) if vistd_vrtx_list[-1]!=root_key: vistd_vrtx_list.append(root_key) return vistd_vrtx_list def find_cost(a,b, graph): for e in graph[a]: if b==e[0]: return e[1] return float("inf") #if the next vertex is already visited, look two places ahead and if there's a path to that and the distance through that parth is shorter #(yes, this needs to be checked as it is not always true) then shortcut it.T def prim_shortchut_traversal(traversal, graph): visited = [traversal[0]] i = 0 while i < len(traversal)-2: v_1 = traversal[i] v_2 = traversal[i+1] v_3 = traversal[i+2] #if find_cost(v_1,v_3, graph)<float("inf"):#if there is any edge at all shortcut it if (find_cost(v_1,v_3, graph)<find_cost(v_1,v_2, graph)+find_cost(v_2,v_3, graph)) and (v_2 in visited):#shortcut only if the new edge is better visited.append(v_3) i+=2 else: visited.append(v_2) i+=1 return visited #a dict with keys as vertices and values as an index of set, which is initially all different but set same for unioning 2 sets def kruskal_min_spanning_tree(edge_data, vertex_data, graph): vertex_sets_indices = {key[0]:key[0] for key in vertex_data}#assign all set indices as distinct T = set() edge_cost_pairs = set() for key in graph: for element in graph[key]: edge_cost_pairs.add((element[2],element[1])) heap = [] for x in list(edge_cost_pairs): heap = INSERT(x,heap) n_vert = len(vertex_data) while len(T)<n_vert-1: to_put_back = [] while True: heap, smallest = DELETEMIN(heap) smallest = smallest[0] indx_sm_edge_data = find_index_in_edge_data(smallest,edge_data) v_1 = edge_data[indx_sm_edge_data][3] v_2 = edge_data[indx_sm_edge_data][4] if vertex_sets_indices[v_1]!=vertex_sets_indices[v_2]: T.add(smallest) n1 = vertex_sets_indices[v_1] n2 = vertex_sets_indices[v_2] n = max([n1,n2]) for key in vertex_sets_indices: if vertex_sets_indices[key]==n1 or vertex_sets_indices[key]==n2: vertex_sets_indices[key]=n for edg in to_put_back: heap = INSERT((edg,edge_data[find_index_in_edge_data(edg,edge_data)][5]),heap) break else: to_put_back.append(smallest) return T def prim_preorder(start_vertex, vertex_data, edge_data): graph_new = construct_graph(vertex_data[5:], edge_data[20:], False, False) #delete the black hole and corners vertices and edges min_tree_edges = min_span_tree(graph_new, start_vertex, edge_data[20:]) prim_min_spanning_tree = tree_from_edges(min_tree_edges, vertex_data[5:], edge_data[20:]) traversal = pre_order_trvsl(prim_min_spanning_tree, start_vertex, []) output = create_output(traversal,graph_new,edge_data[20:], False) print('Would you like to plot the result from Route.txt into the brandeis map? (Requires the python package PIL to be installed)') print('y/n - default n? ') plot = input() print(output) create_route_file(traversal,vertex_data) if plot.lower() == 'y': plot_on_map() #plot_traversal(traversal, vertex_data) #plot_traversal(traversal, vertex_data) return output, traversal def prim_shortcut(start_vertex, vertex_data, edge_data): graph_new = construct_graph(vertex_data[5:], edge_data[20:], False, False) #delete the black hole and corners vertices and edges min_tree_edges = min_span_tree(graph_new, start_vertex, edge_data[20:]) prim_min_spanning_tree = tree_from_edges(min_tree_edges, vertex_data[5:], edge_data[20:]) traversal = pre_order_trvsl(prim_min_spanning_tree, start_vertex, []) prim_shortcut_trav = prim_shortchut_traversal(traversal, graph_new) output = create_output(prim_shortcut_trav,graph_new,edge_data[20:], False) print('Would you like to plot the traversal onto the brandeis map? (Requires the python package PIL to be installed)') print('y/n - default n? ') plot = input() print(output) create_route_file(prim_shortcut_trav,vertex_data) if plot.lower() == 'y': plot_on_map() #plot_traversal(traversal, vertex_data) #plot_traversal(prim_shortcut_trav, vertex_data) return output, prim_shortcut_trav def kruskal_preorder(start_vertex, vertex_data, edge_data): graph_new = construct_graph(vertex_data[5:], edge_data[20:], False, False) #delete the black hole and corners vertices and edges kruskal_edges = kruskal_min_spanning_tree(edge_data[20:],vertex_data[5:], graph_new) k_min_spanning_tree = tree_from_edges(kruskal_edges, vertex_data[5:], edge_data[20:]) traversal = pre_order_trvsl(k_min_spanning_tree, start_vertex, []) output = create_output(traversal,graph_new,edge_data[20:], False) print('Would you like to plot the traversal onto the brandeis map? (Requires the python package PIL to be installed)') print('y/n - default n? ') plot = input() print(output) create_route_file(traversal,vertex_data) if plot.lower() == 'y': plot_on_map() #plot_traversal(traversal, vertex_data) return output, traversal def tour(start_vertex, vertex_data, edge_data): print('Enter one of these tour options:') print(' 0: Preorder traversal of Prim tree') print(' 1: Triangle shorcuts of Prim traversal') print(' 2: Preorder traversal of Kruskal tree') print(' or return to quit') option = input() if option == '0': prim_preorder(start_vertex, vertex_data, edge_data) elif option == '1': prim_shortcut(start_vertex, vertex_data, edge_data) elif option == '2': kruskal_preorder(start_vertex, vertex_data, edge_data) elif option == '': sys.exit('You pressed return') else: print('Enter valid option') tour(start_vertex) return # In[9]: def find_path(start_vertex, end_vertex, vertex_data, edge_data, has_skateboard, minimize_time): graph = construct_graph(vertex_data, edge_data, has_skateboard, minimize_time) back_pointer = run_Dijkstras(start_vertex,graph) l = make_path(graph, start_vertex, end_vertex, back_pointer, edge_data, has_skateboard) output = create_output(l, graph, edge_data, has_skateboard) return l, output def run_map(vertex_data, edge_data): print("******************************WELCOME TO THE BRANDEIS MAP******************************\n") print('Entered locations may be: \nthe map location(eg L1, U22 etc) or, \nthe exact name (farber library etc), or, \na substring that uniqiely identifies the place (eg., farber l etc)\n') got_location = False while got_location == False: print('Enter start (return to quit):') inp = input() if inp == '': sys.exit('You pressed return.') start_vertex = get_vertex_id(inp,vertex_data) if start_vertex!=0: got_location = True got_location = False while got_location == False: print('Enter finish (or return to do a tour):') inp = input() if inp == '': tour(start_vertex, vertex_data, edge_data) sys.exit() end_vertex = get_vertex_id(inp,vertex_data) if end_vertex!=0: got_location = True print('Have a skateboard (y/n - default=n)?') sk = input() print('Minimize time (y/n - default=n)?') ti = input() #t f has_skateboard = False minimize_time = False if sk.lower() == 'y': has_skateboard = True if ti.lower() == 'y': minimize_time = True path_list, output = find_path(start_vertex, end_vertex, vertex_data, edge_data, has_skateboard, minimize_time) print(output) print('Creating the files Route.txt and Routecropped.txt with pixels for the path..') create_route_file(path_list,vertex_data) print('Done') print('Would you like to plot the result from Route.txt into the brandeis map? (Requires the python package PIL to be installed)') print('y/n - default n? ') plot = input() if plot.lower() == 'y': plot_on_map() return def output_for_samples(vertex_data, edge_data): filename = 'sample_output_cases.txt' file = open(r"Output.txt","w+") with open(filename) as f: for line in f: fields = line.split() board = fields[3].split('=')[1] time = fields[4].split('=')[1] if board == 'n': has_board = False else: has_board = True if time == 'n': minimize_time = False else: minimize_time = True start_vertex = get_vertex_id(fields[1],vertex_data) end_vertex = get_vertex_id(fields[2],vertex_data) path_list, output = find_path(start_vertex, end_vertex, vertex_data, edge_data, has_board, minimize_time) file.write(line+'\n') file.write(output) def tour_outputs_vertex_J(vertex_data, edge_data): start_vertex = get_vertex_id('J',vertex_data) graph_new = construct_graph(vertex_data[5:], edge_data[20:], False, False) #delete the black hole and corners vertices and edges min_tree_edges = min_span_tree(graph_new, start_vertex, edge_data[20:]) file = open(r"OutputP.txt","w+") file.write(plotting_cordinates_from_edges(min_tree_edges, edge_data, vertex_data)) krus_edge = kruskal_min_spanning_tree(edge_data[20:], vertex_data[5:], graph_new) file = open(r"OutputK.txt","w+") file.write(plotting_cordinates_from_edges(krus_edge, edge_data, vertex_data)) file = open(r"OutputPP.txt","w+") file.write(prim_preorder(start_vertex, vertex_data, edge_data)) file = open(r"OutputPS.txt","w+") file.write(prim_shortcut(start_vertex, vertex_data, edge_data)) file = open(r"OutputKP.txt","w+") file.write(kruskal_preorder(start_vertex, vertex_data, edge_data)) return vertex_data = create_vertex_data() edge_data = create_edge_data() run_map(vertex_data, edge_data) #output_for_samples(vertex_data, edge_data) #tour_outputs_vertex_J(vertex_data, edge_data) #used to create the several output files
true
4774c9f8023d73bbea0a50f30f5849ba2ca1a610
Python
newfull5/Baekjoon-Online-Judge
/[11399] ATM.py
UTF-8
158
3.046875
3
[]
no_license
input() cost = list(map(int, input().split())) cost = sorted(cost) answer = 0 for i in range(1,len(cost)+1): answer += sum(cost[:i]) print(answer)
true
6a122314914452ee9d4d921c4069fbadaf9404ef
Python
operfly/distribute_scpider
/test_2.py
UTF-8
1,994
3.65625
4
[]
no_license
# -*-coding:utf-8-*- import threading mutex_lock = threading.RLock() # 互斥锁的声明 ticket = 100000 # 总票数 # 用于统计各个线程的得票数 ticket_stastics = [] class myThread(threading.Thread): # 线程处理函数 def __init__(self, name): threading.Thread.__init__(self) # 线程类必须的初始化 self.thread_name = name # 将传递过来的name构造到类中的name def run(self): # 声明在类中使用全局变量 global mutex_lock global ticket while 1: mutex_lock.acquire() # 临界区开始,互斥的开始 # 仅能有一个线程↓↓↓↓↓↓↓↓↓↓↓↓ if ticket > 0: ticket -= 1 # 统计哪到线程拿到票 print ("线程%s抢到了票!票还剩余:%d。" % (self.thread_name, ticket)) ticket_stastics[self.thread_name] += 1 else: break # 仅能有一个线程↑↑↑↑↑↑↑↑↑↑↑↑ mutex_lock.release() # 临界区结束,互斥的结束 mutex_lock.release() # python在线程死亡的时候,不会清理已存在在线程函数的互斥锁,必须程序猿自己主动清理 print ("%s被销毁了!" % (self.thread_name)) # 初始化线程 threads = [] # 存放线程的数组,相当于线程池 for i in range(0, 5): thread = myThread(i) # 指定线程i的执行函数为myThread threads.append(thread) # 先讲这个线程放到线程threads ticket_stastics.append(0) # 初始化线程的得票数统计数组 for t in threads: # 让线程池中的所有数组开始 t.start() for t in threads: t.join() # 等待所有线程运行完毕才执行一下的代码 print ("票都抢光了,大家都散了吧!") print ("=========得票统计=========") for i in range(0, len(ticket_stastics)): print ("线程%d:%d张" % (i, ticket_stastics[i]))
true
bf859c72db9b4e519f2c4623e64f716e11df32f1
Python
MonchoG/Computer-Vision
/modules/face_recognition/Server.py
UTF-8
3,091
2.65625
3
[]
no_license
import base64 import pickle import socket import struct import sys import time from _thread import start_new_thread import cv2 import modules.face_recognition.recognize_faces as recognizer def string_to_image(string, title): fh = open("{}.png".format(title), "wb") fh.write(base64.b64decode(string)) print("Done writing file.") fh.close() HOST = '192.168.43.134' PORT = 9999 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: print("Could not create socket. Error Code: ", str(msg[0]), "Error: ", msg[1]) sys.exit(0) print("[-] Socket Created") # bind socket try: s.bind((HOST, PORT)) print("[-] Socket Bound to host " + str(HOST)) print("[-] Socket Bound to port " + str(PORT)) except socket.error as msg: print("Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1])) sys.exit() s.listen(10) print("Listening...") # Client handler def client_thread(conn, addr): try: recv_0 = 0 data = b"" payload_size = struct.calcsize(">L") print("payload_size: {}".format(payload_size)) while True: while len(data) < payload_size: print("Recv: {} from {}".format(len(data), addr[0])) data += conn.recv(4096) if len(data) == 0: recv_0 += 1 # if recv_0 >= 1000: # break print("Done Recv: {} from {}".format(len(data), addr[0])) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack(">L", packed_msg_size)[0] print("msg_size: {}".format(msg_size)) while len(data) < msg_size: data += conn.recv(4096) if str(data).__contains__('Bye'): break frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data, fix_imports=True, encoding="bytes") frame = cv2.imdecode(frame, cv2.IMREAD_COLOR) t = time.localtime() timestamp = time.strftime('%b-%d-%Y_%H%M%S', t) cv2.imwrite('{}.png'.format(timestamp), frame) print("[ INFO ] Starting recognizer for {}".format(addr[0])) result = recognizer.find_face(frame, scaleFactor=1.1, minNeighbors=7, minSize=(35, 35), reSample=3) cv2.imwrite('result_{}.png'.format(timestamp), result) print("[ INFO ] Finished recognizer for {}".format(addr[0])) time.sleep(10) except Exception as exp: print(exp) print(exp.with_traceback()) exit() finally: print("Exited all loops closing connections") conn.close() while True: # blocking call, waits to accept a connection try: conn, addr = s.accept() print("[-] Connected to " + addr[0] + ":" + str(addr[1])) start_new_thread(client_thread, (conn, addr)) except socket.error as e: print("Error occurred during initializing connection") print(e.strerror)
true
99983da8be525ee89e20e4c9a95ba2cc3a4ac471
Python
GriffinPeirce/Aquabot_Streaming
/udpServer_pi.py
UTF-8
814
3.21875
3
[]
no_license
import socket def main(): #host = '192.168.1.101' #port = 22 #port for server #pass tuple of host and port #DGRAM = datagram s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #by default, socket is TCP so we should specify it is UDP host = '192.168.1.101' port = 5000 #bind socket to port s.bind((host, port)) print("Server started.") #UDP is connectionless while True: #no connection to receive from. just store data and addr data, addr = s.recvfrom(1024) data = data.decode('utf-8') print("Message from: " + str(addr)) print("From connected user: " + data) data.upper() print("Sending: " + data) s.sendto(data.encode('utf-8'), addr) s.close() if __name__ == '__main__': main()
true
c6910f5ccefea5b2a641830d9dc8603254f64f62
Python
ambv/aiotone
/aiotone/uspectro.py
UTF-8
3,841
2.671875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 from __future__ import annotations from functools import lru_cache import os from pathlib import Path import click import numpy from PIL import Image from aiotone import audiofile from aiotone.colors import get_color, colors_to_buckets, convert_html_to_hsv BETA = 3.14159265359 * 2.55 def freq_from_pcm(pcm, window, step, channels): """Yields real FFTs from data chunks of `window` size in `pcm` double array.""" # XXX doesn't pad data with zeroes at the start offset = 0 while offset < pcm.shape[0]: data = numpy.zeros(window, numpy.float64) for ch in channels: chunk = pcm[offset : offset + window, ch] if len(chunk) < window: chunk = numpy.pad(chunk, [(0, window - len(chunk))]) data += chunk result = numpy.fft.rfft(data * kaiser(len(data))) # some transformations suggested by # https://lo.calho.st/posts/numpy-spectrogram/ result = result[: window // 2] result = numpy.absolute(result) * 2.0 / window # result = (20 * numpy.log10(result)).clip(-120) yield result offset += step @lru_cache() def kaiser(length): """Memoized Kaiser window, saves a lot of time recomputing the same shape. See more at: https://en.wikipedia.org/wiki/Kaiser_window """ return numpy.kaiser(length, BETA) def convert_channels_to_list(channels): if channels is None or channels == "ALL": return [] return [int(elem.strip()) for elem in channels.split(",")] @click.command() @click.argument("file") @click.option( "-b", "--brightness", type=click.IntRange(min=1), default=8, help="Brightness multiplier", ) def main( file, window=4800, step=600, brightness=8, prepend=0, fps=10, crop_height=2160, colors=None, channels=None, ): width = 0 height = 0 if not colors: colors = "#000000,#0000ff,#008080,#00ff00,#ffffff" if not channels: channels = "ALL" colors = convert_html_to_hsv(colors) color_buckets = colors_to_buckets(colors, min=0, max=1) channels = convert_channels_to_list(channels) audio_data, audio_rate = audiofile.read(file) audio_channels = audio_data.shape[1] audio_duration = audio_data.shape[0] / audio_rate freq_samples = [] window = window or audio_rate step = step or int(round(audio_rate / fps)) channels = channels or list(range(audio_channels)) print(file) print(" duration:", audiofile.duration_str(audio_duration)) print(" sample rate:", audio_rate) print(" channels:", audio_channels) print(" window:", window) print(" step:", step, "(fps: {})".format(fps)) print("Calculating FFT...", end="\r") for freq in freq_from_pcm(audio_data, window, step, channels): width += 1 height = len(freq) freq_samples.append(freq) rgb = numpy.zeros((height, width + prepend, 3), "uint8") print(" image width:", width) print(" image height:", height) print("Preparing image...", end="\r") custom_black = get_color(0, brightness, color_buckets) for x in range(prepend): for y in range(height): rgb[y, x] = custom_black print("Applying colors...", end="\r") for x, freq in enumerate(freq_samples, prepend): freq = freq[:height] for y, f in enumerate(reversed(freq)): rgb[y, x] = get_color(f, brightness, color_buckets) print("Creating in-memory PNG image", end="\r") i = Image.fromarray(rgb, mode="RGB") img_path = Path(file).stem + f".b{brightness}.png" print("Saving image to", img_path, " " * 10, end="\r") i.save(img_path) print("Saved image to", img_path, " " * 10) if __name__ == "__main__": main()
true
15e82493228fb5e225f8d4a3089f689bb8cfeba1
Python
Sho-Tamura-Create/LearningPY
/pyxel/test00.py
UTF-8
1,611
2.96875
3
[]
no_license
import pyxel alphaChanel = 11 charset = {'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,'.':26,':':27,'!':28,'?':39,'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} s = 0 class App: def __init__(self): pyxel.init(160, 120,caption='レトロゲー',scale=4,fps=60) pyxel.image(0).load(0,0, 'res/font.png') pyxel.image(1).load(0,0, 'res/sf00.png') self.x = 0 pyxel.run(self.update, self.draw) def update(self): if pyxel.btnp(pyxel.KEY_Q): pyxel.quit() # self.x = (self.x + 1) % pyxel.width def draw(self): pyxel.cls(1) # pyxel.rect(self.x, 0, self.x + 7, 7, 9) # pyxel.text(55, 41, "Hello world!", 16) # pyxel.blt(0,0,0,0,0,8,8,alphaChanel) # pyxel.blt(80,60,1,0,0,16,16,alphaChanel) self.char() self.score(self.char(),50,2) self.text("SCORE:",2,2) def char(self): x = pyxel.mouse_x y = pyxel.mouse_y if pyxel.btn(pyxel.MOUSE_LEFT_BUTTON): pyxel.blt(x,y,1,0,0,16,-16,alphaChanel) global s s += 1 else: pyxel.blt(x,y,1,0,0,16,16,alphaChanel) return str(s) def text(self,text,x,y): for i in range(len(text)): pyxel.blt(x+i*8,y,0,charset[text[i]]*8,0,8,8,alphaChanel) def score(self,s,x,y): for i in range(len(s)): pyxel.blt(x+i*8,y,0,charset[s[i]]*8,8,8,8,alphaChanel) App()
true
801beb7d522948ed45d8c59b1929a0a8e58d1db2
Python
DevMayurJ/Duplicate-File-Finder
/DuplicateFileFinder.py
UTF-8
2,090
3.328125
3
[]
no_license
from sys import * import os; import hashlib; def hashfile(path, blocksize = 1024): fd = open(path, 'rb') hasher = hashlib.md5() buff = fd.read(blocksize) while len(buff) > 0: hasher.update(buff) buff = fd.read(blocksize) fd.close() return hasher.hexdigest() def FindDuplicate(path): flag = os.path.isabs(path) if flag == False: path = os.path.abspath(path) exists = os.path.isdir(path) dups = {} if exists: for dirName, subdirs, fileList in os.walk(path): for filen in fileList: path = os.path.join(dirName, filen) file_hash = hashfile(path) if file_hash in dups: dups[file_hash].append(path) else: dups[file_hash] = [path] return dups else: print ("Invalid path") def PrintDuplicate(dict1): results = list(filter(lambda x: len(x) > 1, dict1.values())) if len(results) > 0: print ("Duplicate files found") print ("The following are identical files.") for result in results: for subresult in result: print ("\t\t%s" % subresult) print ("-------------------------------------------------------------------------") else: print("No dulplicate files found") def DisplayHelp(): print ("This script List all duplicate files from provided directory path") print ("python.exe .\DuplicateFileFinder.py <Directory>") print ("e.g python.exe .\DuplicateFileFinder.py F:\\Users\DevMJ\\") def main(): if len(argv) != 2: print ("ERROR! Invalid arguments") DisplayHelp() return if (argv[1] == "-h") or (argv[1] == "-H"): DisplayHelp() return try: arr = {} arr = FindDuplicate(argv[1]) PrintDuplicate(arr) except ValueError: print("ERROR: Invalid datatype of imput") if __name__ == "__main__": main()
true
55ba7e5f885c735a1352a557d239f433c75ba1e5
Python
RaymondZano/MBAN-Python-Course
/6_pandas and matplotlib essentials.py
UTF-8
2,670
3.625
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 10 18:11:26 2018 @author: chase.kusterer Working Directory: /Users/chase.kusterer/Desktop/PyCourse Purpose: To introduce pandas and matplotlib """ ############################################################################### # Importing libraries and base dataset ############################################################################### import pandas as pd # Checking the arguments for pd.to_numeric() pd.to_numeric() # Testing pd.to_numeric() x = '7.9484141' pd.to_numeric(x) print(x) # Checking the documentation on pd.datetools() help(pd.datetools) # Testing pd.cut() x = range(100) y = pd.cut(x, 5) print(y) print(pd.value_counts(y)) ############################################################################### # matplotlib Essentials ############################################################################### import pandas as pd import matplotlib.pyplot as plt file ='diamonds_missing_values.xlsx' diamonds = pd.read_excel(file) plt.hist(x = 'price', data = diamonds)#lazy printing - not shown immediately, need to call #plt.show() plt.hist(x = 'carat', data = diamonds)#another column name from file plt.show() plt.hist(x = 'price', data = diamonds, bins = 15, normed = True) plt.show() plt.hist(x = 'price', data = diamonds, bins = 150, normed = True) plt.show() plt.hist(x = 'price', data = diamonds, bins = 150, normed = True) plt.show() # Finding the optimal number of bins with the # Freedman-Diaconis rule iqr_max = pd.np.percentile(diamonds['price'], [75]) iqr_min = pd.np.percentile(diamonds['price'], [25]) iqr_price = float(iqr_max - iqr_min) h = 2 * iqr_price * (len(diamonds['price']) ** -(1/3)) price_range = max(diamonds['price']) - min(diamonds['price']) print(price_range / h) plt.hist(x = 'price', data = diamonds, bins = 21, normed = True) """ Prof. Chase: The Freedman-Diaconis rule can be cumbersome if done manually in Python. Luckily, it is built into plt.hist as an option for bins. This is one of the major advantages of open source communities. """ plt.hist(x = 'price', data = diamonds, bins = 'fd', normed = True)#fd is freedman-diaconis, best form of data, optimized # Scatterplot example plt.scatter(x = 'carat', y = 'price', data = diamonds) plt.xlabel('Carat Weight') plt.ylabel('Price') plt.axhline(y = 25000) plt.axvline(x = 1)#vertical line plt.axvline() plt.show()
true
8602ab26cba7c4992d475b5fc0024141f5c0016b
Python
ArdelH/spaceGame
/classes.py
UTF-8
7,237
2.953125
3
[]
no_license
import pygame as pg from PIL import ImageFont pg.font.init() # Parent class buttons_and_labels(): def __init__(self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): self.game_display = game_display self.rectX = rectX self.rectY = rectY self.rectW = rectW self.rectH = rectH self.rectC = rectC self.text = text text_font = ImageFont.truetype(font.lower() + '.ttf', size) current_textW, current_textH = text_font.getsize(text) self.textX = rectX + ((rectW / 10) * 0.5) self.textY = rectY + ((rectH - current_textH) / 3.0) self.textY = rectY + ((rectH - size) / 2.5) self.textC = textC self.font = font self.size = size self.bold = bold self.italic = italic self.rect = pg.Rect(self.rectX, self.rectY, self.rectW, self.rectH) def draw(self): myfont = pg.font.SysFont(self.font, self.size, self.bold, self.italic) text_to_show = myfont.render(self.text, False, self.textC) pg.draw.rect(self.game_display, self.rectC, self.rect) self.game_display.blit(text_to_show, (self.textX, self.textY)) def change_text(self, new_text): self.text = new_text class buttons(buttons_and_labels): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) text_font = ImageFont.truetype(font.lower() + '.ttf', size) current_textW, current_textH = text_font.getsize(text) self.textX = rectX + ((rectW - current_textW) / 2.5) self.textY = rectY + ((rectH - current_textH) / 3.0) class label(buttons_and_labels): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) class custom_label_fix_pos_left(label): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) class custom_label_fix_pos_center(buttons_and_labels): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) text_font = ImageFont.truetype(font.lower() + '.ttf', size) current_textW, current_textH = text_font.getsize(text) self.textX = rectX + ((rectW - current_textW) / 2.5) self.textY = rectY + ((rectH - current_textH) / 3.0) class custom_label_custom_pos_left(label): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) class custom_label_custom_pos_center(label): def __init__ (self, game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) text_font = ImageFont.truetype(font.lower() + '.ttf', size) current_textW, current_textH = text_font.getsize(text) self.textX = rectX + ((rectW - current_textW) / 2.5) self.textY = rectY + ((rectH - current_textH) / 3.0) class menu_bar(label): def __init__(self, game_display, rectX, rectY, rectW, rectH, rectC, barC, max_nr, current_nr, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, text, textC, font, size, bold, italic) self.front_barC = barC self.max_nr = max_nr self.current_nr = current_nr self.background_barC = rectC self.background_barX = rectX self.background_barY = rectY self.background_barW = rectW self.background_barH = rectH self.front_barX = rectX self.front_barY = rectY if rectW * (current_nr / max_nr) > self.background_barW: self.front_barW = self.background_barW else: self.front_barW = rectW * (current_nr / max_nr) self.front_barH = rectH self.background_bar = pg.Rect(self.background_barX, self.background_barY, self.background_barW, self.background_barH) self.front_bar = pg.Rect(self.front_barX, self.front_barY, self.front_barW, self.front_barH) def draw(self): myfont = pg.font.SysFont(self.font, self.size, self.bold, self.italic) if self.current_nr > self.max_nr: self.text_with_nr = self.text + ' ' + str(self.current_nr) + ' / ' + str(self.max_nr) + ' ' + self.over_max_text else: self.text_with_nr = self.text + ' ' + str(self.current_nr) + ' / ' + str(self.max_nr) self.text_to_show = myfont.render(self.text_with_nr, False, self.textC) if self.background_barW * (self.current_nr / self.max_nr) > self.background_barW: self.front_barW = self.background_barW else: self.front_barW = self.background_barW * (self.current_nr / self.max_nr) self.front_bar = pg.Rect(self.front_barX, self.front_barY, self.front_barW, self.front_barH) pg.draw.rect(self.game_display, self.background_barC, self.background_bar) pg.draw.rect(self.game_display, self.front_barC, self.front_bar) self.game_display.blit(self.text_to_show, (self.textX, self.textY)) def change_current_max(self): self.current_nr = self.max_nr def change_current_set(self, set_nr): self.current_nr = set_nr def change_current_sub(self, sub_nr): if self.current_nr - sub_nr < 0: self.current_nr = 0 else: self.current_nr -= sub_nr class menu_bar_max(menu_bar): def __init__(self, game_display, rectX, rectY, rectW, rectH, rectC, barC, max_nr, current_nr, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, barC, max_nr, current_nr, text, textC, font, size, bold, italic) def change_current_add(self, add_nr): if self.current_nr + add_nr > self.max_nr: self.current_nr = self.max_nr else: self.current_nr += add_nr class menu_bar_no_lim(menu_bar): def __init__(self, game_display, rectX, rectY, rectW, rectH, rectC, barC, max_nr, current_nr, over_max_text, text, textC, font, size, bold, italic): super().__init__(game_display, rectX, rectY, rectW, rectH, rectC, barC, max_nr, current_nr, text, textC, font, size, bold, italic) self.over_max_text = over_max_text def change_current_add(self, add_nr): self.current_nr += add_nr class global_var(): def __init__(self, state): self.state = state def change_state(self, new_state): self.state = new_state
true
fa5ded646961aa362414beafda4b7ea8136f28a5
Python
lettergram/DataProfiler
/dataprofiler/validators/base_validators.py
UTF-8
4,684
3.28125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python """ coding=utf-8 Build model for a dataset by identifying type of column along with its respective parameters. """ from __future__ import print_function from __future__ import division def is_in_range(x, config): """ Checks to see x is in the range of the config. :param x: number :type x: int/float :param config: configuration :type config: dict :returns: bool """ try: return config['start'] <= float(x) <= config['end'] except: raise TypeError("Value is not a float") def is_in_list(x, config): """ Checks to see x is in the config list. :param x: item :type x: string :param config: configuration :type config: dict :returns: bool """ return float(x) in config class Validator(): def __init__(self): self.config = None self.report = None self.validation_run = False self.validation_report = dict() def validate(self, data, config): """ Validate a data set. No option for validating a partial data set. Set configuration on run not on instantiation of the class such that you have the option to run multiple times with different configurations without having to also reinstantiate the class. :param data: The data to be processed by the validator. Processing occurs in a column-wise fashion. :type data: DataFrame Dask/Pandas :param config: configuration for how the validator should run across the given data. Validator will only run over columns specified in the configuration. :type config: dict :Example: This is an example of the config:: config = { <column_name>: { range: { 'start': 1, 'end':2 }, list: [1,2,3] } } """ if not config: raise ValueError("Config is required") known_anomaly_validation = config.get('known_anomaly_validation', {}) for iter_key, value in known_anomaly_validation.items(): if len(value) < 1: raise Warning( f"Pass at a minimum one value for a specified column " f"(i.e. iter_key variable) -- not both for {iter_key}") self.config = config df_type = config.get('df_type', '').lower() for iter_key, value in known_anomaly_validation.items(): self.validation_report[iter_key] = dict() df_series = data[iter_key] for sub_key, sub_value in value.items(): self.validation_report[iter_key][sub_key] = dict() if sub_key not in ["range", "list"]: raise TypeError( 'Range and list only acceptable key values.') apply_type = is_in_range if sub_key == "range" else is_in_list if df_type == 'dask': temp_results = df_series.apply( apply_type, meta=(iter_key, 'bool'), args=(sub_value,)) temp_results = temp_results.compute() # Dask evaluates this to be an nd array so we have to # convert it to a normal list self.validation_report[iter_key][sub_key] = [ idx for idx, val in enumerate(temp_results.values.tolist()) if val ] elif df_type == 'pandas': temp_results = df_series.apply( apply_type, args=(sub_value,) ) self.validation_report[iter_key][sub_key] = [ idx for idx, val in temp_results.items() if val ] else: raise ValueError( 'Dask and Pandas are the only supported dataframe ' 'types.') del temp_results self.validation_run = True def get(self): """ Get the results of the validation run. """ if self.validation_run: return self.validation_report else: raise Warning( "Precondition for get method not met. Must validate data prior " "to getting results.")
true
55959cb38abe6244116ea968c4ec9e830590b4ca
Python
mingzeng8/ionization_calculator
/ADK_calculator.py
UTF-8
3,260
3.078125
3
[]
no_license
#calculate the parameters in ADK model import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy.special import gamma from scipy.constants import c, e, m_e, physical_constants from fbpic.particles.elementary_process.ionization.read_atomic_data import get_ionization_energies class ADK_calculator(object): def __init__( self, element, level_max=None ): """ This is mostly copied from fbpic/particles/elementary_process/ionization/ionizer.py but with some modifications. Initialize parameters needed for the calculation of ADK ionization rate Parameters ---------- element: string The atomic symbol of the considered ionizable species (e.g. 'He', 'N' ; do not use 'Helium' or 'Nitrogen') See Chen, JCP 236 (2013), equation (2) for the ionization rate formula """ self.set_element(element, level_max) def set_element( self, element, level_max=None ): # Get the array of energies Uion = get_ionization_energies( element ) # Check whether the element string was valid if Uion is None: raise ValueError("Unknown ionizable element %s.\n" %element + \ "Please use atomic symbol (e.g. 'He') not full name (e.g. Helium)") else: self.element = element # Determine and set the maximum level of ionization self.level_max = level_max if self.level_max is None: self.level_max = len(Uion) else: assert type(self.level_max) is int, "level_max must be integer" if self.level_max>len(Uion): raise ValueError("Chosen level_max for {}".format(element) + \ " cannot exceed {}".format(len(Uion))) # Calculate the ADK prefactors (See Chen, JCP 236 (2013), equation (2)) # - Scalars alpha = physical_constants['fine-structure constant'][0] r_e = physical_constants['classical electron radius'][0] wa = alpha**3 * c / r_e Ea = m_e*c**2/e * alpha**4/r_e # - Arrays (one element per ionization level) UH = get_ionization_energies('H')[0] Z = np.arange( len(Uion) ) + 1 self.n_eff = n_eff = Z * np.sqrt( UH/Uion ) l_eff = n_eff[0] - 1 self.C2 = C2 = 2**(2*n_eff) / (n_eff * gamma(n_eff+l_eff+1) * gamma(n_eff-l_eff)) # For now, we assume l=0, m=0 self.adk_power = - (2*n_eff - 1) self.adk_prefactor = wa * C2 * ( Uion/(2*UH) ) \ * ( 2*(Uion/UH)**(3./2)*Ea )**(2*n_eff - 1) self.adk_exp_prefactor = -2./3 * ( Uion/UH )**(3./2) * Ea def get_ADK_parameters(self): return np.transpose([self.adk_prefactor, self.adk_exp_prefactor, self.adk_power]) def ionization_rate(self, E, level=None): ''' return the ionization rate ''' if level is None: return self.adk_prefactor * np.exp(self.adk_exp_prefactor/E) * E**self.adk_power else: return self.adk_prefactor[level] * np.exp(self.adk_exp_prefactor[level]/E) * E**self.adk_power[level] if __name__ == '__main__': ion=ADK_calculator('O') print(ion.get_ADK_parameters())
true
aca8078a350790d5cceb7626e0e9e266d3aca80d
Python
shamoldas/pythonBasic
/numpy/empty.py
UTF-8
269
3.796875
4
[]
no_license
# Python Programming illustrating # numpy.empty method import numpy as geek b = geek.empty(2, dtype = int) print("Matrix b : \n", b) a = geek.empty([2, 2], dtype = int) print("\nMatrix a : \n", a) c = geek.empty([3, 3]) print("\nMatrix c : \n", c)
true
dd1b6a3bd78415bd3d49561510c29f385b950ca9
Python
Deadlysmurf/Code-Scraps
/t_test_summary_stats.py
UTF-8
1,276
2.8125
3
[]
no_license
### For t-test hypothesis testing when only summary statistics are provided ## DEPENDANCIES: ## import numpy as np ## import scipy.stats as ss def t_test(sample_mean, mu, sd, n, alpha, tails): if tails == 1: t_critical = (sample_mean-mu)/(sd/(np.sqrt(n))) pval = ss.t.sf(np.abs(t_critical), n-1) print("T-critical value: %f" % t_critical) print("P-value: %f" % pval) if pval > alpha: print("As %f is greater than %f, there is insufficent evidence to reject the null hypothesis." % (pval, alpha)) else: print("As %f is less than %f, there is sufficent evidence to reject the null hypothesis, and accept the alternative." % (pval, alpha)) elif tails == 2: t_critical = (sample_mean-mu)/(sd/(np.sqrt(n))) pval = ss.t.sf(np.abs(t_critical), n-1)*2 print("T-critical value: %f" % t_critical) print("P-value: %f" % pval) if pval > alpha: print("As %f is greater than %f, there is insufficent evidence to reject the null hypothesis." % (pval, alpha)) else: print("As %f is less than %f, there is sufficent evidence to reject the null hypothesis, and accept the alternative." % (pval, alpha)) ### March 17, 2018 ### ## MEAK ##
true
9ee6f4db7e25a239e2725a8c95d7cc841b3d9015
Python
Iammagneat/gl_test_numbers1
/count_numbers.py
UTF-8
170
3.3125
3
[]
no_license
with open('numbers.txt') as file: text_list = [line.rstrip() for line in file] x = 0 for i in text_list: if not i.startswith('#'): x += float(i) print(x)
true
734175ef5d647a7f807616e06a1cd73c3c482606
Python
impelfin/rpi_with_iot
/python/p17_if.py
UTF-8
161
3.828125
4
[]
no_license
a = int(input("Input the First number : ")) b = int(input("Input the Second number : ")) if a > b: print("Max is %d" % a) else: print("Max is %d" % b)
true
c2c6506fcfaa21c79ce94e1b2db30218f6d062dd
Python
Bootstrap360/RL
/environments/gridworld2.py
UTF-8
10,105
2.859375
3
[]
no_license
import numpy as np import random, copy, math import itertools import scipy.misc import matplotlib.pyplot as plt from PIL import Image import cv2 class gameOb(): def __init__(self,coordinates,size,color,reward,name): self.x = coordinates[0] self.y = coordinates[1] self.size = size self.color = color self.name = name self.reward = reward class Hero(gameOb): def __init__(self, coordinates, size, sizeX, sizeY): self.color = [0,0,255] super(Hero, self).__init__(coordinates, size, self.color, None,'hero') self.sizeX = sizeX self.sizeY = sizeY def take_action(self, action): # up down left right if action == 0 and self.y >= 1: self.y -= 1 if action == 1 and self.y < self.sizeY - 2: self.y += 1 if action == 2 and self.x >= 1: self.x -= 1 if action == 3 and self.x < self.sizeX - 2: self.x += 1 @staticmethod def get_num_actions(): return 4 class Goal(gameOb): def __init__(self,coordinates,size): self.color = [0,255,0] super(Goal, self).__init__(coordinates,size, self.color,1,'goal') class Fire(gameOb): def __init__(self,coordinates,size): self.color = [255,0,0] super(Fire, self).__init__(coordinates,size, self.color,-11,'fire') class GridEnvironment(): def __init__(self, height, width, channels, partial = False): self.partial = partial self.height = height self.width = width self.channels = channels self.reset() def update(self, objects): self.observation_space = np.zeros([self.height,self.width, self.channels], dtype=int) hero = None for item in objects: for i, val in enumerate(item.color): self.observation_space[item.y+1:item.y+item.size+1,item.x+1:item.x+item.size+1,i] = val if item.name == 'hero': hero = item if self.partial == True: self.observation_space = self.observation_space[hero.y:hero.y+3,hero.x:hero.x+3,:] def reset(self): if self.partial: self.observation_space = np.zeros([3, 3, 3], dtype=int) else: self.observation_space = np.zeros([self.height,self.width, self.channels], dtype=int) def get_empty(self): return np.zeros([self.height,self.width, self.channels], dtype=int) def get_grid_observations(self, objects): return self.observation_space def get_num_states(self): return self.height * self.width * self.channels class AbsPositionsEnvironment(): def __init__(self, height, width, channels, partial = False): self.partial = partial self.height = height self.width = width self.channels = channels self.reset() def update(self, objects): hero = None goal = None for i, item in enumerate(objects): if item.name == 'hero': hero = item if item.name == 'goal': goal = item self.observation_space = np.array([[hero.x, hero.y, goal.x, goal.y]]) def reset(self): self.observation_space = self.get_empty() def get_empty(self): return np.zeros([1,4], dtype=int) def get_grid_observations(self, objects): grid_space = np.zeros([self.height,self.width, self.channels], dtype=int) hero = None for item in objects: for i, val in enumerate(item.color): grid_space[item.y+1:item.y+item.size+1,item.x+1:item.x+item.size+1,i] = val return grid_space def get_num_states(self): return 4 class DeltaPositionsEnvironment(): def __init__(self, height, width, channels, partial = False): self.partial = partial self.height = height self.width = width self.channels = channels self.reset() def update(self, objects): hero = None goal = None for i, item in enumerate(objects): if item.name == 'hero': hero = item if item.name == 'goal': goal = item self.observation_space = np.array([[goal.x - hero.x, goal.y - hero.y]]) def reset(self): self.observation_space = self.get_empty() def get_empty(self): return np.zeros([1,2], dtype=int) def get_grid_observations(self, objects): grid_space = np.zeros([self.height,self.width, self.channels], dtype=int) hero = None for item in objects: for i, val in enumerate(item.color): grid_space[item.y+1:item.y+item.size+1,item.x+1:item.x+item.size+1,i] = val return grid_space def get_num_states(self): return 2 class GameEnv(): def __init__(self, partial, size, state_type = 'image'): self.actions = 4 self.objects = [] self.partial = partial self.height = size self.width = size self.channels = 3 self.state_type = state_type self.min_distance = 1000000 self.env = DeltaPositionsEnvironment(size, size, 3) self.max_reward = math.sqrt(size * size * 2) self.reset() a = self.env.get_grid_observations(self.objects) plt.imshow(a,interpolation="nearest") def get_num_states(self): return self.env.get_num_states() @staticmethod def get_num_actions(): return Hero.get_num_actions() def get_state(self): self.env.update(self.objects) return self.env.observation_space def reset(self): self.objects = [] hero = Hero(self.newPosition(),1, self.width, self.height) self.objects.append(hero) for i in range(1): goal = Goal(self.newPosition(),1) self.objects.append(goal) for i in range(0): fire = Fire(self.newPosition(),1) self.objects.append(fire) return self.get_state() def take_action(self,action): hero = self.objects[0] heroX = hero.x heroY = hero.y penalize = 0.0 hero.take_action(action) if hero.x == heroX and hero.y == heroY: penalize = 0.0 self.objects[0] = hero return penalize def newPosition(self): iterables = [ range(self.width-1), range(self.height-1)] points = [] for t in itertools.product(*iterables): points.append(t) currentPositions = [] for objectA in self.objects: if (objectA.x,objectA.y) not in currentPositions: currentPositions.append((objectA.x,objectA.y)) for pos in currentPositions: points.remove(pos) location = np.random.choice(range(len(points)),replace=False) return points[location] @staticmethod def get_distace(target, hero): return math.sqrt(math.pow(target.x - hero.x, 2) + math.pow(target.y - hero.y, 2)) @staticmethod def _get_correct_action(target, hero): if(target.y < hero.y): return 0 if(target.y > hero.y): return 1 if(target.x < hero.x): return 2 if(target.x > hero.x): return 3 def get_correct_action(self): others = [] for obj in self.objects: if obj.name == 'hero': hero = obj else: others.append(obj) ended = False target = others[0] return GameEnv._get_correct_action(target, hero) def check_goal(self, action): others = [] for obj in self.objects: if obj.name == 'hero': hero = obj else: others.append(obj) ended = False target = others[0] correct_action = GameEnv._get_correct_action(target, hero) reward = 0 if action == correct_action: reward = 1 else: reward = 0 # distance = GameEnv.get_distace(target, hero) # if distance != 0: # reward = (1.0 / distance) / self.max_reward # if distance < self.min_distance and distance != 0: # reward = 0.1 # self.min_distance = distance if hero.x == target.x and hero.y == target.y: self.objects.remove(target) self.objects.append(Goal(self.newPosition(),1)) self.min_distance = 100000000 return 1, True return reward, False # for other in others: # if hero.x == other.x and hero.y == other.y: # self.objects.remove(other) # if other.reward == 1: # self.objects.append(Goal(self.newPosition(),1)) # # else: # # self.objects.append(gameOb(self.newPosition(),1,1,self.colors['fire'],-1,'fire')) # return 1, True def render_env(self): a = copy.deepcopy(self.env.get_grid_observations(self.objects)) render_height = 128 * 2 render_width = 128 * 2 b = scipy.misc.imresize(a[:,:,0],[render_width, render_height, 1],interp='nearest') c = scipy.misc.imresize(a[:,:,1],[render_width, render_height, 1],interp='nearest') d = scipy.misc.imresize(a[:,:,2],[render_width, render_height, 1],interp='nearest') a = np.stack([b,c,d],axis=2) return a def render(self): rendered_env = self.render_env() cv2.imshow('game', rendered_env) cv2.waitKey(100) def step(self,action): penalty = self.take_action(action) reward, done = self.check_goal(action) state = self.get_state() info = 'I dont know' if reward == None: print(done) print(reward) print(penalty) return state,(reward+penalty),done, info else: return state,(reward+penalty),done, info
true
db71ec188766bf306982476b1f7c1715afe7a993
Python
Teenspirit-Hao/Discrete-Event-Simulator
/model.py
UTF-8
1,660
2.671875
3
[]
no_license
import numpy as np import os import random """ Machines are created here Whenever you use the machine release it """ class Machine(object): def __init__(self, name): self.machineID = int(name) self.machineName = "Machine_"+str(name) self.machineBusy = False self.jobOverTime = 0 self.now = 0 self.jobsDone = [] def processJob(self, jobID, time, pTime): # check if machine is busy or not assert self.machineBusy == False self.onJob = jobID self.now = time self.processTime = pTime # import pdb; pdb.set_trace() self.jobOverTime = self.now + self.processTime self.machineBusy = True return def releaseMachine(self): # check if currently in use assert self.machineBusy == True self.jobsDone.append(self.onJob) self.machineBusy = False return """ Jobs are created here Always use the job then release it too """ class Jobs(object): def __init__(self, name): self.jobID = name self.jobName = "Job_"+str(name) self.jobBusy = False self.processDetails = [] self.noOfProcess = 0 self.now = 0 self.machineVisited = 0 def getProcessed(self): # print("{} requested".format(self.jobName)) assert self.jobBusy == False self.jobBusy = True return def releaseJob(self): # print("{} released".format(self.jobName)) assert self.jobBusy == True self.machineVisited += 1 self.jobBusy = False return
true
09044b8a8fcc699a61a9bc9fbf7a6d39f10fa07b
Python
pbharathkoundinya/CSD-LAB
/CSD LAB/Lab 1/problem4.py
UTF-8
252
3.234375
3
[]
no_license
l=[] n=int(input("enter no.of elements :")) for i in range(n): i=int(input("enter element :")) l.append(i) d=max(l) a=[] l.remove(max(l)) for i in l: a.append(i) s=2*max(a) if d>=s: print("true") else: print("false")
true
10febffda3220a7edaf2fe9c65f3d6fe7edd3937
Python
laiy/Distributed_Computing
/wsgi/wsgi_app_on_tornado.py
UTF-8
433
2.515625
3
[]
no_license
import tornado.web import tornado.httpserver import tornado.wsgi def simple_app(environ, start_response): status = "200 OK" response_headers = [("Content-type", "text/plain")] start_response(status, response_headers) return ["Hello world!\n"] container = tornado.wsgi.WSGIContainer(simple_app) http_server = tornado.httpserver.HTTPServer(container) http_server.listen(8888) tornado.ioloop.IOLoop.current().start()
true
536e1643495f44085345c591facd6f46371452e2
Python
Dwape/domotics
/back/webapp/read_db.py
UTF-8
2,896
3.1875
3
[]
no_license
#!/usr/bin/python #import MySQLdb import pymysql pymysql.install_as_MySQLdb() import datetime #cur = None # Database cursor db = None # A reference to the database def connect(): ''' Connects to the database use to store sensore values. ''' global db db = pymysql.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="tpintrocom", # your password db="domotics") # name of the data base #global cur cur = db.cursor() cur.execute("SELECT * FROM data") cur.close() def close_connection(): ''' Closes the connection to the database. ''' db.close() def get_latest_values(): ''' Returns the latest values saved in the database. :return: str[] The latest values in the database A list of six elements with all the values. The elements represent (in this order): humidity, temperature, LPG amount, CO amount, Smoke, light. ''' #connect() #cur = db.cursor() #result = cur.fetchall()[0] #cur.close() cur = db.cursor() cur.execute("SELECT * FROM data ORDER BY datetime DESC") # This for some reason fixes the cursor problem result = cur.fetchall()[0] cur.close() return result def get_range_values(fromDate, toDate): ''' Returns all the values saved in the database from the first date to the second date. The dates passed as method parameters must be in the following format. 'YYYY-MM-DD HH:MI:SS' For example: '2008-11-11 13:23:44' :param fromDate: str A string representing the starting date. :param toDate: str A string representing the end date. :return: str[[]] The values in the database withing the specified date range. A list with lists of six elements with all the values. The elements represent (in this order): humidity, temperature, LPG amount, CO amount, Smoke, light. ''' #connect() #cur = db.cursor() cur = db.cursor() cur.execute("SELECT * FROM data WHERE (datetime > " + fromDate + " AND datetime < " + toDate +") ORDER BY datetime DESC") result = cur.fetchall() cur.close() #cur.close() return result # Check if the return value is correct or we need to remove the last value (like we do in get_latest_values()) def save_values(values): ''' Saves the values passed as function parameter to the database :param values: str[] A list of six elements with all the values to be saved. The elements represent (in this order): humidity, temperature, LPG amount, CO amount, Smoke, light. ''' cur = db.cursor() cur.execute("INSERT INTO data VALUES (%s, %s, %s, %s, %s, %s, %s)", (datetime.datetime.now(), values[0], values[1], values[2], values[3] ,values[4], values[5])) cur.close() db.commit()
true
073336cf5dafa02e3eef78460604fb7ec33d0945
Python
Moenupa/MINEWORLDY
/titanic/sklearnimputer.py
UTF-8
2,209
2.609375
3
[]
no_license
# -*- coding: utf-8 -*- # @Author: Moenupa 2019/05/21 import pandas as pd import numpy as np from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer, SimpleImputer from sklearn.impute import KNNImputer def func_procs(): try: dir = "C:\\Github\\MINEWORLDY\\titanic\\" X_train = pd.read_csv(open(dir + "train.csv")).loc[ :, ["PassengerId", "Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"] ] y_train = pd.read_csv(open(dir + "train.csv")).loc[ :, "Survived" ] X_test = pd.read_csv(open(dir + "test.csv")).loc[ :, ["PassengerId", "Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"] ] except ValueError: print("VE") except FileNotFoundError: print("FE") X_train.loc[X_train['Sex']=='male','Sex'] = 1 X_train.loc[X_train['Sex'] == 'female', 'Sex'] = 2 X_train.loc[X_train['Embarked'] == 'S', 'Embarked'] = 1 X_train.loc[X_train['Embarked'] == 'C', 'Embarked'] = 2 X_train.loc[X_train['Embarked'] == 'Q', 'Embarked'] = 3 X_test.loc[X_test['Sex'] == 'male','Sex'] = 1 X_test.loc[X_test['Sex'] == 'female', 'Sex'] = 2 X_test.loc[X_test['Embarked'] == 'S', 'Embarked'] = 1 X_test.loc[X_test['Embarked'] == 'C', 'Embarked'] = 2 X_test.loc[X_test['Embarked'] == 'Q', 'Embarked'] = 3 # 数据映射 #imp_mean = IterativeImputer(random_state=0) #imp_mean.fit(X_train) #imp_mean.transform(X_train) #imp_mean.transform(X_test) age_median = X_train["Age"].median() fare_median = X_train["Fare"].median() emb_median = X_train["Embarked"].median() X_train = X_train.fillna({'Age': age_median, 'Fare': fare_median, 'Embarked': emb_median}) X_test = X_test.fillna({'Age':age_median, 'Fare':fare_median, 'Embarked':emb_median}) X_train = X_train.to_csv(dir + "X_train_median_proc.csv") X_test = X_test.to_csv(dir + "X_test_median_proc.csv") print("Output Complete.") #X_train_child = X_train.loc[X_test['Age'] <= 18, 'Age'] if __name__ == "__main__": func_procs()
true
da7348722198a214518ffb9dc426529b8a862c6f
Python
shazack/LeetCode-Pythonsolns-
/reverseVowels.py
UTF-8
1,186
3.578125
4
[]
no_license
class Solution(object): def reverseVowels(self, s): vowels = ('a','e','i','o','u','A','E','I','O','U') if len(s)==0: return "" r = list(s) start=0 end=len(s)-1 while start!=end or start+1==end: #both consonants if r[start] not in vowels and r[end] not in vowels: if start+1 == end or end-1 == start: break start += 1 end -= 1 #print "if1",start,end #one ptr - vowel one ptr - consonant elif (r[start] in vowels and r[end] not in vowels): end -= 1 #print "if2", start, end elif (r[end] in vowels and r[start] not in vowels): start += 1 #print "if3", start, end elif (r[start] in vowels and r[end] in vowels): r[start],r[end] = r[end],r[start] #print "if4", start, end if start == end or start+1==end or end-1==start: break start += 1 end -= 1 return ''.join(r)
true
fd12bbd584d6976f93c98517494ed4ea1d40eb50
Python
renukadeshmukh/Leetcode_Solutions
/142_LinkedListCycleII.py
UTF-8
1,974
4.25
4
[]
no_license
''' 142. Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Note: Do not modify the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. Follow up: Can you solve it without using extra space? ''' ''' ALGORITHM: 1. Traverse linked list using two pointers - fast and slow. 2. Move one pointer by one and other pointer by two. 3. If these pointers meet at same node then there is a loop. If pointers do not meet then linked list doesn’t have loop. 4. If a loop is found, initialize slow pointer to head, let fast pointer be at its position. 5. Move both slow and fast pointers one node at a time. 6. The point at which they meet is the start of the loop. RUNTIME COMPLEXITY: O(N) SPACE COMPLEXITY: O(1) ''' class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast = slow = head is_cycle = False while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: is_cycle = True break if is_cycle: slow = head while slow != fast: slow = slow.next fast = fast.next return slow return None
true
b54efff3d63c72f2d7678de530f8727c6ea9b594
Python
harshit0810/Acadview-Python-Assignments
/Assignment-4/solution.py
UTF-8
774
4.21875
4
[]
no_license
#QUESTION-1 list1=[23,34,553,542] print(list1[::-1]) #QUESTION-2 string1='Game Of Thrones' for i in string1: if(i.isupper()): print(i,end=' ') print() #QUESTION-3 string2=input("Enter the list:- ") string2=string2.split(',') list2=[] for i in string2: list2.append(int(i)) print(list2) #QUESTION-4 string3=input("Enter string:- ") if(string3==string3[::-1]): print("Palindromic no.") else: print("Not Palindromic no.") #QUESTION-5 import copy li1 = [1,2,[3,5],4] li2 = copy.copy(li1) print ("The original elements before shallow copying") for i in range(0,len(li1)): print (li1[i],end=" ") print("\r") li2[2][0] = 7 print ("The original elements after shallow copying") for i in range(0,len( li1)): print (li1[i],end=" ")
true
af2bce3e12318369dcd612b306c39d93518901b5
Python
joanaosoriosousa/small-python-projects
/tic-tac-toe.py
UTF-8
6,230
4.375
4
[ "MIT" ]
permissive
import random game_board = """ {} | {} | {} --------- {} | {} | {} --------- {} | {} | {} """ def display_board(board): print(game_board.format(*board)) def ask_player_name(): player1 = input("Player 1, what's your name? \n") player2 = input("Player 2, what's your name? \n") return player1, player2 # Function that selects randomly which is thr first player def choose_first(): return random.randint(1, 2) # Function that saves the input player def player_marker(player1): available_choices = ['X', 'O'] # While the result is not X or O, it keeps asking for the correct input. while True: if (player1 := input(f'{first_player}, please select X or O: ')) not in available_choices: print(f'\nSorry {first_player}, but you did not select X or O. Please try again.') else: player2 = 'X' if player1 == 'O' else 'O' return player1, player2 # Function that receives the user choice 'X' or 'O' and position 1-9 and updates the board def place_marker(board, marker, position): board[position-1] = marker display_board(board) return board def player_position(board, name): position = 0 while True: try: position = int(input(f'{name}, please choose a position (1-9): ')) except ValueError: print(f'\nSorry {name}, but you did not select a position between 1 and 9. Please try again.') continue # Check if the input position is a digit between 1 and 9 if not 1 <= position <= 9: print(f'\nSorry {name}, but you did not select a position between 1 and 9. Please try again.') continue # Check if the position is not available taken if board[position-1] != ' ': print(f'\nSorry {name}, but that position is already taken. Please try again.') continue else: break return position # Function that checks if the player has won. Returns True if yes. def win_check(board, marker): # Check diagonals if board[0] == marker and board[4] == marker and board[8] == marker: return True if board[2] == marker and board[4] == marker and board[6] == marker: return True # Check horizontal positions if board[0] == marker and board[1] == marker and board[2] == marker: return True if board[3] == marker and board[4] == marker and board[5] == marker: return True if board[6] == marker and board[7] == marker and board[8] == marker: return True # Check vertical positions if board[0] == marker and board[3] == marker and board[6] == marker: return True if board[1] == marker and board[4] == marker and board[7] == marker: return True if board[2] == marker and board[5] == marker and board[8] == marker: return True return False # Function that checks if the board is full. Returns True if full, False otherwise. def full_board_check(board): print(board) for position in board: # The board is not full. There is at least one position available. if position == ' ': return False # The board is full. return True # Function that asks the player if they want to play again and returns True if they want def replay(): choice = ' ' available_choices = ['Y', 'N'] while True: choice = input('Would you like to play again? Please select Y or N: \n') if choice not in available_choices: print('Sorry, but you did not select Y or N. Please try again.') elif choice == 'Y': return True else: return False # MAIN print('Welcome to Tic Tac Toe Game!') # Show the board index positions positions_board = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] display_board(positions_board) # Begin the game with an empty board board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] playing = True game_on = True while playing: # Randomly selecting which player is playing first p1_name, p2_name = ask_player_name() if choose_first() == 1: first_player = p1_name second_player = p2_name print(f"\n{p1_name} is playing first.") else: first_player = p2_name second_player = p1_name print(f"\n{p2_name} is playing first.") # The first player chooses the marker X or O first_marker, second_marker = player_marker(first_player) while game_on: # FIRST PLAYER'S TURN # First Player chooses the position to place the marker first_position = player_position(board, first_player) # The board is updated board = place_marker(board, first_marker, first_position) # Check if the first player has won the game if win_check(board, first_marker): print(f'Congratulations, {first_player}! You won!\n') if replay(): board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] break else: playing = False break # Check if all the positions are completed if full_board_check(board): print('GAME OVER') if replay(): board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] break else: playing = False break # SECOND PLAYER'S TURN second_position = player_position(board, second_player) board = place_marker(board, second_marker, second_position) if win_check(board, second_marker): print(f'Congratulations, {second_player}! You won!\n') if replay(): board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] break else: playing = False break # Check if all the positions are completed if full_board_check(board): print('GAME OVER') if replay(): board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] break else: playing = False break # if __name__ == '__main__': # main()
true
006ca52082311ef223ecdb1ebb36ecb59e540c04
Python
EduardoAlbert/python-exercises
/Mundo 2 - Estruturas de controle/057-065 Estrutura de repetição while/ex065.py
UTF-8
449
3.71875
4
[]
no_license
opcao = '' c = 0 soma = 0 lista = [] media = 0 while opcao in 'S': valor = int(input('\033[36mDigite um número: ')) lista.append(valor) c += 1 soma += valor opcao = str(input('\033[30mQuer continuar [S|N]? ')).strip().upper()[0] media = soma / c print('\033[31mA média entre todos o valores é {}'.format(media)) print('\033[33mO maior valor é {}'.format(max(lista))) print('\033[34mO menor valor é {}'.format(min(lista)))
true
e2d3d22f35f4c8c976941e4a3a082eb6de73133d
Python
peskin55/PythonProgramming1
/Zachary_Peskin_Final_Programming_Assignment.py
UTF-8
3,185
2.96875
3
[]
no_license
#!/usr/bin/env python from bs4 import BeautifulSoup from re import findall from urllib.parse import urljoin from urllib.parse import urlparse from html.parser import HTMLParser from urllib.request import urlopen class Vocab(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) self.url = url self.links = [] def handle_starttag(self, tag, attrs): if tag == 'a': for attribs in attrs: if attribs[0] == "href": absolute = urljoin(self.url, attribs[1]) if absolute[:4] == 'http': self.links.append(absolute) def getlinks(self): return self.links def decode_url(url): analysis = urlopen(url).read().decode() importer = Vocab(url) importer.feed(analysis) finished = importer.getlinks() return finished has_been_viewed = set() def parse_dictionary(url): vocab = [] for link in range(len(url)): path = urlparse(url[link]).path word = path[8:] print("Parsing info for " + word + ".") vocab.append([word, ""]) return vocab def delete_duplicates(url): new_list = [] global has_been_viewed unique = decode_url(url) unique.sort() has_been_viewed.add(url) for uniq in unique: if uniq not in has_been_viewed: try: has_been_viewed.add(uniq) if findall("http://dictionary.reference.com/browse/+",uniq) != []: new_list.append(uniq) except: pass return new_list def change_definition(list): terms = [] for n in range(len(list)): terms.append(list[n][0]) update_vocab = input("Would you like to update a definition (Y/N)? ") while update_vocab in ["Y", "Yes", "y", "yes"]: term = input("Term: ") if term in terms: index = terms.index(term) list.pop(index) new_def = input("Definition: ") list.insert(index, [term,new_def]) else: print("ERROR! Term not found.") return change_definition(list) edited_list = list return edited_list story_path = input("What's the short story path? ") full_url = "http://classicshorts.com/stories/" + story_path + ".html" try: test = urlopen(full_url) deflist = delete_duplicates(full_url) if len(deflist) > 0: vocablist = parse_dictionary(deflist) print("Short story found. There are " + str(len(vocablist)) + " unique vocabulary words.") updated_list=change_definition(vocablist) file_export = input("What would you like to save the file as? ") outfile = open(file_export,'w') words = [] for k in range(len(vocablist)): words.append(vocablist[k][0]) cell_size = len(max(words, key = len)) row_format = "{:<" + str(cell_size) + "} - {}\n" for line in range(len(updated_list)): outfile.writelines(row_format.format(updated_list[line][0],updated_list[line][1])) print("File saved!") else: print("Short story found. There are no vocabulary words.") except: print("Short story not found.")
true
b4a42fb58d1ef59e54a3be25ac257f0b53bd33cf
Python
amolpandit38/fingercursor
/handTrackingModule.py
UTF-8
4,363
3.140625
3
[]
no_license
"""------------------Creating Hand trackig Package----------------------------""" import cv2 import mediapipe as np import time import math """-------------------------------Creation of Hand_Detection Class---------------------------------""" """ Methods inside Hand Detection Class 1.findHands() :- Detect No of Hands Inside The Frame 2.FindPosition() :- Find location Of Hands Points 3. FingerUp() :- Count Number Of Finger Up 4. Distance() :- Find Distance Between Two Points Of Finger's """ class handDetector: def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5): self.mode = mode self.maxHands = maxHands self.detectionCon = detectionCon self.trackCon = trackCon self.npHands = np.solutions.hands self.hands = self.npHands.Hands( self.mode, self.maxHands, self.detectionCon, self.trackCon ) self.npDraw = np.solutions.drawing_utils self.tipIds = [4, 8, 12, 16, 20] def findHands(self, img, draw=True): imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.results = self.hands.process(imgRGB) if self.results.multi_hand_landmarks: for handLMS in self.results.multi_hand_landmarks: if draw: self.npDraw.draw_landmarks( img, handLMS, self.npHands.HAND_CONNECTIONS ) return img def findPosition(self, img, handNo=0, draw=True): xList = [] yList = [] bbox = [] self.lmlist = [] if self.results.multi_hand_landmarks: myhand = self.results.multi_hand_landmarks[handNo] for id, lm in enumerate(myhand.landmark): h, w, c = img.shape cx, cy = int(lm.x * w), int(lm.y * h) # print(id,cx,cy) xList.append(cx) yList.append(cy) self.lmlist.append([id, cx, cy]) if draw: cv2.circle(img, (cx, cy), 7, (255, 0, 255), cv2.FILLED) Xmin, Xmax = min(xList), max(xList) Ymin, Ymax = min(yList), max(yList) bbox = Xmin, Ymin, Xmax, Ymax if draw: cv2.rectangle( img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2 ) return self.lmlist, bbox def fingerUp(self): finger = [] # Thumb if self.lmlist[self.tipIds[0]][1] < self.lmlist[self.tipIds[0] - 1][1]: finger.append(0) else: finger.append(1) # 4 finger for id in range(1, 5): if self.lmlist[self.tipIds[id]][2] < self.lmlist[self.tipIds[id] - 2][2]: finger.append(1) else: finger.append(0) return finger def Distance(self, img, Top_1, Top_2, draw=True): x1, y1 = self.lmlist[Top_1][1:] x2, y2 = self.lmlist[Top_2][1:] cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 length = math.hypot(x1 - x2, y1 - y2) if draw: cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.circle(img, (x1, y1), 7, (255, 0, 255), cv2.FILLED) cv2.circle(img, (x2, y2), 7, (255, 0, 255), cv2.FILLED) cv2.circle(img, (cx, cy), 7, (0, 0, 255), cv2.FILLED) return (length, img, [x1, y1, x2, y2, cx, cy]) """--------------------------Main Function-----------------------------------""" def main(): pTime = 0 cTime = 0 cap = cv2.VideoCapture(0) detector = handDetector() while True: success, img = cap.read() img = detector.findHands(img) lmlist = detector.findPosition(img) if len(lmlist) != 0: print(lmlist[4]) cTime = time.time() fps = 1 / (cTime - pTime) pTime = cTime cv2.putText( img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_COMPLEX, 3, (0, 255, 170), 2 ) cv2.imshow("output", img) if cv2.waitKey(1) == 27: break if __name__ == "__main__": main()
true
e0c5795434c4aec4a669371f5cc6dbe6f6c79d33
Python
RJHarvest/book-web-scraper
/scrapeInfo.py
UTF-8
1,244
3.328125
3
[]
no_license
import requests import pandas as pd from bs4 import BeautifulSoup def main(): titles = [] prices = [] ratings = [] for i in range(1,51): html_page = requests.get(f'http://books.toscrape.com/catalogue/page-{i}.html') content = html_page.content soup = BeautifulSoup(content, 'html.parser') book_sections = soup.find_all('article', class_='product_pod') for book in book_sections: title = book.h3.a.get('title') price = book.find('p', class_='price_color').text rating = getRating(book.p.get('class')[1]) # append to array to store all titles.append(title) prices.append(price) ratings.append(rating) df = pd.DataFrame({ 'titles': titles, 'prices': prices, 'ratings': ratings, }) df.to_csv('bookinfo.csv', index=False) def getRating(strRating): if (strRating == 'One'): return 1 elif (strRating == 'Two'): return 2 elif (strRating == 'Three'): return 3 elif (strRating == 'Four'): return 4 elif (strRating == 'Five'): return 5 else: return None if __name__ == '__main__': main()
true
b593f6e13c384045c0dcdb719d6fa4003551caf8
Python
ypark54/Python
/discord_test/keyboard_test.py
UTF-8
95
2.703125
3
[]
no_license
import keyboard while True: a = keyboard.read_key() #print(a)
true
ade8e27ddc455e3e6d82dec3ecf0b01988ba42d1
Python
matiasimc/RedesNeuronales
/tarea1/src/Network.py
UTF-8
1,497
2.9375
3
[]
no_license
from Layer import * class NeuralNetwork: def __init__(self, opts): self.learningRate = opts.learningRate self.iterations = opts.iterations self.layers = [] self.layers.append(Layer(opts.input_size, opts.input_size)) for (i, c) in enumerate(opts.hidden_layers): self.layers.append(Layer(len(self.layers[len(self.layers)-1].neurons), c)) self.layers.append(OutputLayer(len(self.layers[len(self.layers)-1].neurons), opts.output_size)) def feed(self, inputs): data = inputs for l in self.layers: data = l.feed(data) def backpropagate(self, expected_output): for (i,l) in enumerate(reversed(self.layers)): if i != 0: l.backpropagate(expected_output, self.layers[len(self.layers)-i]) else: l.backpropagate(expected_output, None) def update(self, inputs): data = inputs for l in self.layers: data = l.update(data, self.learningRate) def learn(self, data_set): for i in range(self.iterations): for d in data_set: self.feed(d["input"]) self.backpropagate(d["output"]) self.update(d["input"]) def calculate(self, test): self.feed(test) return [n.output for n in self.layers[len(self.layers) -1].neurons] def predict(self,test): output = self.calculate(test) return output.index(max(output))
true
b02714461499f2c5976014c7d94bb4bfaf84a1b1
Python
LakhanShanker/TextConvertor
/speechToText.py
UTF-8
975
3.375
3
[]
no_license
import speech_recognition as speech def takeCommand(): #method to take audio r = speech.Recognizer() #recognizer class of speech recognition with speech.Microphone() as source: #taking input through microphone r.adjust_for_ambient_noise(source) #adjusting noise print("Listening.....") audio = r.listen(source) try: query = r.recognize_google(audio) #google api to recognise audio print(f"User said : {query}\n") with open('textFile.txt','a+') as t: #opening file and appending to it if 'thank you' not in query: t.write("\n" + query) #writing in file except Exception as e: print("Sorry I cannot hear this properly, Say that again please....") return "None" return query if __name__ == '__main__': #main method while(True): query = takeCommand().lower() if 'thank you' in query: exit()
true
ebc456fcb0bf5c1381cb041a38b34ca24caef050
Python
kbala42ylv/ebabot
/classes/browser.py
UTF-8
2,250
2.515625
3
[]
no_license
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.support.ui import WebDriverWait import classes.log as log import settings chromedriver_path = settings.driver_path web_headless = settings.web_headless web_profile = settings.web_profile web_implicitly_wait = settings.web_implicitly_wait web_size = settings.web_size class Browser(object): """docstring for Browser""" def __init__(self, user): super(Browser, self).__init__() self.options = webdriver.ChromeOptions() self.options.add_experimental_option("excludeSwitches", ["enable-logging"]) self.options.headless = web_headless self.options.add_argument("user-data-dir={}\\{}".format(web_profile,user['name'])) self.__web = webdriver.Chrome(chromedriver_path, options=self.options) self.__web.implicitly_wait(web_implicitly_wait) if web_size == "max": self.__web.maximize_window() else: self.__web.set_window_size(web_size[0], web_size[1]) log.write("Tarayıcı varsayılan ayarlarda açıldı.", "header") log.write("<blue>Gizli mi?:</> {}".format("Evet" if web_headless else "Hayır")) def get(self): return self.__web def wait(self, ec, seconds = 300, isNot = False): try: ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,) wait = WebDriverWait(self.__web, seconds,ignored_exceptions=ignored_exceptions) if isNot: return wait.until_not(ec) return wait.until(ec) except TimeoutException: return False def element(self, xpath, multiple = False): try: if multiple == True: element = self.__web.find_elements_by_xpath(xpath) else: element = self.__web.find_element_by_xpath(xpath) except NoSuchElementException: return False return element def switchTab(self, tab): self.__web.switch_to.window(self.__web.window_handles[tab])
true
b9ff020e560202b96093a4d1844f6f4e428a79a4
Python
Data-Tach/ML-4-e
/operations-on-opencv/ex2.py
UTF-8
207
2.5625
3
[ "MIT" ]
permissive
# Blur image import cv2 import imutils img = cv2.imread("resizeImg.png") gaussianBlur = cv2.GaussianBlur(img, (21,21), 0) cv2.imshow("gaussianBlur.png", gaussianBlur) cv2.waitKey(0) cv2.destroyAllWindows()
true
fcbd4a19dc0269f8b94b3b1b1000b79ae3a2ad7a
Python
yangyuxiang1996/leetcode
/out/production/leetcode/225.用队列实现栈.py
UTF-8
1,305
3.75
4
[]
no_license
# # @lc app=leetcode.cn id=225 lang=python3 # # [225] 用队列实现栈 # # @lc code=start from collections import deque class MyStack: def __init__(self): """ Initialize your data structure here. """ self.deque1 = deque() self.deque2 = deque() def push(self, x: int) -> None: """ Push element x onto stack. """ self.deque1.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. 这里只能利用deque的popleft方法,因此需要deque2存储 """ size = len(self.deque1) while size > 1: self.deque2.append(self.deque1.popleft()) size -= 1 tmp = self.deque1.popleft() self.deque1, self.deque2 = self.deque2, self.deque1 return tmp def top(self) -> int: """ Get the top element. """ return self.deque1[-1] def empty(self) -> bool: """ Returns whether the stack is empty. """ return len(self.deque1) == 0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty() # @lc code=end
true
7ab93dbabb0b11f2e22e6bb98cbee14e33a7c288
Python
qiufengdiewu/LPInsider
/039description2POS.py
UTF-8
2,441
2.734375
3
[ "Apache-2.0" ]
permissive
# coding=utf-8 import stanfordcorenlp import pandas as pd """ 注释一是将lncrinter的正样本作为训练集 """ def precess(description): description = description.replace('(', ' ') description = description.replace(',', ' ') description = description.replace(')', ' ') description = description.replace('.', ' ') description = description.replace("'", ' ') description = description.replace(':', ' ') description = description.replace('[', ' ') description = description.replace(']', ' ') description = description.replace('/', ' ') return description #将正负样本转换成Stanford ner可以处理的格式 if __name__ == '__main__': path = 'I:/stanford_parser/stanford-corenlp-full-2018-10-05' nlp = stanfordcorenlp.StanfordCoreNLP(path) sample = pd.read_csv('./in/pos_neg_sample.txt', sep='\t', header=None) f = open("./out/039sample2wordPOS.txt","w") for i in range(len(sample)): lncRNA = str(sample[0][i]) protein = str(sample[1][i]) description = str(sample[2][i]) sentence = precess(description) sentence_pos = nlp.pos_tag(sentence) for i in range(len(sentence_pos)): word = sentence_pos[i][0] if word == lncRNA: f.write(word +"\tlncRNA\n") elif word == protein: f.write(word+"\tprotein\n") else: pos = sentence_pos[i][1] f.write(word+"\t"+pos+"\n") nlp.close() """#注释一 if __name__ == '__main__': path = 'I:/stanford_parser/stanford-corenlp-full-2018-10-05' nlp = stanfordcorenlp.StanfordCoreNLP(path) sample = pd.read_csv('./in/pos_sample.txt', sep='\t', header=None) f = open("./out/039description2wordPOS.txt","w") for i in range(len(sample)): lncRNA = str(sample[0][i]) protein = str(sample[1][i]) description = str(sample[3][i]) sentence = precess(description) sentence_pos = nlp.pos_tag(sentence) for i in range(len(sentence_pos)): word = sentence_pos[i][0] if word == lncRNA: f.write(word +"\tlncRNA\n") elif word == protein: f.write(word+"\tprotein\n") else: pos = sentence_pos[i][1] f.write(word+"\t"+pos+"\n") nlp.close() """
true
806bb757144b41b9e12627e25277317dcea6ba31
Python
c18gour/K_book
/chapter8/8-printTime.py
UTF-8
452
3.625
4
[]
no_license
class Time: pass def printTime(time): print(str(time.hours)+':'+str(time.minutes)+':'+str(time.seconds)) currentTime = Time() currentTime.hours = 9 currentTime.minutes = 14 currentTime.seconds = 30 printTime(currentTime) class Time: def printTime(time): print(str(time.hours)+':'+str(time.minutes)+':'+str(time.seconds)) class Time: def printTime(self): print(str(self.hours)+':'+str(self.minutes)+':'+str(self.seconds))
true
ab477d85c8ff0a2b42799f6745ee6db12150118c
Python
joordan/greyhound-bus-scraper
/scrape.py
UTF-8
2,032
2.828125
3
[]
no_license
import numpy as np from selenium import webdriver from selenium.webdriver.support.ui import Select outputfile = open("output.txt","w+",encoding='utf-8') options = webdriver.ChromeOptions() options.add_argument('headless') #driver = webdriver.Chrome() driver = webdriver.Chrome(chrome_options=options) #driver.get("https://www.google.com") driver.get("http://75.126.140.163/stops/893740/Stockton_CA/arriving") #driver.implicitly_wait(10) odd = driver.find_elements_by_class_name("odd") even = driver.find_elements_by_class_name("even") a = np.array(odd) b = np.array(even) # interweave 2 list ex. [1,3] & [2,4] becomes [1,2,3,4] c = np.empty((a.size + b.size,), dtype=a.dtype) c[0::2] = a c[1::2] = b departures = c.tolist() temparr = [] select = Select(driver.find_element_by_id('select-date-stop')) for x in departures: # print(x.text) # has breaks #temparr is html row temparr[1] is location temparr = x.text.split(' ') #separation needs to be done here for row in temparr: row = row.replace('\n',' ') outputfile.write(row) outputfile.write(' ') outputfile.write('\n') # start new line for each row select = Select(driver.find_element_by_id('select-date-stop')) options = len(select.options) if (options > 1): select.select_by_index(1) tomorrow_deps = driver.find_elements_by_class_name("odd") even = driver.find_elements_by_class_name("even") if (even): a = np.array(tomorrow_deps) b = np.array(even) # interweave 2 list ex. [1,3] & [2,4] becomes [1,2,3,4] c = np.empty((a.size + b.size,), dtype=a.dtype) c[0::2] = a c[1::2] = b tomorrow_deps = c.tolist() nextday = [] for x in tomorrow_deps: nextday = x.text.split(' ') for row in nextday: row = row.replace('\n',' ') outputfile.write(row) outputfile.write(' ') driver.close()
true
a139822cec07ad589557b6938ea59d9305582c7c
Python
mohrobati/JS-Buxter
/repair/live_variables_extractor.py
UTF-8
3,265
2.75
3
[ "MIT" ]
permissive
from copy import deepcopy class LiveVariablesExtractor: def __init__(self, program): self.__program = program self.__live_variable_elements = self.__getLiveVariableElements('./configs/live_variable_elements.txt') self.__variables = [] def __getLiveVariableElements(self, path): live_variable_elements = [] file = open(path) for line in file: live_variable_elements.append(line.replace("\n", "")) return live_variable_elements def __closeScope(self, first, last): for var in self.__variables: if (not var["isDone"]) and first <= var["scope"][0] and last >= var["scope"][1]: var["scope"][1] = last var["isDone"] = True def __getTypes(self, programPoint, live_variables, runner): live_variables_types_str = "" for var in live_variables: live_variables_types_str += "typeof (" + var + ") + ' $$split$$ ' + " live_variables_str = live_variables_types_str[:len(live_variables_types_str) - len(" + $$split$$ + ")] typesCode = "\nconsole.log('%%insp '+ " + live_variables_str + " %%insp ');\n" \ "console.log('%%insp '+ " + live_variables_str + " %%insp ');\nreturn\n" typesProgram = deepcopy(self.__program) typesProgram = typesProgram[:programPoint] + \ typesCode + typesProgram[programPoint:] return runner.run(typesProgram) def extractLiveVariables(self, node, meta): if node.type in self.__live_variable_elements: first = meta.start.offset last = meta.end.offset if node.type == 'VariableDeclaration' and node.declarations[0].init and \ node.declarations[0].init.type != "ArrowFunctionExpression" \ and node.declarations[0].init.type != "FunctionExpression": self.__variables.append({"name": node.declarations[0].id.name, "scope": [first, last], "isDone": False}) elif node.type == 'ArrowFunctionExpression' or node.type == 'FunctionExpression' or node.type == 'FunctionDeclaration': for var in node.params: self.__variables.append({"name": var.name, "scope": [first, last], "isDone": True}) elif node.type == 'BlockStatement' or node.type == 'ForStatement': self.__closeScope(first, last) def getLiveVariablesUpToPoint(self, programPoint, runner, curr_variables=None): live_variables = set() types = None for var in self.__variables: if not var["isDone"]: live_variables.add(var["name"]) continue if var["scope"][0] <= programPoint <= var["scope"][1]: live_variables.add(var["name"]) if curr_variables: for var in curr_variables: if var in live_variables: live_variables.remove(var) live_variables = list(curr_variables) + list(live_variables) while None in live_variables: live_variables.remove(None) if runner: types = self.__getTypes(programPoint, live_variables, runner) return live_variables, types
true
f2f745d476bba9cd17b9ffefdce7018a9af41e01
Python
jdpatt/AoC
/2020/day_8/day_8.py
UTF-8
2,310
3.65625
4
[]
no_license
"""Day 8""" import copy from os import read from pathlib import Path from typing import Tuple class BootCodeError(Exception): ... def read_in_boot_code(): """Each line consists of an operation and an argument.""" with open(Path(__file__).parent.joinpath("input.txt")) as puzzle_input: instructions = list() for line in puzzle_input: operation, argument = line.split(" ") instructions.append( {"operation": operation, "argument": argument, "executed": False} ) return instructions def has_executed(instruction) -> bool: return instruction["executed"] def run_program(instructions) -> Tuple[int, int]: accumulator = 0 instruction_pointer = 0 while True: try: instruction = instructions[instruction_pointer] if has_executed(instruction): return -1, accumulator if instruction["operation"] == "jmp": instruction_pointer += int(instruction["argument"]) elif instruction["operation"] == "acc": accumulator += int(instruction["argument"]) instruction_pointer += 1 elif instruction["operation"] == "nop": instruction_pointer += 1 else: raise BootCodeError("Unhandled Operation") instruction["executed"] = True except IndexError: print(f"Program Completed...\t{accumulator=}") # 2060 return 0, accumulator if __name__ == "__main__": boot_code = read_in_boot_code() return_code, accumulator = run_program(copy.deepcopy(boot_code)) print(f"Value prior to repeating instructions: {accumulator}") # 1801 for index, instruction in enumerate(boot_code): if instruction["operation"] == "acc": continue # Skip running this loop. modified_boot_code = copy.deepcopy(boot_code) if instruction["operation"] == "jmp": modified_boot_code[index]["operation"] = "nop" elif instruction["operation"] == "nop": modified_boot_code[index]["operation"] = "jmp" print(f"Running program...{index}") return_code, accumulator = run_program(modified_boot_code) if return_code == 0: break
true
aa4650835a8287ce9ed7c7a6b097cabde1f18a71
Python
nickliqian/keep_learning
/KnowledgeMapping/SpiderExp/1-Code/panyu.goodjob.cn/run.py
UTF-8
699
2.6875
3
[ "MIT" ]
permissive
import requests from lxml import etree import csv url = "http://panyu.goodjob.cn/job/pos970735.html" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36", } r = requests.get(url=url) html = etree.HTML(r.text) lis = html.xpath("//ul[@class='c6']/li/text()") item = {} for li in lis: content = li.split(":") if len(content) == 1: content.append("NULL") item[content[0]] = content[1] print(item) with open("data.csv", "w", newline='', encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(item.keys()) writer.writerow(item.values())
true
1d530679716fe70c37d8e34991cce9d5045e162f
Python
piotrszleg/symbolic_manipulation
/expression.py
UTF-8
1,325
2.90625
3
[]
no_license
from itertools import zip_longest, product, accumulate from blist import sorteddict from dataclasses import dataclass, field @dataclass(unsafe_hash=True) class Expression: def matches(self, other, variables): return True def cost(self): return 1 def __lt__(self, other): return self.cost()>other.cost() def possible_transformations(self, transformations): for transformation in transformations: variables={} if transformation.matches(self, variables): yield transformation.transform(self, variables) def simplify_recursive(self, transformations, path, paths, depth, max_depth): if depth>max_depth: return for transformation in self.possible_transformations(transformations): if not transformation in paths: path.append(transformation) paths[transformation]=path transformation.simplify_recursive(transformations, path.copy(), paths, depth+1, max_depth) def simplify(self, transformations, max_depth=10): paths=sorteddict() self.simplify_recursive(transformations, [self], paths, 0, max_depth) return paths def visit(self, fn): fn(self) def replace_variables(self, variables): return self
true
32a77271e31d021b0af76d9c43df900a813f7d38
Python
1MT3J45/pyprog
/max.py
UTF-8
79
2.90625
3
[]
no_license
a = [8,5,9,6,8,4] max1 = a[0] for i in a : if i < max1: max1=i print max1
true
2596fc8ea7ceadae2dc5e3e49808bc7e00547a17
Python
jmslip/clever-historical-data
/service/calculos_geral.py
UTF-8
3,055
2.796875
3
[ "MIT" ]
permissive
from datetime import datetime, timedelta import pandas as pd from service.historico import HistoricoService from utils.clever_generics import CleverGenerics class CalculosGeral: def __init__(self) -> None: self.historico_service = HistoricoService() self.clever_generics = CleverGenerics() self.key_carteria = 'Carteira' self.key_inflacao_meta = 'Inflacao_meta' def rd_default(self, ativos, from_date, to_date): historico = self.get_historico( ativos=ativos, from_date=from_date, to_date=to_date) desvio_padrao = self.calcula_desvio_padrao(historico=historico) desvio_normalizado = desvio_padrao.apply(self.normalize) soma_desvio_normalizado = self.get_soma_desvio(desvio_normalizado) rd = dict() for chave, item in desvio_normalizado.iteritems(): rd[chave] = self.calcula_rd(item[0], soma_desvio_normalizado) return rd def get_historico(self, ativos, from_date, to_date) -> dict: historico = dict() for ativo in ativos: historico_ativo = self.historico_service.passado( ativo, to_date=to_date, from_date=from_date, model_to_json=True) if len(historico_ativo['historico']) > 0: historico[ativo] = historico_ativo else: historico[ativo] = {'historico': [{'variacao': '0.0'}]} return historico def calcula_desvio_padrao(self, historico: dict): historico_variacao = dict() for ativo in historico: variacao = [] for item in historico[ativo]['historico']: variacao.append(float(item['variacao'])) historico_variacao[ativo] = variacao self.iguala_tamanho_listas_historico(historico_variacao) df = pd.DataFrame(historico_variacao) dp = df.std() return pd.DataFrame(dp).transpose() def iguala_tamanho_listas_historico(self, historico_variacao: dict): maior = 0 for chave in historico_variacao: aux = len(historico_variacao[chave]) if (aux > maior): maior = aux for chave in historico_variacao: if len(historico_variacao[chave]) < maior: for i in range(maior - len(historico_variacao[chave])): historico_variacao[chave].append(0.0) def get_soma_desvio(self, desvio): soma_desvio_series = desvio.sum(axis=0) soma_desvio = soma_desvio_series.values return soma_desvio[0] def calcula_rd(self, desvio_normalizado, soma_desvio_normalizado): return (desvio_normalizado / soma_desvio_normalizado) def normalize(self, x): if x.item() == 0.0: return 0.0 return 1/x def get_from_and_to_date(self): from_date = self.clever_generics.data_formato_banco( (datetime.today() + timedelta(days=-365*2))) to_date = self.clever_generics.data_formato_banco(datetime.today()) return from_date, to_date
true
c3459f21f5be23e39a8cd31008b0b8f4bfa8d405
Python
bitgrease/python_bases_exercises_1
/Chapter10Ex/10.3Ex/Dog.py
UTF-8
444
4.125
4
[]
no_license
class Dog: species = "Canis Familiaris" def __init__(self, age, name): self.age = age self.name = name def __str__(self): return f"{self.name} is {self.age} years old." def speak(self, sound): return f"{self.name} says {sound}." class GoldenRetriever(Dog): def speak(self, sound="Bark"): return super().speak(sound) gr = GoldenRetriever(13, "Dave") print(gr) print(gr.speak())
true
c7fd0888b68ae03ac5597c632dd23fd0a5c7f337
Python
gurlwithcurlz/hackday_django_test
/backend/power_analysis/models.py
UTF-8
1,502
2.765625
3
[]
no_license
from django.db import models import numpy as np from scipy.stats import norm, ttest_ind, ttest_ind_from_stats def binomial_std(n, p): """Calculate the standard deviation of the sample i.e. sqrt( var(X/n) ) or standard error.""" return np.sqrt(p*(1 - p)/n) # Create your models here. class PowerAnalysis(models.Model): base_conversion = models.FloatField() a_grade_proportion = models.FloatField() uplift = models.FloatField() days_max = models.IntegerField() calls_per_day = models.IntegerField() def calculate_power_analysis(self): avg_conversion = self.base_conversion A_conversion = self.base_conversion * (1 + self.uplift) n_non_A = self.calls_per_day * (1 - self.a_grade_proportion) n_A = self.calls_per_day * self.a_grade_proportion days_list = range(2, self.days_max) confidence = [] nAs_sig = [] p_sig = [0.80, 0.85, 0.90, 0.95, 0.99] for days in days_list: t, p = ttest_ind_from_stats( avg_conversion, binomial_std(n_non_A, avg_conversion), days , A_conversion, binomial_std(n_A, A_conversion), days, equal_var=False ) confidence.append(1 - p) nAs_sig.append(n_A * days) first_day = np.array(days_list)[np.where(np.array(confidence)>=0.95)][0] nAs_firstday = np.array(nAs_sig)[np.where(np.array(confidence)>=0.95)][0] return first_day, np.round(nAs_firstday)
true
05f3075883fb76081dab850a71ca33c2162d4a6a
Python
talkowski-lab/rCNV2
/data_curation/other/curate_gnomad_sv_gene_counts.py
UTF-8
3,058
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020 Ryan L. Collins <rlcollins@g.harvard.edu> # and the Talkowski Laboratory # Distributed under terms of the MIT license. """ Curates counts of functional SVs from gnomAD-SV VCF """ import pandas as pd import numpy as np import argparse from os.path import splitext import pysam import subprocess def main(): """ Main block """ # Parse command-line arguments and options parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--gnomad-sv-vcf', help='gnomad-SV VCF. Required.', required=True) parser.add_argument('--genes', help='list of gene symbols to consider. Required.', required=True) parser.add_argument('-o', '--outfile', help='Path to output tsv file. [default: ' + 'stdout]', default='stdout') parser.add_argument('-z', '--gzip', action='store_true', help='Compress ' + 'output tsv file with gzip. [Default: do not compress]') args = parser.parse_args() gz_suf = 'gz gzip'.split() # Open connection to outfile if args.outfile in '- stdout'.split(): outfile = stdout else: if splitext(args.outfile)[-1].replace('.' ,'') in gz_suf: outfile_path = splitext(args.outfile)[0] else: outfile_path = args.outfile outfile = open(outfile_path, 'w') # Build dict of genes & counts zeros = {'lof_any' : 0, 'lof_del' : 0, 'lof_other' : 0, 'cg' : 0, 'ied' : 0} gdict = {g.rstrip() : zeros.copy() for g in open(args.genes).readlines()} # Parse VCF for sv in pysam.VariantFile(args.gnomad_sv_vcf).fetch(): if 'PASS' not in sv.filter: continue if 'PROTEIN_CODING__LOF' in sv.info.keys(): for gene in sv.info.get('PROTEIN_CODING__LOF', []): if gene in gdict.keys(): gdict[gene]['lof_any'] += 1 if sv.info['SVTYPE'] == 'DEL': gdict[gene]['lof_del'] += 1 else: gdict[gene]['lof_other'] += 1 if 'PROTEIN_CODING__COPY_GAIN' in sv.info.keys(): for gene in sv.info.get('PROTEIN_CODING__COPY_GAIN', []): if gene in gdict.keys(): gdict[gene]['cg'] += 1 if 'PROTEIN_CODING__DUP_LOF' in sv.info.keys(): for gene in sv.info.get('PROTEIN_CODING__DUP_LOF', []): if gene in gdict.keys(): gdict[gene]['ied'] += 1 # Write to outfile header = '\t'.join('#gene lof_any lof_del lof_other cg ied'.split()) outfile.write(header + '\n') for gene, gdat in gdict.items(): gline = gene + '\t' + '\t'.join([str(x) for x in gdat.values()]) outfile.write(gline + '\n') outfile.close() # Gzip output, if optioned if args.gzip: subprocess.run(['gzip', '-f', outfile_path]) if __name__ == '__main__': main()
true
cf8a29c6366c0759d6b1c4c33dda9e658af5c03c
Python
ArakelyanEdgar/MachineLearningAlgorithms
/SVR/svr.py
UTF-8
1,089
3.125
3
[]
no_license
#SVR #importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.formula.api as sm from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import PolynomialFeatures from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.svm import SVR #retrieve dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values #featureScale X X_Scaler = StandardScaler() y_Scaler = StandardScaler() X = X_Scaler.fit_transform(X) y= y.reshape(-1,1) y = y_Scaler.fit_transform(y) #svr regressor regressor = SVR(kernel='rbf') regressor.fit(X, y) #visualizing SVR results plt.scatter(X, y, color='red') plt.plot(X, regressor.predict(X), color='blue') plt.title('SVR Regression') plt.xlabel('LEVEL') plt.ylabel('SALARY') plt.show() print(y_Scaler.inverse_transform( regressor.predict(X_Scaler.transform(np.array([[6.5]])) )))
true
34dc9e5bc782e41718c86374e453af8f6c266a12
Python
simuxs123/Python
/exercise/exercise9.py
UTF-8
522
3.734375
4
[]
no_license
import random a = random.randint(1, 9) kiek=0; while True: inpt=input("Guess the number:") if inpt=="exit": break if inpt.isnumeric(): if a==int(inpt): print("Corect, you did",kiek,"guesses") print("Play again") a = random.randint(1, 9) kiek=0; else: kiek += 1 if int(inpt)>a: print("To high") else: print("To low") else: print("Enter the number or exit")
true
7607d066f6dcd9cd9fd4efb25191d435f69f6135
Python
lukas-manduch/spoj
/ADDREV/adding_reversed_numbers.py
UTF-8
132
3.296875
3
[]
no_license
i = int(input()) while i > 0: i -= 1 arr = input().split() print(int(str(int(arr[0][::-1]) + int(arr[1][::-1]))[::-1]))
true
491619af3190e0edbde90d9c3e045578a84704f4
Python
rodrigocarlos2/TermoGeralPA
/source.py
UTF-8
183
3.5
4
[]
no_license
a1 = input('Write the first name: ') r = input('Write the reason: ') n = input('Write the wished element number: ') an = a1+(n-1)*r print(an) while a1<=an: print(a1), a1 += r
true
906ebfcb9c624728e45a9f57ec87d4f99d6657a8
Python
marcosD67/HackerEarth
/MayEasy/subsets.py
UTF-8
101
2.734375
3
[]
no_license
#Result: 60/100 #Solved: 2:06:45 #Mainly meant to test their testcases. n = int(input()) print(n)
true
79b5ae6675325b55477fca9f6c7a5b59fa37a2ab
Python
dbgithub/recommender-systems
/recommendationasaservice/utils.py
UTF-8
1,719
3
3
[]
no_license
""" This module is called 'utils' because it owns miscellaneous methods that can come in handy in different scenarios throughout the project/application. For instance, statistics methods, subroutines for main methods in main, etc. """ __author__ = "Aitor De Blas Granja" __email__ = "aitor.deblas@ugent.be" from main import SUGESTIOCLIENT, LOG_STATUS def delete_all_consumptions_user(userID): """ Deletes all consumptions made by user identified by userID. :param userID: int number of the user identifier :return: """ s, response = SUGESTIOCLIENT.delete_user_consumptions(userID) if s == 200 or s == 202: if LOG_STATUS is True: print "[",s,"]: All consumptions of user ",userID," were deleted successfully!" else: print "[",str(s),"]: Something went wrong." def get_rating(userID, movieID): """ Retrieves the consumption from the recommender service provided the user ID. :param userID: int number of the user identifier :param movieID: int number of the movie identifier :return: the rating. It returns a list with a single item containing tuples accessed as attributes of an object """ s, rating = SUGESTIOCLIENT.get_user_consumptions(userID, movieID) if s == 200 or s == 202: if LOG_STATUS is True: print "[", s, "]: Movie rating retrieved successfully!" return s, rating else: print "[", str(s), "]: Something went wrong." return s def decode_stars(detailfield): """ Decodes the stars rating from the provided parameter :param detailfield: string representation of the rating for a certain movie :return: float of the rating """ return float(detailfield.split(':')[3])
true
a28b98295caac98462e1e408e94ac1067aa84078
Python
rgommers/scipy
/scipy/stats/tests/test_odds_ratio.py
UTF-8
6,705
2.609375
3
[ "BSL-1.0", "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "Qhull", "BSD-3-Clause" ]
permissive
import pytest import numpy as np from numpy.testing import assert_equal, assert_allclose from .._discrete_distns import nchypergeom_fisher, hypergeom from scipy.stats._odds_ratio import odds_ratio from .data.fisher_exact_results_from_r import data class TestOddsRatio: @pytest.mark.parametrize('parameters, rresult', data) def test_results_from_r(self, parameters, rresult): alternative = parameters.alternative.replace('.', '-') result = odds_ratio(parameters.table) # The results computed by R are not very accurate. if result.statistic < 400: or_rtol = 5e-4 ci_rtol = 2e-2 else: or_rtol = 5e-2 ci_rtol = 1e-1 assert_allclose(result.statistic, rresult.conditional_odds_ratio, rtol=or_rtol) ci = result.confidence_interval(parameters.confidence_level, alternative) assert_allclose((ci.low, ci.high), rresult.conditional_odds_ratio_ci, rtol=ci_rtol) # Also do a self-check for the conditional odds ratio. # With the computed conditional odds ratio as the noncentrality # parameter of the noncentral hypergeometric distribution with # parameters table.sum(), table[0].sum(), and table[:,0].sum() as # total, ngood and nsample, respectively, the mean of the distribution # should equal table[0, 0]. cor = result.statistic table = np.array(parameters.table) total = table.sum() ngood = table[0].sum() nsample = table[:, 0].sum() # nchypergeom_fisher does not allow the edge cases where the # noncentrality parameter is 0 or inf, so handle those values # separately here. if cor == 0: nchg_mean = hypergeom.support(total, ngood, nsample)[0] elif cor == np.inf: nchg_mean = hypergeom.support(total, ngood, nsample)[1] else: nchg_mean = nchypergeom_fisher.mean(total, ngood, nsample, cor) assert_allclose(nchg_mean, table[0, 0], rtol=1e-13) # Check that the confidence interval is correct. alpha = 1 - parameters.confidence_level if alternative == 'two-sided': if ci.low > 0: sf = nchypergeom_fisher.sf(table[0, 0] - 1, total, ngood, nsample, ci.low) assert_allclose(sf, alpha/2, rtol=1e-11) if np.isfinite(ci.high): cdf = nchypergeom_fisher.cdf(table[0, 0], total, ngood, nsample, ci.high) assert_allclose(cdf, alpha/2, rtol=1e-11) elif alternative == 'less': if np.isfinite(ci.high): cdf = nchypergeom_fisher.cdf(table[0, 0], total, ngood, nsample, ci.high) assert_allclose(cdf, alpha, rtol=1e-11) else: # alternative == 'greater' if ci.low > 0: sf = nchypergeom_fisher.sf(table[0, 0] - 1, total, ngood, nsample, ci.low) assert_allclose(sf, alpha, rtol=1e-11) @pytest.mark.parametrize('table', [ [[0, 0], [5, 10]], [[5, 10], [0, 0]], [[0, 5], [0, 10]], [[5, 0], [10, 0]], ]) def test_row_or_col_zero(self, table): result = odds_ratio(table) assert_equal(result.statistic, np.nan) ci = result.confidence_interval() assert_equal((ci.low, ci.high), (0, np.inf)) @pytest.mark.parametrize("case", [[0.95, 'two-sided', 0.4879913, 2.635883], [0.90, 'two-sided', 0.5588516, 2.301663]]) def test_sample_odds_ratio_ci(self, case): # Compare the sample odds ratio confidence interval to the R function # oddsratio.wald from the epitools package, e.g. # > library(epitools) # > table = matrix(c(10, 20, 41, 93), nrow=2, ncol=2, byrow=TRUE) # > result = oddsratio.wald(table) # > result$measure # odds ratio with 95% C.I. # Predictor estimate lower upper # Exposed1 1.000000 NA NA # Exposed2 1.134146 0.4879913 2.635883 confidence_level, alternative, ref_low, ref_high = case table = [[10, 20], [41, 93]] result = odds_ratio(table, kind='sample') assert_allclose(result.statistic, 1.134146, rtol=1e-6) ci = result.confidence_interval(confidence_level, alternative) assert_allclose([ci.low, ci.high], [ref_low, ref_high], rtol=1e-6) @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided']) def test_sample_odds_ratio_one_sided_ci(self, alternative): # can't find a good reference for one-sided CI, so bump up the sample # size and compare against the conditional odds ratio CI table = [[1000, 2000], [4100, 9300]] res = odds_ratio(table, kind='sample') ref = odds_ratio(table, kind='conditional') assert_allclose(res.statistic, ref.statistic, atol=1e-5) assert_allclose(res.confidence_interval(alternative=alternative), ref.confidence_interval(alternative=alternative), atol=2e-3) @pytest.mark.parametrize('kind', ['sample', 'conditional']) @pytest.mark.parametrize('bad_table', [123, "foo", [10, 11, 12]]) def test_invalid_table_shape(self, kind, bad_table): with pytest.raises(ValueError, match="Invalid shape"): odds_ratio(bad_table, kind=kind) def test_invalid_table_type(self): with pytest.raises(ValueError, match='must be an array of integers'): odds_ratio([[1.0, 3.4], [5.0, 9.9]]) def test_negative_table_values(self): with pytest.raises(ValueError, match='must be nonnegative'): odds_ratio([[1, 2], [3, -4]]) def test_invalid_kind(self): with pytest.raises(ValueError, match='`kind` must be'): odds_ratio([[10, 20], [30, 14]], kind='magnetoreluctance') def test_invalid_alternative(self): result = odds_ratio([[5, 10], [2, 32]]) with pytest.raises(ValueError, match='`alternative` must be'): result.confidence_interval(alternative='depleneration') @pytest.mark.parametrize('level', [-0.5, 1.5]) def test_invalid_confidence_level(self, level): result = odds_ratio([[5, 10], [2, 32]]) with pytest.raises(ValueError, match='must be between 0 and 1'): result.confidence_interval(confidence_level=level)
true
22118959ff67e0105463724ec921e4874058ea06
Python
marchampson/cbir_api
/cbir/quantize_example.py
UTF-8
1,222
2.703125
3
[]
no_license
from __future__ import print_function from mainwaring.ir import BagOfVisualWords from sklearn.metrics import pairwise import numpy as np # rand gen vocabular/cluster centers along with the feature vectors, we'll generate 10 FV containing # 6 real-valued entries, along with a codebook containing 3 'visual words' np.random.seed(42) vocab = np.random.uniform(size=(3,6)) features = np.random.uniform(size=(10,6)) print("[INFO] vocabulary:\n{}\n".format(vocab)) print("[INFO] features:\n{}\n".format(features)) # init bovw - it will contain 3 entries one for each of the possible visual words hist = np.zeros((3,), dtype="int32") # loop over the individual feature vectors for (i, f) in enumerate(features): # compute euclidean dist between current fv and teh 3 visual words; then, find the index of the # word with teh smallest distance D = pairwise.euclidean_distances(f.reshape(1, -1),Y=vocab) j = np.argmin(D) print("[INFO] Closest visual word to feature #{}: {}".format(i, j)) hist[j] += 1 print("[INFO] Updated histogram: {}".format(hist)) #apply our BOVW class bovw = BagOfVisualWords(vocab, sparse=False) hist = bovw.describe(features) print("[INFO] BOVW histogram: {}".format(hist))
true
958a6d467305cfa427ee92c93773ebd60f38d986
Python
RVaishnavi-999/Advanced-Python-Programs
/Employee payroll programpy.py
UTF-8
701
3.890625
4
[]
no_license
# -*- coding: utf-8 -*- """ @author: Vaishnavi R """ """8. Program to calculate the employee weekly payroll using method overloading concept.""" class emp: def weekly_pay(self,whrs=None,pay=None,ohrs=None): if whrs!=None and pay!=None and ohrs!=None: total=whrs*pay+ohrs*pay print("total pay of employee is ",total) elif whrs!=None and pay!=None: total=whrs*pay print("total pay of employee is",total) e=emp() whrs=eval(input("enter hours worked by employee: ")) ohrs=eval(input("enter the hours worked over time: ")) pay=eval(input("enter the pay per hour: ")) if ohrs>0: e.weekly_pay(whrs,pay,ohrs) else: e.weekly_pay(whrs,pay)
true
ad0ed6bfab03bb63177aaba00ed38c565acfe944
Python
jnaneshjain/PythonProjects
/com/underscorepython/pythonunderscoreinterpretor.py
UTF-8
165
3.0625
3
[]
no_license
''' >>> 5 + 4 9 >>> _ # stores the result of the above expression 9 >>> _ + 6 15 >>> _ 15 >>> a = _ # assigning the value of _ to another variable >>> a 15 '''
true
971fef3cce531b8247a4d35a8d3ea1e5cf30fb80
Python
gitman00/Pygame
/Demo Collision/collision_file.py
UTF-8
952
2.953125
3
[]
no_license
import pygame as p p.init() SCREEN_WIDTH,SCREEN_HEIGHT=1100,2250 SCREEN=p.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) rect1=p.Rect(500,500,200,200) x_speed,y_speed=5,-4 rect2=p.Rect(400,1000,200,400) rect2_speed=2 def moving_rect(): global x_speed,y_speed rect1.x += x_speed rect1.y += y_speed if rect1.right >= SCREEN_WIDTH or rect1.left<= 0: x_speed *= -1 if rect1.bottom >= SCREEN_HEIGHT or rect1.top<= 0: y_speed *= -1 collision_tolerance=10 if rect1.colliderect(rect2): if abs(rect2.top-rect1.bottom)< collision_tolerance: y_speed *= -1 if abs(rect2.bottom-rect1.top)< collision_tolerance: y_speed *= -1 if abs(rect2.right-rect1.left)< collision_tolerance: x_speed *= -1 if abs(rect2.left-rect1.right)< collision_tolerance: x_speed *= -1 p.draw.rect(SCREEN,((255,0,0)),rect1) p.draw.rect(SCREEN,((0,0,255)),rect2) On=True while On: SCREEN.fill((0,0,0)) moving_rect() p.display.update()
true
ab0061747c4085c779edaba1567fb455198e9acf
Python
JZDBB/tensorflow
/basis/session_basis.py
UTF-8
597
3.421875
3
[]
no_license
# tf.Session() # 创建一个会话,当上下文管理器退出时会话关闭和资源释放自动完成。 # # tf.Session().as_default() # 创建一个默认会话,当上下文管理器退出时会话没有关闭,还可以通过调用会话进行run()和eval()操作. import tensorflow as tf a = tf.constant(1.0) b = tf.constant(2.0) with tf.Session() as sess: print(a.eval()) print(b.eval(session=sess)) a = tf.constant(1.0) b = tf.constant(2.0) with tf.Session().as_default() as sess: print(a.eval()) # sess.close() 加上这句话效果就一样啦 print(b.eval(session=sess))
true
bf847af14dbea2c27ea4ab879d495b3e6da0134c
Python
JY-Justin/pydailynotes
/pach/test_002.py
UTF-8
2,442
3.734375
4
[]
no_license
# python 解析库 lxml from lxml import etree text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> ''' # 构建一个 html 对象 html = etree.HTML(text) # print(html) # 将其转换为 bytes 对象 result = etree.tostring(html) # 进行 bytes 到 str 的转换 # print(result.decode('utf-8')) # print(type(result.decode('utf-8'))) # 也可以直接读取文本进行解析 html = etree.parse('./test.html', etree.HTMLParser()) result = etree.tostring(html) # print(result.decode('utf-8')) # 如果我们要选取所有的节点 可以这样进行 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//*') # print(result) # 如果我们只想获取其中的某一种节点 例如 li html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//li') # print(result) # print(result[0]) # 获取子节点以及孙子节点 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//li/a') # print(result) # // 获取所有的孙子节点 / 获取直接的子节点 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//ul//a') # print(result) # 首先选中 href 是 link4.html 的 a 节点,然后再获取其父节点,然后再获取其 class 属性 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//a[@href="link4.html"]/../@class') # print(result) # 同时我们也可以通过 parent:: 来获取父节点 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//a[@href="link4.html"]/parent::*/@class') # print(result) # 属性匹配 要选取 class 为 item-1 的 li 节点 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//li[@class="item-0"]') # print(result) # 文本获取: 用 XPath 中的 text() 方法可以获取节点中的文本 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//li[@class="item-0"]/text()') # print(result) # 先到 a 节点下面再获取文本 html = etree.parse('./test.html', etree.HTMLParser()) result = html.xpath('//li[@class="item-0"]/a/text()') print(result)
true
2bfee52174d8686c1042c2d372a6c78f8a38b48b
Python
Hanler/Project-bio-beta
/animation.py
UTF-8
819
2.875
3
[]
no_license
from PyQt5 import QtCore class Animation(): @property def center(self): return self._center def animation(self, lb, x_center, y_center, parent): initial_rect = QtCore.QRect( x_center, y_center, 171, 171 ) zoom_factor = 1.5 final_rect = QtCore.QRect( x_center, y_center, int(initial_rect.width() * zoom_factor), int(initial_rect.height() * zoom_factor), ) final_rect.moveCenter(initial_rect.center()) an = QtCore.QPropertyAnimation(lb, b"geometry", parent) an.setEasingCurve(QtCore.QEasingCurve.InOutSine) an.setStartValue(initial_rect) an.setEndValue(final_rect) an.setDuration(2500) return an
true
185b94d18e39bcbdbeb5e11dfb31169eb8a75e3e
Python
pulakanamnikitha/nikki
/21.py
UTF-8
56
2.828125
3
[]
no_license
a,b,c=map(int,raw_input().split()) s=b+c c=s*a print(c)
true
14852021adb74dfdc2a3ec52f39119ec2d759e15
Python
JosiahRooney/Python
/sum.py
UTF-8
99
3.3125
3
[ "MIT" ]
permissive
def sumArray(arr): sum = 0 for x in arr: sum += x return sum print sumArray([1,2,5,10,255,3])
true
afa89c20f7c3dd75db788dc8d325363bb72c369b
Python
SuperZG/MyPythonLearning
/my_first_project/day3/chapter9/demo4(持续追加).py
UTF-8
373
3.328125
3
[]
no_license
with open('D:\\inout9\\multi2.txt', 'w') as example: flag = True while flag: message = input('Input anything, quit to exit:\n') if message == 'quit': flag = False else: message = message + '\n' example.write(message) with open('D:\\inout9\\multi2.txt', 'r') as exampleread: print(exampleread.read())
true
a0bd848d8d6b45213fe6788efab634ecc4cec125
Python
SahilMund/A_ML_Cheatsheets
/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/datapreprocessingtamplete.py
UTF-8
616
2.921875
3
[]
no_license
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the data set dataset = pd.read_csv("Data.csv") #distinguishing bn independent and dependent coloumns in dataset X = dataset.iloc [:, :-1].values Y=dataset.iloc[:,3] #splitting data into test and train sets from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0) #Feature scaling """from sklearn.preprocessing import StandardScaler sc_X=StandardScaler() X_train=sc_X.fit_transform(X_train) X_test=sc_X.transform(X_test)"""
true
d1f788d554e9cea1f9656901af308bca0d431cb5
Python
chui101/covid-vis
/calculate_trends.py
UTF-8
2,982
3.171875
3
[]
no_license
#!/usr/bin/python3 import numpy from states import state_info, state_historic_data from matplotlib import pyplot def growth_rate(data, data_name='positive'): values = map(lambda x: 0 if (data_name not in x or x[data_name] is None) else x[data_name], data) nonzero = filter(lambda x: x > 0, values) y = numpy.array(list(nonzero)) return weighted_exponential_fit(numpy.arange(len(y)), y) def death_growth_rate(data): deaths = map(lambda x: 0 if ('death' not in x or x['death'] is None) else x['death'], data) nonzero = filter(lambda x: x > 0, deaths) y = numpy.array(list(nonzero)) return weighted_exponential_fit(numpy.arange(len(y)), y) def exponential_fit(x, y): return numpy.polyfit(x,numpy.log(y),1) def weighted_exponential_fit(x, y): return numpy.polyfit(x,numpy.log(y),1,w=numpy.sqrt(y)) def to_exponential_function(fit): return "y=" + str(numpy.exp(fit[1])) + "*exp(" + str(fit[0]) + "*t)" def doubling_time(data, data_name='positive'): fit = growth_rate(data, data_name) return numpy.log(2)/fit[0] if __name__ == "__main__": si = state_info() states = si.get_states() # calculate doubling time for last seven days for all tracked states doubling_time_last_seven = [] for state in states: data = state_historic_data(state).get_latest_n(7) doubling_time_last_seven.append(doubling_time(data)) pyplot.bar(range(len(states)), doubling_time_last_seven, tick_label=list(states)) pyplot.title("Average doubling time over past 7 days") pyplot.ylabel("Average doubling time (days)") fig = pyplot.gcf() fig.set_size_inches(10, 7) pyplot.show() pyplot.close() # calculate doubling time for each seven day window for all tracked states for state in ['KY',"TN","NY","IN","LA","OH", "MI"]: data = state_historic_data(state).data doubling_time_last_seven = [] if len(data) > 7: for i in range(len(data)-6): doubling_time_last_seven.append(doubling_time(data[i:i+7])) pyplot.plot(range(3,len(doubling_time_last_seven)+3), doubling_time_last_seven, label=state) pyplot.title("Average doubling time (7 day moving average, higher is better)") pyplot.ylabel("Average case doubling time (days)") pyplot.xlabel("Days since first reported case") pyplot.legend() pyplot.grid(b=True) fig = pyplot.gcf() fig.set_size_inches(10, 7) pyplot.show() pyplot.close() print("Average death doubling time in days for past 7 days of data") for state in states: data = state_historic_data(state) latest_data = data.get_latest_n(7) print(state + "," + str(doubling_time(latest_data,'death'))) print("Average case doubling time in days since 10th confirmed case") for state in states: data = state_historic_data(state) latest_data = data.get_after_n_cases(10) print(state + "," + str(doubling_time(latest_data)))
true
783648533d356a7e8db1e3e04e55b2fc61f0332a
Python
neilrobertson/BICRCode
/Baselib/genemapping/genelookup.py
UTF-8
2,683
3.09375
3
[]
no_license
# class for looking up information about a gene # so far includes: # - coordinate lookup (what coord for gene x?) # - name lookup (given gene id, provide common name?) # - interval overlap (given interval, what genes overlap?) from genemapping.coordlookup import * from datastructures.genomicintervalfinder import * class GeneLookup: def __init__(self): self._coordlookup = None self._overlaplookup = None self._poverlaplookup = None def initCoordsFromFile(self, filename, filesettings): self._coordlookup = CoordLookup() self._coordlookup.setFromFile(filename, filesettings) def initOverlapsFromCoords(self): print "converting gene coordinate lookup into overlap lookup" assert not self._coordlookup is None self._overlaplookup = GenomicIntervalFinder("Gene") self._overlaplookup.initFromCoordLookup(self._coordlookup) def initPromoterOverlapsFromCoords(self, pbounds): print "converting gene coordinate lookup into promoter lookup" assert not self._coordlookup is None self._poverlaplookup = GenomicIntervalFinder("Gene Promoters") self._poverlaplookup.initPromotersFromCoordLookup(self._coordlookup, pbounds) def lookupName(self, gid): assert not self._coordlookup is None return self._coordlookup.getName(gid) def getGeneIDsByInterval(self, chrom, start, end): if self._overlaplookup is None: self.initOverlapsFromCoords() return self._overlaplookup.lookupInterval(chrom, start, end) def getPromotersByInterval(self, chrom, start, end, promoterbounds): assert self._poverlaplookup is not None return self._poverlaplookup.lookupInterval(chrom, start, end) def promoterOverlap(self, geneid, promoterbounds, elementgif): """ looks to see whether a geneid has any of the given elements in its promoter geneid -- a gene id (str) promoterbounds -- pair (tuple) of integers (upstream, downstream) elementgif -- a GenomicIntervalFinder object with the elements to lookup """ chrom, start, end = self._coordlookup.getCoord(geneid) strand = self._coordlookup.getStrand(geneid) if strand == "1": promoterstart = start - promoterbounds[0] promoterend = start + promoterbounds[1] if strand == "-1": promoterstart = start - promoterbounds[1] promoterend = start + promoterbounds[0] return elementgif.getOverlappingIntervalCount(chrom, promoterstart, promoterend) if __name__ == "__main__": genefile = "/home/pzs/genebuilds/genelists/human-genes-ncbi36.csv" gfsettings = { "id" : 0, "strand": 2, "chrom" : 3, "start" : 4, "end" : 5 } gl = GeneLookup() gl.initCoordsFromFile(genefile, gfsettings) gl.initOverlapsFromCoords() gl.initPromoterOverlapsFromCoords((500, 1000))
true
40a64286d5cd10347dc43c6f6dbd8eefa8b2edaa
Python
shujji/iot
/snk/AnalogLight/al2.py
UTF-8
1,166
2.78125
3
[]
no_license
#!/usr/bin/env python # Example for RC timing reading for Raspberry Pi # Must be used with GPIO 0.3.1a or later - earlier verions # are not fast enough! import RPi.GPIO as GPIO, time, os import requests import time import datetime from time import gmtime, strftime DEBUG = 1 GPIO.setmode(GPIO.BCM) today = datetime.date.today() def RCtime (RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) #time.sleep(0.1) time.sleep(0.05) GPIO.setup(RCpin, GPIO.IN) # This takes about 1 millisecond per loop cycle while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return reading while True: print RCtime(4) , strftime("%m/%d/%Y" , gmtime()) , strftime("%H:%M:%S" , gmtime()) # Read RC timing using pin #18 #r = requests.post("https://thingspace.io/dweet/for/RPiRND1_analogLight", data={ 'rc_time': RCtime(4) }) r = requests.post("https://thingspace.io/dweet/for/RPiRND1_analogLight", data={ 'light': RCtime(4) , 'date': strftime("%m/%d/%Y" , gmtime()) , 'time': strftime("%H:%M:%S" , gmtime()) })
true
ec4018b16a5f78247377ce139b7117969499d5d2
Python
abhishek8899/Space-Invaders
/classes.py
UTF-8
362
2.984375
3
[]
no_license
class freeze(): def __init__(self, x, y, ti): self.x = x self.y = y self.t = ti class fire(): def __init__(self, x, y): self.x = x self.y = y class fire1(fire): def __init__(self, x, y): fire.__init__(self, x, y) class fire2(fire): def __init__(self, x, y): fire.__init__(self, x, y)
true
0a3eb7fbfb6dd0731c4f17f065d8c8e206abe293
Python
F1schGott/CSC108
/A1/admission_functions.py
UTF-8
4,545
3.9375
4
[]
no_license
"""Starter code for Assignment 1 CSC108 Summer 2018""" SPECIAL_CASE_SCHOOL_1 = 'Fort McMurray Composite High' SPECIAL_CASE_SCHOOL_2 = 'Father Mercredi High School' SPECIAL_CASE_YEAR = '2017' # Add other constants here DEGREE_LEN = 6 COURSE_LEN = 9 def is_special_case(record: str) -> bool: """Return True iff the student should be handled using the special case rules. >>> is_special_case('Jacqueline Smith,Fort McMurray Composite High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts') True >>> is_special_case('Jacqueline Smith,Father Something High School,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts') False >>> is_special_case('Jacqueline Smith,Fort McMurray Composite High,2015,MAT,90,94,ENG,92,88,CHM,80,85,BArts') False """ # Complete the body of the function here case_one = SPECIAL_CASE_SCHOOL_1 case_two = SPECIAL_CASE_SCHOOL_2 year = SPECIAL_CASE_YEAR #I renamed them to make the code shorter return ((case_one in record) or (case_two in record)) and (year in record) # Complete the rest of the functions here def get_final_mark(record: str, course_mark: str, exam_mark: str) -> float: """Return the student's final mark of the course, by calculating the average of course_mark and exam_mark in the record. A missing exam mark counts as a zero, unless the student is a special case. >>> get_final_mark('Jacqueline Smith,Fort McMurray Composite High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts', '90', '94') 92.0 >>> get_final_mark('Jacqueline Smith,Fort McMurray Composite High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts', '92', 'NE') 92.0 >>> get_final_mark('Jacqueline Smith,Fort McDonald Composite High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts', '80', 'NE') 40.0 """ if exam_mark == 'NE' and is_special_case(record): return float(course_mark) elif exam_mark == 'NE' and not is_special_case(record): return int(course_mark)/ 2 else: return (int(course_mark) + int(exam_mark))/ 2 def get_both_marks(course_record: str, course_code: str) -> str: """Return a string containing the coursework mark in the course_record if the course_code matches the course_record and the exam mark separated by a single space. Otherwise, return the empty string. >>> get_both_marks('MAT,90,94', 'MAT') '90 94' >>> get_both_marks('MAT,90,94', 'ACT') '' >>> get_both_marks('ENG,92,88', 'ENG') '92 88' """ if course_code in course_record: return course_record[4:6] + ' ' + course_record[7:9] else: return '' def extract_course(transcript: str, course_num: int) -> str: """Return the coursework mark from the transcript. The course_num represents which course to extract. The first course in the transcript being course 1, the second being course 2, etc. >>> extract_course('MAT,90,94,ENG,92,88,CHM,80,85', 1) 'MAT,90,94' >>> extract_course('MAT,90,94,ENG,92,88,CHM,80,85', 2) 'ENG,92,88' >>> extract_course('MAT,90,94,ENG,92,88,CHM,80,85', 3) 'CHM,80,85' """ return transcript[(course_num - 1)* 10 : (course_num - 1)* 10 + COURSE_LEN] def applied_to_degree(record: str, degree: str) -> bool: """Return True if and only if the student represented by the record applied to the degree. >>> applied_to_degree('Jacqueline Smith,Fort McMurray Composite High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts', 'BArts') True >>> applied_to_degree('Jacqueline Smith,Fort McMurray BComuter High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BArts', 'BCom') False >>> applied_to_degree('Jacqueline Smith,Fort McMurray BComuter High,2017,MAT,90,94,ENG,92,88,CHM,80,85,BCom', 'BCom') True """ return degree in record[-DEGREE_LEN:] def decide_admission(course_average: float, degree_cutoff: float) -> str: """Return 'accept' if the course_average is at least the degree_cutoff but below the threshold for a scholarship, 'accept with scholarship' if the course_average is at or above the threshold for a scholarship, and 'reject' if the course_average is below the degree_cutoff. >>> decide_admission(70,80) 'reject' >>> decide_admission(80,80) 'accept' >>> decide_admission(85,80) 'accept with scholarship' """ if course_average < degree_cutoff: return 'reject' elif course_average >= degree_cutoff + 5: return 'accept with scholarship' else: return 'accept' # Programer: SongQi Wang # Student number: 1003439442
true
6bc6815baa190c14aa42dd41a854930f3e6c61e2
Python
facelessuser/sublime-markdown-popups
/st3/mdpopups/coloraide/spaces/ipt.py
UTF-8
2,871
2.65625
3
[ "MIT" ]
permissive
""" The IPT color space. https://www.researchgate.net/publication/\ 221677980_Development_and_Testing_of_a_Color_Space_IPT_with_Improved_Hue_Uniformity. """ from ..spaces import Space, Labish from ..channels import Channel, FLG_MIRROR_PERCENT from ..cat import WHITES from .. import algebra as alg from ..types import Vector from typing import Tuple # The IPT algorithm requires the use of the Hunt-Pointer-Estevez matrix, # but it was originally calculated with the assumption of a slightly different # D65 white point than what we use. # # - Theirs: [0.9504, 1.0, 1.0889] -> xy chromaticity points (0.3127035830618893, 0.32902313032606195) # - Ours: [0.9504559270516716, 1, 1.0890577507598784] -> calculated from xy chromaticity points [0.31270, 0.32900] # # For a good conversion, our options were to either set the color space to a slightly different D65 white point, # or adjust the algorithm such that it accounted for the difference in white point. We chose the latter. # # ``` # theirs = alg.diag([0.9504, 1.0, 1.0889]) # ours = alg.diag(white_d65) # return alg.multi_dot([MHPE, theirs, alg.inv(ours)]) # ``` # # Below is the Hunter-Pointer-Estevez matrix combined with our white point compensation. XYZ_TO_LMS = [ [0.4001764512951712, 0.7075, -0.08068831054981859], [-0.2279865839462744, 1.15, 0.061191135138152386], [0.0, 0.0, 0.9182669691320122] ] LMS_TO_XYZ = [ [1.8503518239760197, -1.1383686221417688, 0.23844898940542367], [0.36683077517134854, 0.6438845448402356, -0.01067344358438], [0.0, 0.0, 1.089007917757562] ] LMS_P_TO_IPT = [ [0.4, 0.4, 0.2], [4.455, -4.851, 0.396], [0.8056, 0.3572, -1.1628] ] IPT_TO_LMS_P = [ [1.0000000000000004, 0.0975689305146139, 0.2052264331645916], [0.9999999999999997, -0.1138764854731471, 0.13321715836999803], [1.0, 0.0326151099170664, -0.6768871830691793] ] def xyz_to_ipt(xyz: Vector) -> Vector: """XYZ to IPT.""" lms_p = [alg.npow(c, 0.43) for c in alg.dot(XYZ_TO_LMS, xyz, dims=alg.D2_D1)] return alg.dot(LMS_P_TO_IPT, lms_p, dims=alg.D2_D1) def ipt_to_xyz(ipt: Vector) -> Vector: """IPT to XYZ.""" lms = [alg.nth_root(c, 0.43) for c in alg.dot(IPT_TO_LMS_P, ipt, dims=alg.D2_D1)] return alg.dot(LMS_TO_XYZ, lms, dims=alg.D2_D1) class IPT(Labish, Space): """The IPT class.""" BASE = "xyz-d65" NAME = "ipt" SERIALIZE = ("--ipt",) # type: Tuple[str, ...] CHANNELS = ( Channel("i", 0.0, 1.0, bound=True), Channel("p", -1.0, 1.0, bound=True, flags=FLG_MIRROR_PERCENT), Channel("t", -1.0, 1.0, bound=True, flags=FLG_MIRROR_PERCENT) ) WHITE = WHITES['2deg']['D65'] def to_base(self, coords: Vector) -> Vector: """To XYZ.""" return ipt_to_xyz(coords) def from_base(self, coords: Vector) -> Vector: """From XYZ.""" return xyz_to_ipt(coords)
true
1c4b589a00eea38377806ffdcba657aac40f3261
Python
khua19/k
/flower.py
UTF-8
261
3.84375
4
[]
no_license
import turtle window = turtle.Screen() flower=turtle.Turtle() for i in range(25): flower.forward(150) flower.left(90) flower.forward(150) flower.left(90) flower.forward(150) flower.left(90) flower.forward(150) flower.left(75)
true
5140804f171aa8d6e8306c338549ee4d7f1b2dbe
Python
rootcoma/imageglitch
/image_glitch.py
UTF-8
24,387
2.734375
3
[ "MIT" ]
permissive
import ctypes from OpenGL import GL as gl from PIL import Image import sdl2 from shader_filters import * import random DEF_WINDOW_WIDTH = 1024 DEF_WINDOW_HEIGHT = 768 class View: """ Holds coordinates for navigating ortho view """ offset = (0.0, 0.0) zoom = 1 def reset(self): self.offset = (0.0, 0.0) self.zoom = 1 class Console: """ Hold logic for dealing with console input and output """ console_prompt = ">" input_buffer = [] output_buffer = [] current_input = "" max_buffer_len = 100 line_number = 0 console_filter = None def cleanup(self): if self.console_filter: self.console_filter.cleanup_shader() self.console_filter = None def _create_shader(self): if not self.console_filter: offset = (0, 0) self.console_filter = ConsoleFilter() self.console_filter.add_str(self.console_prompt, offset) def render(self, window_dimensions): self._create_shader() offset = (0, 0) self.console_filter.render(offset, window_dimensions) def clear(self): self.line_number = 0 self.output_buffer = [] self.console_filter.clear() offset = (0, 0) self.console_filter.add_str(self.console_prompt, offset) def get_formatted_input(self, text): return "%s%s" % (self.console_prompt, text) def add_input(self, text): self._create_shader() self.input_buffer = [text] + \ self.input_buffer[:self.max_buffer_len - 1] self.add_output(self.get_formatted_input(text), update_filter=False) def add_output(self, text, update_filter=True, update_line_number=True): for t in text.split("\n"): if update_line_number: self.line_number += 1 if update_filter: self.console_filter.backspace(len(self.get_input())) self.console_filter.add_str( "%s\n%s" % (t, self.get_input()), (0, 0)) self.output_buffer = [t] + \ self.output_buffer[:self.max_buffer_len - 1] def get_output(self, num_lines): return self.output_buffer[:num_lines] def get_input(self): return self.get_formatted_input(self.current_input) def backspace(self): if self.current_input: self.console_filter.backspace() self.current_input = self.current_input[:-1] def parse_input(self, text): """ returns any commands that are detected, keeps track of input and updates output """ inputted_commands = [] txt = text self._create_shader() # Seems like first time console is opened the backquote is added # to input so for now manually removing it until I find out cause txt = txt.replace('`', '') char_width = self.console_filter.img_dimensions[0] / 16 while '\n' in txt: txt_split = txt.split('\n', 1) self.current_input += txt_split[0] self.add_input(self.current_input) curr_offset = len(self.get_input())-len(txt_split[0]) coords = ((len(self.console_prompt)+curr_offset) * char_width, 0) self.console_filter.add_str(txt_split[0], coords) self.console_filter.add_str("\n%s" % (self.console_prompt), (0, 0)) inputted_commands.append(self.current_input) self.current_input = "" txt = txt_split[1] self.current_input += txt curr_offset = len(self.current_input) - len(txt) coords = ((len(self.console_prompt)+curr_offset) * char_width, 0) self.console_filter.add_str(txt, coords) return inputted_commands class ImageGlitch: """ Image glitching class, uses opengl shaders to filters images. SDL2 window and opengl context can be created using this class """ fb_ids = { "a": -1, "b": -1, } target_texture = -1 target_fb = -1 fb_texture_map = { "a": "fb_tex", "b": "fb_tex_alt", } texture_ids = { "img": -1, "fb_tex": -1, "fb_tex_alt": -1, } img_dimensions = (-1, -1) view = View() window = None window_dimensions = (DEF_WINDOW_WIDTH, DEF_WINDOW_HEIGHT) all_filters = {} filters = [] final_filter = None console = Console() console_enabled = False frame = 0 playing = False recording = False recording_remaining_frames = -1 recording_frame_num = -1 fps = 10 last_update = sdl2.SDL_GetTicks() def __init__(self): self.init_sdl() self.all_filters = {k: v() for k, v in ALL_FILTERS.iteritems()} def filter_img(self, img, filters): """ this should destroy any existing resources if they exist, then init program for new image """ self.cleanup_img_fb() self.cleanup_image_texture() self.img_dimensions = img.size assert all(name in self.all_filters for name in filters), ( "Error, filter not found") self.filters = [self.all_filters[n] for n in filters] if not self.final_filter: self.final_filter = OrthoFilter() self.init_image_texture(img) self.init_img_fb() self.update_filtered_image(update_frame_count=False) def init_sdl(self): """ Create a window and initialize opengl """ sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 2) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_CORE) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24) sdl2.SDL_GL_SetSwapInterval(0) # 0 = no vsync self.window = sdl2.SDL_CreateWindow( "DPT GLITCH GUY", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, DEF_WINDOW_WIDTH, DEF_WINDOW_HEIGHT, sdl2.SDL_WINDOW_OPENGL | sdl2.SDL_WINDOW_SHOWN) assert self.window, "Error: Could not create window" sdl2.SDL_SetWindowResizable(self.window, True) glcontext = sdl2.SDL_GL_CreateContext(self.window) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_CULL_FACE) gl.glEnable(gl.GL_BLEND) gl.glClearColor(0.6, 0.6, 0.6, 0.0) def cleanup_img_fb(self): """ Destroy any allocated framebuffers """ for k, v in self.fb_ids.iteritems(): if v != -1: gl.glDeleteFramebuffers(1, int(v)) self.fb_ids[k] = -1 def init_img_fb(self): """ Create 2 framebuffers to use for swapping image to texture for post processing shaders """ for name in self.fb_ids: self.fb_ids[name] = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fb_ids[name]) gl.glFramebufferTexture2D( gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self.texture_ids[ self.fb_texture_map[name]], 0) assert (gl.GL_FRAMEBUFFER_COMPLETE == gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)), ( "Frame buffer %s isn't completely initialized" % (name)) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) def cleanup_image_texture(self): """ Cleanup allocated textures """ for k, v in self.texture_ids.iteritems(): if v != -1: gl.glDeleteTextures(v) self.texture_ids[k] = -1 def init_image_texture(self, img): """ allocate textures that are the size of the imported image. One will be attached to a framebuffer. """ image_bytes = img.convert("RGBA").tobytes("raw", "RGBA", 0, -1) for name in self.texture_ids: self.texture_ids[name] = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_ids[name]) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA8, img.size[0], img.size[1], 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, image_bytes) def record(self, folder_name="mov"): """ """ filename = "%s/%03d.png" % (folder_name, self.recording_frame_num) self.console.add_output( "Saved frame %s/%s" % (self.recording_frame_num + 1, self.recording_frame_num + self.recording_remaining_frames)) self.recording_frame_num += 1 self.recording_remaining_frames -= 1 if self.recording_remaining_frames <= 0: self.console.add_output("Done recording") self.recording = False self.recording_frame_num = 0 self.recording_remaining_frames = -1 image = self.get_filter_img() image.save(filename, compress_level=3) image.close() def get_filter_img(self): width = self.img_dimensions[0] height = self.img_dimensions[1] gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.target_fb) gl.glReadBuffer(gl.GL_COLOR_ATTACHMENT0) pixels = gl.glReadPixels( 0, 0, width, height, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) #gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) image = Image.frombytes("RGBA", (width, height), pixels) image = image.transpose(Image.FLIP_TOP_BOTTOM) return image def screenshot(self, filename): """ bind the last framebuffer used during filtering and copy pixels to image and save as filename """ image = self.get_filter_img() image.save(filename, compress_level=3) def update_filtered_image(self, update_frame_count=True): """ Update the image by processing it with all of the shaders. """ gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_ids['img']) current_fb = [(x, y) for x, y in self.fb_texture_map.iteritems()] for val in self.filters: gl.glBindFramebuffer( gl.GL_FRAMEBUFFER, self.fb_ids[current_fb[0][0]]) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) val.render(self.img_dimensions, self.frame) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_ids[ current_fb[0][1]]) self.target_texture = self.texture_ids[current_fb[0][1]] self.target_fb = self.fb_ids[current_fb[0][0]] current_fb = current_fb[1:] + current_fb[:1] if update_frame_count: self.frame += 1 if self.recording: self.record() #gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) def update_screen(self): """ Updates what is on the screen. """ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) # This renders the filters into an orho view to allow # scaling and offseting for preview tar_tex = self.target_texture if self.filters else self.texture_ids[ 'img'] gl.glBindTexture(gl.GL_TEXTURE_2D, tar_tex) self.final_filter.render(self.view.offset, self.view.zoom, self.window_dimensions, self.img_dimensions) # This renders the console if self.console_enabled: self.console.render(self.window_dimensions) sdl2.SDL_GL_SwapWindow(self.window) def handle_resize(self, dimensions): """ Called when the window is resized """ self.window_dimensions = dimensions def do_command(self, cmd): update_image = False update_screen = False update_frame_count = False cmd = cmd.strip() if not cmd: return False, True, False if cmd == 'clear': self.console.clear() update_screen = True elif cmd == 'shuffle': random.shuffle(self.filters) update_screen = True update_image = True self.console.add_output("Filter order shuffled.") elif cmd == 'all': self.console.add_output( "%s" % ("\n".join(sorted([name for name in ALL_FILTERS])))) update_screen = True elif cmd == 'help': self.console.add_output("You are on your own ;(") update_screen = True elif cmd[:5] == 'echo ': self.console.add_output(cmd[5:]) update_screen = True elif cmd[:4] == 'add ': target = cmd[4:] if target in self.all_filters: self.filters.append(self.all_filters[target]) self.console.add_output("Success adding filter %s." % (target)) update_image = True else: self.console.add_output("Could not find filter %s." % (target)) update_screen = True elif cmd[:4] == 'mov ': targets = cmd[4:].split(' ') target_x = None target_y = None try: target_x = int(targets[0]) target_y = int(targets[1]) except: self.console.add_output("Failed to parse int!") if target_x is not None and target_y is not None: if target_x < 0 or target_x >= len(self.filters): self.console.add_output("Target x is out of bounds!") if target_y < 0 or target_y >= len(self.filters): self.console.add_output("Target y is out of bounds!") target_x = target_y self.console.add_output( "Success, switched %s and %s." % (target_x, target_y)) if target_x != target_y: tmp = self.filters[target_y] self.filters[target_y] = self.filters[target_x] self.filters[target_x] = tmp update_image = True update_screen = True elif cmd[:5] == 'load ': target = cmd[5:] img = None try: img = Image.open(target) except: self.console.add_output("Could not load image %s" % (target)) if img is not None: filters = [k for k, v in self.all_filters.iteritems() for f in self.filters if v == f] self.filter_img(img, filters) img.close() self.console.add_output("Success, loaded image %s" % (target)) update_screen = True elif cmd[:7] == 'record ': num_frames = None try: num_frames = int(cmd[7:]) except: self.console.add_output("Failed to parse int") if num_frames is not None: self.console.add_output("Recording %s frames." % (num_frames)) self.recording = True self.recording_remaining_frames = num_frames self.recording_frame_num = 0 update_screen = True elif cmd[:4] == 'rem ': target = None if cmd[4:] == 'all': self.filters = [] self.console.add_output("Success.") update_image = True else: try: target = int(cmd[4:]) except: self.console.add_output("Could not parse int!") if target is not None: if target < 0 or target > len(self.filters): self.console.add_output("That index is out of bounds!") else: self.console.add_output("Success.") self.filters = self.filters[ :target] + self.filters[target + 1:] update_image = True update_screen = True elif cmd == 'list': for i in range(len(self.filters)): self.console.add_output("%d %s" % (i, str(self.filters[i]))) update_screen = True elif cmd == 'next': self.console.add_output('Success.') update_image = True update_screen = True update_frame_count = True elif cmd == 'play': self.playing = True self.console.add_output("Success. Playing: %s" % self.playing) update_screen = True elif cmd == 'screenshot': self.screenshot('out.png') self.console.add_output("Success, saved out.png.") update_screen = True elif cmd == 'stop': self.playing = False self.console.add_output("Success: Playing: %s" % self.playing) update_screen = True else: self.console.add_output("Command not recognized.") update_screen = True return update_image, update_screen, update_frame_count def run(self): run, update_img, update_view, update_frame = self.poll_events() if (run and self.playing and sdl2.SDL_GetTicks() - self.last_update > 1000 / self.fps): self.update_filtered_image() self.last_update = sdl2.SDL_GetTicks() self.update_screen() else: if update_img: self.update_filtered_image( update_frame_count=update_frame) if update_view: self.update_screen() delay = 10 sdl2.SDL_Delay(delay) return run def poll_events(self): """ Wait for a SDL2 event, handle it once encountered """ update_img = False update_view = False update_frame = False event = sdl2.SDL_Event() while sdl2.SDL_PollEvent(ctypes.byref(event)): # resize events if event.type == sdl2.SDL_WINDOWEVENT: if event.window.event == sdl2.SDL_WINDOWEVENT_RESIZED: self.handle_resize( (event.window.data1, event.window.data2)) if event.window.event in [sdl2.SDL_WINDOWEVENT_RESIZED, sdl2.SDL_WINDOWEVENT_EXPOSED]: update_view = True # quit events if event.type == sdl2.SDL_QUIT: return False, False, False, False # Console inputs if self.console_enabled: commands = [] if event.type == sdl2.SDL_TEXTINPUT: event_str = event.text.text[:] commands += self.console.parse_input(event_str) update_view = True if event.type == sdl2.events.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_BACKSPACE: self.console.backspace() update_view = True elif event.key.keysym.sym == sdl2.SDLK_RETURN: commands += self.console.parse_input('\n') update_view = True for cmd in commands: update_img, update_view, update_frame = self.do_command( cmd) # hotkeys if event.type == sdl2.events.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: return False, False, False, False elif event.key.keysym.sym == sdl2.SDLK_BACKQUOTE: self.console_enabled = not self.console_enabled if self.console_enabled: sdl2.SDL_StartTextInput() else: sdl2.SDL_StopTextInput() update_view = True if self.console_enabled: return True, update_img, update_view, update_frame if event.key.keysym.sym == sdl2.SDLK_a: self.playing = True update_view = True update_img = True elif event.key.keysym.sym == sdl2.SDLK_s: self.playing = False update_view = True update_img = True elif event.key.keysym.sym == sdl2.SDLK_r: random.shuffle(self.filters) update_img = True update_view = True elif event.key.keysym.sym == sdl2.SDLK_UP: self.view.offset = ( self.view.offset[0], self.view.offset[1] - 8) update_view = True elif event.key.keysym.sym == sdl2.SDLK_DOWN: self.view.offset = ( self.view.offset[0], self.view.offset[1] + 8) update_view = True elif event.key.keysym.sym == sdl2.SDLK_LEFT: self.view.offset = ( self.view.offset[0] + 8, self.view.offset[1]) update_view = True elif event.key.keysym.sym == sdl2.SDLK_RIGHT: self.view.offset = ( self.view.offset[0] - 8, self.view.offset[1]) update_view = True elif event.key.keysym.sym == sdl2.SDLK_EQUALS: self.view.zoom += 0.05 update_view = True elif event.key.keysym.sym == sdl2.SDLK_MINUS: self.view.zoom -= 0.05 update_view = True return True, update_img, update_view, update_frame def cleanup(self): """ destroys opengl and sdl resources allocated """ for val in self.all_filters.itervalues(): val.cleanup_shader() self.filters = [] if self.final_filter: self.final_filter.cleanup_shader() if self.console: self.console.cleanup() self.final_filter = None self.cleanup_img_fb() self.cleanup_image_texture() if self.window: sdl2.SDL_DestroyWindow(self.window) self.window = None self.view.reset() def __del__(self): self.cleanup() if __name__ == "__main__": img = Image.open('selena.jpg') ig = ImageGlitch() import atexit atexit.register(ig.cleanup) ig.filter_img(img, [ 'first', # 'second', # 'third', 'rgb_shift', # 'repeat_end', # 'static', # 'static2', 'scanlines', ]) img.close() running = True ig.update_screen() while running: running = ig.run()
true
119bcc198438a5c304bba7d3824e007f12b828d5
Python
avielb/DevOps0803
/11.py
UTF-8
356
3.15625
3
[]
no_license
myfile = open("read_my_contents.txt", "r") all_lines = myfile.readlines() for line in all_lines: print(line, end='') myfile.close() my_new_file = open("my_file.txt", "w") my_new_file.write("Hello my file....") my_new_file.close() my_other_file = open("read_my_contents.txt", "a") my_other_file.write("\nthis is the last line") my_other_file.close()
true
2cdeb1295969b6e9d21e01202713432f050a021f
Python
turner3467/football_scores
/scripts/download.py
UTF-8
1,206
2.765625
3
[]
no_license
#! /usr/bin/env python import csv import urllib.request as req import io base_url = "http://football-data.co.uk/mmz4281/" # 1516/E0.csv seasons = [str(i % 100).zfill(2) + str((i + 1) % 100).zfill(2) for i in range(100, 116)] leagues = [1, 2] cntry = {"eng": "E", "ger": "D", "fra": "F", "spa": "SP", "ita": "I"} for s in seasons: for l in leagues: for c in cntry: if c == 'eng': # premiership = 0 l_tmp = l - 1 else: l_tmp = l url = base_url + "{}/{}{}.csv".format(s, cntry[c], l_tmp) r = req.urlopen(url) reader = csv.reader(io.TextIOWrapper(r, errors="ignore")) file = "../data/raw_data/{}_{}_{}.csv".format(c, s, str(l)) with open(file, "w") as outfile: writer = csv.writer(outfile, delimiter=",") for row in reader: writer.writerow(row) print("Historic seasons downloaded successfully.")
true
60d40adc65941e4f13ab2a1daac1ed64b71fde5e
Python
iCodeIN/pe
/test/test__parse.py
UTF-8
3,317
2.84375
3
[ "MIT" ]
permissive
from pe.operators import ( Dot, Literal, Class, Sequence, Choice, Optional, Star, Plus, Nonterminal, And, Not, Capture, Bind, ) from pe._parse import loads def eloads(s): start, defmap = loads(s) return defmap[start] def test_loads_dot(): assert eloads('.') == Dot() assert eloads('. # comment') == Dot() def test_loads_literal(): assert eloads('"foo"') == Literal('foo') assert eloads('"foo" # comment') == Literal('foo') assert eloads('"\\t"') == Literal('\t') assert eloads('"\\n"') == Literal('\n') assert eloads('"\\v"') == Literal('\v') assert eloads('"\\f"') == Literal('\f') assert eloads('"\\r"') == Literal('\r') assert eloads('"\\""') == Literal('"') assert eloads("'\\''") == Literal("'") assert eloads("'\\['") == Literal("[") assert eloads("'\\\\'") == Literal("\\") assert eloads("'\\]'") == Literal("]") assert eloads("'\\123'") == Literal('S') assert eloads("'\\x61'") == Literal('a') assert eloads("'\\u0061'") == Literal('a') assert eloads("'\\U00000061'") == Literal('a') def test_loads_class(): assert eloads('[xyz]') == Class('xyz') assert eloads('[xyz] # comment') == Class('xyz') assert eloads('[x-z]') == Class('x-z') assert eloads('[\\[\\]]') == Class('[]') assert eloads('[xy\\u007a]') == Class('xyz') assert eloads('[\xe1bc]') == Class('ábc') def test_loads_nonterminal(): assert eloads('foo') == Nonterminal('foo') assert eloads('foo # comment') == Nonterminal('foo') def test_loads_optional(): assert eloads('"a"?') == Optional('a') assert eloads('"a"? # comment') == Optional('a') def test_loads_star(): assert eloads('"a"*') == Star('a') assert eloads('"a"* # comment') == Star('a') def test_loads_plus(): assert eloads('"a"+') == Plus('a') assert eloads('"a"+ # comment') == Plus('a') def test_loads_sequence(): assert eloads('"a" "b"') == Sequence('a', 'b') assert eloads('"a" "b" # comment') == Sequence('a', 'b') def test_loads_choice(): assert eloads('"a" / "b"') == Choice('a', 'b') assert eloads('"a" / "b" # comment') == Choice('a', 'b') def test_loads_and(): assert eloads('&"a"') == And('a') assert eloads('&"a" # comment') == And('a') def test_loads_not(): assert eloads('!"a"') == Not('a') assert eloads('!"a" # comment') == Not('a') def test_loads_capture(): assert eloads('~"a"') == Capture('a') assert eloads('~"a" # comment') == Capture('a') def test_loads_bind(): assert eloads('x:"a"') == Bind('a', name='x') assert eloads('x:"a" # comment') == Bind('a', name='x') assert eloads('x: "a"') == Bind('a', name='x') assert eloads('x : "a"') == Bind('a', name='x') def test_loads_def(): assert loads('A <- "a"') == ('A', {'A': Literal('a')}) assert loads('A <- "a" # comment') == ('A', {'A': Literal('a')}) assert loads('A <- "a" "b"') == ('A', {'A': Sequence('a', 'b')}) assert loads('A <- "a" B <- "b"') == ('A', {'A': Literal('a'), 'B': Literal('b')}) assert loads(''' A <- "a" Bee Bee <- "b" ''') == ('A', {'A': Sequence('a', Nonterminal('Bee')), 'Bee': Literal('b')})
true
34055eba8478acc8b7fe99b62b1268a1855f1cbc
Python
nathantheinventor/solved-problems
/URI Online Judge/Beginner/1017 Fuel Spent/fuel.py
UTF-8
56
2.546875
3
[]
no_license
print("{:.3f}".format(int(input()) * int(input()) / 12))
true
113dd3323512d928c75262939970dfb2d43d69f6
Python
ChanceQZ/rs-img-classification
/src/readTif.py
UTF-8
353
2.5625
3
[]
no_license
import cv2 import numpy as np import tifffile img = tifffile.imread('678.tif') a = img[:,:,0]+img[:,:,1]+img[:,:,2] b = np.zeros(a.shape, dtype=np.uint8) b[np.where(a == 0)] = 255 print(img.shape, np.max(img)) cv2.namedWindow("Image") cv2.imshow("Image", cv2.resize(b, (img.shape[0]//10, img.shape[1]//10))) cv2.waitKey (0) cv2.destroyAllWindows()
true
6188784782489cd05bc1e843a03216e728968647
Python
StasyaZlato/Home-Work
/2016-2017/classworks/programming_test.py
UTF-8
1,528
3.671875
4
[]
no_license
#Задание1. Открыть файл и вывести на экран строчки, содержащие союз with open ('freq.txt', 'r', encoding = 'utf-8') as f: lines = f.readlines () for line in lines: if 'союз' in line: print (line) #Задание2. Распечатать через запятую все существительные женского рода #единственного числа и вывести сумму ipm with open ('freq.txt', 'r', encoding = 'utf-8') as f: lines = f.readlines () a = [] for line in lines: line = line.split () if 'жен' in line and 'ед' in line: print (line[0], end = ', ') a.append (line[-1]) ipm_sum = 0 for elem in a: elem = float (elem) ipm_sum += elem print (ipm_sum) #Задание3. Спрашиваем слова, пока пользователь не введет пустое слово. #Выводим для каждого морф. информацию и ipm with open ('freq.txt', 'r', encoding = 'utf-8') as f: lines = f.readlines () word = input () while word: for line in lines: line = line.split() if word in line: print ('Морфологическая информация: ' + ' '.join (line[2:-2])) print ('IPM = ' + line[-1]) word = input ()
true
142077bb9333312704700bde57afb717423c0017
Python
emarahimself/mnist-pytorch
/dataset.py
UTF-8
3,654
2.875
3
[]
no_license
import idx2numpy from sklearn import preprocessing from sklearn.datasets import load_iris, load_digits, make_blobs from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA class DatasetBase: x_train = None x_test = None y_train = None y_test = None def normalize(self): raise NotImplementedError def binarize_labels(self): self.binarizer = preprocessing.LabelBinarizer() self.y_train = self.binarizer.fit_transform(self.y_train) self.y_test = self.binarizer.fit_transform(self.y_test) @property def features(self): return self.x_train.shape[1] @property def train_size(self): return self.x_train.shape[0] @property def test_size(self): return self.x_test.shape[0] @property def classes(self): return self.y_test.shape[1] class BlobsDataset(DatasetBase): def __init__(self, samples=1000, centers=3, features=20): x, y = make_blobs(n_samples=samples, centers=centers, n_features=features) self.x_train, self.x_test, self.y_train, self.y_test = train_test_split( x, y, test_size=0.25, random_state=1 ) self.normalize() self.binarize_labels() def normalize(self): scaler = preprocessing.MinMaxScaler() self.x_train = scaler.fit_transform(self.x_train) self.x_test = scaler.fit_transform(self.x_test) class IrisDataset(DatasetBase): def __init__(self): x, y = load_iris(return_X_y=True) x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.25, random_state=1 ) self.x_train = x_train self.x_test = x_test self.y_train = y_train self.y_test = y_test self.normalize() self.binarize_labels() def normalize(self): scaler = preprocessing.MinMaxScaler() self.x_train = scaler.fit_transform(self.x_train) self.x_test = scaler.fit_transform(self.x_test) class MNISTDataset(DatasetBase): def __init__(self): train_images_path = 'dataset/train-images-idx3-ubyte' test_images_path = 'dataset/t10k-images-idx3-ubyte' train_labels_path = 'dataset/train-labels-idx1-ubyte' test_labels_path = 'dataset/t10k-labels-idx1-ubyte' self.x_train = idx2numpy.convert_from_file(train_images_path) self.y_train = idx2numpy.convert_from_file(train_labels_path) self.x_test = idx2numpy.convert_from_file(test_images_path) self.y_test = idx2numpy.convert_from_file(test_labels_path) features = 28 * 28 train_size = self.x_train.shape[0] test_size = self.x_test.shape[0] self.x_train = self.x_train.reshape(train_size, features) self.x_test = self.x_test.reshape(test_size, features) self.normalize() self.binarize_labels() def normalize(self): self.x_train = self.x_train / 255.0 self.x_test = self.x_test / 255.0 class DigitsDataset(DatasetBase): def __init__(self): x, y = load_digits(return_X_y=True) x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.25, random_state=1 ) self.x_train = x_train self.x_test = x_test self.y_train = y_train self.y_test = y_test self.normalize() self.binarize_labels() def normalize(self): scaler = preprocessing.MinMaxScaler() self.x_train = scaler.fit_transform(self.x_train) self.x_test = scaler.fit_transform(self.x_test)
true
8ffb9e82c988e8a26e41b8f39025f79e25df8327
Python
AleksanderKarmazin/Test_july_2020
/test.py
UTF-8
10,710
2.953125
3
[ "Apache-2.0" ]
permissive
import time from selenium import webdriver import pytest from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException from loginPage import LoginPage from homePage import HomePage @pytest.mark.usefixtures("driver_init") class Test_Class_01(): # ТС_1.1. Логин с корректным ID пользователя и корректным паролем def test_TC_01(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() # homepage = HomePage(driver) # homepage.open_profile_menu() # homepage.click_logout() # ТС_1.2. Логин с пустым полем ID пользователя и пустым полем паролем def test_TC_02(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("") login.enter_password("") login.click_login() openElement = driver.find_element_by_css_selector("div.invalid-feedback") elementText = openElement.text Text = "Login is not given." assert Text == elementText openElement2 = driver.find_element_by_xpath("//form/div[2]/div") elementText2 = openElement2.text Text2 = "Password is not given." assert Text2 == elementText2 # ТС_1.3. Логин с корректным ID пользователя и не корректным паролем (5 символов) def test_TC_03(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("12345") login.click_login() openElement = driver.find_element_by_xpath("//form/div[2]/div") elementText = openElement.text Text = "The entered password must be not less than 6 symbols." assert Text == elementText # ТС_1.4. Логин с корректным ID пользователя и не корректным паролем (6 символов) def test_TC_04(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123455") login.click_login() openElement = driver.find_element_by_xpath("//form/div/div") elementText = openElement.text Text = "Login or password is incorrect!" assert Text == elementText # ТС_1.5. Логин с корректным ID пользователя и не корректным паролем (7 символов) def test_TC_05(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("1234567") login.click_login() openElement = driver.find_element_by_xpath("//form/div/div") elementText = openElement.text Text = "Login or password is incorrect!" assert Text == elementText # ТС_1.6. Логин с не корректным ID пользователя и корректным паролем def test_TC_06(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.comm") login.enter_password("123456") login.click_login() openElement = driver.find_element_by_xpath("//form/div/div") elementText = openElement.text Text = "Login or password is incorrect!" assert Text == elementText # ТС_1.7. Логин с не корректным ID пользователя и не корректным паролем (6 символов) def test_TC_07(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.comm") login.enter_password("123455") login.click_login() openElement = driver.find_element_by_xpath("//form/div/div") elementText = openElement.text Text = "Login or password is incorrect!" assert Text == elementText # ТС_2.1 Корректный номер телефона (Russia, номер 9181234567, Health Care) def test_TC_08(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("Russia") homepage.enter_phone("9181234567") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # ТС_2.2. Повторный ввод корректного телефона без изменений информации (Russia, номер 9181234567, Health Care ) def test_TC_09(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("Russia") homepage.enter_phone("9181234567") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.3. Повторный ввод корректных данных с изменениями дропдауна Business segment def test_TC_10(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("Russia") homepage.enter_phone("9181234567") homepage.select_business_segment("Finance") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.4. Повторный ввод корректного телефона с изменениями дропдауна Country (United States , номер 2026794501, Health Care ) def test_TC_11(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("United States") homepage.enter_phone_code("+1") homepage.enter_phone("2026794501") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.5. Пустое поле кода (USA , номер 2026794501) def test_TC_12(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("United States") homepage.enter_phone_code("") homepage.enter_phone("2026794501") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.6. Пустое поле телефон def test_TC_13(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("United States") homepage.enter_phone_code("+1") homepage.enter_phone("") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.7. Ввод номера телефона не корректного формата def test_TC_14(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("United States") homepage.enter_phone_code("+1") homepage.enter_phone("202 679 45 01") homepage.select_business_segment("Health Care") homepage.click_update() homepage.open_profile_menu() homepage.click_logout() # 2.8. Ввод не действительного номера телефона def test_TC_15(self): driver = self.driver driver.get("https://area.mtg-bi.com") login = LoginPage(driver) login.sign_in() login.enter_username("testcaseqa5@gmail.com") login.enter_password("123456") login.click_login() homepage = HomePage(driver) homepage.open_profile_menu() homepage.open_profile() homepage.select_country("United States") homepage.enter_phone_code("+1") homepage.enter_phone("956-42-84") homepage.select_business_segment("Health Care") homepage.click_update() time.sleep(10) homepage.open_profile_menu() homepage.click_logout()
true
77ad1958758f8a399d137006b7eab0b92f900673
Python
davidcolton/bitesofpy
/304/max_letter.py
UTF-8
1,258
3.765625
4
[]
no_license
from typing import Tuple from collections import Counter import re def max_letter_word(text) -> Tuple[str, str, int]: """ Find the word in text with the most repeated letters. If more than one word has the highest number of repeated letters choose the first one. Return a tuple of the word, the (first) repeated letter and the count of that letter in the word. >>> max_letter_word('I have just returned from a visit...') ('returned', 'r', 2) >>> max_letter_word('$5000 !!') ('', '', 0) """ max_word = "" max_letter = "" max_count = 0 if isinstance(text, str): for idx, word in enumerate(text.split()): most_frequent = Counter( "".join(filter(str.isalpha, word.casefold())) ).most_common(1) try: letter, cnt = most_frequent[0] if cnt > max_count: max_word = word max_letter = letter max_count = cnt except IndexError: pass else: raise ValueError max_word = "".join([c for c in max_word if c.isalpha() or c in ["'", "-"]]) return (max_word, max_letter, max_count)
true
dba44ccc13d136c8a703806e079aa30b96b2d197
Python
levit123/Basic-Python-Projects
/Budget/Budget.py
UTF-8
579
4.03125
4
[]
no_license
#new function named "calcBills" def calcBills(): #creates a variable with the following properties myBills = {'Electric': 120.00, 'Rent': 1200.00, 'Water_Sewer': 60.00, 'Car_Insurance': 75.00, 'Phone': 65.00} #creates an integer and sets its value to 0 total = 0 #uses a for loop to add all the numbers in "myBills" to "total" for i in myBills: total += myBills[i] #creates a string that has a sentence with the "total" owed = 'The total cost for bills this month is: ${}'.format(total) #returns the "owed" string return owed
true
62b37d7d3843b46916ad86b61a882f1e1bdc2f9d
Python
otak007/RailNL
/code/algorithms/depth_first.py
UTF-8
6,128
2.90625
3
[]
no_license
from code.classes.map import Map from code.classes.stations import Station from code.classes.traject import Traject import copy import csv import matplotlib.pyplot as plt def all_stations(distance, color, map, all_critical, max_time, crit_stations, steps): ## Goes over all start stations and chooses best traject is_critical(map, all_critical) # Initialize lists trajecten = [] scores = [] t = [] s = [] # Goes over all start stations for x in range(len(map.stations)): for connection in map.connections: connection.travelled = False # Create new traject and travel traject = Traject(map.stations[x]) trajects, score = travel(traject, map.stations[x], "y", steps, t, s, map, max_time, crit_stations) trajecten.append(copy.deepcopy(trajects)) scores.append(copy.copy(score)) t = [] s = [] # Choose traject with highest score index = scores.index(max(scores)) best_traject = trajecten[index] # add connections from best traject to list of already driven connections for connection in best_traject.connections: map.driven_connections.append(connection.id) map.driven_connections = list(set(map.driven_connections)) trajecten.append(copy.deepcopy(best_traject)) # Plot traject plot_traject(best_traject, color, distance) return best_traject def is_critical(map, all_critical): # Checks if connection is connected to critical station for connection in map.connections: for station in map.stations: if (station.name == connection.stationA or station.name == connection.stationB) and station.critical == True: connection.critical = 1 if map.driven_connections: for id in map.driven_connections: if id == connection.id: connection.critical = 0 else: if all_critical == "yes": connection.critical = 1 def find_neighbours(station, map): # Initialize lists connections = [] stations = [] # Add relevant connections to relevant lists for connection in map.connections: if station.name == connection.stationA: connections.append(connection) stations.append(to_station(connection.stationB, map)) elif station.name == connection.stationB: connections.append(connection) stations.append(to_station(connection.stationA, map)) return connections, stations def find_subroutes(stations, connections, last_station, steps, traject, t, s, map, max_time, crit_stations, depth = 0, trajecten = [], scores = []): # Start with appending start station if depth == 0: traject.traject.append(last_station) # If max depth and time is not reached if depth < steps and sum(traject.times) <= max_time: # Iterate over stations for station in stations: # Find connected stations for that station connections, stations = find_neighbours(station, map) # Go nodes back if max depth is reached while len(traject.traject) > (depth + 1): lost_connection = traject.connections.pop() # If connection no longer travelled, reset variable if lost_connection not in traject.connections: lost_connection.travelled = False traject.traject.pop() traject.times.pop() traject.scores.pop() # Find connection to node and add to list if possible for connection in connections: if (last_station.name == connection.stationA and station.name == connection.stationB) or (station.name == connection.stationA and last_station.name == connection.stationB): if sum(traject.times) + connection.travelTime <= max_time: traject.times.append(connection.travelTime) traject.scores.append(connection.calc_val(crit_stations)) connection.travelled = True traject.traject.append(station) traject.connections.append(connection) # Prevent travelling back for next_station in stations: if last_station.name is next_station.name: stations.remove(next_station) for connection in connections: if (next_station.name == connection.stationA and station.name == connection.stationB) or (station.name == connection.stationA and next_station.name == connection.stationB): connections.remove(connection) # Travel again find_subroutes(stations, connections, station, steps, traject, t, s, map, max_time, crit_stations, depth + 1) else: traject.score = sum(traject.scores) traject.time = sum(traject.times) t.append(copy.deepcopy(traject)) s.append(traject.score) return t, s def travel(traject, station, color, steps, t, s, map, max_time, crit_stations): connections, stations = find_neighbours(station, map) trajecten, scores = find_subroutes(stations, connections, station, steps, traject, t, s, map, max_time, crit_stations) best_score = max(scores) best_traject = trajecten[scores.index(max(scores))] return best_traject, best_score def plot_traject(traject, color, distance): ## plots traject once best traject is chosen # goes over every station in traject and plots it for x in range(1, len(traject.traject)): station1 = traject.traject[x-1] station2 = traject.traject[x] plt.plot([float(station1.yCoordinate) - 0.02, float(station2.yCoordinate) - 0.02], [float(station1.xCoordinate) + distance * 0.01, float(station2.xCoordinate) + distance * 0.01], color+"-") def to_station(name, map): ## Transforms a station(str) to Station(obj) for row in map.stations: if name == row.name: name = row return name
true
81aa66e73d243eae8768e1461f83acbeab3591d2
Python
DanielBaudry/makemegreen
/engine/footprint.py
UTF-8
4,481
2.59375
3
[]
no_license
""" Footprint """ from models import BaseObject, Footprint, User, FootprintType from engine import dictionnary as info from flask import current_app as app class BadUserException(Exception): pass class BadArgException(Exception): pass class ComputeFootprint: def __init__(self): pass def getCO2Footprint(self, data): redmeatFootprint = float(data.get('red_meat_frequency')) * info.dic['serving'] * info.dic['nb_meals'] * info.dic['red_meat'] whitemeatFootprint = float(data.get('white_meat_frequency')) * info.dic['serving'] * info.dic['nb_meals'] * info.dic['white_meat'] clothesFootprint = float(data.get('clothes_composition')) * info.dic['quantity_clothes'] * info.dic['cotton'] \ + (1 - float(data.get('clothes_composition'))) * info.dic['quantity_clothes'] * info.dic['polyester/wool'] trainFootprint = float(data.get('train_frequency')) * info.dic['train'] if float(data.get('personal_vehicule_consumption')) == -1: carFootprint = float(data.get('personal_vehicule_frequency')) * info.dic['car'] else: carFootprint = float(data.get('personal_vehicule_frequency')) * float(data.get('personal_vehicule_consumption'))/100. * info.dic['car_liter'] carFootprint = carFootprint - carFootprint * float(data.get('carpooling_frequency')) * (info.dic['nb_passengers'] - 1.)/info.dic['nb_passengers'] return redmeatFootprint + whitemeatFootprint + clothesFootprint + carFootprint def getTrashFootprint(self, data): greentrashFootprint = float(data.get('green_garbage')) * info.dic['green_trash'] yellowtrashFootprint = float(data.get('yellow_garbage')) * info.dic['yellow_trash'] return greentrashFootprint + yellowtrashFootprint def getWaterFootprint(self, data): bathFootprint = float(data.get('bath_shower_frequency')) * float(data.get('bath_or_shower')) * info.dic['bath'] showerFootprint = float(data.get('bath_shower_frequency')) * (1 - float(data.get('bath_or_shower'))) * info.dic['shower'] * info.dic['time_shower'] return bathFootprint + showerFootprint def execute(self, data): return [ { "id": 1, "type": { "label": "carbon" }, "value": self.getCO2Footprint(data) }, { "id": 2, "type": { "label": "waste" }, "value": self.getTrashFootprint(data) }, { "id": 3, "type": { "label": "water" }, "value": self.getWaterFootprint(data) } ] class GetFootprintHistory: def __init__(self): pass def execute(self, user: User) -> Footprint: if user is None: raise BadUserException() footprints = [] for type in FootprintType: footprint_type = type.value.get('label') if footprint_type != "total": footprint = Footprint.query. \ filter_by(user_id=user.get_id()). \ filter_by(type=footprint_type). \ order_by(Footprint.date_created.asc()). \ all() footprints.append(footprint) return footprints class GetFootprints: def __init__(self): pass def execute(self, user: User) -> Footprint: if user is None: raise BadUserException() footprints = [] for type in FootprintType: footprint_type = type.value.get('label') if footprint_type != "total": footprint = Footprint.query. \ filter_by(user_id=user.get_id()). \ filter_by(type=footprint_type). \ order_by(Footprint.date_created.desc()). \ first() footprints.append(footprint) return footprints class SaveFootprint: def __init__(self, footprint: Footprint): self.footprint = Footprint def execute(self, footprint: Footprint) -> Footprint: if footprint is None: raise BadArgException() BaseObject.check_and_save(footprint) return footprint
true
72c304aa7723b031632e35521b6b044ca579ac55
Python
erasta/blockly-cv2
/prj/water/code.py
UTF-8
274
2.609375
3
[]
no_license
import cv2 import numpy as np image = cv2.imread('media/lena.jpg',1) markers = [(10,10), (100,100), None] water = cv2.watershed(image,markers) print(water) cv2.imshow('mywin',image) cv2.imshow('watershed',water) if cv2.waitKey(0)&0xff == 27: pass cv2.destroyAllWindows()
true
1900ebf9d609ac767d5e0349077683068fa1055e
Python
tuxmsantos/exemple02
/operations.py
UTF-8
129
3.515625
4
[]
no_license
num1 = input("digite o primeiro numero....:") num2 = input("digite o segundo numero.....:") total = int(num1 / num2) print total
true