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
fd8d35816b91b3f7caa6ebf38b9ed7f7a48fdf91
Python
nickto/covid-latvia
/scripts/clean.py
UTF-8
1,768
3
3
[ "MIT" ]
permissive
#!/usr/bin/env python import pandas as pd import yaml from openpyxl import load_workbook def clean(resource_configs): filepath = resource_configs["raw"]["path"] metadata = yaml.safe_load(open(filepath + ".meta.yaml", "r")) if resource_configs["raw"]["format"] == "csv": print(f"Reading CSV from {filepath:s}.") df = pd.read_csv(filepath, encoding=resource_configs["raw"]["encoding"], sep=resource_configs["raw"]["sep"], na_values=resource_configs["raw"]["na_values"], quotechar=resource_configs["raw"]["quotechar"]) elif resource_configs["raw"]["format"] == "xlsx": print(f"Reading XLSX from {filepath:s}.") wb = load_workbook(resource_configs["raw"]["path"]) ws = wb[resource_configs["raw"]["sheet"]] df = pd.DataFrame(ws.values) if resource_configs["raw"]["header"]: df, df.columns = df[1:], df.iloc[0] # 1st row to headers else: raise NotImplementedError # Rename columns if "rename" in resource_configs["raw"].keys(): df = df.rename(resource_configs["raw"]["rename"], axis=1) # Save filepath = resource_configs["clean"]["path"] print(f"Saving clean data to {filepath:s}.") df.to_csv(filepath, index=False) yaml.safe_dump(metadata, open(filepath + ".meta.yaml", "w"), default_flow_style=False, allow_unicode=True) def main(): configs = yaml.safe_load(open("configs.yaml", "r")) for resource in configs["data"].keys(): print(f"Cleaning {resource:s}.") clean(resource_configs=configs["data"][resource], ) if __name__ == "__main__": main()
true
c56f37752005bdb6051bbf1a27a09cd8de0d64ed
Python
Aryan-Satpathy/SWARMTaskRound2021
/code.py
UTF-8
17,305
2.578125
3
[]
no_license
import sys from api import * from time import sleep import numpy as np import random as rnd import cv2 import math ####### YOUR CODE FROM HERE ####################### CommsFilePath = r'Status.txt' BlackFilePath = r'Gone.txt' stringFormat = 'i : Status jj : len\n' # Index helper :012345678901234567890123 while True : try : CommsFile = open(CommsFilePath, 'r+') break except : _file = open(CommsFilePath, 'w') _file.write('''0 : Sleeping : 1 : Sleeping : 2 : Sleeping : 3 : Sleeping : 4 : Sleeping : 5 : Sleeping : 6 : Sleeping : 7 : Sleeping : ''') _file.flush() _file.close() while True : try : BlackFile = open(BlackFilePath, 'r+') break except : _file = open(BlackFilePath, 'w') _file.write('None, ') _file.flush() _file.close() numbots = get_numbots() goalList = get_greenZone_list() blackList = [] NeighbourMap = {(-1, -1) : 1, (0, -1) : 2, (1, -1) : 3, (1, 0) : 4, (1, 1) : 5, (0, 1) : 6, (-1, 1) : 7, (-1, 0) : 8} obsList = get_obstacles_list() redList = get_redZone_list() def getPathLenStr(pathLen) : a = pathLen // 100 b = (pathLen % 100) // 10 c = (pathLen % 10) return '{}{}{}'.format(a, b, c) def getGoalIDStr(goalID) : b = goalID // 10 c = goalID % 10 return '{}{}'.format(b, c) def decodeComms(message) : botID = int(message[0]) status = message[4 : 15].rstrip() try : goalID = int(message[16 : 18]) except : goalID = None pathLen = 0 try : pathLen = int(message[21 : ]) except : pass return (botID, status, goalID, pathLen) def isValid(pos, obsList) : for obs in obsList : if liesIn(pos, obs) : return False return True def decode(pos1, pos2) : delY , delX = pos2[0] - pos1[0], pos2[1] - pos1[1] return NeighbourMap[delX, delY] def reconstruct_path(cameFrom, current) : total_path = [] prev = cameFrom[current] total_path.append(decode(prev, current)) while prev in cameFrom : prev, current = cameFrom[prev], cameFrom[current] total_path.append(decode(prev, current)) return total_path[ : : -1] ''' total_path = [current] while current in cameFrom: current = cameFrom[current] total_path.append(current) return total_path[ : : -1] ''' def A_Star(start, goal, h, obsList, redList) : # The set of discovered nodes that may need to be (re-)expanded. # Initially, only the start node is known. # This is usually implemented as a min-heap or priority queue rather than a hash-set. openSet = [start] # For node n, cameFrom[n] is the node immediately preceding it on the cheapest path from start # to n currently known. cameFrom = {} # For node n, gScore[n] is the cost of the cheapest path from start to n currently known. gScore = [[math.inf for i in range(200)] for j in range(200)] gScore[start[0]][start[1]] = 0 # For node n, fScore[n] := gScore[n] + h(n). fScore[n] represents our current best guess as to # how short a path from start to finish can be if it goes through n. fScore = [[math.inf for i in range(200)] for j in range(200)] fScore[start[0]][start[1]] = h(start, goal) while len(openSet) : # print(len(openSet)) # This operation can occur in O(1) time if openSet is a min-heap or a priority queue current = min(openSet, key = lambda pos : fScore[pos[0]][pos[1]]) # Get node from openSet with min fScore if current == goal : print("Cost = {}".format(gScore[current[0]][current[1]])) return reconstruct_path(cameFrom, current) openSet.remove(current) # neighbours = [(-1, -1), ] neighbours = [(x, y) for x in range(-1, 2) for y in range(-1, 2) if (not(x == 0 and y == 0)) and 0 <= current[0] + x < 200 and 0 <= current[1] + y < 200 and isValid((current[0] + x, current[1] + y), obsList)] for neighbor in neighbours : # d(current,neighbor) is the weight of the edge from current to neighbor # tentative_gScore is the distance from start to the neighbor through current x, y = neighbor costMultiplier = 1 for red in redList : if liesIn((current[0] + x, current[1] + y), red) : costMultiplier = 2 break tentative_gScore = gScore[current[0]][current[1]] + costMultiplier * [1, 1.4][x * y] if tentative_gScore < gScore[current[0] + x][current[1] + y] : # This path to neighbor is better than any previous one. Record it! cameFrom[(current[0] + x, current[1] + y)] = current gScore[current[0] + x][current[1] + y] = tentative_gScore fScore[current[0] + x][current[1] + y] = gScore[current[0] + x][current[1] + y] + h((current[0] + x, current[1] + y), goal) if (current[0] + x, current[1] + y) not in openSet : openSet.append((current[0] + x, current[1] + y)) # Open set is empty but goal was never reached return None def heuristic(pos, goal) : return distance(pos, goal) def distance(pos1, pos2) : return math.sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2) def liesIn(pos, rect) : tl, br = rect[0], rect[2] xmin, ymin = tl xmax, ymax = br x, y = pos return (xmin <= x <= xmax) and (ymin <= y <= ymax) class Node : def __init__(self, pos) : self.pos = pos self.cameFrom = None self.id = None class Graph : def __init__(self, step) : self.step = step self.nodes = [] self.occupiedPos = [] self.goalNodes = {} self.edges = [] self.len = 0 self.obsList = None self.map = None def addNode(self, node) : if node.pos in self.occupiedPos : return False node.id = self.len self.nodes.append(node) self.occupiedPos.append(node.pos) self.len += 1 return node.id def getClosestNode(self, pos) : return min(self.nodes, key = lambda node : distance(node.pos, pos)) def canMakeLine(self, pos1, pos2) : for obs in self.obsList : flag = Graph._canMakeLine(pos1, pos2, obs) if flag == False : return False return True @staticmethod def _canMakeLine(pos1, pos2, obs) : (xmin, ymin), (xmax, ymax) = obs[0], obs[2] Y = Graph.getY(pos1, pos2, xmin) if Y != None and ymin <= Y <= ymax : if min(pos1[1], pos2[1]) <= Y <= max(pos1[1], pos2[1]) : return False Y = Graph.getY(pos1, pos2, xmax) if Y != None and ymin <= Y <= ymax : if min(pos1[1], pos2[1]) <= Y <= max(pos1[1], pos2[1]) : return False X = Graph.getX(pos1, pos2, ymin) if X != None and xmin <= X <= xmax : if min(pos1[0], pos2[0]) <= X <= max(pos1[0], pos2[0]) : return False X = Graph.getX(pos1, pos2, ymax) if X != None and xmin <= X <= xmax : if min(pos1[0], pos2[0]) <= X <= max(pos1[0], pos2[0]) : return False return True def createNodeBetween(self, node1, pos2) : pos1 = node1.pos D = distance(pos1, pos2) if D <= self.step : finalPos = pos2 else : m, n = D - self.step, self.step m /= D n /= D finalPos = int(pos1[0] * m + pos2[0] * n), int(pos1[1] * m + pos2[1] * n) node = Node(finalPos) success = self.addNode(node) if success : node.cameFrom = node1 self.edges.append((node.id, node1.id)) return success def expand (self) : x, y = rnd.randint(0, 199), rnd.randint(0, 199) while True : if False in (self.map[(x, y)] == np.array((0, 0, 0))) : break x, y = rnd.randint(0, 199), rnd.randint(0, 199) closestNode = self.getClosestNode((x, y)) if self.canMakeLine(closestNode.pos, (x, y)) : success = self.createNodeBetween(closestNode, (x, y)) return success return self.expand() def bias(self, goal) : x, y = goal closestNode = self.getClosestNode((x, y)) if self.canMakeLine(closestNode.pos, (x, y)) : success = self.createNodeBetween(closestNode, (x, y)) return success return False def checkGoals (self) : greenList = get_greenZone_list() l = len(greenList) foundAtLeastOne = False for ind in range(self.len) : for ind2 in range(l) : if liesIn(self.occupiedPos[ind], greenList[ind2]) : self.goalNodes[ind2] = ind foundAtLeastOne = True return foundAtLeastOne def constructPath(self, goalInd) : if goalInd in self.goalNodes : print('Constructing Path') path = [] curr = self.nodes[self.goalNodes[goalInd]] path.append(curr.pos) while curr.cameFrom != None : curr = curr.cameFrom path.append(curr.pos) return path[ : : -1] return False @staticmethod def getX(pos1, pos2, y) : if pos1[1] - pos2[1] == 0 : return None x = pos2[0] + (y - pos2[1]) * (pos1[0] - pos2[0]) / (pos1[1] - pos2[1]) return x @staticmethod def getY(pos1, pos2, x) : if pos1[0] - pos2[0] == 0 : return None y = pos2[1] + (x - pos2[0]) * (pos1[1] - pos2[1]) / (pos1[0] - pos2[0]) return y ## THEIR CODE BELOW, DONOT CROSS THIS LINE ########## Default Level 1 ########## ''' def level1(botId): mission_complete=False botId=0 while(not mission_complete): successful_move, mission_complete = send_command(botId,r.randint(1,8)) if successful_move: print("YES") else: print("NO") if mission_complete: print("MISSION COMPLETE") pos=get_botPose_list() print(pos[0]) ''' ''' def level1(botId) : toSeek = botId * len(stringFormat) CommsFile.write('{} : Calculating\n'.format(botId)) CommsFile.seek(toSeek) while True : try : _map = get_Map() break except : pass RRTGraph = Graph(10) RRTGraph.map = _map RRTGraph.obsList = get_obstacles_list() start = tuple(get_botPose_list()[botId]) print('Start Color : {}'.format(RRTGraph.map[start])) print('One obstacle rect : {}'.format(RRTGraph.obsList[0])) startNode = Node(start) RRTGraph.addNode(startNode) pathFound = False Choices = [0] * 2000 + [1] * 20 checkInterval = 100 i = 0 while not pathFound : choice = rnd.choice(Choices) if choice == 0 : RRTGraph.expand() else : goal = (199, 199) RRTGraph.bias(goal) i += 1 if not (i % checkInterval) : pathFound = RRTGraph.checkGoals() path = None if pathFound : # path = RRTGraph.constructPath(RRTGraph.goalNodes[list(RRTGraph.goalNodes.keys())[0]]) print(RRTGraph.goalNodes) GoAl = list(RRTGraph.goalNodes.keys())[0] print(list(RRTGraph.goalNodes.keys())[0] == 0) print(0 in RRTGraph.goalNodes) path = RRTGraph.constructPath(GoAl) print(path) TotalPath = [] for i in range(len(path) - 1) : TotalPath += A_Star(path[i], path[i + 1], heuristic, RRTGraph.obsList) print(TotalPath) TotalPath2 = A_Star(start, (197, 197), heuristic, RRTGraph.obsList) print(TotalPath2) CommsFile.write('{} : Travelling \n'.format(botId, 0)) CommsFile.seek(toSeek) for comm in TotalPath : successful_move, mission_complete = send_command(botId,comm) if successful_move: print("YES") else: print("NO") if mission_complete: print("MISSION COMPLETE") CommsFile.write('{} : Sleeping \n'.format(botId, 0)) CommsFile.seek(toSeek) return False print(get_botPose_list()[botId]) CommsFile.write('{} : Sleeping \n'.format(botId, 0)) CommsFile.seek(toSeek) return True ''' def selectGoal(start, goalList, blackList) : minDistance = math.inf minGoal = 'not Possible' for ind in range(len(goalList)) : if ind not in blackList : tl, br = goalList[ind][0], goalList[ind][1] center = (tl[0] + br[0]) // 2, (tl[1] + br[1]) // 2 D = distance(center, start) if minDistance > D : minDistance = D minGoal = ind return minGoal def level1(botId) : # Seek to the pos in file where current bot's info is present toSeek = (botId) * len(stringFormat) # Get list of bot Posi botPosList = get_botPose_list() start = tuple(botPosList[botId]) CommsFile.seek(toSeek) ''' CommsFile.seek(0) blackList = eval(CommsFile.read(len(stringFormat))) CommsFile.seek(toSeek) ''' while True : # Calculating Path print('Calculating') # Update so in file CommsFile.write('{} : Calculating : \n'.format(botId)) CommsFile.flush() CommsFile.seek(toSeek) # Get Goal based on blacklist and proximity ind = selectGoal(start, goalList, blackList) # Unexpected Scenario, shouldnt happen at all if ind is None : print('Got None, blacklist = ', blackList) # No goal possible, send to sleep if ind == 'not Possible' : print('{} Sleeping'.format(botId)) CommsFile.write('{} : Sleeping : \n'.format(botId)) CommsFile.flush() return False toBreak = False # Goal center coords goal = (goalList[ind][0][0] + goalList[ind][2][0]) // 2, (goalList[ind][0][1] + goalList[ind][2][1]) // 2 # Calculate path to goal center path = A_Star(start, goal, heuristic, obsList, redList) # Update file with calculated goal ind and path len CommsFile.write('{} : Calculated {} : {}\n'.format(botId, getGoalIDStr(ind), getPathLenStr(len(path)))) CommsFile.flush() CommsFile.seek(toSeek) # Wait till all bots have finished 'Calculating' wait = True while wait : BlackFile.seek(0) # BlackList evaluated _Black = eval(BlackFile.read()) # Add non existing goals to blackList blackList.extend([b for b in _Black if b not in blackList and b is not None]) # Read all statuses (only 'numbots' statuses) CommsFile.seek(0) Statuses = CommsFile.readlines()[ : numbots] CommsFile.seek(toSeek) _Statuses = [] _Goals = [] _pathLens = [] # By default do not wait wait = False # Iterate over statuses # Decode comms format to get values for status in Statuses : bot, _status, goalTo, pathLen = decodeComms(status[ : -1]) # If One bot's status is calculating, MUST WAIT if _status == 'Calculating' : wait = True break # If someone is travelling while we are waiting, we must take their goal and add to our blacklist if _status == 'Travelling' : if goalTo not in blackList : blackList.append(goalTo) # Append all info _Statuses.append(_status) _Goals.append(goalTo) _pathLens.append(pathLen) # Sleep, bcoz you got time time.sleep(0.005) # FROM HERE ON, ALL BOTS HAVE ATLEAST REACHED STAGE 'CALCULATED' or 'TRAVELLING' or ARE DONE ('SLEEPING') # List, rather dictionary of unique goals sought after uniqueGoals = {} # print(_Statuses, _Goals, _pathLens) # Bots that need to recalculate path ToRecalculate = [] for i in range(numbots) : # goal of some bot (may not even exist == None) goalTo = _Goals[i] # If goal in blacklist, current bot must recalculate if goalTo in blackList : ToRecalculate.append(i) continue # If valid comms if goalTo is not None and _pathLens[i] != 0 : # If already sought after if goalTo in uniqueGoals : # Get currently shortest path to that goal and the bot who has that path minD, b = uniqueGoals[goalTo] # If current is even shorter if _pathLens[i] <= minD : # Recalculate prev bot, HAHA ToRecalculate.append(b) # update unique goals dict uniqueGoals[goalTo] = (_pathLens[i], i) else : ToRecalculate.append(i) # First bot iterated, going after this goal, take it as reference else : uniqueGoals[goalTo] = (_pathLens[i], i) print('To recalculate : ', ToRecalculate) # If me not in ToRecalucate, Imma head out if botId not in ToRecalculate : toBreak = True # Remove this # toBreak = True if toBreak : break # THOSE WHO HAVE TO RECALCULATE REACH HERE # For all those who are recalculating, the unique goals are taken by other bots by now so add to blacklist for G in uniqueGoals : if G not in blackList : blackList.append(G) CommsFile.write('{} : Travelling {} : \n'.format(botId, getGoalIDStr(ind))) CommsFile.flush() CommsFile.seek(toSeek) BlackFile.seek(0, 2) BlackFile.write('{}, '.format(ind)) BlackFile.flush() print('Writing To File {}'.format(ind)) time.sleep(0.005) blackList.append(ind) # Tavelling for comm in path : successful_move, mission_complete = send_command(botId,comm) if successful_move: # print("YES") pass else: # print("NO") pass if mission_complete: print("MISSION COMPLETE") CommsFile.write('{} : Sleeping : \n'.format(botId)) CommsFile.flush() ManageGoneTxt = open(BlackFilePath, 'w') ManageGoneTxt.write('None, ') ManageGoneTxt.flush() ManageGoneTxt.close() return False # CommsFile.write('{} : Sleeping : \n'.format(botId, 0)) # CommsFile.seek(toSeek) # Finish, POG return True def level2(botId) : toLoop = True while toLoop : toLoop = level1(botId) print('Bot {} has done its part'.format(botId)) def level3(botId) : # obs list same for all bots # pog print('OBS LIST\n{} : {}'.format(botId, get_obstacles_list())) level2(botId) def level4(botId): level2(botId) def level5(botId): level2(botId) def level6(botId): level2(botId) ####### DON'T EDIT ANYTHING BELOW ####################### if __name__=="__main__": botId = int(sys.argv[1]) level = get_level() if level == 1: level1(botId) elif level == 2: level2(botId) elif level == 3: level3(botId) elif level == 4: level4(botId) elif level == 5: level5(botId) elif level == 6: level6(botId) else: print("Wrong level! Please restart and select correct level") CommsFile.close() BlackFile.close()
true
38d6b2b0993172a4681fb0d9ca4d298a4182e2db
Python
shan18/Solutions-to-Machine-Learning-by-Andrew-Ng
/KMeans_and_PCA/PCA/pca_script.py
UTF-8
1,513
3.015625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from KMeans_and_PCA.PCA.RunPCA import pca from KMeans_and_PCA.PCA.ProjectData import project_data from KMeans_and_PCA.PCA.RecoverData import recover_data # ----------------------- Load data ------------------------------------ data = loadmat('ex7data1.mat') X = data['X'] # ----------------------- Plotting ------------------------------------- print('Plotting Data ...') fig, ax = plt.subplots(figsize=(12, 8)) ax.scatter(X[:, 0], X[:, 1]) plt.show() # ----------------------- PCA ----------------------------- print('\n\nRunning PCA on example dataset...') U, S, V = pca(X) Z = project_data(X, U, 1) print('First reduced example value:', Z[0]) X_recovered = recover_data(Z, U, 1) print('First recovered example value:', X_recovered[0]) # ----------------------- Viewing the result ---------------------- fig, ax = plt.subplots(figsize=(12, 8)) ax.scatter(np.array(X_recovered[:, 0]), np.array(X_recovered[:, 1])) plt.show() # ----------------------- PCA on Face Dataset ---------------------- print('\n\nLoading face dataset...') faces = loadmat('ex7faces.mat') X = faces['X'] print('Face dataset shape:', X.shape) print('\nLoading one face..') face = np.reshape(X[3, :], (32, 32)) plt.imshow(face) plt.show() print('\nRunning PCA on face dataset...\n') U, S, V = pca(X) Z = project_data(X, U, 100) X_recovered = recover_data(Z, U, 100) face = np.reshape(X_recovered[3, :], (32, 32)) plt.imshow(face) plt.show()
true
dc0ff5efcbff9257d6644789c0f0058d2961aa9a
Python
RyanKung/magic-parameter
/magic_parameter/parameter_declaration.py
UTF-8
2,766
2.703125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- from __future__ import ( division, absolute_import, print_function, unicode_literals, ) from builtins import * # noqa from future.builtins.disabled import * # noqa from collections import namedtuple, Iterable from magic_parameter.type_declaration import type_decl_factory class ParameterDecl(object): def __init__(self, name, raw_type, with_default, default): self.name = name self.type_decl = type_decl_factory(raw_type) self.with_default = with_default self.default = default def check_argument(self, arg): if arg is None: # 1. None by default and implicitly set. # 2. None by default and explicitly set. # 3. type(None). if self.with_default and self.default is None or\ self.type_decl.type_ is type(None): # noqa pass else: raise TypeError( 'cannot pass None to {0}.'.format(self.name), ) else: self.type_decl.check_argument(arg) # intput: (<name>, <type decl>, [<default>])... # output: ParameterDeclPackage def build_parameters_decl_package(raw_parameter_decls): if not isinstance(raw_parameter_decls, Iterable): raise TypeError( 'raw_parameter_decls should be Iterable.', ) name_hash = {} parameter_decls = [] start_of_defaults = -1 for raw_parameter_decl in raw_parameter_decls: if len(raw_parameter_decl) < 2: raise TypeError( 'Should be (<name>, <type decl>, [<default>])', ) name = raw_parameter_decl[0] raw_type = raw_parameter_decl[1] if len(raw_parameter_decl) >= 3: with_default = True default = raw_parameter_decl[2] else: with_default = False default = None if name in name_hash: raise SyntaxError('duplicates on ' + name) parameter_decls.append( ParameterDecl(name, raw_type, with_default, default), ) idx = len(parameter_decls) - 1 name_hash[name] = idx if with_default: if start_of_defaults < 0: start_of_defaults = idx else: if start_of_defaults >= 0: raise SyntaxError( 'Parameter without default should be placed ' 'in front of all parameters with default.' ) ParameterDeclPackage = namedtuple( 'ParameterDeclPackage', ['parameter_decls', 'name_hash', 'start_of_defaults'], ) return ParameterDeclPackage( parameter_decls, name_hash, start_of_defaults, )
true
400350b86e6724b7e36b32c75336f1e9d775addb
Python
ramanmishra/Code-Chef-Solutions
/Beginner/Coins_And_Triangle.py
UTF-8
170
3.609375
4
[]
no_license
t = int(input()) def sum_n(n): return n * (n + 1) // 2 for i in range(t): n = int(input()) h = 0 while sum_n(h) <= n: h += 1 print(h - 1)
true
33d200c928756f57f336003c3352e6b04f7989a4
Python
RobertNimmo26/quizBuddy
/population_script.py
UTF-8
11,815
2.796875
3
[]
no_license
import os import random os.environ.setdefault('DJANGO_SETTINGS_MODULE','quiz_buddy.settings') import django django.setup() from django.utils import timezone from quiz.models import Character,User,Class, Quiz, Question, Option, QuizTaker from quiz.managers import CustomUserManager def populate(): #CREATE USERS AND CHARACTERS #------------------------------------------------------------------------------------------------------------------------------------ student_users = {'Alice':{'email':'alice@test.com', 'username':'alice9','password':'12364','is_student':True, 'character':1,'evolve_score':2}, 'Tom':{'email':'tom@test.com', 'username':'Tom','password':'password','is_student':True,'character':2,'evolve_score':3}} teacher_users = {'David':{'email':'david@staff.com', 'username':'david','password':'2856','is_teacher':True,'is_staff':True}, 'Anna':{'email':'anna@testteacher.com', 'username':'anna','password':'anna123','is_teacher':True,'is_staff':True}} admin_user = {'Tania':{'email':'tania@admin.com','password':'hello'}, 'Jim':{'email':'jim@admin.com','password':'bye'}} characters = [{'type':1,'evolutionStage':1},{'type':1,'evolutionStage':2},{'type':1,'evolutionStage':3}, {'type':2,'evolutionStage':1},{'type':2,'evolutionStage':2},{'type':2,'evolutionStage':3}, {'type':3,'evolutionStage':1},{'type':3,'evolutionStage':2},{'type':3,'evolutionStage':3}] for c in characters: add_character(c['type'],c['evolutionStage']) for s, s_data in student_users.items(): add_student(s,s_data['username'],s_data['email'],s_data['password'],s_data['is_student'],s_data['character'],s_data['evolve_score']) for t, t_data in teacher_users.items(): add_teacher(t,t_data['username'],t_data['email'],t_data['password'],t_data['is_teacher'],t_data['is_staff']) for a, a_data in admin_user.items(): add_admin(a_data['email'],a_data['password'],a) #CREATE CLASSES AND ADD QUIZZES TO THE CLASSES #------------------------------------------------------------------------------------------------------------------------------------ math_quiz = [{'name':'MCQSet1', 'description':'A quiz that covers basic arithmetic operations','question_count':3, 'teacher':teacher_users['Anna']}, {'name': 'MCQSet2' ,'description':'Covers basic geometry questions' , 'question_count':4, 'teacher':teacher_users['David']}] computing_quiz = [{'name':'Programming' , 'description': 'Covers basics of programming', 'question_count': 3, 'teacher':teacher_users['Anna']}] psyc_quiz = [{'name': 'Psych-Basics', 'description':'Covers the content covered in lectures','question_count':5, 'teacher':teacher_users['David']}] course = {'Maths': {'quiz':math_quiz, 'teacher':teacher_users['David'],'student': student_users['Alice']}, 'Computing': {'quiz':computing_quiz,'teacher':teacher_users['Anna'],'student':student_users['Tom']}, 'Psychology':{'quiz':psyc_quiz,'teacher':teacher_users['David'], 'student':student_users['Alice']}} quizTaker = {'MCQSet1':{'student':student_users['Alice'],'class':'Maths','correctAns':3,'is_completed':True}, 'Programming':{'student':student_users['Tom'],'class':'Computing','correctAns':2,'is_completed':True}} #Add courses and quizzes to courses for course, course_data in course.items(): c = add_class(course,course_data['student']['email'],course_data['teacher']['email']) for q in course_data['quiz']: add_quiz(c,q['name'],q['description'],q['question_count'],course_data['teacher']['email']) #Make students do quizzes for q,q_taker in quizTaker.items(): q = add_quizTaker(q_taker['student']['email'],q,q_taker['class'],q_taker['correctAns'],q_taker['is_completed']) #ADD QUESTIONS TO THE QUIZZES AND THEN ADD OPTIONS TO THE QUESTIONS #------------------------------------------------------------------------------------------------------------------------------------ questions1 = [{'text': 'What is 3+8*11 ?', 'options':[{'text': '121','is_correct': False},{'text':'91','is_correct':True},{'text':'-91','is_correct':False}]}, {'text':'What is the next number in the series: 2, 9, 30, 93, …?', 'options':[{'text': '282','is_correct':True},{'text':'102','is_correct':False},{'text':'39','is_correct':False}]}, {'text':'What is nine-tenths of 2000?', 'options':[{'text':'2222','is_correct':False},{'text':'1800','is_correct':True},{'text':'20','is_correct':False}]}] questions2 = [{'text': 'What is sum of angles in a triangle?', 'options':[{'text': '360','is_correct': False},{'text':'180','is_correct':True},{'text':'Do not know','is_correct':False}]}, {'text':'Which triangle has all three equal sides?', 'options':[{'text': 'Scalene','is_correct':False},{'text':'Isosceles','is_correct':False},{'text':'Equilateral','is_correct':True}]}, {'text':'How many degrees is a right angle?', 'options':[{'text':'90','is_correct':True},{'text':'180','is_correct':False},{'text':'0','is_correct':False}]}, {'text':'How many sides does a hexagon have?', 'options':[{'text':'7','is_correct':False},{'text':'6','is_correct':True},{'text':'Hexagon does not exits','is_correct':False}]}] programming = [{'text':'A syntax error means:', 'options':[{'text':'Breaking the language rules','is_correct':True},{'text':'Error with the logic','is_correct':False},{'text':'Dont Know','is_correct':False}]}, {'text':'What symbol is used in Java for "AND"', 'options':[{'text':'$$','is_correct':False},{'text':'&&','is_correct':True},{'text':'&','is_correct':False}]}, {'text':'Which symbol is used to denote single line comments in Python', 'options':[{'text':'#','is_correct':True},{'text':'@@','is_correct':False},{'text':'\\','is_correct':False}]}] psych_basics = [{'text': 'Pavlov is famous for conducting experiments on ?', 'options':[{'text': 'Birds','is_correct': False},{'text':'Rats','is_correct':False},{'text':'Dogs','is_correct':True}]}, {'text':'What area of psychology is Piaget famous for providing theories?', 'options':[{'text': 'Sexuality','is_correct':False},{'text':'Child Development','is_correct':True},{'text':'Aging','is_correct':False}]}, {'text':'The first step of classical conditioning is pairing a neutral stimulus with an _____ stimulus.', 'options':[{'text':'Conditioned','is_correct':False},{'text':'Unconditioned','is_correct':True},{'text':'Novel','is_correct':False}]}, {'text':'What is the main difference between a psychologist and a psychiatrist?', 'options':[{'text':'A psychiatrist is classified as a medical doctor','is_correct':True}, {'text':'A pschologist only holds Associate Degree','is_correct':False},{'text':'Both are the same','is_correct':False}]}, {'text':'Psychology is the study of mind and ____', 'options':[{'text':'behaviour','is_correct':True},{'text':'body','is_correct':False},{'text':'Dont Know','is_correct':False}]}] quiz__ques = {'MCQSet1':{'questions':questions1},'MCQSet2':{'questions':questions2}, 'Programming':{'questions':programming},'Psych-Basics':{'questions':psych_basics}} for quiz, ques in quiz__ques.items(): for q in ques['questions']: add_ques(quiz,q['text']) for opt in q['options']: add_option(q,opt['text'],opt['is_correct']) #PRINT #---------------------------------------------------------------------------------------------------------------------------------- print('\nAdmins') print('--------------------') for admin in User.objects.filter(is_superuser = True): print(f'{admin.name}:{admin}') print('\nTeachers') print('--------------------') for teacher in User.objects.filter(is_teacher = True): print(f'{teacher.name}:{teacher}') print('\nCharacters...') print('--------------------') for charac in Character.objects.all(): print(f' Character:{charac} Evolution Stage:{charac.evolutionStage}') print('\nStudents') print('--------------------') for student in User.objects.filter(is_student = True): print(f'Name:{student.name} Email:{student} CharacterType:{student.character} EvolutionStage:{student.evolveScore}') print('\nCourses and Quizzes') print('---------------------') # Print out the classes we have added. for c in Class.objects.all(): for (k,v) in zip(c.teacher.all(),c.student.all()): print(f'Course: {c} Teacher: {k} Student: {v}') for q in Quiz.objects.filter(course=c): print(f'\nCourse: {c}: Quiz: {q} Due Date: {q.due_date}') print('-----------------') for ques in Question.objects.filter(quiz = q): print(f'Question: {ques}') for opt in Option.objects.filter(question = ques): print(f' Option: {opt}') print('\nStudent Quiz Scores') print('---------------------') for q in QuizTaker.objects.all(): print(f'Student: {q.user.name}, Quiz: {q.quiz}, Complete: {q.is_completed} Correct Answers: {q.correctAnswers}') #----------------------------------------------------------------------------------------------------------------------------------- def add_student(name,username,email,password,is_student,charac,evol_score): charact = Character.objects.get(characterType = charac,evolutionStage = evol_score) u = User.objects.create_user(email = email, password = password, name = name, username = username,is_student = is_student,character = charact,evolveScore = evol_score ) u.save() return u def add_teacher(name,username,email,password,is_teacher,is_staff): u = User.objects.create_user(email = email, password = password, name = name, username = username, is_teacher = is_teacher, is_staff = is_staff ) u.save() return u def add_admin(email,password,name): admin = User.objects.create_superuser(email = email,password = password, name = name) admin.save() return admin def add_class(name, s, t): c = Class.objects.get_or_create(name=name)[0] c.save() c.student.add(User.objects.get(email = s)) c.teacher.add(User.objects.get(email = t)) return c def add_quiz(c,name,desc,ques_count,teacher): randomDay=random.randint(-5,20) date_time = timezone.now() + timezone.timedelta(days=randomDay) get_teacher = User.objects.get(email = teacher) q = Quiz.objects.get_or_create(name = name,description=desc,due_date=date_time,question_count=ques_count,teacher=get_teacher)[0] q.save() q.course.add(c) return q def add_ques(q,text): get_quiz = Quiz.objects.get(name = q) ques = Question.objects.get_or_create(quiz = get_quiz,text = text)[0] ques.save() return ques def add_option(ques,text,is_correct): get_ques = Question.objects.get(text = ques['text']) opt = Option.objects.get_or_create(question = get_ques, text = text, is_correct = is_correct)[0] opt.save() return opt def add_character(charac_type, evolStage ): charac = Character.objects.get_or_create(characterType= charac_type, evolutionStage = evolStage)[0] charac.save() return charac def add_quizTaker(user,q,course,correctAns,complete): quiz = Quiz.objects.get(name = q) courseObj = Class.objects.get(name=course) student = User.objects.get(email = user) quizTaker = QuizTaker.objects.get_or_create(quiz = quiz, user = student,course=courseObj, correctAnswers = correctAns, is_completed = complete, quizDueDate=quiz.due_date)[0] quizTaker.save() return quizTaker if __name__ == '__main__': print('Starting Quiz population script...') populate()
true
be406ef455dff038f483f17eee5373e567bd0751
Python
1109israel/AprendiendoGit
/margarita/palindromo.py
UTF-8
282
3.71875
4
[]
no_license
palabra=input() #Pedir al usuario una frase nva_palabra=palabra.lower() palabra2=nva_palabra.replace(' ','') reversa=palabra2[::-1] if reversa == palabra2: print('La frase que ingresaste SÍ es un palíndromo.') else: print('La frase que ingresaste NO es un palíndromo.')
true
d8b5d7b58768ff357637e98615789972ab11f9a4
Python
lixiang2017/leetcode
/explore/2020/november/Longest_Substring_with_At_Least_K_Repeating_Characters.1.py
UTF-8
997
3.34375
3
[]
no_license
''' Brute Force Time: O(26 * n^2) = O(n^2) Space: O(1) Success Details Runtime: 9240 ms, faster than 5.30% of Python online submissions for Longest Substring with At Least K Repeating Characters. Memory Usage: 14.1 MB, less than 9.93% of Python online submissions for Longest Substring with At Least K Repeating Characters. ''' class Solution(object): def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ longest_length = 0 size = len(s) for i in range(size): countMap = defaultdict(int) for j in range(i, size): countMap[s[j]] += 1 if self.isValid(countMap, k): longest_length = max(longest_length, j - i + 1) return longest_length def isValid(self, countMap, k): for ch, times in countMap.iteritems(): if times < k: return False return True
true
34747b1c2333c7eeb9bf71b44d16e40a869573fb
Python
xu20160924/leetcode
/leetcodepython/app/leetcode/61.py
UTF-8
874
3.140625
3
[]
no_license
from app.algorithm.Entity import ListNode class Solution(object): def rotateRight(self, head: 'ListNode', k: 'int') -> 'ListNode': if not head: return None if not head.next: return head old_tail = head n = 1 while old_tail.next: old_tail = old_tail.next n += 1 old_tail.next = head new_tail = head for i in range(n - k % n - 1): new_tail = new_tail.next new_head = new_tail.next new_tail.next = None return new_head if __name__ == '__main__': node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node4.next = node5 node3.next = node4 node2.next = node3 node1.next = node2 solution = Solution() solution.rotateRight(node1, 2)
true
8a0f8e21abf97f7f077fb89caf36bf63cc06f923
Python
wancongji/python-learning
/lesson/7/practice4.py
UTF-8
198
4.09375
4
[]
no_license
n = int(input("Please input a number: ")) for i in range(2,n): if n%i == 0: print(i) print("The number is SUSHU.") break else: print("The number is not SUSHU.")
true
9b6eddf6c38ce9bb9485e35880943b54879fb0d4
Python
cwarje/AWSBotoLab
/p1.py
UTF-8
940
2.625
3
[]
no_license
import boto3 import sys def main(tag, toggle): client = boto3.client('ec2') response = client.describe_instances( Filters=[ { 'Name': 'tag:Tag', 'Values': [ tag, ] }, ] ) responseInstanceId = response["Reservations"][0]["Instances"][0]["InstanceId"] if toggle == "Stop": #TODO check if instance not running, exit loop. print("Stopping Instance ", responseInstanceId) response = client.stop_instances( InstanceIds=[ responseInstanceId, ] ) elif toggle == "Start": print("Starting Instance ", responseInstanceId) #TODO check if instance running, exit loop. response = client.start_instances( InstanceIds=[ responseInstanceId, ] ) else: print("Please enter a valid command: Start or Stop") if __name__ == '__main__': tag = sys.argv[1] toggle = sys.argv[2] main(tag, toggle)
true
bd6b3644afc104e7ba772eedf48f6077f38cdacf
Python
ThomasQuer/FIUBA_ALGO_TP2_G5_2020
/chatbot_training.py
UTF-8
1,381
2.53125
3
[]
no_license
import os from chatterbot import ChatBot from chatterbot import comparisons from chatterbot import response_selection from chatterbot import filters from chatterbot.trainers import ListTrainer chat = ChatBot( 'Crux', read_only=True, logic_adapters=[ { 'import_path': "chatterbot.logic.BestMatch", "statement_comparison_function": ( comparisons.LevenshteinDistance ), "response_selection_method": ( response_selection.get_first_response ), "default_response": ( "Lo siento, no entendí tu pregunta. " "¿Podrías volver a intentarlo?" ), 'maximum_similarity_threshold': 0.90 }, ], preprocessors=[ 'chatterbot.preprocessors.clean_whitespace' ], filters=[ filters.get_recent_repeated_responses ] ) directory = 'training_data' # Entrenamiento del bot. for filename in os.listdir(directory): if filename.endswith(".txt"): print( '\n Chatbot training with '+os.path.join(directory, filename) + ' file' ) training_data = ( open(os.path.join(directory, filename),encoding="latin1").read().splitlines() ) trainer = ListTrainer(chat) trainer.train(training_data)
true
2727c6b20db3b13dbe46561dc47374f5af0c8ffd
Python
harneyp2/bikemap
/bike_scraper/averages.py
UTF-8
3,801
3.140625
3
[]
no_license
import sqlite3 import datetime class averager(object): def getHourAverage(self, cur, id, day): '''THe function takes in as parameters a cursor to a database, the day of the week to be queried and the station id and returns the average available bikes available in the station for an hourly basis''' hourlyData = [] selected_day = self.getDay(day) data = cur.execute('SELECT round(avg(Bikes_Available)) FROM Station_data WHERE Station_Number = ? AND strftime("%H",Time_Stamp) >= "06" AND strftime("%w",Time_Stamp) IN (?) GROUP BY strftime("%H",Time_Stamp)', (id, selected_day)) reading = data.fetchall() for i in reading: hourlyData.append(str(i[0])) return hourlyData def getDayAverage(self, cur, id): '''This function just takes in as parameters a cursor to a database and the station ID to be queried and returns the overall average available bike count for each day of the week''' dailyData = [] data = cur.execute('SELECT round(avg(Bikes_Available)) FROM Station_data WHERE Station_Number = ? GROUP BY strftime("%w",Time_Stamp)', [id]) reading = data.fetchall() for i in reading: dailyData.append(str(i[0])) return dailyData def calculate_freetime(self, cur, id, day): day = self.getDay(day) # First we start with an empty array freetimedetails = [] # This will pull data regarding stations overall totalRequests = cur.execute('SELECT strftime("%H",Time_Stamp)/3, count(*) FROM Station_data WHERE Station_Number = ? AND strftime("%H",Time_Stamp) >= "06" AND strftime("%w",Time_Stamp) IN (?) GROUP BY strftime("%H",Time_Stamp)/3', (id, day)) total = totalRequests.fetchall() # This will pull data regarding stations if a stop is empty at one point during a three hour period empty_requests = cur.execute('SELECT strftime("%H",Time_Stamp)/3, count(*) FROM Station_data WHERE Bikes_Available = 0 AND Station_Number = ? AND strftime("%H",Time_Stamp) >= "06" AND strftime("%w",Time_Stamp) IN (?) GROUP BY strftime("%H",Time_Stamp)/3', (id, day)) empty = empty_requests.fetchall() for detail in range(0, len(total)): full = total[detail][1] # This will pull the relevant empty data from the query, if it matches a station number found in total. emptydata = [val[1] for val in empty if val[0] == total[detail][0]] # This will set the value of empty data to 0 if a station number is never empty emptydata = 0 if len(emptydata) == 0 else emptydata[0] # This is the weighted calculation, where we get the percentage of emptyness during a three hour period, then get the average of that. average_wait_time = (emptydata/full)*180*emptydata/full # The next three lines gets it to the closest minute, averaged upwards. average_wait_time_minutes = int(average_wait_time//1) if average_wait_time%1*100 >= 1: average_wait_time_minutes += 1 freetimedetails.append(average_wait_time_minutes) # print(freetimedetails) return freetimedetails def getHour(self, h): '''Returns the hour of the day used in an SQL query as a string''' if h < 10: return "0" + str(h) else: return str(h) def getDay(self, d): '''Returns the day of the week as it is represented in SQLite as a string that can be used for comparison''' days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] return str(days.index(d))
true
a658887f69d044aa0d909f9358784ec36e218d22
Python
Aasthaengg/IBMdataset
/Python_codes/p03565/s344958162.py
UTF-8
341
2.984375
3
[]
no_license
S = input() Sa = S.replace("?", "a") T = input() nt = len(T) ans = list() for i in range(len(S) - nt + 1): X = S[i: i + nt] for x, t in zip(X, T): if x == "?": continue if x != t: break else: ans.append(Sa[:i] + T + Sa[i + nt:]) ans.sort() print(ans[0] if ans else "UNRESTORABLE")
true
607bb63d853b7df667e7dc67ae932eecfb6ced2e
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_97/1736.py
UTF-8
869
2.8125
3
[]
no_license
#!/usr/bin/python import sys T=input() for nin in range(T): line=sys.stdin.readline() n1=int(line.split(" ")[0]) n2=int(line.split(" ")[1][:-1]) length=len(str(n1)) count=0 if(n1>=n2): count=0 sys.stdout.write("Case #"+str(nin+1)+": "+str(count)+"\n") continue for x in xrange(n1,n2,1): l=[] for y in range(length): x1=str(x) z=x1[y:]+x1[:y] if z[0]=="0": continue; z=int(z); iwc=0 for i in l: if i==z: iwc=1 continue if iwc==1: continue l.append(z) if z>x and z<=n2: count=count+1 sys.stdout.write("Case #"+str(nin+1)+": "+str(count)+"\n")
true
e496f800367f4b43a72e03aed8fcd6d35fd0f61b
Python
DanielSantin1/Phyton-1--semestre
/exercicio 9.py
UTF-8
404
3.640625
4
[]
no_license
#FUAQ calculao consumo de combustível em uma viagem em um carro #que faz media de 12km/L. Ler o tempo da viagem e a velocidade #média. Calcule a distância utilizando a fórmula: #D=V*T e o cosumo = D/12 T=float(input("tempo de viagem: ")) V=float(input("Velocidade média: ")) D=V*T print('Foram {:.2f}'.format(D), 'Km De Distância') D=D/12 print('Foram gastos {:.2f}'.format(D), 'De combustivel1')
true
9e4c1a2dddf57290dc103957c2837f13c94d2e77
Python
aravind-sundaresan/python-snippets
/Interview_Questions/first_nonrepeated_char.py
UTF-8
449
4.25
4
[]
no_license
# Question: print the first non repeated character from a string def non_repeated_character(test_string): char_count = {} for character in test_string: if character in char_count.keys(): char_count[character] += 1 else: char_count[character] = 1 for key in char_count: if char_count[key] == 1: return key if __name__ == '__main__': input_string = "geeksforgeeks" result = non_repeated_character(input_string) print(result)
true
6139eb89d4550565ac5fa60de60b025afe27147e
Python
helensanni/pihat
/hat_random_pixels.py
UTF-8
400
3.546875
4
[]
no_license
#!/usr/bin/env python # this script will display random pixels with random colors on the Pi HAT from sense_hat import SenseHat import time import random sense = SenseHat() # assign a random integer between 0 and 7 to a variable named x x = random.randint(0, 7) y = random.randint(0, 7) print("the random number is"), x, ("this time") sense.set_pixel(x, y, (0, 0, 255)) time.sleep(1) sense.clear()
true
30c18de1a90068260bb23cb6aaa63a5ef20484df
Python
happyxuwork/data-preprocess
/src/getImageFromDataSet/passive.py
UTF-8
182
2.609375
3
[]
no_license
# -*- coding: UTF-8 -*- ''' @author: xuqiang ''' def sayHello(): print("i am xuqiang") def main(): print("i am main function") if __name__ == "__main__": sayHello()
true
a546ded46effdcafe15c4ae278c22cfe67ab33c5
Python
2efPer/Siamese-LSTM
/src/utils.py
UTF-8
2,692
2.765625
3
[]
no_license
from tensorflow.python.keras import backend as K from tensorflow.python.keras.layers import Layer from tensorflow.python.keras.preprocessing.sequence import pad_sequences import gensim import numpy as np import itertools def make_w2v_embeddings(df, embedding_dim=20): vocabs = {} vocabs_cnt = 0 vocabs_not_w2v = {} vocabs_not_w2v_cnt = 0 print("Loading word2vec model(it may takes 2-3 mins) ...") word2vec = gensim.models.word2vec.Word2Vec.load("../data/Atec.w2v").wv for index, row in df.iterrows(): # Print the number of embedded sentences. if index != 0 and index % 1000 == 0: print("{:,} sentences embedded.".format(index)) # Iterate through the text of both questions of the row for sentence in ['s1', 's2']: q2n = [] # q2n -> question numbers representation for word in str(row[sentence]).split(","): # If a word is missing from word2vec model. if word not in word2vec.vocab: if word not in vocabs_not_w2v: vocabs_not_w2v_cnt += 1 vocabs_not_w2v[word] = 1 # If you have never seen a word, append it to vocab dictionary. if word not in vocabs: vocabs_cnt += 1 vocabs[word] = vocabs_cnt q2n.append(vocabs_cnt) else: q2n.append(vocabs[word]) # Append question as number representation df.at[index, sentence + '_n'] = q2n embeddings = 1 * np.random.randn(len(vocabs) + 1, embedding_dim) # This will be the embedding matrix embeddings[0] = 0 # So that the padding will be ignored # Build the embedding matrix for word, index in vocabs.items(): if word in word2vec.vocab: embeddings[index] = word2vec.word_vec(word) del word2vec return df, embeddings def split_and_zero_padding(df, max_seq_length): x = {'left': df['s1_n'], 'right': df['s2_n']} for dataset, side in itertools.product([x], ['left', 'right']): dataset[side] = pad_sequences(dataset[side], padding='pre', truncating='post', maxlen=max_seq_length) return dataset class ManDist(Layer): def __init__(self, **kwargs): self.result = None super(ManDist, self).__init__(**kwargs) def build(self, input_shape): super(ManDist, self).build(input_shape) def call(self, x, **kwargs): self.result = K.exp(-K.sum(K.abs(x[0] - x[1]), axis=1, keepdims=True)) return self.result def compute_output_shape(self, input_shape): return K.int_shape(self.result)
true
2ec68a20043e0f73cd531c9e3c5e461c14e9e36c
Python
romeorizzi/cms_algo2020
/for2_std/sol/soluzione_fast_py.py
UTF-8
236
2.53125
3
[]
no_license
#!/usr/bin/env python # -*- codingxs: utf-8 -*- # Soluzione di for2_std # Romeo Rizzi, last: 2020-04-01 N=int(input()) idx=list(range(1,N+1)) # creo lista [1,2,...,N] for k in range(1,N+1): print(' '.join(map(str, [k*x for x in idx])))
true
2bfb4cf46117150164810e5c02ae98785c50f059
Python
Greenwicher/Competitive-Programming
/LeetCode/63.py
UTF-8
831
2.828125
3
[]
no_license
# Version 1, Dynamic Programming, O(m*n) time complexity, O(m*n) space complexity class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ m, n = len(obstacleGrid), len(obstacleGrid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = [0, 1][obstacleGrid[0][0] == 0] for i in range(1, m): dp[i][0] = [dp[i-1][0], 0][obstacleGrid[i][0] == 1] for j in range(1, n): dp[0][j] = [dp[0][j-1], 0][obstacleGrid[0][j] == 1] for i in range(1, m): for j in range(1, n): if obstacleGrid[i][j]: dp[i][j] = 0 else: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m - 1][n - 1]
true
2c0bfa0afa8384fa53fe93a4eac9ba7e4f1efd0d
Python
Himanshu372/what-s_cooking_kaggle_dataset
/weighted_approach.py
UTF-8
3,930
3.109375
3
[]
no_license
import json import pandas as pd from pandas.io.json import json_normalize from urllib import request from bs4 import BeautifulSoup import re import datetime import pandas as pd def read_json(path): ''' Reads json file from path and converts it into pandas dataframe :param path: :return dataframe: ''' with open(path, 'r', encoding = 'utf') as f: train = json.load(f) train_df = json_normalize(train) return train_df def calculate_count(df): ''' Generates count dictionary for a key which has a list of values in the format [key : {value_1:5, value_2:10}] :param dataframe: :return dictionary: ''' cuisine = {} for i in range(len(df)): each_cuisine = df[i:i+1]['cuisine'].values[0] if each_cuisine in cuisine.keys(): ingredients_list = df[i:i+1]['ingredients'].values[0] for each_ing in ingredients_list: if each_ing in cuisine[each_cuisine].keys(): cuisine[each_cuisine][each_ing] += 1 else: cuisine[each_cuisine][each_ing] = 0 else: ingredients_list = df[i:i + 1]['ingredients'].values[0] cuisine[each_cuisine] = {each_ing:0 for each_ing in ingredients_list} return cuisine def calculate_weights(d): ''' Generates weights for list in format [key : {value_1:w1, value_2:w2}] :param dictionary: :return count_list: ''' for each_cuisine in d.keys(): total_sum = sum(d[each_cuisine][k] for k in d[each_cuisine].keys()) for each_ing in d[each_cuisine].keys(): d[each_cuisine][each_ing] = round(d[each_cuisine][each_ing]/total_sum, 4) return d def test_score(test_df): ''' Predicting score for test dataframe based on train frame of the format [key : {value_1:w1, value_2:w2}], calculating weighted scores for all permutations :param dataframe: :return dataframe: ''' # List for storing predictions pred = [] # Iterating over rows of test for row in range(len(test_df)): # Creating an empty score_list score_list = [] # Extracting ingredients from each test row ingredients_list = test_df[row:row + 1]['ingredients'].values[0] # Calculating score for each cuisine from extracted ingredients list for each_cuisine in weighted_cuisine_dict.keys(): score = 0 for each_ing in ingredients_list: # As ingredients are stored in the format {cuisine: {ind: score, ..}}, checking if ingredient is present or not for the cuisine if each_ing in weighted_cuisine_dict[each_cuisine].keys(): # If ingredient is then add the weight to score score += weighted_cuisine_dict[each_cuisine][each_ing] # Score for each cuisine gets added to score_list for each row(ingredient list) in test score_list.append((each_cuisine, round(score, 4))) # Sorting score list based upon score score_list = sorted(score_list, key = lambda x:x[1], reverse = True) # For each row, appending the predicted cuisine match based upon sorted score_list pred.append(score_list[0][0]) test_df['pred'] = pred return test_df def list_to_seq(df_col): ''' :param df_col: :return: ''' return df_col.apply(lambda x : ' '.join(x)) if __name__=='__main__': train = read_json('/content/train.json') test = read_json('/content/test.json') train, val = train_test_split(train, test_size=0.2, random_state=42) print(len(train), len(val)) d = calculate_count(train) weighted_cuisine_dict = calculate_weights(d) val_features = val[['id', 'ingredients']] val_pred = test_score(val_features) print(classification_report(val_labels, val_pred['pred'])) print(accuracy_score(val_labels, val_pred['pred']))
true
18ab1a87de3dce17aab226234a985affdc26b211
Python
mt3141/regex-replacer
/main.py
UTF-8
10,674
2.84375
3
[]
no_license
# 122520200014 010620210228 # ============================================================================== # main script # ------------------------------------------------------------------------------ # get options and arguments from command line # get backup from files if specified in options # find all match regex in file, convert them to target regex using convert.py # ============================================================================== import re import convert from optparse import OptionParser from os.path import isfile, isdir, splitext, join from os import walk, getcwd, makedirs from shutil import copy2 from uuid import uuid1 # feel free to add supported files SUPPORT_TYPES = ['txt', 'html', 'css', 'js'] # if BACKUP_DIRECTION = None, current directory will be use for get backup BACKUP_DIRECTION = None # log file name for using log (it's possible to use this file to restore changes) LOG_FILE = 'log.txt' # ============================================================================== # validate_regex function # ------------------------------------------------------------------------------ # compile entered regex and check is support? # ============================================================================== def validate_regex(reg): try: re.compile(reg) return True except: return False # ============================================================================== # get_file_extension function # ------------------------------------------------------------------------------ # return extension of given file. # ============================================================================== def get_file_extension(file): return splitext(file)[1][1:] # ============================================================================== # handle_command_errors function # ------------------------------------------------------------------------------ # handles error(s) in command. # ============================================================================== def handle_command_errors(parser, OPTIONS, ARGS): # 3 argument need if len(ARGS) != 3: parser.error("Wrong number of arguments.") # is first argument a valid file or directory? elif (not isfile(ARGS[0]) and not isdir(ARGS[0])): parser.error("Enter a valid file or directory!") # validate regex: second and third arguments elif (not validate_regex(ARGS[1]) or not validate_regex(ARGS[2])): parser.error("Enter a valid Regex!") # if a directory and type option entered: are all entered types supporte? elif (isdir(ARGS[0]) and not set(OPTIONS.TYPE).issubset(set(SUPPORT_TYPES))): parser.error( f"Not support type! Supported types: {', ' .join(OPTIONS.TYPE)}!") # if a file entered: is entered file extension supported? elif (isfile(ARGS[0]) and not get_file_extension(ARGS[0]) in SUPPORT_TYPES): parser.error( f"Not support type! Supported types: {', ' .join(OPTIONS.TYPE)}!") # ============================================================================== # commandParser function # ------------------------------------------------------------------------------ # define and pars command-line options. # ============================================================================== def command_parser(): # -h, --help: show usage parser = OptionParser(usage="usage: %prog [options] <filename or directory path> <regex to find> <target regex>", version="%prog 0.0.1") # backup option parser.add_option("-b", "--backup", action="store_true", dest="BACKUP", default=False, help="Create backup file before changing content of file!") # recursive search in directory (only if a diectory itered) parser.add_option("-r", "--recursive", action="store_true", dest="RECURSIVE", default=False, help="Search directories recursively (if directory entered).",) # specifies which type should change parser.add_option("-t", "--type", action="store", dest="TYPE", default="", help="Change file if it is specific type (if directory entered). ex: txt or txt,html",) # specifies files that contain a phrase should change parser.add_option("-c", "--contain", action="store", dest="CONTAIN", default="", help="Change file if its name contains specific phrase (if directory entered).",) (OPTIONS, ARGS) = parser.parse_args() # convert TYPE option to list or set default list if (OPTIONS.TYPE): OPTIONS.TYPE = OPTIONS.TYPE.split(',') else: OPTIONS.TYPE = SUPPORT_TYPES handle_command_errors(parser, OPTIONS, ARGS) return OPTIONS, ARGS # ============================================================================== # file_contain function # ------------------------------------------------------------------------------ # check existance of specific string in file's name. # ============================================================================== def file_contain(filename, contain): return True if contain.lower() in filename.lower() else False # ============================================================================== # create_file_list function # ------------------------------------------------------------------------------ # create a list of files that should change. # ============================================================================== def create_file_list(path, OPTIONS): files = [] if (isfile(path)): files.append(path) # is direction else: # append files that theri type for (dirpath, dirnames, filenames) in walk(path): for filename in filenames: #just supported files if (get_file_extension(filename) in OPTIONS.TYPE and file_contain(filename, OPTIONS.CONTAIN)): files.append(join(dirpath, filename)) # if recursive == false breaks and does not search in inside directions if(not OPTIONS.RECURSIVE): break return files # ============================================================================== # create_files_dic function # ------------------------------------------------------------------------------ # create a dictionary that its key is primitive file path # and its value is a uniqe valid name for backup file # ============================================================================== def create_files_dic(files): files_dic = {} # remove not valid characters for file name for file in files: file = file.replace('\\', '/') files_dic[file] = str(uuid1()) + '_' + file.replace('/', '_').replace(':', '_') return files_dic # ============================================================================== # create_file_in function # ------------------------------------------------------------------------------ # create a file in given directory, if not exist. # ============================================================================== def create_file_in(file, direcory): if (not isdir(direcory)): makedirs(direcory) # in this case there is no need to if condition # if ile exist this function will not called if (not isfile(f"{direcory}/{file}")): file = open(f"{direcory}/{file}", 'w') file.close() # ============================================================================== # create_log function # ------------------------------------------------------------------------------ # create a log file. it's possible to use this file to restore changes. # ============================================================================== def create_log(files_dic, back_dir): # create log file if not exist if (not isfile(f"{back_dir}/{LOG_FILE}")): create_file_in(LOG_FILE, back_dir) with open(f"{back_dir}/{LOG_FILE}", "w") as log: log.write("LOG FILE: this file contain information for restoring changes done by script!!!\n") log.write("===============================================================================\n") with open(f"{back_dir}/{LOG_FILE}", "a") as log: for key, value in files_dic.items(): log.write(f"{key}: {value}.bak\n") log.write("===============================================================================\n") # ============================================================================== # backup function # ------------------------------------------------------------------------------ # backup files befoe change them in BACKUP_DIRECTION or working directory. # ============================================================================== def backup(files): if(BACKUP_DIRECTION and isdir(BACKUP_DIRECTION)): back_dir = BACKUP_DIRECTION else: back_dir = f'{getcwd()}/bak'.replace('\\', '/') # create a dictioanry of files and its backup names (in uniform shape) files_dic = create_files_dic(files) # create log, for restore changes create_log(files_dic, back_dir) for file_pair in files_dic.items(): copy2(file_pair[0], f'{back_dir}/{file_pair[1]}.bak') # ============================================================================== # main function # ------------------------------------------------------------------------------ # Initialize command-line argument parser, loggers, searchs input files. # ============================================================================== def main(): # parse command OPTIONS, ARGS = command_parser() # ARGS[0] is file or directory path. # Lets create a list of all files that should change files = create_file_list(ARGS[0], OPTIONS) # if backup need so get a backup from file(s) if (OPTIONS.BACKUP): backup(files) # replace all matched regex to target regex for file in files: convert.main(ARGS[1], ARGS[2], file) # ============================================================================== # Application code # ------------------------------------------------------------------------------ # Calls main function. # ============================================================================== if __name__ == "__main__": main()
true
94e688f901a9570c29e13601371f6787e3acb2cb
Python
ricardoaraujo/boku-engine
/random_client.py
UTF-8
1,401
3.203125
3
[ "Unlicense" ]
permissive
import urllib.request import sys import random import time if len(sys.argv)==1: print("Voce deve especificar o numero do jogador (1 ou 2)\n\nExemplo: ./random_client.py 1") quit() # Alterar se utilizar outro host host = "http://localhost:8080" player = int(sys.argv[1]) # Reinicia o tabuleiro resp = urllib.request.urlopen("%s/reiniciar" % host) done = False while not done: # Pergunta quem eh o jogador resp = urllib.request.urlopen("%s/jogador" % host) player_turn = int(resp.read()) # Se jogador == 0, o jogo acabou e o cliente perdeu if player_turn==0: print("I lose.") done = True # Se for a vez do jogador if player_turn==player: # Pega os movimentos possiveis resp = urllib.request.urlopen("%s/movimentos" % host) movimentos = eval(resp.read()) # Escolhe um movimento aleatoriamente movimento = random.choice(movimentos) # Executa o movimento resp = urllib.request.urlopen("%s/move?player=%d&coluna=%d&linha=%d" % (host,player,movimento[0],movimento[1])) msg = eval(resp.read()) # Se com o movimento o jogo acabou, o cliente venceu if msg[0]==0: print("I win") done = True if msg[0]<0: raise Exception(msg[1]) # Descansa um pouco para nao inundar o servidor com requisicoes time.sleep(1)
true
e19bfde8b4c36ea305720b188444c1c727d4ed97
Python
tenpaMk2/myrogue
/npcai.py
UTF-8
6,974
2.65625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'tenpaMk2' import logging import logging.config logging.config.fileConfig("config/logging.conf") from abc import ABCMeta, abstractmethod import warnings import model import astar import shadowcasting import position class STATE(object): stop = 0 wander = 1 chase = 2 escape = 3 class AIBase(metaclass=ABCMeta): def __init__(self, map_model: "model.MapModel"): self.map_model = map_model self.state = STATE.stop @abstractmethod def act(self): if self.state == STATE.stop: self.stop() elif self.state == STATE.wander: self.wander() elif self.state == STATE.chase: self.chase() elif self.state == STATE.escape: self.escape() else: raise Exception("Invalid STATE!") @abstractmethod def stop(self): pass @abstractmethod def wander(self): pass @abstractmethod def chase(self): pass @abstractmethod def escape(self): pass class VillagerAI(AIBase): def __init__(self, map_model: "model.MapModel", villager: "model.Villager"): super(VillagerAI, self).__init__(map_model) self.state = STATE.stop self.villager = villager def act(self): super(VillagerAI, self).act() def stop(self): logging.info("VillagerAI") self.villager.do_nothing() def wander(self): logging.info("VillagerAI") self.villager.do_nothing() def chase(self): logging.info("VillagerAI") self.villager.do_nothing() def escape(self): logging.info("VillagerAI") self.villager.do_nothing() class EnemyAI(AIBase): def __init__(self, map_model: "model.MapModel", enemy: "model.Enemy"): super(EnemyAI, self).__init__(map_model) self.state = STATE.stop self.enemy = enemy self.target_pos = None def act(self): super(EnemyAI, self).act() def stop(self): logging.info("EnemyAI") nearest_target_pos = self._get_nearest_target_pos() if self._is_in_fov(nearest_target_pos): logging.info("change mode : chase") self.state = STATE.chase self.target_pos = nearest_target_pos self.enemy.do_nothing() else: logging.info("Hero not found") self.enemy.do_nothing() def wander(self): logging.info("EnemyAI") self.enemy.do_nothing() def chase(self): logging.info("EnemyAI") self.target_pos = self._get_nearest_target_pos() logging.info("target_pos : %r", self.target_pos) # TODO 近いかどうかではなく、有効射程かどうかで判断したいところ。 if self._is_near(self.target_pos): logging.info("target is near!") self._attack_to(self.target_pos) else: ast = self._make_ast() next_position = ast.get_next_position() logging.info("next position is %r", next_position) y_n, x_n = next_position y_e, x_e = self.enemy.get_position() if [y_e, x_e] == [y_n + 1, x_n]: self.enemy.move_north() elif [y_e, x_e] == [y_n, x_n - 1]: self.enemy.move_east() elif [y_e, x_e] == [y_n - 1, x_n]: self.enemy.move_south() elif [y_e, x_e] == [y_n, x_n + 1]: self.enemy.move_west() else: self.enemy.do_nothing() def escape(self): logging.info("EnemyAI") self.enemy.do_nothing() def _attack_to(self, defender_pos): if defender_pos == self.enemy.get_north_position(): self.enemy.attack_to(position.DIRECTION.north) elif defender_pos == self.enemy.get_east_position(): self.enemy.attack_to(position.DIRECTION.east) elif defender_pos == self.enemy.get_south_position(): self.enemy.attack_to(position.DIRECTION.south) elif defender_pos == self.enemy.get_west_position(): self.enemy.attack_to(position.DIRECTION.west) else: if self._is_near(defender_pos): raise Exception("Invalid DIRECTION!!") else: raise Exception("Target is too far!!") def _is_near(self, pos): return tuple(pos) in position.get_direction_poses_of(self.enemy.get_position()) def _return_map_for_astr(self): height = self.map_model.height width = self.map_model.width # 床と壁の追加 parsed_map = astar.SearchingMap.make_empty_map(height, width, astar.MAP.nothing) for obs in self.map_model.obstacle_objects: y, x = obs.get_position() parsed_map.set_value_at(y, x, astar.MAP.wall) # スタート(自分の位置)の追加 y_s, x_s = self.enemy.get_position() parsed_map.set_value_at(y_s, x_s, astar.MAP.start) # ゴール(Heroの位置)の追加 y_t, x_t = self.target_pos parsed_map.set_value_at(y_t, x_t, astar.MAP.goal) return parsed_map def _return_map_for_fov(self): height = self.map_model.height width = self.map_model.width # 床と壁の追加 parsed_map = shadowcasting.MAPParser.make_empty_map(height, width, shadowcasting.MAP.nothing) for obs in self.map_model.obstacle_objects: y, x = obs.get_position() parsed_map.set_value_at(y, x, shadowcasting.MAP.wall) return parsed_map def _get_nearest_target(self) -> "model.Character": y_e, x_e = self.enemy.get_position() # FIXME これもユーティリティモジュールに分けたほうが良さそう。 calculate_euclid_square_distance = lambda chara: \ (chara.get_position()[0] - y_e) ^ 2 + (chara.get_position()[1] - x_e) ^ 2 return min(self.map_model.get_characters_by_hostility(model.HOSTILITY.friend), key=calculate_euclid_square_distance) def _is_in_fov(self, target_pos: list): fov = self._make_fov() y_e, x_e = self.enemy.get_position() fov.do_fov(y_e, x_e, self.enemy.get_fov_distance()) return fov.is_in_fov(*target_pos) def _make_fov(self): parsed_map = self._return_map_for_fov() return shadowcasting.FOVMap(parsed_map) def _get_nearest_target_pos(self): nearest_target = self._get_nearest_target() if nearest_target: return nearest_target.get_position() else: warnings.warn("No nearest target!!") return None def _make_ast(self): parsed_map = self._return_map_for_astr() searching_map = astar.SearchingMap(parsed_map) logging.info("made searching_map") return astar.Astar(searching_map)
true
f3148a0d7a12279035255c0412ed4b751b6fc84a
Python
af-orozcog/python4everybody
/UsingPythonToAccesData/socket1.py
UTF-8
427
3
3
[]
no_license
#python program to examine the http response to a get request import socket mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) mysocket.connect(('data.pr4e.org',80)) getRequest = "GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n".encode() mysocket.send(getRequest) while True: data = mysocket.recv(512) if(len(data) < 1): break print(data.decode()) print("Connection finished by foreign host")
true
00f8fb41df1e5f7a87247fb02c5ff2b09bcbfcb7
Python
tiagomenegaz/frac-turtle
/runner.py
UTF-8
1,457
3.3125
3
[ "MIT" ]
permissive
from turtle import Turtle, colormode from random import randint import sys def randColor(): return randint(0,255) def drawTriangle(t,dist): t.fillcolor(randColor(),randColor(),randColor()) t.down() t.setheading(0) t.begin_fill() t.forward(dist) t.left(120) t.forward(dist) t.left(120) t.forward(dist) t.setheading(0) t.end_fill() t.up() def sierpinski(t,levels,size): if levels == 0: # Draw triangle drawTriangle(t,size) else: half = size/2 levels -= 1 # Recursive calls sierpinski(t,levels,half) t.setpos(t.xcor()+half,t.ycor()) sierpinski(t,levels,half) t.left(120) t.forward(half) t.setheading(0) sierpinski(t,levels,half) t.right(120) t.forward(half) t.setheading(0) def main(configuration): t = Turtle() t.speed(10) t.up() t.setpos(-configuration['size']/2,-configuration['size']/2) colormode(255) sierpinski(t,configuration['level'],configuration['size']) def start(): configuration = {'level': 2, 'size': 480} if len(sys.argv) >= 2 and sys.argv[1].isdigit(): configuration['level'] = int(sys.argv[1]) if len(sys.argv) == 3 and sys.argv[2].isdigit(): configuration['size'] = int(sys.argv[2]) main(configuration) raw_input("Press ENTER to continue") start()
true
7f97672e9989079ecf723aad9f71c57952440e35
Python
josephcardillo/lpthw
/ex15.py
UTF-8
795
3.96875
4
[]
no_license
# imports argv module from sys from sys import argv # the two argv arguments script, filename = argv # Using only input instead of argv # filename = input("Enter the filename: ") # Opens the filename you gave when executing the script txt = open(filename) # prints a line print(f"Here's your file {filename}:") # The read() function opens the filename that's set to the txt variable print(txt.read()) print("Type the filename again:") txt.close() # prompt to input the filename again file_again = input("> ") # sets variable txt_again equal to the open function with one parameter: the variable file_again txt_again = open(file_again) # prints the content of the example15_sample.txt file by calling the read function on the txt_again variable. print(txt_again.read()) txt_again.close()
true
fc831f350cfe5cac647ba130d31510dd30d9a2bd
Python
prempshaw/automatic-attendance-using-face-recognition
/img_recog_name_confidnce.py
UTF-8
803
2.546875
3
[]
no_license
from urllib2 import Request, urlopen values = """ { "image": "http://35.154.49.223/image/ankit/ankit_enroll2.jpg", "gallery_name": "MyGallery" } """ headers = { 'Content-Type': 'application/json', 'app_id': 'fe2b1d88', 'app_key': '622354d3f6cbcfde77192f290ef6e293' } request = Request('https://api.kairos.com/recognize', data=values, headers=headers) response_body = urlopen(request).read() #print response_body b=() b=response_body.split(":") c=b[3] d=c.split(",") a="Ankit_Sinha" b="Anurag_Kumar" if a in response_body : print ("Attendance Updated.") print ("Ankit Sinha Found.") print ("Confidence: "+d[0]) elif b in response_body : print ("Attendance Updated.") print ("Anurag Kumar Found.") print ("Confidence: "+d[0]) else : print ("Not Found.") print ("Authentication Failure.")
true
36abc0001d5210ff814d0e68a1c298a8c4dda3a8
Python
huangshu91/gamebuilders_f14
/hud.py
UTF-8
2,356
2.890625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Shuheng Huang' import pygame from constants import * class hud(): def __init__(self, level, parent): self.FONT = pygame.font.SysFont('Calibri', 25, False, False) self.parent = parent self.level = level self.screen = pygame.display.get_surface() self.heart_sprite = pygame.image.load('images/health.png').convert_alpha() self.coin_sprite = pygame.image.load('images/coins.png').convert_alpha() self.skull_sprite = pygame.image.load('images/skull.png').convert_alpha() self.sword_sprite = pygame.image.load('images/sword.png').convert_alpha() def render_sprite(self): progress = int(self.level.get_progress()*100) text = self.FONT.render("Progress: "+str(progress)+"%", True, (0, 0, 0)) cur_items = self.parent.cur_items cur_text = "Current: " + " x"+str(cur_items.count("health")) cur_text += " x"+str(cur_items.count("coins")) cur_text += " x"+str(cur_items.count("skull")) cur_text += " x"+str(cur_items.count("sword")) current_text = self.FONT.render(cur_text, True, (0, 0, 0)) next_items = self.parent.next_items next_text = "Next: " + " x"+str(next_items.count("health")) next_text += " x"+str(next_items.count("coins")) next_text += " x"+str(next_items.count("skull")) next_text += " x"+str(next_items.count("sword")) nextgen_text = self.FONT.render(next_text, True, (0, 0, 0)) gen_text = self.FONT.render("Generation: "+str(self.level.gen), True, (0, 0, 0)) self.screen.blit(text, (10, 10)) self.screen.blit(gen_text, (10, 40)) self.screen.blit(current_text, (10, 70)) self.screen.blit(nextgen_text, (10, 120)) self.screen.blit(self.heart_sprite, (100, 60)) self.screen.blit(self.coin_sprite, (160, 60)) self.screen.blit(self.skull_sprite, (230, 60)) self.screen.blit(self.sword_sprite, (300, 60)) self.screen.blit(self.heart_sprite, (100, 110)) self.screen.blit(self.coin_sprite, (160, 110)) self.screen.blit(self.skull_sprite, (230, 110)) self.screen.blit(self.sword_sprite, (300, 110))
true
9b0fbf75bcd54dc279197f29619cc14fd2779e47
Python
beeverycreative/Filaments
/tools/bee2cura.py
UTF-8
4,984
2.734375
3
[]
no_license
#!/usr/bin/python2 # -*- coding: utf-8 -*- import os import sys import glob import re import argparse import xml.etree.ElementTree as ET """bee2cura.py: This script attempts to generate ini files to be used in Cura from the XML files that are located in the folder this script is located in. The resulting ini files will be deposited in the path requested by the user.""" __author__ = 'João Grego' __email__ = "jgrego@beeverycreative.com" COMPATIBLE_VERSION_MAJOR="2" START_GCODE="M300\n\t" + \ "M107\n\t" + \ "G28\n\t" + \ "G92 E\n\t" + \ "M130 T6 U1.3 V80\n\t" + \ "G1 X-98.0 Y-20.0 Z5.0 F3000\n\t" + \ "G1 Y-70.0 Z0.3\n\t" + \ "G1 X-98.0 Y66.0 F500 E40\n\t" + \ "G92 E" END_GCODE="M300\n\t" + \ "G28 X\n\t" + \ "G28 Z\n\t" + \ "G1 Y65\n\t" + \ "G92 E" def fetch_files(path_to_files, version): """ Obtain a list of XML files present in the current folder, check their version and, if the version is compatible, add them to a list. In the end, return that list. Args: path_to_files: the path where the search for XML files will be performed version: string of the version of the XML filament files that are to be fetched Returns: List of XML files (as an ElementTree structure, starting at the root) """ xml_temp_list = [] for filename in glob.glob(path_to_files + "/*.xml"): tree = ET.parse(filename) root = tree.getroot() version_major = root.find('version').text.split('.')[0] if(version_major == COMPATIBLE_VERSION_MAJOR): xml_temp_list.append(root) return xml_temp_list def generate_ini_from_xml(xml_file, output_path): """ Receive a XML file (as an ElementTree structure) and output the resulting ini files to the given path. Args: xml_file: XML file, as an ElementTree structure output_path: path to the folder in which the ini files will be placed Returns: the number of ini files generated from the given XML """ defaults = {} count = 0 filament_name = xml_file.find('name').text.strip() for param in xml_file.find('defaults').findall('parameter'): defaults[param.get('name')] = param.get('value') for printer in xml_file.findall('printer'): printer_name = printer.get('type') for nozzle in printer.findall('nozzle'): nozzle_size = nozzle.get('type') for res in nozzle.findall('resolution'): resolution = res.get('type') if resolution == "high+": resolution = "highplus" output_filename = filament_name + "_" + printer_name + \ "_" + resolution + "_" + "NZ" + \ nozzle_size + ".ini" count += 1 overrides = {} for param in res.findall('parameter'): overrides[param.get('name')] = param.get('value') merged_settings = defaults.copy() merged_settings.update(overrides) output_file = open(output_path + "/" + output_filename, 'w') output_file.write("[profile]") for param in merged_settings.items(): output_file.write('\n' + param[0] + "=" + param[1]) output_file.write("\n\n[alterations]") output_file.write('\n' + "start.gcode" + "=" + "M109 S" + \ merged_settings['print_temperature'] + "\n\t" + \ START_GCODE) output_file.write('\n' + "end.gcode" + "=" + END_GCODE) output_file.close() return count if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert all the BEESOFT XML " "files in a given path to cura compatible ini files.") parser.add_argument('xml_path', metavar='INPUT_PATH', type=str, help='path' ' where the XML files are located') parser.add_argument('ini_path', metavar="OUTPUT_PATH", type=str, help= 'path where the ini files are to be placed') args = parser.parse_args() if os.path.isfile(args.xml_path): print("ERROR: The given input path is a file. Please specify a path to" " a folder.") sys.exit(1) try: os.mkdir(args.ini_path) except OSError as ex: if ex.errno == 17 and os.path.isfile(args.ini_path): print("ERROR: The given output path is a file. Please specify a " "path to a folder.") sys.exit(1) xml_files = fetch_files(args.xml_path, COMPATIBLE_VERSION_MAJOR) total_count = 0 for f in xml_files: total_count += generate_ini_from_xml(f, args.ini_path) print(str(total_count) + " ini files have been generated") sys.exit(0)
true
472e1c5b0b0f394d1d3a4a4e4143ad55030a6632
Python
sweetherb100/python
/interviewBit/Strings/01_StrStr.py
UTF-8
1,448
4.3125
4
[]
no_license
''' Another question which belongs to the category of questions which are intentionally stated vaguely. Expectation is that you will ask for correct clarification or you will state your assumptions before you start coding. Implement strStr(). strstr - locate a substring ( needle ) in a string ( haystack ). Try not to use standard library string functions for this question. Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. NOTE: Good clarification questions: What should be the return value if the needle is empty? What if both haystack and needle are empty? For the purpose of this problem, assume that the return value should be -1 in both cases. ''' ### ASK WHICH IS SUBSTRING/STRING class Solution: # @param A : string # @param B : string # @return an integer def strStr(self, A, B): #I chose A as substring, B as string ### DB, helloDB ## Exception if len(A) == 0 or len(B) == 0: return -1 if len(A) > len(B): # substring cannot be longer than the string return -1 sublen = len(A) for i in range(len(B)): if A[0] == B[i] and sublen + i <= len(B): ## SHOULD BE <=, NOT < if B[i:i + sublen:1] == A: return i #return that index return -1 # Can be out of index solution = Solution() print(solution.strStr("DB","helloDB"))
true
ff7a79dd377db9608d820faa6def653ecb955108
Python
choiasher/problem-solving
/greedy7_scale.py
UTF-8
1,548
4.0625
4
[]
no_license
''' (1) 어떤 임의의 수열 A={a1... an}에서 이 수들을 가지고 구간합 [1, S]까지의 수들을 모두 표현할 수 있다고 가정할 때, 이 수열에 S+1를 추가하면 수열 끝에 S+1이 추가된 수열 A(after)={a1. an, S+1}은 추가되지 않은 수열 A(before)={a1.. an}이 구간 [1, S]까지 표현이 가능하니까 1.. S까지 각각 S+1을 더한 [S+2, 2S+1]를 추가로 표현할 수 있게됨 따라서 [1, 2S+1]까지 수들을 누락없이 모두 표현이 가능해진다. (2) 그러면 이 수열A에 S+2를 추가할 경우를 살펴보면 수열끝에 S+2이 추가된 {a1.. an, S+2}은 수열 {a1.. an}이 구간 [1, S]까지 표현이 가능하니까 1.. S까지 각각 S+2을 더한 [S+3, 2S+2]를 추가로 표현할 수 있게됨 [1, S] + [S+2, S+2] + [S+3, 2S+2] == [1, 2S+2]는 거짓 반례) 구간[S+1]을 표현하지 못함. S+3을 추가할경우 [S+1, S+2] / S+4를 추가할 경우 [S+1, S+3]에 대해서 계속 불만족되는 구간이 생김 따라서 수열 {a1, a2, ..an}이 구간합 S까지 표현을 할 수 있을때 S+1보다 큰 수를 수열에 넣으면 표현을 하지 못하는 구간이 생기게 되며 표현하지 못하는 최소구간은 S+1부터이다. ''' def solution(weights): weights.sort() S = weights.pop(0) for w in weights: if w > S+1: break else: S += w return S+1 print(solution([3, 1, 6, 2, 7, 30, 1])) #21 print(solution([1, 1, 3])) #6 print(solution([1, 1, 1, 1, 1, 1])) #7
true
80db105c4a4946d9234564668f1bf0328c73f271
Python
dymnz/ShitHappened
/email_sender.py
UTF-8
885
2.828125
3
[]
no_license
import smtplib from util import * class EmailSender: _user = 'user' _password = 'password' _stmp_url = 'smtp.gmail.com' _stmp_port = 465 def __init__(self, user, password, stmpURL, stmpPort): self._user = user self._password = password self._stmp_url = stmpURL self._stmp_port = stmpPort # https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python def send_email(self, recipient, message): # SMTP_SSL Example server_ssl = smtplib.SMTP_SSL(self._stmp_url, self._stmp_port) server_ssl.ehlo() # optional, called by login() server_ssl.login(self._user, self._password) # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail(self._user, recipient, message.as_string()) #server_ssl.quit() server_ssl.close() logging.info("Email sent to {}".format(recipient))
true
f68b82f018d4e2d9d8a7a8a2b47e248e92bc513a
Python
cuimin07/LeetCode-test
/109.二叉搜索树中的众数.py
UTF-8
1,690
3.734375
4
[]
no_license
''' 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 假定 BST 有如下定义: 结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树 例如: 给定 BST [1,null,2,2], 1 \ 2 / 2 返回[2]. 提示:如果众数超过1个,不需考虑输出顺序 进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内) ''' #答:【使用额外空间的中序遍历】 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findMode(self, root: TreeNode) -> List[int]: if not root: return [] ans = self.order(root) n = len(ans) target = [0,0] m=0 count =1 while m<n-1: if ans[m]==ans[m+1]: m +=1 count+=1 else: if count>target[0]: target = [count,ans[m]] elif count==target[0]: target.append(ans[m]) count = 1 m += 1 if count>target[0]: target = [count,ans[m]] elif count==target[0]: target.append(ans[m]) return target[1:] def order(self,root): if not root: return [] return self.order(root.left)+[root.val]+self.order(root.right)
true
e10a0cce80a2950c7df8207c3e7244a4db84661d
Python
jiasir803/character
/future_work/get_genres_representation_of_gender.py
UTF-8
6,234
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # This script is designed to apply a particular model of # gender to characters in a particular span of time, # and record the predicted probabilities. # It summarizes and records the predicted probabilities # both at the author level and at the "story" (document) # level. In this dataset, some 19c stories include more # than one volume. import csv, os, sys import pandas as pd import numpy as np from collections import Counter import SonicScrewdriver as utils outdir = 'output' # LOAD DATA def normalize_title(title): if '/' in title: title = title.split('/')[0] if '|' in title: title = title.split('|')[0] title = title.strip('. ,;') return title genremeta = dict() fallbackdocids = dict() with open('rawgenredata.csv', encoding = 'utf-8') as f: reader = csv.DictReader(f) for row in reader: normalizedauth = row['author'].strip('[](),. ') if len(normalizedauth) > 20: normalizedauth = normalizedauth[0:20] key = (row['author'], normalize_title(row['title']), normalizedauth) value = (row['pubdate'], row['genre'], row['authgender']) genremeta[key] = value fallbackdocids[key] = row['volid'] def match(targetauth, targettitle, possibleauth, possibletitle): if possibleauth in aliases: possibleauth = aliases[possibleauth] possibleauth = possibleauth.strip('[](),. ') if len(possibleauth )> 20: possibleauth = possibleauth[0:20] if len(targettitle) > 15: targettitle = targettitle[0:15] if len(possibletitle) > 15: possibletitle = possibletitle[0:15] if targetauth.lower() == possibleauth.lower() and targettitle.lower() == possibletitle.lower(): return True else: return False # Read in aliasfile: aliases = dict() with open('genre_aliases_in_filteredfic.tsv', encoding = 'utf-8') as f: reader = csv.DictReader(f, delimiter = '\t') for row in reader: aliases[row['alias']] = row['ourname'] # find matches key2docid = dict() volbackup = dict() with open('../metadata/filtered_fiction_plus_18c.tsv', encoding = 'utf-8') as f: reader = csv.DictReader(f, delimiter = '\t') for row in reader: try: intval = int(row['docid']) docid = row['docid'] except: docid = utils.clean_pairtree(row['docid']) possibleauth = row['author'] possibletitle = normalize_title(row['title']) found = False for key, value in genremeta.items(): author, title, normauth = key if match(normauth, title, possibleauth, possibletitle): key2docid[key] = docid volbackup[key] = utils.clean_pairtree(row['volid']) found = True print('Found: ', possibleauth, author, possibletitle) break print('Found a total of ', len(key2docid)) for key, docid in fallbackdocids.items(): if key not in key2docid and docid in fallbackdocids: print("adding ", key) key2docid[key] = docid # now let's get all the characters for each story data = pd.read_csv('gender_probabilities.tsv', sep = '\t', dtype = {'docid': 'object'}) #loads characters storyout = [] ctr = 0 for key, docid in key2docid.items(): author, thistitle, normalizedauth = key pubdate, genre, authgender = genremeta[key] ctr += 1 print(ctr) story_probs = dict() story_genders = Counter() story_words = Counter() storymeta = dict() # initialize the output record chars = data.loc[(data.docid == docid) & (data.numwords > 10), : ] if len(chars.pubdate) < 1: volid = volbackup[key] chars = data.loc[(data.docid == volid) & (data.numwords > 10), : ] if len(chars.pubdate) > 0: charsizes = chars.numwords undifferentiated_probs = chars.probability femininechars = chars.loc[chars.gender == 'f', : ] masculinechars = chars.loc[chars.gender == 'm', : ] story_genders['f'] = len(femininechars.index) story_genders['m'] = len(masculinechars.index) story_words['f'] = np.sum(femininechars.numwords) story_words['m'] = np.sum(masculinechars.numwords) story_probs['f'] = femininechars.probability story_probs['m'] = masculinechars.probability else: continue prob_mean = np.mean(undifferentiated_probs) if story_genders['f'] > 0 and story_genders['m'] > 0: prob_diff = np.mean(story_probs['f']) - np.mean(story_probs['m']) weighted_diff = np.average(femininechars.probability, weights = femininechars.numwords) - np.average(masculinechars.probability, weights = masculinechars.numwords) else: prob_diff = float('nan') weighted_diff = float('nan') prob_stdev = np.std(undifferentiated_probs) if (story_words['f'] + story_words['m']) > 0: wordratio = story_words['f'] / (story_words['f'] + story_words['m']) charratio = story_genders['f'] / (story_genders['f'] + story_genders['m']) else: wordratio = float('nan') charratio = float('nan') charsize_mean = np.mean(charsizes) storymeta['prob_mean'] = prob_mean storymeta['prob_stdev'] = prob_stdev storymeta['prob_diff'] = prob_diff storymeta['weighted_diff'] = weighted_diff storymeta['wordratio'] = wordratio storymeta['pct_women'] = charratio storymeta['charsize'] = charsize_mean storymeta['numchars'] = len(charsizes) storymeta['author'] = author storymeta['title'] = thistitle storymeta['authgender'] = authgender storymeta['docid'] = docid storymeta['genre'] = genre storymeta['pubdate'] = pubdate storyout.append(storymeta) storycolumns = ['docid', 'author', 'title', 'authgender', 'pubdate', 'genre', 'numchars', 'charsize', 'pct_women', 'wordratio','prob_diff', 'weighted_diff', 'prob_stdev', 'prob_mean'] outpath = os.path.join(outdir, 'genre_storymeta.tsv') with open(outpath, mode = 'w', encoding = 'utf-8') as f: writer = csv.DictWriter(f, delimiter = '\t', fieldnames = storycolumns) writer.writeheader() for s in storyout: writer.writerow(s)
true
debb7cef4e413fd3abd650b56361501cdfe987de
Python
kiayria/epam-python-hw
/homework02/task04/function_cache/function_cache.py
UTF-8
614
3.796875
4
[]
no_license
""" Write a function that accepts another function as an argument. Then it should return such a function, so the every call to initial one should be cached. def func(a, b): return (a ** b) ** 2 cache_func = cache(func) some = 100, 200 val_1 = cache_func(*some) val_2 = cache_func(*some) assert val_1 is val_2 """ import pickle from collections.abc import Callable def cache(func: Callable) -> Callable: cached = dict() def cached_func(*args): hash = pickle.dumps(args) if hash not in cached: cached[hash] = func(*args) return cached[hash] return cached_func
true
bfb7e0e4417bf5c776ef64dcf7677f8ff20c4b7f
Python
AndrewKalil/private
/Holberton_projects/copy_holby_challenge/champ.py
UTF-8
8,510
2.796875
3
[]
no_license
#!/usr/bin/python3 """""" from base import Base import json import random class Champ(Base): T_dmg_done = 0 T_dmg_taken = 0 T_dmg = 0 CRIT = 0 reset = 0 energy = 200 energy_reset = energy def __init__( self, name, race, gender, element=None, id=None, weapon="", armor="", champ_class="", health=0, attack=0, defence= 0, magic=0, speed=0, dmg_reduction=0): self.champ_class = champ_class self.name = name self.race = race self.gender = gender self.element = element self.health = health self.attack = attack self.defence = defence self.magic = magic self.weapon = weapon self.armor = armor self.speed = speed self.dmg_reduction = dmg_reduction self.T_dmg_done = Champ.T_dmg_done self.T_dmg_taken = Champ.T_dmg_taken self.T_dmg = Champ.T_dmg self.CRIT = Champ.CRIT self.reset = health self.energy = Champ.energy self.energy_reset = Champ.energy_reset super().__init__(id) @property def name(self): return self.__name @name.setter def name(self, value): self.validator('name', value) self.__name = value @property def race(self): return self.__race @race.setter def race(self, value): if type(value) is int: self.validator('race', int(value)) race_list = ["Human", "Elf", "Dwarf", "Hobbit", "Orc"] self.__race = str(race_list[int(value) - 1]) else: self.__race = value @property def gender(self): return self.__gender @gender.setter def gender(self, value): if type(value) is int: self.validator('gender', int(value)) gender_list = ["Male", "Female", "Other"] self.__gender = str(gender_list[int(value) - 1]) else: self.__gender = value @property def element(self): return self.__element @element.setter def element(self, value): if type(value) is int: self.validator('element', int(value)) element_list = ['Solar', 'Arc', 'Void'] self.__element = str(element_list[int(value) - 1]) else: self.__element = value @property def speed(self): return self.__speed @speed.setter def speed(self, value): self.__speed = value @property def dmg_reduction(self): return self.__dmg_reduction @dmg_reduction.setter def dmg_reduction(self, value): self.__dmg_reduction = value def validator(self, name, value): if name is 'name' and len(value) > 10: raise Exception("Name is too long, only 10 characters allowed") if name is 'race' and (1 > value > 5): raise Exception("No race was chosen") if name is 'gender' and (1 > value > 3): raise Exception("No gender was chosen") if name is 'element' and (1 > value > 3): raise Exception("No element was chosen") def validate_list(self, name, value): if name is 'race' and value not in ["Human", "Elf", "Dwarf", "Hobbit", "Orc"]: raise Exception("Not a valid race") if name is 'gender' and value not in ["Male", "Female", "Other"]: raise Exception("Not a valid gender") if name is 'element' and value not in ['Solar', 'Arc', 'Void']: raise Exception("Not a valid element") def __str__(self): str = "Class: {}\nName: {}\nRace: {}\nGender: {}\nElement: {}\nHealth: {}\nAttack: {}\nDefence: {}\nMagic: {}\nWeapon: {}\nArmor: {}\nSpeed: {}%\nDamage Reduction: {}%\nLevel: {}\nEXP for Next Level: {}\nCurrent EXP: {}\nTotal EXP: {}\nStat Points: {}\nChampion id: {}\n" return (str.format( self.champ_class, self.name, self.race, self.gender, self.element, self.health, self.attack, self.defence, self.magic, self.weapon, self.armor, self.speed, self.dmg_reduction, self.Level, self.EXP_N_L, self.C_EXP, self.T_EXP, self.S_Points, self.id)) def to_dictionary(self): """turns attributes to a dictionary Returns: dict: dictionary with all attributes """ dic = {} ls = [ 'champ_class', 'name', 'race', 'gender', "element", 'health', 'attack', 'defence', 'magic', 'weapon', 'armor', 'speed', 'dmg_reduction', 'Level', 'EXP_N_L', 'C_EXP', 'T_EXP', 'S_Points', 'id' ] for i in ls: dic[i] = getattr(self, i) return dic def update(self, **kwargs): """udates an object """ for key, value in kwargs.items(): setattr(self, key, value) def save_to_file(self): """saves a json string to a file Args: list_objs (objcet): object to convert to string """ with open("{}.json".format(self.name), mode='w') as fd: fd.write(self.to_json_string(self.to_dictionary())) def level_up(self): self.S_Points += 3 self.Level += 1 self.EXP_N_L = self.EXP_N_L + (self.EXP_N_L * self.Level) self.T_EXP += self.EXP_N_L self.C_EXP = 0 self.energy += 50 self.energy_reset = self.energy def gain_xp(self): self.C_EXP = (0.5 * self.T_dmg) + 10 if self.C_EXP >= self.EXP_N_L: self.level_up() def death(self): self.C_EXP -= (0.5 * self.C_EXP) if self.C_EXP <= 0: self.C_EXP = 0 def stat_reset(self): self.health = self.reset self.T_dmg = 0 self.energy = self.energy_reset def increase_stats(self, **kwargs): """udates an object """ if len(kwargs) <= self.S_Points: for key, value in kwargs.items(): if key in ['health', 'attack', 'defence', 'magic']: value = getattr(self, key) + 5 setattr(self, key, value) elif key in ['armor']: value_speed = getattr(self, "speed") + 0.5 setattr(self, "speed", value_speed) value_dmg_reduction = getattr(self, "dmg_reduction") + 0.5 setattr(self, "dmg_reduction", value_dmg_reduction) else: print("You cannot access that attribute") self.S_Points -= len(kwargs) else: print("You can only use the attribute points available") self.reset = self.health def attack_action(self, enemy=None): value = random.randint(1, 100) if 1 <= value <= self.speed: self.CRIT = (self.speed / 100) if self.champ_class is "Rogue": self.T_dmg_done = (.60*self.attack) + (self.CRIT * self.attack) elif self.champ_class is "Fighter": self.T_dmg_done = (self.attack) + (self.CRIT * self.attack) elif self.champ_class is "Mage": self.T_dmg_done = (.60*self.magic) + (self.CRIT * self.magic) value = self.T_dmg_done self.T_dmg += value self.energy -= (value * .05) if self.energy <= 0: self.energy = 0 self.CRIT = 0 return value def defend_action(self): value = (.40 * self.defence) + ((self.dmg_reduction/100)*self.defence) return value def total_defence(self, dmg, enemy=None): if self.element is "Solar" and enemy is "Void": value = dmg + (dmg * .25) elif self.element is "Arc" and enemy is "Solar": value = dmg + (dmg * .25) elif self.element is "Void" and enemy is "Arc": value = dmg + (dmg * .25) else: value = dmg rand = random.randint(1, 100) if 1 <= rand <= self.speed: self.T_dmg_taken = 0 else: self.T_dmg_taken = value - self.defend_action() self.health -= self.T_dmg_taken if self.health <= 0: self.health = 0 def display_battle_stats(self): str = "Name: {}\nHealth: {:.2f}\nEnergy: {:.2f}" if self.health <= 0: self.health = 0 print(str.format(self.name, float(self.health), float(self.energy))) def win(self): self.gain_xp() self.stat_reset() self.save_to_file() def lose(self): self.death() self.stat_reset() self.save_to_file()
true
64eb7baba8d175e4d4deac617d8f46c786cdbe57
Python
salmanmohebi/DetPoisson_Python
/funLtoK.py
UTF-8
995
3.25
3
[ "MIT" ]
permissive
# K=funLtoK(L) # The function funLtoK(L) converts a (non-singular) kernel L matrix into a (normalized) # kernel K matrix. The L matrix has to be semi-positive definite. import numpy as np #NumPy package for arrays, random number generation, etc def funLtoK(L): eigenValuesL,eigenVectLK=np.linalg.eig(L); #eigen decomposition eigenValuesK=eigenValuesL/(1+eigenValuesL); #eigenvalues of K eigenValuesK=np.diagflat(eigenValuesK); ##eigenvalues of L as diagonal matrix K=np.matmul(np.matmul(eigenVectLK,eigenValuesK),eigenVectLK.transpose()); #recombine from eigen components K=np.real(K); #make sure all values are real return K # TEST # B=np.array([[3, 2, 1],[4, 5,6],[ 9, 8,7]]) # A=np.matmul(B.transpose(),B) # A= # array([[3, 4, 9], # [2, 5, 8], # [1, 6, 7]]) # # K=funLtoK(L) # K= #array([[ 0.76022099, 0.33480663, -0.09060773], # [ 0.33480663, 0.3320442 , 0.32928177], # [-0.09060773, 0.32928177, 0.74917127]])
true
b292a9dc6083659217f708569ea8e17115efdcb9
Python
skyblue3350/marksheet-reader
/scripts/cli.py
UTF-8
8,718
3.046875
3
[]
no_license
import argparse import csv from pathlib import Path import cv2 import numpy as np from PIL import Image def open_dir(path): p = Path(path) if not p.exists(): raise argparse.ArgumentTypeError("not exists : {}".format(p)) if not p.is_dir(): raise argparse.ArgumentTypeError("not dir : {}".format(p)) return p class MarkSheetResult(object): def __init__(self, **kargs): self.path = kargs.get("path") self.number = kargs.get("number") self.question = kargs.get("question") self.score = kargs.get("score") self.x = kargs.get("x") self.y = kargs.get("y") self.image = kargs.get("image") def __str__(self): return "{} student: {} score: {}".format(self.__class__.__name__, self.number, self.score) class MarkSheetParser(object): def __init__(self, path: Path, thresh: int): self.path = path self.thresh = thresh self.color_image = np.array(Image.open(self.path.open("rb")).convert("L")) _, self.image = cv2.threshold(self.color_image, self.thresh, 255, cv2.THRESH_BINARY) self.image = 255 - self.image self.h, self.w = self.image.shape def trackPoisiton(self) -> (list, list): width = int(self.w * 0.03) height = int(self.h * 0.03) padding = 10 for w in range(self.w // padding): start_h = self.h - padding * (w + 1) end_h = self.h - padding * w markers_x = self.__trackPosition(self.image[start_h:end_h, 0:self.w], 0) if len(markers_x) == 47: break else: raise IndexError("cant find width marker") for h in range(self.h // padding): start_w = self.w - padding * (h + 1) end_w = self.w - padding * h markers_y = self.__trackPosition(self.image[0:self.h, start_w:end_w], 1) if len(markers_y) == 25: break else: raise IndexError("cant find height marker") return markers_x, markers_y def __trackPosition(self, image: np.ndarray, axis: int) -> list: # マーカー検出 image, contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # マーカー重心位置取得 result = [] for c in contours: mu = cv2.moments(c) try: x, y = int(mu["m10"] / mu["m00"]) , int(mu["m01"] / mu["m00"]) except ZeroDivisionError: pass else: result.append((x, y)) result.sort(key=lambda x: x[axis]) return result def getNumber(self, markers_x: list, markers_y: list) -> str: student_number = "" for x in markers_x[:7]: for number, y in enumerate(markers_y[:10]): # 上から順に探して見つけたらその行は終了 if self.image[y[1]][x[0]]: student_number += str(number) break else: return student_number def getQuestion(self, markers_x: list, markers_y: list) -> list: result = [] for i, v in enumerate(list(zip(*[iter(markers_x[7:])]*10))): for y in markers_y: ans = [] # 交点位置を参照して色が塗られてるかチェック for number, x in enumerate(v): # マークされていたら1 if self.image[y[1]][x[0]]: ans.append(1) else: ans.append(0) else: # 1行終わったら1問追加 result.append(ans) else: return np.asarray(result) class MarkSheetReader(object): def __init__(self, args): if args.config: self.config = self.load_config(args.config) else: self.config = args self.load_answer() def load_config(self, path: Path) -> list: pass def load_answer(self): f = csv.reader(self.config.answer) header = next(f) self.answer = [] for row in f: row = row[1:] row = np.asarray(row, dtype=bool).astype(int) if not row.shape[0] == 10: raise SyntaxError self.answer.append(row) if not len(self.answer) == 100: raise EOFError def __iter__(self): for ext in self.config.ext: for p in self.config.input.glob("*." + ext): parser = MarkSheetParser(p, self.config.thresh) x, y = parser.trackPoisiton() number = parser.getNumber(x, y) question = parser.getQuestion(x, y) score = 0 for i, q in enumerate(question): if np.allclose(q, self.answer[i]): score += 1 yield MarkSheetResult( path=p, number=number, question=question, score=score, x=x, y=y, image=parser.image ) raise StopIteration if __name__ == "__main__": parser = argparse.ArgumentParser(description="CLI Mode Marksheet parser") parser.add_argument("-i", "--input", type=open_dir, required=True, help="input directory") parser.add_argument("-o", "--output", type=open_dir, required=True, help="output directory") parser.add_argument("-r", "--result", type=argparse.FileType("w"), required=True, help="result file") parser.add_argument("-t", "--thresh", type=int, required=False, default=240, help="threshold value") parser.add_argument("-e", "--ext", type=str, required=False, default=["jpg", "png", "gif"], nargs="+", help="target file extension") parser.add_argument("-a", "--answer", type=argparse.FileType("r"), required=True, help="answer csv file") parser.add_argument("-c", "--config", type=argparse.FileType("r"), required=False, help="config file path TBD") # TODO: argparse POSITION_MARKER = (255, 0, 0) POSITION_MARKER_LINE = (0, 0, 255) ANSWER_MARKER = (0, 255, 0) args = parser.parse_args() reader = MarkSheetReader(args) result = [] for sheet in reader: print(sheet.path, sheet) result.append({ "number": sheet.number, "score": sheet.score, }) h, w = sheet.image.shape image = np.array(Image.open(sheet.path.open("rb"))) # 結果書き込み # TODO: fix for x in sheet.x[:7]: for number, y in enumerate(sheet.y[:10]): if sheet.image[y[1]][x[0]]: radius = int(w * 0.01) border = int(radius / 3) cv2.circle(image, (x[0], y[1]), radius, POSITION_MARKER, border) cv2.putText( image, str(number), (x[0] - int(radius/2), y[1] + int(radius/2)), cv2.FONT_HERSHEY_COMPLEX, fontScale=int(border / 5), color=POSITION_MARKER, thickness=border) break for i, v in enumerate(list(zip(*[iter(sheet.x[7:])]*10))): for y in sheet.y: # 交点位置を参照して色が塗られてるかチェック for number, x in enumerate(v): # マークされていたら1 if sheet.image[y[1]][x[0]]: cv2.circle(image, (x[0], y[1]), radius, POSITION_MARKER, border) cv2.putText( image, str(number + 1), (x[0] - int(radius/2), y[1] + int(radius/2)), cv2.FONT_HERSHEY_COMPLEX, fontScale=int(border / 5), color=POSITION_MARKER, thickness=border) # 書き出し output = args.output / sheet.path.name Image.fromarray(image).save(output) writer = csv.DictWriter(args.result, lineterminator="\n", fieldnames=result[0].keys()) writer.writeheader() writer.writerows(result)
true
22070f5b6fdfe797d378433f0b7e1c68daa007cd
Python
codeAligned/Leet-Code
/src/P-160-Intersection-of-Two-Linked-Lists.py
UTF-8
1,276
3.625
4
[]
no_license
''' P-160 - Intersection of Two Linked Lists Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to intersect at node c1. Notes:If the two linked lists have no intersection at all, returnnull.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory. Credits:Special thanks to@stellarifor adding this problem and creating all test cases. Tags: Linked List ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param two ListNodes # @return the intersected ListNode def getIntersectionNode(self, headA, headB): ptr1, ptr2 = headA, headB if ptr1 == None or ptr2 == None: return None while ptr1 != ptr2: ptr1, ptr2 = ptr1.next, ptr2.next if ptr1 == ptr2: return ptr1 if ptr1 == None: ptr1 = headB if ptr2 == None: ptr2 = headA return ptr1
true
6073f734d95c4dfc0ae3017b72626247991baf88
Python
hcxxn/case_pyspark
/global/analyze.py
UTF-8
3,228
3.140625
3
[]
no_license
# -*- coding: utf-8 -*- from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession from pyspark.ml.feature import StringIndexer, IndexToString from pyspark.ml import Pipeline import pandas as pd import matplotlib.pyplot as plt import mpl_toolkits.basemap conf = SparkConf().setMaster("local").setAppName("analyze") sc = SparkContext(conf = conf) sc.setLogLevel('WARN') # 减少不必要的log输出 spark = SparkSession.builder.config(conf = SparkConf()).getOrCreate() dataFile = 'earthquakeData.csv' rawData = spark.read.format('csv') \ .options(header='true', inferschema='true') \ .load(dataFile) # 1.全球每年发生重大地震的次数 def earthquakesPerYear(): yearDF = rawData.select('Year').dropna().groupBy(rawData['Year']).count() yearDF = yearDF.sort(yearDF['Year'].asc()) yearPd = yearDF.toPandas() # 数据可视化 plt.bar(yearPd['Year'], yearPd['count'], color='skyblue') plt.title('earthquakes per year') plt.xlabel('Year') plt.ylabel('count') plt.show() # 2.全球不同年份每月发生重大地震的次数 def earthquakesPerMonth(): data = rawData.select('Year', 'Month').dropna() yearDF = data.groupBy(['Year', 'Month']).count() yearPd = yearDF.sort(yearDF['Year'].asc(), yearDF['Month'].asc()).toPandas() # 数据可视化 x = [m+1 for m in range(12)] for groupName, group in yearPd.groupby('Year'): # plt.plot(x, group['count'], label=groupName) plt.scatter(x, group['count'], color='g', alpha=0.15) plt.title('earthquakes per month') # plt.legend() # 显示label plt.xlabel('Month') plt.show() # 3.全球重大地震深度和强度之间的关系 def depthVsMagnitude(): data = rawData.select('Depth', 'Magnitude').dropna() vsPd = data.toPandas() # 数据可视化 plt.scatter(vsPd.Depth, vsPd.Magnitude, color='g', alpha=0.2) plt.title('Depth vs Magnitude') plt.xlabel('Depth') plt.ylabel('Magnitude') plt.show() # 4.全球重大地震深度和类型之间的关系 def magnitudeVsType(): data = rawData.select('Magnitude', 'Magnitude Type').dropna() typePd = data.toPandas() # 准备箱体数据 typeBox = [] typeName = [] for groupName, group in typePd.groupby('Magnitude Type'): typeName.append(groupName) typeBox.append(group['Magnitude']) # 数据可视化 plt.boxplot(typeBox, labels=typeName) plt.title('Type vs Magnitude') plt.xlabel('Type') plt.ylabel('Magnitude') plt.show() # 5.全球经常发生重大地震的地带 def location(): data = rawData.select('Latitude', 'Longitude', 'Magnitude').dropna() locationPd = data.toPandas() # 世界地图 basemap = mpl_toolkits.basemap.Basemap() basemap.drawcoastlines() # 数据可视化 plt.scatter(locationPd.Longitude, locationPd.Latitude, color='g', alpha=0.25, s=locationPd.Magnitude) plt.title('Location') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show() if __name__ == '__main__': earthquakesPerYear() # earthquakesPerMonth() # depthVsMagnitude() # magnitudeVsType() # location()
true
a43788999e31e0bd6e0e58e33eb9f4044eedc67f
Python
piyushkumar344/sabre
/pythonWithNode/face_recog.py
UTF-8
1,369
3.09375
3
[ "MIT" ]
permissive
import face_recognition import cv2 import sys # Open the input movie file input_video = cv2.VideoCapture(sys.argv[1]) length = int(input_video.get(cv2.CAP_PROP_FRAME_COUNT)) # Load some sample pictures and learn how to recognize them. curr_image = face_recognition.load_image_file(sys.argv[2]) curr_face_encoding = face_recognition.face_encodings(curr_image)[0] known_faces = [ curr_face_encoding ] # Initialize some variables face_locations = [] face_encodings = [] face_names = [] frame_number = 0 while True: # Grab a single frame of video ret, frame = input_video.read() frame_number += 1 # Quit when the input video file ends if not ret: break # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_frame = frame[:, :, ::-1] # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) face_names = [] for face_encoding in face_encodings: # See if the face is a match for the known face(s) match = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.50) if match[0]: print("Found Person") # All done! input_video.release() cv2.destroyAllWindows()
true
0708871fff9f89a1f288dc6696fa0e5a93d3527b
Python
luchesii/LogisticMap
/RNN/ESN/generator.py
UTF-8
364
2.78125
3
[]
no_license
import numpy as np import random r = 4 x0=0.1 n=10000 #número de dados no dataset file = open('esn_data10000_x0.1_r4.csv','w+') for i in range(200): x1=x0*r*(1-x0) x0=x1 x=[] for i in range(n*10): x1=x0*r*(1-x0) x0=x1 x.append(x1) x=np.asarray(x) for i in range(n): file.write('{}'.format(x[i])) file.write('\n') file.close()
true
a1c78c30ffcc3a42d575a6fc80bea500d164f418
Python
wangtao090620/LeetCode
/wangtao/leetcode/0107.py
UTF-8
1,170
3.609375
4
[]
no_license
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : wangtao # @Contact : wangtao090620@gmail.com # @Time : 2020-02-15 09:41 """ 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其自底向上的层次遍历为: [ [15,7], [9,20], [3] ] """ from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: levels = [] return self.helper(root,levels,0) def helper(self,root,levels,level): if not root: return if len(levels) == level: levels.insert(0,[]) if root.left: self.helper(root.left,levels,level + 1) if root.right: self.helper(root.right,levels,level + 1) levels[len(levels) - 1 - level].append(root.val) return levels if __name__ == '__main__': pass
true
1c6281ba681b145b1eaf70555327681b080eed1f
Python
johndurde14/Python_Learn
/《Python编程从入门到实践》/10-文件和异常/eg_remember_me.py
UTF-8
755
3.578125
4
[]
no_license
#coding = uft-8 import json class RememberMe(object): def __init__(self): self.filePath = 'username.json' def areYouThere(self, file): try: with open(file) as f_obj: username = json.load(f_obj) except FileNotFoundError: username = input("What is your name?") with open(file, 'w') as f_obj: json.dump(username, f_obj) print("We'll remember you when you come back, " + username + "!") except Exception: print("Unknow Error!Something Must Went Wrong!") else: print("Welcome back, " + username + "!") remember = RememberMe() remember.areYouThere(remember.filePath)
true
c9cd540e63d42760f186f9cd0a889e0b5eef21d0
Python
dewiballard/ProjectEuler
/Problem07.py
UTF-8
884
3.984375
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 16 20:42:29 2019 @author: dewiballard """ # Problem 7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see # that the 6th prime is 13. What is the 10 001st prime number? i = 0 count = 0 def isprime(n): # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n & 1: return False # range starts with 3 and only needs to go up the squareroot of n for all odd numbers for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False return True for i in range(1,1000000): if isprime(i) == True: count = count + 1 if count == 10001: print(i)
true
7f232902dbebbd0f3aa6324c5ed1b1e41d97cbaa
Python
komony/sync-teams
/sync-teams.py
UTF-8
4,657
2.875
3
[]
no_license
import sys, requests, json # global vars ROLE_MAINTAINER = "maintainer" ROLE_MEMBER = "member" GITHUB_API = "https://api.github.com" def get_org(full_team): return (full_team.split("/")[0]) def get_team(full_team): return (full_team.split("/")[1]) def get_team_id(full_team, auth_token): r = requests.get(GITHUB_API + "/orgs/" + get_org(full_team) + "/teams", headers = {'Authorization': 'token ' + auth_token}) if(r.ok): org_teams = json.loads(r.text or r.content) for team in org_teams: if team['name'] == get_team(full_team): return team["id"] return None def get_team_users(team_id, auth_token, role): members = [] r = requests.get(GITHUB_API + "/teams/" + str(team_id) + "/members?role=" + role, headers = {'Authorization': 'token ' + auth_token}) if(r.ok): team_members = json.loads(r.text or r.content) for team_member in team_members: members.append(team_member["login"]) return members def add_or_update_membership(team_id, username, auth_token, role): payload = {'role': role} r = requests.put(GITHUB_API + "/teams/" + str(team_id) + "/memberships/" + username, headers = {'Authorization': 'token ' + auth_token}, data = json.dumps(payload)) if(not r.ok): raise Exception("Request failed with error: " + r.content) return True def remove_membership(team_id, username, auth_token): r = requests.delete(GITHUB_API + "/teams/" + str(team_id) + "/memberships/" + username, headers = {'Authorization': 'token ' + auth_token}) if(not r.ok): raise Exception("Request failed with error: " + r.content) return True def format_and_print(user_list, role, action): if (len(user_list) > 0): string_joiner = ", " print("{0} {1}s {2}ed = {3}".format(len(user_list), role, action, string_joiner.join(user_list))) def sync_teams(source_team, dest_team, auth_token): source_team_id = get_team_id(source_team, auth_token) dest_team_id = get_team_id(dest_team, auth_token) source_team_maintainers = get_team_users(source_team_id, auth_token, ROLE_MAINTAINER) source_team_members = get_team_users(source_team_id, auth_token, ROLE_MEMBER) dest_team_maintainers = get_team_users(dest_team_id, auth_token, ROLE_MAINTAINER) dest_team_members = get_team_users(dest_team_id, auth_token, ROLE_MEMBER) maintainers_added = [] members_added = [] maintainers_removed = [] members_removed = [] for source_team_maintainer in source_team_maintainers: if source_team_maintainer not in dest_team_maintainers: # add as maintainer to destination team add_or_update_membership(dest_team_id, source_team_maintainer, auth_token, ROLE_MAINTAINER) maintainers_added.append(source_team_maintainer) for source_team_member in source_team_members: if source_team_member not in dest_team_members: # add as member to destination team add_or_update_membership(dest_team_id, source_team_member, auth_token, ROLE_MEMBER) members_added.append(source_team_member) dest_team_maintainers = get_team_users(dest_team_id, auth_token, ROLE_MAINTAINER) dest_team_members = get_team_users(dest_team_id, auth_token, ROLE_MEMBER) for dest_team_maintainer in dest_team_maintainers: if dest_team_maintainer not in source_team_maintainers: # remove as maintainer from destination team remove_membership(dest_team_id, dest_team_maintainer, auth_token) maintainers_removed.append(dest_team_maintainer) for dest_team_member in dest_team_members: if dest_team_member not in dest_team_members: # remove as member from destination team remove_membership(dest_team_id, dest_team_member, auth_token) members_removed.append(dest_team_member) format_and_print(maintainers_added, ROLE_MAINTAINER, "add") format_and_print(members_added, ROLE_MEMBER, "add") format_and_print(maintainers_removed, ROLE_MAINTAINER, "remove") format_and_print(members_removed, ROLE_MEMBER, "remove") print("Teams have been synced") source_team = sys.argv[1] # org/teamname format dest_team = sys.argv[2] # org/teamname format auth_token = sys.argv[3] # auth token with admin:org scope (https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) if len(sys.argv) == 4: sync_teams(source_team, dest_team, auth_token) else: print("Please use command in following format: python3 sync-teams.py '<SOURCE_TEAM>' '<DESTINATION_TEAM>' '<OAUTH_TOKEN>'")
true
e0a192d2833546db99ab4a4b39a3f4a51dc87916
Python
clifftseng/stock_python
/StockPicking/StockPicking_10.py
UTF-8
1,832
2.921875
3
[]
no_license
from haohaninfo import MarketInfo from haohaninfo import GOrder # 取公司配息資訊 (資訊代碼,股票標的) Data = MarketInfo.GetMarketInfo('3006','All') ProdList = sorted(set([ i[1] for i in Data ])) for Prod in ProdList: # 該商品資料 Data1 = [ i for i in Data if i[1] == Prod ] # 該商品近10年資料 Data2 = Data1[-10:] # 該商品近10年的現金股利 Data3 = [ i[2] for i in Data2 ] # 若資料內有NA值則略過這檔股票 if 'NA' in Data3: continue # 將股利資訊從 字串型態 轉為 浮點位型態 Data4 = [ float(i) for i in Data3 ] # 近10年發放現金股利的次數 Num = len([ i for i in Data4 if float(i) > 0 ]) # 連續10年都有發放現金股利 if Num >= 10: # 每一年發放的現金股利都不低於前一年 Check = True for i in range(1,10): if Data3[i] < Data3[i-1]: Check = False break # 印出符合條件的股票代碼及近10年發放的現金股利 if Check == True: # 取該檔股票的歷史日K棒 (K棒數量,商品代碼,商品種類,日夜盤) KBar = GOrder.GetHistoryKBar('250', Prod, 'Stock', '1') # 目前無法取到上櫃股票的歷史資料 if KBar != ['']: Close = [ i.split(',') for i in KBar ] # 依照逗號分隔欄位 Close = [ float(i[5]) for i in Close ] # 取出收盤價 MA250 = round(sum(Close)/250,2) # 計算年均線(一年約250個交易日) TodayClose = Close[-1] # 最近一日的收盤價 # 收盤價 > 年均線 if TodayClose > MA250: print(Prod,'TodayClose:',TodayClose,'MA250:',MA250)
true
748e3d97e97f60d05335e26200312895087d8739
Python
scott2b/webtools
/webtools/search.py
UTF-8
2,281
2.71875
3
[ "MIT" ]
permissive
import datetime import requests import time class BingWebPage(dict): """ No real attempt is made to stylize or format the full snippet or full rich caption (below). These are primarily useful for preliminary inspection of web page content, not so much for e.g. user interface display """ def get_full_snippet(self): snippets = [link.get('snippet', '').strip() for link in self.get('deepLinks',[]) if link.get('snippet', '').strip()] return '\n'.join([self.get('snippet', '')] + snippets) """ The richCaption parameter does not seem to be documented in Azure documentation. Use with caution. """ def get_full_richcaption_description(self): descriptions = [section.get('description', '').strip() for section in self.get('richCaption', {}).get('sections', []) if section.get('description', '').strip()] return '\n'.join(descriptions) class BingSearcher(object): SEARCH_URL = "https://api.cognitive.microsoft.com/bing/v7.0/search" def __init__(self, bing_api_key, rate_limit=3): self._api_key = bing_api_key self._rate_limit = rate_limit # calls per second self._rate = 1 / rate_limit self._last_search_time = None self._last_results = {} def search(self, query, count=50, offset=0): if self._last_search_time is not None: now = datetime.datetime.now() delta = (now - self._last_search_time).total_seconds() delay = self._rate - delta if delay > 0: time.sleep(delay) headers = {"Ocp-Apim-Subscription-Key" : self._api_key} params = { 'q': query, 'textDecorations':False, 'textFormat':'HTML', 'count': count, # max 50 default 10 'offset': offset } response = requests.get(self.SEARCH_URL, headers=headers, params=params) response.raise_for_status() self._last_search_time = datetime.datetime.now() data = response.json() self._last_results = data return data def last_search_pages(self): return (BingWebPage(page) for page in self._last_results.get('webPages', {}).get('value', []))
true
4eda9e19865c07f0951961e916ab759eb9f00358
Python
florinbordeanu/bookstore
/rent/models.py
UTF-8
974
2.8125
3
[]
no_license
from django.db import models from accounts.models import User from store.models import Product class RentBook(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Product, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, blank=False) phone = models.CharField(max_length=15, blank=False) address = models.CharField(max_length=255, blank=False) rent_date = models.DateTimeField(auto_now=True) start_date = models.DateField() end_date = models.DateField() price_rent = models.DecimalField(max_digits=4, decimal_places=2, default=2.00) def rent_period(self): from_date = self.start_date to_date = self.end_date result = to_date - from_date return result.days def total_price(self): return self.price_rent*self.rent_period()
true
9bca1d7686eb8166ce8ebf1322d3b588703cf43d
Python
caerulius/RTAOC
/cae/seven/part2.py
UTF-8
1,530
2.734375
3
[]
no_license
import itertools from subprocess import Popen, PIPE import os import sys highest_signal = 0 def translateOutput(output): print(output) #for some reason this line makes this work return int(output.decode("utf-8").replace("\r", "").replace("\n", "")) def nextIndex(index): if index == 4: return 0 return index+1 max_val = 0 for i in itertools.permutations(["5","6","7","8","9"]): amps = [Popen([sys.executable, 'computer.py'], stdin=PIPE, stdout=PIPE), Popen([sys.executable, 'computer.py'], stdin=PIPE, stdout=PIPE), Popen([sys.executable, 'computer.py'], stdin=PIPE, stdout=PIPE), Popen([sys.executable, 'computer.py'], stdin=PIPE, stdout=PIPE), Popen([sys.executable, 'computer.py'], stdin=PIPE, stdout=PIPE)] amps[0].stdin.write(bytes(i[0] + "\r\n", "utf-8")) amps[1].stdin.write(bytes(i[1] + "\r\n", "utf-8")) amps[2].stdin.write(bytes(i[2] + "\r\n", "utf-8")) amps[3].stdin.write(bytes(i[3] + "\r\n", "utf-8")) amps[4].stdin.write(bytes(i[4] + "\r\n", "utf-8")) index = 0 amps[0].stdin.write(bytes("0\r\n", "utf-8")) amps[0].stdin.flush() while True: outInt = translateOutput(amps[index].stdout.readline()) index = nextIndex(index) write = bytes(str(outInt) + "\r\n", "utf-8") amps[index].stdin.write(write) try: amps[index].stdin.flush() except: if outInt > max_val: max_val = outInt break print(max_val)
true
01c9444e82f3e1f0192a0a4c86f0af44a58ee4ca
Python
B1rch/aoc-2020
/2018/3/3.py
UTF-8
1,410
3.125
3
[]
no_license
import itertools as it import more_itertools as mi import numpy as np import fileinput, math from collections import defaultdict def gridPrint(grid): for line in grid: s = " ".join([str(x) for x in line]) print(f'{s}\n') data = defaultdict(dict) for line in fileinput.input(): id,_,coords,size = str(line).strip().split(' ', maxsplit=3) id = id[1:] x,y = coords[:-1].split(',') w,h = size.split('x') data[id] = tuple(map(int,(x,y,w,h))) def doOverlap(a,b): # If one rectangle is on left side of other if(a[0] >= b[0] + b[2] or b[0] >= a[0] + a[2]): return False # If one rectangle is above other if(a[1] <= b[1] + b[3] or b[1] <= a[1] + a[3]): return False return True def fillSheet(): mw, mh = max([x+w for x,_,w,_ in data.values()]), max([y+h for _,y,_,h in data.values()]) return np.zeros((mw,mh), dtype=int) def part1(sheet): for x,y,w,h in data.values(): sheet[y:y+h, x:x+w] += 1 return sheet, np.count_nonzero(sheet > 1) def part2(sheet): for id,(x,y,w,h) in list(data.items()): if all(sheet[y:y+h, x:x+w].flatten() == 1): return id return 'test' sheet = fillSheet() newSheet, part_1 = part1(sheet) print(f"\n---- PART 1 ----\n") print(f'PART 1: {part_1}') print(f"\n----------------------\n") part_2 = part2(newSheet) print(f"\n---- PART 2 ----\n") print(f'PART 2: {part_2}') print(f"\n----------------------\n")
true
baa1a4b97a671a46ff97180f110b4c0a3e74ad7c
Python
Daimy0u/PyPracticeDump
/PlatformerPhysics.py
UTF-8
1,704
3.25
3
[]
no_license
import pygame import time pygame.init() print("Created by Daimy0u - 2018") def sleep(s): time.sleep(s) screenWidth = 500 screenHeight = 500 gamewin = pygame.display.set_mode((screenWidth,screenHeight)) pygame.display.set_caption("Platformer Test") x = 40 y = 460 width = 40 height = 40 xvel = 10 yvel = 10 jumpCount = 10 active = True isJump = False while active: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: active = False keys = pygame.key.get_pressed() if keys[pygame.K_a] and x > 0: x -= xvel print("Pos: " + str(x) + " " + str(y)) if keys[pygame.K_d] and x < screenWidth - width: x += xvel print("Pos: " + str(x) + " " + str(y)) if not(isJump): if keys[pygame.K_w] and y > 0: isJump = True if keys[pygame.K_s] and y < screenHeight - height: y += yvel print("Pos: " + str(x) + " " + str(y)) else: if jumpCount >= -10: neg = 1 if jumpCount < 0: neg = -1 y -= (jumpCount ** 2) * 0.5 * neg jumpCount -= 1 else: isJump = False jumpCount = 10 if x == 0: print("Obj: HIT LEFT BOUNDARY") if x == screenWidth - width: print("Obj: HIT RIGHT BOUNDARY") if y == 0: print("Obj: HIT TOP BOUNDARY") if y == screenHeight - height: print("Obj: HIT BOTTOM BOUNDARY") gamewin.fill((0,0,0)) pygame.draw.rect(gamewin, (255, 255, 255), (x, y, width, height)) pygame.display.update() pygame.quit()
true
8d9148605137ecfa94719b3896bb58a4334d443e
Python
majaszymajda/Internet_Rzeczy
/lista3/apka4.py
UTF-8
467
2.65625
3
[]
no_license
import base def zwroc_dane(czas): for i in range(1, 97): czas_z_danych = f'{str(czas[0]).rjust(2, "0")}:{str(czas[1]).rjust(2, "0")}' if czas_z_danych == dane[i][0]: return {"Time": dane[i][0], "Peoples": dane[i][1]} if __name__ == '__main__': # base.wyslij_dane(zwroc_dane,'ilosc_osob_w_domu') dane = base.importowanie_danych_csv('Dane/ilosc_osob_w_domu.csv') base.start_serwer(zwroc_dane, 'ilosc_osob_w_domu', 2324)
true
77184010dd4a05f000a8394c19b64b478d15b17d
Python
linkinpark213/leetcode-practice
/pysrc/987.py
UTF-8
1,121
3.46875
3
[]
no_license
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: d = {} queue = [(root, 0, 0)] while len(queue) > 0: node, x, y = queue.pop(0) if node is not None: if x not in d: d[x] = {} if y not in d[x]: d[x][y] = [] d[x][y].append(node.val) queue.append((node.left, x - 1, y + 1)) queue.append((node.right, x + 1, y + 1)) ans = [] for x in sorted(list(d.keys())): vals = [] for y in sorted(d[x].keys()): vals.extend(sorted(d[x][y])) ans.append(vals) return ans if __name__ == '__main__': solution = Solution() root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print(solution.verticalTraversal(root))
true
1b52ee2e203564339241470a1b107ac3b49db12e
Python
zbh123/hobby
/人脸识别/1、Logistic_Regression/lr_test.py
UTF-8
2,762
3.421875
3
[]
no_license
# coding:UTF-8 import numpy as np def sig(x): ''' Sigmod函数,把模拟结果映射成一个概率 :param x:(mat) feature * w :return: sigmoid(x)(mat):Sigmoid值 ''' return 1.0 / (1 + np.exp(-x)) def error_rate(h, label): ''' 计算损失函数值 :param h: (mat)预测值 :param label: (mat)实际值 :return: err/m(float) ''' m = np.shape(h)[0] sum_err = 0.0 for i in range(m): if h[i, 0] > 0 and (1 - h[i, 0]) > 0: sum_err -= (label[i, 0] * np.log(h[i, 0]) + (1 - label[i, 0]) * np.log(1 - h[i, 0])) else: sum_err -= 0 return sum_err def lr_train_bgd(feature, label, maxCycle, alpha): ''' 梯度下降法训练LR模型 :param feature: (mat)特征 :param label:(mat)标签 :param maxCycle:(int)最大迭代次数 :param alpha:(float)学习率 :return:w(mat)权重 ''' n = np.shape(feature)[1] print(n) # print(n, np.shape(feature)[0]) w = np.mat(np.ones((n, 1))) # print(w) i = 0 while i <= maxCycle: i += 1 h = sig(feature * w) # print(feature * w) print(h) err = label - h if i % 100 == 0: print('\t----iter=%d, train error rate=%s----' % (i, str(error_rate(h, label)))) # 进行误差补偿 w += alpha * feature.T * err return w def load_data(file_name): ''' :param file_name: :return: ''' f = open(file_name, 'r') feature_data = [] label_data = [] for line in f.readlines(): feature_tmp = [] label_tmp = [] lines = line.strip().split(' ') # 假设偏置项为1的前提下,才能实现sigmoid的条件--|偏置假设为1,可以将决策函数(边界条件)简化成一个不带b的公式y=wx feature_tmp.append(1) for i in range(len(lines) - 1): feature_tmp.append(float(lines[i])) label_tmp.append(float(lines[-1])) feature_data.append(feature_tmp) label_data.append(label_tmp) f.close() return np.mat(feature_data), np.mat(label_data) def save_model(file_name, w): ''' :param file_name: :param w: :return: ''' m = np.shape(w)[0] f_w = open(file_name, 'w') w_array = [] for i in range(m): w_array.append(str(w[i, 0])) f_w.write('\t'.join(w_array)) f_w.close() if __name__ == '__main__': # 1.导入训练数据 print('------1. load data-----') feature, label = load_data('data.txt') # print(feature) # 2. 训练LR模型 print('-----2. training-----') w = lr_train_bgd(feature, label, 1000, 0.05) # 3.保存最终的模型 print('----3.save model----') save_model('weights', w)
true
734d748e519c23b61db3c2a231adddf181c8ebf1
Python
jk96491/Aircombat
/AircombatPython/UnityTesting/Class/Actor.py
UTF-8
740
2.625
3
[]
no_license
import tensorflow as tf class Actor: def __init__(self, name, state_size, action_size): with tf.variable_scope(name): self.state = tf.placeholder(tf.float32, [None, state_size]) self.fc1 = tf.layers.dense(self.state, 128, activation=tf.nn.relu, kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=0.8)) self.fc2 = tf.layers.dense(self.fc1, 128, activation=tf.nn.relu, kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=0.8)) self.action = tf.layers.dense(self.fc2, action_size, activation=tf.nn.tanh) # 액션 값이 -1 ~ 1사이로 나오게 하려고 tanh 사용 self.trainable_var = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, name)
true
c88140470655f57646a529e4fafcfaee6c2060c7
Python
susebing/HJ108
/pass/HJ55 挑7.py
UTF-8
632
3.796875
4
[]
no_license
# coding=utf-8 """ 题目描述 输出7有关数字的个数,包括7的倍数,还有包含7的数字(如17,27,37...70,71,72,73...)的个数(一组测试用例里可能有多组数据,请注意处理) 输入描述: 一个正整数N。(N不大于30000) 输出描述: 不大于N的与7有关的数字个数,例如输入20,与7有关的数字包括7,14,17. 示例1 输入 复制 20 输出 复制 3 """ def ff(n): s = 0 for i in range(1, n + 1): if '7' in str(i) or i % 7 == 0: s += 1 return s while 1: try: print(ff(int(input()))) except: break
true
e8d438b34121b8ae6ecc7611a0fdd3222a666554
Python
fujiten/Nand2Tetris
/projects/06/parser.py
UTF-8
4,384
2.75
3
[]
no_license
import re import sys filename = sys.argv[1] def write_file(binary): file = open(f'{filename}.hack','a') file.write(f'{binary}\n') file.close() def create_dest_binary(dest): if dest is None: return "000" elif dest == 'M': return "001" elif dest == 'D': return "010" elif dest == 'MD': return "011" elif dest == 'A': return "100" elif dest == 'AM': return "101" elif dest == 'AD': return "110" elif dest == 'AMD': return "111" def create_comp_binary(comp): if comp == "0": return "0101010" elif comp == "1": return "0111111" elif comp == "-1": return "0111010" elif comp == "D": return "0001100" elif comp == "A": return "0110000" elif comp == "!D": return "0001101" elif comp == "!A": return "0110001" elif comp == "-D": return "0001111" elif comp == "-A": return "0110011" elif comp == "D+1": return "0011111" elif comp == "A+1": return "0110111" elif comp == "D-1": return "0001110" elif comp == "A-1": return "0110010" elif comp == "D+A": return "0000010" elif comp == "D-A": return "0010011" elif comp == "A-D": return "0000111" elif comp == "D&A": return "0000000" elif comp == "D|A": return "0010101" elif comp == "M": return "1110000" elif comp == "!M": return "1110001" elif comp == "-M": return "1110011" elif comp == "M+1": return "1110111" elif comp == "M-1": return "1110010" elif comp == "D+M": return "1000010" elif comp == "D-M": return "1010011" elif comp == "M-D": return "1000111" elif comp == "D&M": return "1000000" elif comp == "D|M": return "1010101" def create_jump_binary(jump): if jump is None: return "000" elif jump == "JGT": return "001" elif jump == "JEQ": return "010" elif jump == "JGE": return "011" elif jump == "JLT": return "100" elif jump == "JNE": return "101" elif jump == "JLE": return "110" elif jump == "JMP": return "111" f = open(f'{filename}.hack', "x") f.close() f = open(f'{filename}.asm') symbol_table = dict() orders = list() line_number = -1 for x in f: x = x.strip() result = re.search('//', x) if not (result is None): chars_number = result.start() x = x[:chars_number].strip() if (x[0:2] == "//") or (x == ""): continue if x[0] == "(" and x[-1] == ")": symbol = x[1:-1] symbol_table[symbol] = (line_number + 1) else: orders.append(x) line_number += 1 symbol_table = {**symbol_table, "SP": 0, "LCL": 1, "ARG": 2, "THIS": 3, "THAT": 4, "SCREEN": 16384, "KBD": 24576} for x in range(0, 16): key = f'R{x}' symbol_table[key] = x value_number = 16 for x in orders: print(x) if (x[0:1] == "@"): print("A命令") if x[1:].isdecimal(): order = str(format(int(x[1:]), '016b')) write_file(order) else: print('シンボル') if x[1:] in symbol_table: num = 9[x[1:]] order = str(format(num, '016b')) else: symbol_table[x[1:]] = value_number order = str(format(value_number, '016b')) value_number += 1 write_file(order) else: print('C命令') result = re.search('=', x) if not (result is None): char_idx = result.start() left_side = x[0:char_idx] right_side = x[char_idx+1:] dest = create_dest_binary(left_side) comp = create_comp_binary(right_side) jump = "000" order = "111" + comp + dest + jump write_file(order) else: result = re.search(';', x) char_idx = result.start() left_side = x[0:char_idx] right_side = x[char_idx+1:] dest = "000" comp = create_comp_binary(left_side) jump = create_jump_binary(right_side) order = "111" + comp + dest + jump write_file(order) f.close()
true
ada239fa5f188d3d3e5e8ce85f46088892f54ab4
Python
wildansupernova/Nthing-Problem-Solver
/src/Main.py
UTF-8
4,231
3.6875
4
[]
no_license
from Board import Board from PawnElement import PawnElement from typing import List from HillClimbing import HillClimbing from SimulatedAnnealing import SimulatedAnnealing from GeneticAlgorithm import GeneticAlgorithm import copy import sys def makingInput(listOfPawn: List[PawnElement]): filename = input(">> Please input file name which contains your pawns: ") print("Loading " + str(filename) + " . . . ") try: with open(filename) as file: stream: str = file.readlines() for inp in stream: splitResult = inp.split(" ") numberOfThisPawn = int(splitResult[2]) while numberOfThisPawn>0: newElementPawn = PawnElement(splitResult[1], splitResult[0]) listOfPawn.append(newElementPawn) numberOfThisPawn -= 1 print("File has been opened successfully. ") except IOError: print("Could not read file : ", filename) sys.exit(1) def menu(): print("Which algorithm do you prefer?") print("1. Hill Climbing") print("2. Simulated Annealing") print("3. Genetic Algorithm") def inputMenu() -> int: x = int(input(">> Input choosen menu (1 or 2 or 3) : ")) while (x < 1) or (x > 3): print("Please input integer 1 or 2 or 3 only.") x = input(">> Input choosen menu (1 or 2 or 3) : ") return x def menuSetting() -> int: print("Do you want to edit algorithm configuration?") print("1. Yes, I want.") print("2. No, use default.") choice = int(input(">> Input your choice (1 or 2) : ")) while (choice < 1) or (choice>2): print("Please input integer 1 or 2 only.") choice = int(input(">> Input your choice (1 or 2) : ")) return choice def inputSettingSimulatedAnnealing() -> (int, int, int): x = int(input(">> Input Temperature : ")) y = float(input(">> Input Descent Rate : ")) z = int(input(">> Input Delay Step : ")) return x,y,z def inputSettingGeneticAlgorithm() -> (int,int,int,int): w = int(input(">> Input Number of Population Member : ")) x = float(input(">> Input Probability of Crossover : ")) y = float(input(">> Input Probability of Mutation : ")) z = int(input(">> Input Number of Generations Generated : ")) return w,x,y,z def main(): listOfPawn = [] makingInput(listOfPawn) board = Board(listOfPawn) board.initRandomState() # board.printBoard() menu() a = inputMenu() if (a == 1): # print("Ini hill climbing") useHillClimbing = HillClimbing(board) newBoard = useHillClimbing.algorithm() newBoard.printBoard() differentColor, sameColor = newBoard.calculatePawnAttack() print(str(sameColor) + " " + str(differentColor)) print(newBoard.scoringListOfPawnWithColor()) elif (a == 2): # print("Ini Simulated Annealing") choice = menuSetting() if (choice == 1): t,desRate,desStep = inputSettingSimulatedAnnealing() else: # choice == 2 t = 10 desRate = 0.1 desStep = 10 useSimulatedAnnealing = SimulatedAnnealing(t, desRate, desStep, board) newBoard = useSimulatedAnnealing.algorithm() newBoard.printBoard() differentColor, sameColor = newBoard.calculatePawnAttack() print(str(sameColor) + " " + str(differentColor)) print(newBoard.scoringListOfPawnWithColor()) else: # a == 3 # print("Ini GA") choice = menuSetting() if (choice == 1): N,probCross,probMuta,generations = inputSettingGeneticAlgorithm() else: #choice == 2 generations = 50 probCross = 1 probMuta = 0.3 N = 50 useGeneticAlgorithm = GeneticAlgorithm(board,N,probCross,probMuta,generations) geneticAlgorithmResult = useGeneticAlgorithm.algorithm() board = copy.deepcopy(geneticAlgorithmResult) board.printBoard() differentColor, sameColor = board.calculatePawnAttack() print(str(sameColor) + " " + str(differentColor)) print(board.scoringListOfPawnWithColor()) if __name__== "__main__": main()
true
0aad883aac2a27bbaa4f76f9c21a9c80a9f0c330
Python
K-State-Computational-Core/example-10-releases-python-denea-clark
/src/guess/Main.py
UTF-8
1,121
3.1875
3
[ "MIT" ]
permissive
"""Main class for guessing game. Author: Russell Feldhausen russfeld@ksu.edu Version: 0.1 """ import random from src.guess.GuessingGame import GuessingGame from src.guess.Renderer import Renderer from typing import List class Main: """Main class for guessing game.""" @staticmethod def main(args: List[str]) -> None: """Main method. Args: args: the command-line arguments """ with open("phrases.txt") as file: phrases: List[str] = [line.strip() for line in file] index: int = random.randrange(len(phrases)) game: GuessingGame = GuessingGame(phrases[index]) Renderer.clear_screen() Renderer.print_hello() while game.in_progress: Renderer.print_lobster(game.wrong_guesses) Renderer.print_phrase(game.revealed_phrase) Renderer.print_guesses(game.guesses) c: str = Renderer.get_guess() Renderer.clear_screen() Renderer.print_message(game.guess(c)) if game.won: Renderer.print_win() if game.lost: Renderer.print_loss()
true
8c7ea1f86f1ea116a92eb79da598f8f863956b51
Python
starstorms9/Insight-CS-Practicals
/toxic_class/Tyler_Habowski_Toxic_v1.py
UTF-8
7,749
2.546875
3
[]
no_license
""" Created on Mon Mar 2 14:46:02 2020 """ #%% Imports import numpy as np import os import time import json import pandas as pd import random import inspect import pickle from tqdm import tqdm import tensorflow as tf import matplotlib.pyplot as plt from collections import * import tensorflow as tf import spacy from tensorflow.keras.layers import Dense, InputLayer, Flatten, Reshape, BatchNormalization, GRU, LSTM, Bidirectional, Embedding, Dropout, SpatialDropout1D, Conv1D, GlobalMaxPooling1D from tensorflow.keras import regularizers from tensorflow.keras.preprocessing.sequence import pad_sequences #%% Load data df_toxic = pd.read_csv('/home/starstorms/Insight/Insight-CS-Practicals/toxic_class/toxic_comment/train.csv') #%% Looking at classes distribution df_female = df_toxic[df_toxic.female >= 0.0] df_ftoxic = df_female[df_female.target==1] #%% Data exploration # Get lengths of comments lens = [] for i, row in tqdm(df_female.iterrows(), total=len(df_female)) : lens.append(len(row.comment_text.split())) #%% Show comment length histogram plt.hist(lens, bins=50) plt.suptitle('Histogram of lengths of comments (words)') plt.show() #%% Config variables cf_max_len = 150 cf_batch_size = 256 cf_vocab_size = 100000 cf_val_split = .2 cf_trunc_type = 'post' cf_padding_type = 'post' cf_oov_tok = '<OOV>' #%% Training data setup df_comments = df_female.comment_text df_labels = df_female.target plt.hist(df_labels) plt.show() df_labels[df_labels >= 0.5] = 1 df_labels[df_labels < 0.5] = 0 plt.hist(df_labels) # histogram of toxicity classifications plt.show() print('Percent of toxic comments {:.1f}'.format( 100 * len(df_labels[df_labels==1]) / len(df_labels) )) #%% Spacy stuff def get_embeddings(vocab): max_rank = max(lex.rank for lex in vocab if lex.has_vector) vectors = np.ndarray((max_rank+1, vocab.vectors_length), dtype='float32') for lex in vocab: if lex.has_vector: vectors[lex.rank] = lex.vector return vectors nlp = spacy.load('en_core_web_md', entity=False) embeddings = get_embeddings(nlp.vocab) #%% Encoding methods def padEnc(text) : texts = text if type(text) == list else [text] ranks = [[nlp.vocab[t].rank for t in sent.replace('.', ' . ').split(' ') if len(t)>0] for sent in texts] padded = pad_sequences(ranks, maxlen=cf_max_len, padding=cf_padding_type, truncating=cf_trunc_type) return padded #%% Generate padded and encoded text sequences pes = [] for i, row in tqdm(df_female.iterrows(), total=len(df_female)) : pes.append(padEnc(row.comment_text)) pesnp = np.stack(pes).squeeze() #%% Get word counts # cnt = Counter() # for i, row in tqdm(df_female.iterrows(), total=len(df_female)) : # for word in row.comment_text.split() : # cnt[word] += 1 # savePickle('counter', cnt) #%% Put into tf datasets raw_dataset = tf.data.Dataset.from_tensor_slices((pesnp, df_labels)) dataset_size = len(df_labels) trn_size = int((1-cf_val_split) * dataset_size) val_size = int(cf_val_split * dataset_size) shuffled_set = raw_dataset.shuffle(1000000) trn_dataset = shuffled_set.take(trn_size) val_dataset = shuffled_set.skip(trn_size).take(val_size) trn_dataset = trn_dataset.batch(cf_batch_size, drop_remainder=True) val_dataset = val_dataset.batch(cf_batch_size, drop_remainder=False) for train_x, train_y in trn_dataset.take(1) : pass trn_batch_num = int(trn_size / cf_batch_size) val_batch_num = int(val_size / cf_batch_size) #%% Model class class Toxic(tf.keras.Model): def __init__(self, learning_rate=6e-4, max_length=100, training=True, embeddings=[]): super(Toxic, self).__init__() self.optimizer = tf.keras.optimizers.Adam(learning_rate) self.training = training self.dropoutRate = 0.15 self.loss_func = tf.keras.losses.BinaryCrossentropy(from_logits=True) spacy_embeddings = self.get_embeddings() if len(embeddings)==0 else embeddings model = tf.keras.Sequential() model.add(Embedding(spacy_embeddings.shape[0], spacy_embeddings.shape[1], input_length=max_length, trainable=False, weights=[spacy_embeddings] ) ) model.add(SpatialDropout1D(self.dropoutRate)) model.add(Bidirectional(GRU(128, kernel_regularizer=regularizers.l2(0.001)))) model.add(Dropout(self.dropoutRate)) model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001))) model.add(Dropout(self.dropoutRate)) model.add(Dense(128, activation='relu', kernel_regularizer=regularizers.l2(0.001))) model.add(Dropout(self.dropoutRate)) model.add(Dense(1)) self.model = model def __call__(self, text) : return self.model(text) @tf.function def compute_loss(self, ypred, y): return self.loss_func(ypred, y) @tf.function def trainStep(self, x, y) : with tf.GradientTape() as tape: ypred = self.model(x, training=True) loss = self.compute_loss(ypred, y) gradients = tape.gradient(loss, self.model.trainable_variables) self.optimizer.apply_gradients(zip(gradients, self.model.trainable_variables)) return loss def saveMyModel(self, dir_path, epoch): self.model.save_weights(os.path.join(dir_path, 'epoch_{}.h5'.format(epoch))) def loadMyModel(self, dir_path, epoch): self.model.load_weights(os.path.join(dir_path, 'epoch_{}.h5'.format(epoch))) def setLR(self, learning_rate) : self.optimizer = tf.keras.optimizers.Adam(learning_rate) def printMSums(self) : print("Text Net Summary:\n") self.model.summary() #%% Define model txtmodel = Toxic(learning_rate=6e-4, max_length=cf_max_len, training=True, embeddings=embeddings) txtmodel.printMSums() txtmodel.model.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy']) #%% Train model history = txtmodel.model.fit(trn_dataset.repeat(), epochs=10, validation_data=val_dataset.shuffle(100).take(10), verbose=1, steps_per_epoch=trn_batch_num) #%% Explore results #%% Manual training methods for debugging def getTestSetLoss(dataset, batches=0) : losses = [] for test_x, test_y in dataset.take(batches) : pred = txtmodel.model(test_x) test_loss_batch = txtmodel.compute_loss(pred, test_y) losses.append(test_loss_batch) return np.mean(losses) def getAcc(dataset, batches=10) : accs = [] for test_x, test_y in dataset.take(batches) : pred = txtmodel.model(test_x).numpy().squeeze() pred[pred < 0.5] = 0 pred[pred >= 0.5] = 1 y_np = test_y.numpy().squeeze() accuracy = (y_np == pred).mean() accs.append(accuracy) return np.mean(accs) def trainModel(epochs) : print('\n\nStarting training...\n') txtmodel.training=True for epoch in range(1, epochs + 1): start_time = time.time() losses = [] for train_x, train_y in trn_dataset : # tqdm(trn_dataset, total=int(dataset_size / cf_batch_size)) : batch_loss = txtmodel.trainStep(train_x, train_y) losses.append(batch_loss) print('Batch loss {:.3f}'.format(batch_loss)) loss = np.mean(losses) if epoch % 1 == 0: test_loss = getTestSetLoss(val_dataset, 10) test_acc = getAcc(val_dataset, 10) print(' TEST LOSS: {:.1f} TEST ACC: {:.1f} for epoch: {}'.format(test_loss, test_acc, epoch)) print('Epoch: {} Train loss: {:.1f} Epoch Time: {:.2f}'.format(epoch, float(loss), float(time.time() - start_time))) #%% Train model trainModel(100)
true
832039df03f64eb3c4094e4848e8c04956da2cc9
Python
inaheaven/Tutorials_Python_Basics
/Day1/exercise3.py
UTF-8
1,593
3.40625
3
[]
no_license
money = 2000 card = 1 if money >= 3000 or card >= 1: print('taxi') else: print('walk') var = 100 if(var == 100): print("check 100") if(var == 200): print("check 200") else: print("check200 failed") count = 0 while(count<9): print('count is', count) count = count+1 print("exit") var = 1 while var == 1: num = int(input("Enter a number:")) print("num", num) var += 1 print("exit") count = 0 while count<5: print(count, "is less than 5") count = count+1 else: print(count, "is or greater than 5") pocket = ['paper', 'cellphone, money'] if 'money' in pocket: pass else: print("can't pass") menus = ['pizza', 'ramen', 'cora'] if 'pizza' in menus: print("I will eat this pizza") else: print("Can't eat pizza because i dont have it") print("done with pizza") pocket = ['paper', 'cell'] card =1 if 'money' in pocket: print("will pay for the taxi") elif 'cell' in pocket: print("call your friend to pick up") else: print("wave your hands for the help") amount = int(input("Enter amount")) if amount < 1000: discount = amount * 0.5 print("discount", discount) else: discount = amount * 0.9 print("discount", discount) print("netpayable", amount-discount) test_list = ['one', 'two', 'three'] for i in test_list: print(i) for letter in 'python': if letter == 'h': pass print("this is pass h block") print(letter) sum =0 for i in range(1,11): sum = sum +i print(sum) for i in range(2,10): print(i) for j in range(1,10): print(i, "X", j, i*j)
true
320083a37fe63d59d9c36d28f3cc66e4b72c79c0
Python
YY-in/PyQt
/src/Event.py
UTF-8
1,019
2.859375
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2021/8/17 12:53 下午 # @Author : infinity-penguin # @File : Event.py from PyQt5.Qt import * import sys class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle('事件机制') self.resize(600, 450) self.move(300, 300) class Btn(QPushButton): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.move(60, 60) self.resize(50, 35) self.setText('按钮控件') self.setStyleSheet('background-color:green') def event(self, evt): print(evt, '事件机制') return super().event(evt) def mousePressEvent(self, evt): print("鼠标按下事件") return super().mousePressEvent(evt) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() btn = Btn(window) def myslot(): print('事件机制') btn.pressed.connect(myslot) window.show() sys.exit(app.exec_())
true
626262876dd0c66a46b6767e029b69bab474e797
Python
mapetranick/python_work
/MichaelPetranick_Assignment_3_1.py
UTF-8
701
4.59375
5
[]
no_license
# CIS 240 Introduction to Programming # Assignment 2.2 # Calculate the cost of installing fiber optic cable at a cost of .87 per ft for a company. print("Hello!") print("What is the name of your company?") name = input() print("The cost of fiber optic cable per foot is 87 cents.") print("How much fiber optic cable would you like to purchase (in feet)?") amount = input() cost = float(amount) * 0.87 if amount <= 100 cost = float(amount) * .80 if amount <= 250 cost = float(amount) * .70 if amount = <= 500 cost = float(amount) * .50 print("The cost of " + str(name) + "'s" + " order is " + str(cost) + " dollars") print("Thank you and have a nice day, " + str(name) + "!")
true
96627fbebec40ff5c466eb48707b1ca71c8e8d3d
Python
amoghrajesh/Coding
/Non Leetcode Solutions/draw.py
UTF-8
333
3.328125
3
[]
no_license
t=int(input()) for i in range(t): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) ma=max(a) a[a.index(ma)]=0 sa=sum(a) mb=max(b) b[b.index(mb)]=0 sb=sum(b) if(sa>sb): print("Bob") elif(sb>sa): print("Alice") else: print("Draw")
true
0f5898d9a0fc7ec8fda1b75b1c1c7dbb9d9ff344
Python
rxwx/impacket
/examples/sniffer.py
UTF-8
2,302
2.703125
3
[ "Apache-2.0", "BSD-2-Clause", "Apache-1.1", "MIT" ]
permissive
#!/usr/bin/env python # Impacket - Collection of Python classes for working with network protocols. # # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Description: # Simple packet sniffer. # # This packet sniffer uses a raw socket to listen for packets # in transit corresponding to the specified protocols. # # Note that the user might need special permissions to be able to use # raw sockets. # # Authors: # Gerardo Richarte (@gerasdf) # Javier Kohen # # Reference for: # ImpactDecoder # from select import select import socket import sys from impacket import ImpactDecoder DEFAULT_PROTOCOLS = ('icmp', 'tcp', 'udp') if len(sys.argv) == 1: toListen = DEFAULT_PROTOCOLS print("Using default set of protocols. A list of protocols can be supplied from the command line, eg.: %s <proto1> [proto2] ..." % sys.argv[0]) else: toListen = sys.argv[1:] # Open one socket for each specified protocol. # A special option is set on the socket so that IP headers are included with # the returned data. sockets = [] for protocol in toListen: try: protocol_num = socket.getprotobyname(protocol) except socket.error: print("Ignoring unknown protocol:", protocol) toListen.remove(protocol) continue s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) sockets.append(s) if 0 == len(toListen): print("There are no protocols available.") sys.exit(0) print("Listening on protocols:", toListen) # Instantiate an IP packets decoder. # As all the packets include their IP header, that decoder only is enough. decoder = ImpactDecoder.IPDecoder() while len(sockets) > 0: # Wait for an incoming packet on any socket. ready = select(sockets, [], [])[0] for s in ready: packet = s.recvfrom(4096)[0] if 0 == len(packet): # Socket remotely closed. Discard it. sockets.remove(s) s.close() else: # Packet received. Decode and display it. packet = decoder.decode(packet) print(packet)
true
e9135e6f315bbdbaf689a7a7048117b5213d4f3c
Python
poulter7/lastfm-history
/lastfm_parse.py
UTF-8
2,398
2.984375
3
[]
no_license
from __future__ import division import pygame, urllib2, json, pprint,time from random import randint, random from datetime import datetime, timedelta from urllib2 import urlopen from colorsys import hsv_to_rgb # setup some useful stuff for display pygame.init() SECONDS_IN_A_DAY = 86400 time_height = 1000 time_width = 1000 size=[time_width, time_height] screen=pygame.display.set_mode(size) max_req=200 display_from_uts = datetime.now() - timedelta(3) display_to_uts = datetime.now() from_date = display_from_uts.date() to_date = display_to_uts.date() split_days = (to_date - from_date).days def seconds_past_midnight(time): return time.hour*3600 + time.minute*60 + time.second def timestamp_from_datetime(datetime): return str(int(time.mktime(datetime.utctimetuple()))) # define the colors we will use in rgb format black = [ 0, 0, 0] width_of_bar = time_width/(split_days + 1) class Track(object): def __init__(self, name = '', datetime = datetime.now()): rgb = hsv_to_rgb(random(), 1, 1) self.color = [i*255 for i in rgb] self.datetime = datetime def update(self, screen): time = self.datetime.time() date = self.datetime.date() time_past_origin = date - from_date # x position is based on how many days you are past the origin x = width_of_bar*time_past_origin.days # y position is based on portion through the day y = int((seconds_past_midnight(time)/SECONDS_IN_A_DAY)*time_height) rect = pygame.Rect((x, y), (width_of_bar,0)) pygame.draw.rect(screen, self.color, rect) ## The actual work is done here! # open the api_detail file f = open('api_details.txt') api_key = f.readline() secret = f.readline() f.close() # get some information user = 'poulter7' response = urlopen('http://ws.audioscrobbler.com/2.0/?format=json&from=' +timestamp_from_datetime(display_from_uts) + 'to='+timestamp_from_datetime(display_to_uts)+'&limit='+str(max_req)+'&method=user.getrecenttracks&user=' + user +'&api_key='+api_key ) json_response = response.read() # process the response data = json.loads(json_response) track_data = data['recenttracks']['track'] tracks = [Track(name = t['name'], datetime = datetime.fromtimestamp(float(t['date']['uts']))) for t in track_data] ### # Now some visuals ### for t in tracks: t.update(screen) pygame.display.update() pygame.quit()
true
34b842371737288383c8003404cac5e3cc31332d
Python
t0m/codeeval
/python-challenges/50_string_substitution.py
UTF-8
1,550
3.0625
3
[]
no_license
from itertools import izip import sys class StringPiece(): def __init__(self, value, scannable=True): self.value = value self.scannable = scannable def scan(string, scan_list): string_pieces = [] string = StringPiece(string) string_pieces.append(string) for scan in scan_list: piece_idx = 0 while piece_idx < len(string_pieces): string_p = string_pieces[piece_idx] if string_p.scannable == False: piece_idx += 1 continue scan_idx = string_p.value.find(scan[0]) if scan_idx > -1: # remove the whole piece and split it up into # piece before replacement # replacement (no scannable) # piece after replacement string_p_idx = string_pieces.index(string_p) string_pieces.remove(string_p) end_p = string_p.value[scan_idx + len(scan[0]):] if len(end_p) > 0: string_pieces.insert(string_p_idx, StringPiece(end_p)) replacement = scan[1] string_pieces.insert(string_p_idx, StringPiece(replacement, False)) start_p = string_p.value[:scan_idx] if len(start_p) > 0: string_pieces.insert(string_p_idx, StringPiece(start_p)) else: piece_idx += 1 final = [] for string_piece in string_pieces: final.append(string_piece.value) print ''.join(final) if __name__ == '__main__': for line in open(sys.argv[1]): if len(line.strip()) > 0: string, scan_list = line.strip().split(';') it = iter(scan_list.split(',')) scan_list = izip(it, it) scan(string, scan_list) sys.exit(0)
true
11ab6f75ded63d6ff86c0f9f9359fe070ebc1049
Python
Shadofisher/Micropython_STM32F746Discovery
/MicropythonScripts/STM7/__main.py
UTF-8
1,603
2.53125
3
[]
no_license
# main.py -- put your code here! # main.py -- put your code here! # main.py -- put your code here! from pyb import Pin,LCD,I2C,ExtInt i2c=I2C(3,I2C.MASTER); #tp_int=Pin(Pin.board.LCD_INT,Pin.IN); t_pressed = 0; def drawText(text,x,y,colour): a = len(text) for n in range(a): lcd.text(text[n],x+(n*15),y,colour); def waitTouch(): global t_pressed; touch = 0; regAddressXLow = 0x04; regAddressXHigh = 0x03; regAddressYLow = 0x06; regAddressYHigh = 0x05; count = 0; while(1): if t_pressed: #print('Pressed: ',count); touch = int(ord(i2c.mem_read(1,0x38,02))) #print(touch); t_pressed = 0; low = int(ord(i2c.mem_read(1,0x38,regAddressXLow))); cord = (low & 0xff); high = int(ord(i2c.mem_read(1,0x38,regAddressXHigh))); tempcord = (high & 0x0f) << 8; cord=cord | tempcord; #print(cord) Y=cord; low = int(ord(i2c.mem_read(1,0x38,regAddressYLow))); cord = (low & 0xff); high = int(ord(i2c.mem_read(1,0x38,regAddressYHigh))); tempcord = (high & 0x0f) << 8; cord=cord | tempcord; #print(cord) X=cord; #print(X,Y); lcd.pixels(X,Y,0xffffff); def TS_Interrupt(): global t_pressed; t_pressed=1; callback = lambda e: TS_Interrupt(); extint = ExtInt(Pin.board.LCD_INT,ExtInt.IRQ_FALLING,pyb.Pin.PULL_UP,callback) lcd=LCD(0);
true
6e6084c76ff6b47e2c89445af66eb073c4e1eb38
Python
vleseg/zmsavings
/zmsavings/utils/converter.py
UTF-8
822
3.03125
3
[ "Apache-2.0" ]
permissive
from datetime import datetime # Third-party imports from money import Money class Converter(object): def __init__(self, model_field_name, convert_method): self.model_field_name = model_field_name self._convert = convert_method def __call__(self, value): return self._convert(value) @classmethod def to_datetime(cls, model_field_name, fmt): def _convert(value): return datetime.strptime(value, fmt) return cls(model_field_name, _convert) @classmethod def to_rubles(cls, model_field_name): def _convert(value): if value == '': value = 0 else: value = value.replace(',', '.') return Money(amount=value, currency='RUR') return cls(model_field_name, _convert)
true
b14b66637cec6ba8c953b5e1ee8c657ee48544ea
Python
Ursuline/dssp14
/tweet_processor.py
UTF-8
19,812
2.6875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 26 21:42:54 2020 tweet_processor.py @author: charles meegnin """ import os import requests import string import re import emoji from nltk.stem.snowball import FrenchStemmer from langdetect import detect from langdetect import DetectorFactory from tweet_io import load_data_by_name def load_stopwords(): # First upload stopword file: filename = 'stopwords-fr.txt' # French stopwords path = 'https://raw.githubusercontent.com/stopwords-iso/stopwords-fr/master/' url = path + filename if not os.path.exists(filename): #check it's not already here r = requests.get(url) with open(filename, 'wb') as file: file.write(r.content) #Read stopwords from file into list stopwords = list() with open(filename, 'r') as filehandle: filecontents = filehandle.readlines() for line in filecontents: # remove linebreak which is the last character of the string current_place = line[:-1] # add item to the list stopwords.append(current_place) return(stopwords) def extract_url(str): ur = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', str) return ur def remove_urls(tweet): urls = extract_url(tweet) if urls: # if list of urls isn't empty for url in urls: tweet = tweet.replace(url, "") return tweet def remove_emoji(text): return emoji.get_emoji_regexp().sub(u'', text) def remove_non_ascii(text): printable = set(string.printable) return ''.join(filter(lambda x: x in printable, text)) def process_surnames(tweet): """ replaces possible spellings of politicians last names to last name """ tweet = tweet.replace('jlmelenchon', 'melenchon') tweet = tweet.replace('jl melenchon', 'melenchon') tweet = tweet.replace('jean-luc melenchon', 'melenchon') tweet = tweet.replace('melanchon', 'melenchon') tweet = tweet.replace('france insoumise', 'lfi') tweet = tweet.replace(' insoumis ', ' lfi ') tweet = tweet.replace('franceinsoumise' , 'lfi') tweet = tweet.replace('villanicedric', 'villani') tweet = tweet.replace('cedricvillani', 'villani') tweet = tweet.replace('cedric villani', 'villani') tweet = tweet.replace('emmanuelmacron', 'macron') tweet = tweet.replace('emmanuel macron', 'macron') tweet = tweet.replace('enmarche', 'lrem') tweet = tweet.replace('angela merkel', 'merkel') tweet = tweet.replace('donald trump', 'trump') tweet = tweet.replace('ccastaner', 'castaner') tweet = tweet.replace(' pen ', ' lepen ') tweet = tweet.replace('rassemblement national', 'rn') tweet = tweet.replace('rnationaloff', 'rn') tweet = tweet.replace('rassemblementnational', 'rn') tweet = tweet.replace('francois ruffin', 'francoisruffin') tweet = tweet.replace('francois_ruffin', 'francoisruffin') tweet = tweet.replace('manonaubryfr', 'manonaubry') return tweet def string_to_list(string): li = list(string.split(" ")) return li def remove_stopwords(tweet): """ removes the stopwords from db allows custom words as stopwords2 """ # List of stopwords for the project stopwords2 = ['mme', 'madame', "monsieur", "m.", "m", "s'est", "s’est", 'lequel', "laquelle", "lesquels", "lesquelles", "ete", "etes", "etait", "etais", "etions", "or", "ca", "ça", "est-ce", "voila", '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ] stopwords = load_stopwords() # from external file stopwords = stopwords + stopwords2 # my stopwords #convert tweet to list of tokens tweet = remove_apostrophes(tweet) tweet = string_to_list(tweet) #tweet_b4 = ' '.join(tweet) #b4 = len(tweet) tweet = [word for word in tweet if word not in stopwords] tweet = ' '.join(tweet) # convert to string return tweet def remove_apostrophes(tweet): """Apostrophes are part of a word and not removed in remove_stopwords()""" # replace french apostrophe with apostrophe tweet = tweet.replace("’", "'") tweet = tweet.replace("l'", "") tweet = tweet.replace("c'", "") tweet = tweet.replace("d'", "") tweet = tweet.replace("j'", "") tweet = tweet.replace("s'", "") tweet = tweet.replace("t'", "") tweet = tweet.replace("m'", "") tweet = tweet.replace("n'", "") tweet = tweet.replace("jusqu'", "") tweet = tweet.replace("qu'", "") return tweet def remove_punctuation(tweet): """ 1. Remove punctuation and add typical french punctuation 2. set to lower case """ punctuation = set(string.punctuation) punctuation.add('»') # French quotes punctuation.add('«') punctuation.add("’") # French apostrophe punctuation.add(u"'️") tweet = ''.join(ch for ch in tweet if ch not in punctuation) return tweet def process_idioms(tweet): """ fine-tuning : tweet is a string - remove slogans - remove signatures - various other tweaks - must be run after process_accents() """ # slogans tweet = tweet.replace('onarrive', '') tweet = tweet.replace('alertedemocratie', '') tweet = tweet.replace('jevoteinsoumis', '') tweet = tweet.replace('entoutefranchise', '') tweet = tweet.replace('maintenantlepeuple', '') tweet = tweet.replace('lacriseetapres', '') # signature tweet = tweet.replace('mlp', '') tweet = tweet.replace('amiensfi', '') tweet = tweet.replace('rouenfi', '') tweet = tweet.replace('toulousefi', '') tweet = tweet.replace('limogesfi', '') tweet = tweet.replace('caenfi', '') tweet = tweet.replace('lyonfi', '') tweet = tweet.replace('saintbrieucfi', '') tweet = tweet.replace('bordeauxfi', '') tweet = tweet.replace('besanconfi', '') tweet = tweet.replace('francaises', 'francais') tweet = tweet.replace('francaise', 'francais') tweet = tweet.replace('cooperations', 'cooperation') tweet = tweet.replace('protections', 'protection') tweet = tweet.replace(' ue', ' europe') tweet = tweet.replace('Union européenne', 'europe') tweet = tweet.replace('union européenne', 'europe') tweet = tweet.replace('union europeenne', 'europe') tweet = tweet.replace('europeens', 'europe') tweet = tweet.replace('europeenes', 'europe') tweet = tweet.replace('europeennes', 'europe') tweet = tweet.replace('europenes', 'europe') tweet = tweet.replace('europeen', 'europe') tweet = tweet.replace('europeene', 'europe') tweet = tweet.replace('europeenne', 'europe') tweet = tweet.replace('europene', 'europe') tweet = tweet.replace('europes', 'europe') tweet = tweet.replace('europe2019', 'europe') tweet = tweet.replace('quelleestvotreeurope', 'europe') tweet = tweet.replace(' retraitees', ' retraite') tweet = tweet.replace(' retraites', ' retraite') tweet = tweet.replace('reformedesretraites', 'retraite') tweet = tweet.replace('reformeretraites', 'retraite') tweet = tweet.replace('meetingretraites', 'meeting retraite') tweet = tweet.replace('grevegenerale', 'greve') tweet = tweet.replace('grevedu5decembre', 'greve') tweet = tweet.replace('greve5decembre', 'greve') tweet = tweet.replace('greve10decembre', 'greve') tweet = tweet.replace('greve12decembre', 'greve') tweet = tweet.replace('grevedu17decembre', 'greve') tweet = tweet.replace('greve17decembre', 'greve') tweet = tweet.replace('greve22decembre', 'greve') tweet = tweet.replace('greve24decembre', 'greve') tweet = tweet.replace('greve27decembre', 'greve') tweet = tweet.replace('greve28decembre', 'greve') tweet = tweet.replace('greve9janvier', 'greve') tweet = tweet.replace('greve11janvier', 'greve') tweet = tweet.replace('greve23janvier', 'greve') tweet = tweet.replace('greve24janvier', 'greve') tweet = tweet.replace('GreveMondialePourLeClimat', 'climat greve') tweet = tweet.replace('grevegenerale5fevrier', 'greve') tweet = tweet.replace('greve greve greve', 'greve') tweet = tweet.replace('greve greve', 'greve') tweet = tweet.replace('retraites', 'retraite') # 20 April # tweet = tweet.replace('religions', 'religion') # tweet = tweet.replace('libres', 'liberte') # tweet = tweet.replace('libre', 'liberte') # tweet = tweet.replace('sociales', 'social') # tweet = tweet.replace('sociale', 'social') # tweet = tweet.replace('travailler', 'travail') # tweet = tweet.replace('jeunes ', 'jeunesse ') # tweet = tweet.replace('jeune ', 'jeunesse ') # end 20 April tweet = tweet.replace('islams', 'islam') tweet = tweet.replace('islamistes', 'islam') tweet = tweet.replace('islamiste', 'islam') tweet = tweet.replace('islamismes', 'islam') tweet = tweet.replace('islamisme', 'islam') tweet = tweet.replace('musulmanes', 'islam') tweet = tweet.replace('musulmane', 'islam') tweet = tweet.replace('musulmans', 'islam') tweet = tweet.replace('musulman', 'islam') tweet = tweet.replace('arabes', 'islam') tweet = tweet.replace('arabe', 'islam') tweet = tweet.replace('juifs', 'juif') tweet = tweet.replace('antisemites', 'antisemite') tweet = tweet.replace("climats", 'climat') tweet = tweet.replace("climatiques", 'climat') tweet = tweet.replace("climatique", 'climat') tweet = tweet.replace("ecologiques", 'ecologique') tweet = tweet.replace("ecologie", 'ecologique') tweet = tweet.replace('intelligence artificielle', 'ai') tweet = tweet.replace('etatsunis', 'usa') tweet = tweet.replace('migratoires', 'immigration') tweet = tweet.replace('migratoire', 'immigration') tweet = tweet.replace('immigrants', 'immigration') tweet = tweet.replace('immigrant', 'immigration') tweet = tweet.replace('migrants', 'immigration') tweet = tweet.replace('migrant', 'immigration') tweet = tweet.replace('immigrations', 'immigration') tweet = tweet.replace('gilets jaunes', 'giletsjaunes') tweet = tweet.replace('gilet jaune', 'giletsjaunes') tweet = tweet.replace('giletjaune', 'giletsjaunes') tweet = tweet.replace(' gjs', ' giletsjaunes') tweet = tweet.replace(' gj', ' giletsjaunes') tweet = tweet.replace('votes', 'vote') tweet = tweet.replace('voter', 'vote') tweet = tweet.replace('votee', 'vote') tweet = tweet.replace('votez', 'vote') tweet = tweet.replace('luttent', 'lutte') tweet = tweet.replace('luttes', 'lutte') tweet = tweet.replace('lutter', 'lutte') tweet = tweet.replace('terroristes', 'terrorisme') tweet = tweet.replace('terroriste', 'terrorisme') tweet = tweet.replace('fondamentalistes', 'fondamentalisme') tweet = tweet.replace('fondamentaliste', 'fondamentalisme') tweet = tweet.replace('elections', 'election') tweet = tweet.replace('libertes', 'liberte') tweet = tweet.replace('peuples', 'peuple') tweet = tweet.replace('violents', 'violence') tweet = tweet.replace('violentes', 'violence') tweet = tweet.replace('violente', 'violence') tweet = tweet.replace('violent', 'violence') tweet = tweet.replace('violences', 'violence') tweet = tweet.replace('policieres', 'police') tweet = tweet.replace('policiere', 'police') tweet = tweet.replace('policiers', 'police') tweet = tweet.replace('policee', 'police') tweet = tweet.replace('policier', 'police') tweet = tweet.replace('dangereux', 'danger') tweet = tweet.replace('dangereuses', 'danger') tweet = tweet.replace('dangereuse', 'danger') tweet = tweet.replace('menacees', 'menace') tweet = tweet.replace('menacee', 'menace') tweet = tweet.replace('menacants', 'menace') tweet = tweet.replace('menacante', 'menace') tweet = tweet.replace('menacant', 'menace') tweet = tweet.replace('menaces', 'menace') tweet = tweet.replace('menacer', 'menace') tweet = tweet.replace('libres', 'libre') tweet = tweet.replace('victimes', 'victime') tweet = tweet.replace('emplois', 'emploi') tweet = tweet.replace(' lois ', ' loi ') tweet = tweet.replace(' forts', ' fort') tweet = tweet.replace('defis', 'defi') tweet = tweet.replace('travaux', 'travail') tweet = tweet.replace('attaques', 'attaque') tweet = tweet.replace('eborgneurs', 'eborgneur') tweet = tweet.replace('veux', 'vouloir') tweet = tweet.replace('veut', 'vouloir') tweet = tweet.replace('voulu', 'vouloir') tweet = tweet.replace('voulons', 'vouloir') tweet = tweet.replace('voulez', 'vouloir') tweet = tweet.replace('veulent', 'vouloir') tweet = tweet.replace('il faut', 'devoir') tweet = tweet.replace('devons', 'devoir') tweet = tweet.replace('annees', 'ans') tweet = tweet.replace('annee', 'ans') tweet = tweet.replace('construction', 'construire') tweet = tweet.replace('arretera', 'arreter') tweet = tweet.replace('regardent', 'regarder') tweet = tweet.replace('faisons', 'faire') tweet = tweet.replace('greve22decembre', 'greve') tweet = tweet.replace('greve9janvier', 'greve') tweet = tweet.replace('grevistes', 'greve') tweet = tweet.replace('greviste', 'greve') tweet = tweet.replace(' 000', '000') tweet = tweet.replace(' publics', ' public') tweet = tweet.replace(' publiques', ' public') tweet = tweet.replace(' publique', ' public') return tweet def map_to_tv(tweet): tv = 'TV_RADIO' tweet = tweet.replace('cnews', tv) tweet = tweet.replace('emacrontf1', tv) tweet = tweet.replace('macrontf1', tv) tweet = tweet.replace('e1matin', tv) tweet = tweet.replace('bfmpolitique', tv) tweet = tweet.replace('le79inter', tv) tweet = tweet.replace('lemissionpolitique', tv) tweet = tweet.replace('sudradiomatin', tv) tweet = tweet.replace('bfmtv', tv) tweet = tweet.replace('rmcinfo', tv) tweet = tweet.replace('rtlfrance', tv) tweet = tweet.replace('bourdindirect', tv) tweet = tweet.replace('jjbourdinrmc', tv) tweet = tweet.replace('europe1', tv) tweet = tweet.replace('legrandrdv', tv) tweet = tweet.replace('legrandjury', tv) tweet = tweet.replace('france2tv', tv) tweet = tweet.replace('rmc', tv) tweet = tweet.replace('jpelkabbach', tv) tweet = tweet.replace('19hruthelkrief', tv) tweet = tweet.replace('lci', tv) tweet = tweet.replace('entoutefranchise', tv) tweet = tweet.replace('brunetneumann', tv) tweet = tweet.replace('punchline', tv) tweet = tweet.replace('classiquematin', tv) tweet = tweet.replace('rtlmatin', tv) tweet = tweet.replace('les4v', tv) tweet = tweet.replace('jlm'+tv, tv) return tweet def perform_stemming(tweet): stemmer = FrenchStemmer() #print(stemmer.stem('continuation')) # test word tweet = [stemmer.stem(w) for w in tweet] return tweet def process_accents(tweet): """Remove accents and ç""" tweet = tweet.replace('é', 'e') tweet = tweet.replace('è', 'e') tweet = tweet.replace('ê', 'e') tweet = tweet.replace('ë', 'e') tweet = tweet.replace('ç', 'c') tweet = tweet.replace('â', 'a') tweet = tweet.replace('à', 'a') tweet = tweet.replace('ô', 'o') tweet = tweet.replace('ü', 'u') tweet = tweet.replace('ù', 'u') tweet = tweet.replace('î', 'i') tweet = tweet.replace('œ', 'oe') return tweet def last_tweak(tweet): """Filter whatever went through the cracks""" tweet = tweet.replace('aujourhui', "aujourdhui") tweet = tweet.replace("aujourd'hui", "aujourdhui") tweet = tweet.replace(u'&#65039;','') tweet = tweet.replace('franceinsoumise000','lfi') return tweet def detect_language(text): try : language = detect(text) except: #print(f"translator skipped '{text}'") return('') return language def iterate_preprocess(raw_tweets, raw_labels, screen_names, stemmer_flag): tweets = list() # processed tweets labels = list() # processed labels n = len(screen_names) for handle in range(n): #print(f'[tweet_processor::iterate_preprocess]: Preprocessing {screen_names[handle]}...') tweet, label = preprocess(raw_tweets[handle], raw_labels[handle], stemmer_flag) tweets.append(tweet) labels.append(label) #print(f'[tweet_processor::iterate_preprocess]: Completed preprocessing {screen_names[handle]}\n') return tweets, labels def preprocess(raw_tweets, labels, stemming_flag): """ raw_tweets, labels: list Performs various tweet pre-processing steps: 1. remove non-French tweets 2. replace accented characters 3. processes surnames 4. remove slogans & signatures 5. removes URLs 6. removes emojis 7. removes punctuation 8. set to lower case 9. filters stopwords (2 steps) 10. (optionally) stemming returns list of tweets as strings and labels """ tv_flag = False if stemming_flag == True : print("*** Stemming performed ***") #if tv_flag == False: print('*** No TV/Radio mapping ***') preprocessed_tweets = list() del raw_tweets[0] # remove header row del labels[0] tweet_index = 0 for tweet in raw_tweets: #tweet is string raw_tweets is list() # Process only French tweets DetectorFactory.seed = 0 if detect_language(tweet) == 'fr': #print(tweet, '\n') # Set tweets to lower case tweet = tweet.lower() tweet = tweet.replace(u'\xa0', u' ') tweet = tweet.replace(u'\n', u' ') tweet = tweet.replace(u',', u' ') tweet = tweet.replace(u'.', u' ') tweet = tweet.replace('il faut', 'devoir') # Replace accented characters tweet = process_accents(tweet) # Replace stopwords tweet = remove_stopwords(tweet) # Take URLs out of tweets (before punctuation) tweet = remove_urls(tweet) # Remove punctuation tweet = remove_punctuation(tweet) # Take emojis out of tweets (may be redundant with broader remove_non_ascii) tweet = remove_emoji(tweet) # Remove non-ascii characters tweet = remove_non_ascii(tweet) # unify different spellings of politicians last names tweet = process_surnames(tweet) # perform project-specific tweet-tweaking tweet = process_idioms(tweet) # Map all tv & radio shows to TV_RADIO if tv_flag: tweet = map_to_tv(tweet) # Remove non-ascii characters # Remove stopwords a second time tweet = remove_stopwords(tweet) # Last ditch filter tweet = last_tweak(tweet) # Optionally perform stemming if stemming_flag: tweet = perform_stemming(tweet) preprocessed_tweets.append(tweet) tweet_index += 1 else : del labels[tweet_index] print(f'Retaining {len(preprocessed_tweets)} tweets out of {len(raw_tweets)} raw tweets') return preprocessed_tweets, labels if __name__ == '__main__': # pass the handle of the target user handle = 'JLMelenchon' # Load the data from the csv file raw_tweets, class_labels = load_data_by_name(handle) print(class_labels[0], raw_tweets[0]) print(class_labels[1], raw_tweets[1]) # Send to pre-processing routines stemmer_flag = False # set to True to perform stemming #processed_tweets = preprocess(raw_tweets, stemmer_flag)
true
a8f08f996786849f5fe30ae5a5e79754dcaa4db1
Python
RadiObad/atm
/Forums/models.py
UTF-8
487
3.5
4
[]
no_license
class Member(): """This class provides a way to store member name and age""" def __init__(self, name, age): self.id = 0 self.name = name self.age = age def __str__(self): return '{} has {} years'.format(self.name, self.age) class Post(): """This class provides a way to store post title and content""" def __init__(self, title, content): self.id = 0 self.title = title self.content= content def __str__(self): return '{} : {}'.format(self.title, self.content)
true
3ec55027dee9fbfcab74655844ab03e3fde49e49
Python
prade7970/PirplePython
/If-statement-assignment.py
UTF-8
478
4.1875
4
[]
no_license
""" Assignment 3 - If Statement """ # function works well with only numbers def Compare(n1,n2,n3): if n1==n2 or n2==n3: return True elif n1!=n2 or n2!=n3: return False #Function works with String aswell def CompareAll(n1,n2,n3): if int(n1)== int(n2) or int(n2)==int(n3): return True elif int(n1)!=int(n2) or int(n2)!=int(n3): return False Result=Compare(6,5,5) print(Result) Result2=CompareAll(6,5,"5") print(Result2)
true
23aec7c62f91307c2f5526b754c878624c94beba
Python
akr19/calcbackend
/src/calculator.py
UTF-8
2,665
2.8125
3
[]
no_license
from flask import Flask, jsonify, make_response, url_for from flask_httpauth import HTTPBasicAuth from sqlalchemy import * from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('Starting application') Base = declarative_base() Tablename = 'mytable' class MyTable(Base): __tablename__ = Tablename id = Column(Integer, primary_key=True) name = Column(String(100)) value = Column(String(100)) def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return "<MyTable(%s, %s)>\n" % (self.name, self.value) # main calculator class class Calculator(object): def add(self,x,y): return x+y class DBTest(): def init(self): # configure database connection try: print('start init') self.engine = create_engine('mysql://root:password1@db/testowa1') self.Session = sessionmaker(bind=self.engine) self.session = self.Session() except Exception, e: logger.error('cannot connect to database: %s' % e) print('cannot connect') def get_values(self): try: self.init() records = self.session.query(MyTable).filter(MyTable.id==28).limit(1).all() return str(records) except Exception,e: logger.error('get_values: cannot connect to database: %s' % e) return 'Cannot connect to database\n' application = Flask(__name__) auth = HTTPBasicAuth() @auth.get_password def get_password(username): if username == "blam": return 'python' return None @auth.error_handler def unauthorised(): return make_response(jsonify({'error':'Unauthorised access'}),401) @application.route('/') def index(): logger.info('Getting / ') return "Hello world\n" @application.route('/add/<int:number1>/<int:number2>') @auth.login_required def count(number1,number2): calc = Calculator() mynumber = calc.add(number1,number2) return jsonify(mynumber) @application.route('/hellodb') def hellodb(): logger.info('getting /hellodb') try: dbtest = DBTest() records = dbtest.get_values() return records except Exception,e: logger.error("error: %s" % e) return 'Cannot connect to database\n' @application.errorhandler(404) def not_found(error): return make_response(jsonify({'error':'Not found'}),200) if __name__ == "__main__": application.run(host='0.0.0.0',port='5555',debug=True)
true
2d9266d7498df7664739921dbf2e29442f7b8035
Python
alexalpz/DressMeBot
/test.py
UTF-8
4,206
2.625
3
[]
no_license
#!/usr/bin/env python print('hello world') ''' import nltk import random import string import re, string, unicodedata from nltk.corpus import wordnet as wn from nltk.stem.wordnet import WordNetLemmatizer import wikipedia as wk from collections import defaultdict import warnings warnings.filterwarnings("ignore") from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import GetPosts, NewPost from wordpress_xmlrpc.methods.users import GetUserInfo from wordpress_xmlrpc.methods import posts client = Client("http://3.234.154.40/xmlrpc.php","user", "hn1JuejIMe4m") postx = WordPressPost() postx.title = "Dress Me Bot" postx.Slug = 'Dress-Me-Bot' from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity, linear_kernel data = open('HR.txt','r',errors = 'ignore') raw = data.read() raw = raw.lower() sent_tokens = nltk.sent_tokenize(raw) def Normalize(text): remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation) # word tokenization word_token = nltk.word_tokenize(text.lower().translate(remove_punct_dict)) # remove ascii new_words = [] for word in word_token: new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignore') new_words.append(new_word) # Remove tags rmv = [] for w in new_words: text = re.sub("&lt;/?.*?&gt;", "&lt;&gt;", w) rmv.append(text) # pos tagging and lemmatization tag_map = defaultdict(lambda: wn.NOUN) tag_map['J'] = wn.ADJ tag_map['V'] = wn.VERB tag_map['R'] = wn.ADV lmtzr = WordNetLemmatizer() lemma_list = [] rmv = [i for i in rmv if i] for token, tag in nltk.pos_tag(rmv): lemma = lmtzr.lemmatize(token, tag_map[tag[0]]) lemma_list.append(lemma) return lemma_list welcome_input = ("hello", "hi", "greetings", "sup", "what's up","hey",) welcome_response = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"] def welcome(user_response): for word in user_response.split(): if word.lower() in welcome_input: return random.choice(welcome_response) def generateResponse(user_response): robo_response='' sent_tokens.append(user_response) TfidfVec = TfidfVectorizer(tokenizer=Normalize, stop_words='english') tfidf = TfidfVec.fit_transform(sent_tokens) #vals = cosine_similarity(tfidf[-1], tfidf) vals = linear_kernel(tfidf[-1], tfidf) idx=vals.argsort()[0][-2] flat = vals.flatten() flat.sort() req_tfidf = flat[-2] if(req_tfidf==0) or "tell me about" in user_response: print("Checking Wikipedia") if user_response: robo_response = wikipedia_data(user_response) return robo_response else: robo_response = robo_response+sent_tokens[idx] return robo_response#wikipedia search def wikipedia_data(input): reg_ex = re.search('tell me about (.*)', input) try: if reg_ex: topic = reg_ex.group(1) wiki = wk.summary(topic, sentences = 3) return wiki except Exception as e: print("No content has been found") flag= True print("My name is Chatterbot and I'm a chatbot. If you want to exit, type Bye!") while(flag==True): user_response = input() user_response=user_response.lower() if(user_response not in ['bye','shutdown','exit', 'quit']): if(user_response=='thanks' or user_response=='thank you' ): flag=False print("Chatterbot : You are welcome..") else: if(welcome(user_response)!=None): print("Chatterbot : "+welcome(user_response)) else: print("Chatterbot : ",end="") print(generateResponse(user_response)) sent_tokens.remove(user_response) else: flag=False print("Chatterbot : Bye!!! ") postx.post_status = 'publish' client.call(posts.NewPost(postx)) postx.content = '' '''
true
c3a074cf93ebcd9d4f5388a9b8ddd977dde002ae
Python
rene84/cfn-python-lint
/src/cfnlint/rules/templates/Base.py
UTF-8
1,160
2.765625
3
[ "MIT-0" ]
permissive
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ from cfnlint.rules import CloudFormationLintRule from cfnlint.rules import RuleMatch class Base(CloudFormationLintRule): """Check Base Template Settings""" id = 'E1001' shortdesc = 'Basic CloudFormation Template Configuration' description = 'Making sure the basic CloudFormation template components are properly configured' source_url = 'https://github.com/aws-cloudformation/cfn-python-lint' tags = ['base'] required_keys = [ 'Resources' ] def match(self, cfn): """Basic Matching""" matches = [] top_level = [] for x in cfn.template: top_level.append(x) if x not in cfn.sections: message = 'Top level template section {0} is not valid' matches.append(RuleMatch([x], message.format(x))) for y in self.required_keys: if y not in top_level: message = 'Missing top level template section {0}' matches.append(RuleMatch([y], message.format(y))) return matches
true
98cbdf0649c70ab9241710cb97aae185a061a841
Python
zhoufwind/py_dictContacts03
/m_search.py
UTF-8
2,513
3.0625
3
[]
no_license
import os,sys from prettytable import PrettyTable import itertools def f_preSearch(contacts): #print "This is precise search!", contacts.keys() while True: Psearch = raw_input("Search Name: ").strip().lower() if len(Psearch) == 0: continue if Psearch == 'q': break if contacts.has_key(Psearch): # output account information if contacts have search content x = PrettyTable(["Name", "TEL", "Company", "Email"]) x.add_row(["\033[32;1m%s\033[0m" % Psearch, contacts[Psearch][0], contacts[Psearch][1], contacts[Psearch][2]]) x.align = "l" x.padding_width = 2 print x else: # error message print "\033[31;1mNo valid record...\033[0m" def f_fuzSearch(contacts): #print "This is fuzzy search!", contacts.keys() while True: x = PrettyTable(["Name", "TEL", "Company", "Email"]) Fsearch = raw_input("Fuzzy keyword: ").strip().lower() if len(Fsearch) == 0: continue if Fsearch == 'q': break info_counter = 0 # matching count if len(Fsearch) < 2: print "\033[31;1mSearching keyword must greater than 1 word!" continue for name, value in contacts.items(): # first layer loop if name.count(Fsearch) != 0: # If name contains searching keyword, print user p = name.find(Fsearch) x.add_row([name[:p] + "\033[32;1m%s\033[0m" % Fsearch + name[p + len(Fsearch):], value[0], value[1], value[2]]) info_counter += 1 continue #print "start second loop" for i in value: # second layer loop if i.count(Fsearch) != 0: x.add_row([name, value[0], value[1], value[2]]) # output raws without highlight # ---BUG02: Cannot using highlight function show output--- # line = name + '\t' + '\t'.join(value) # find 'value' contains Fsearch, generate origin output # lineSplit = line.split(Fsearch) # we need highlight Fsearch, so we split the whole output # print lineSplit # lineMeger = [] # create temp sequence # for j in lineSplit: # loop adding each part to the temp sequence # lineMeger.append(j) # adding each part to temp sequence # lineMeger.append('\033[32;1m%s\033[0m' % Fsearch) # adding highlight part # lineMeger.pop() # removing the highlight at end of the temp sequence # print lineMeger # lineFin = "".join(itertools.chain(*lineMeger)) # print lineFin info_counter += 1 break if info_counter == 0: print "No valid record..." else: x.align = "l" x.padding_width = 2 print x print "Found %s records..." % info_counter
true
9915340935f485603f9e708ee500b29a8d402f3e
Python
antocuni/pytabletop
/pytt/tools.py
UTF-8
1,817
2.828125
3
[ "MIT" ]
permissive
from kivy.event import EventDispatcher from pytt.fogofwar import Tool, RevealRectangle def bounding_rect(pos1, pos2): if pos1 is None or pos2 is None: # this should never happen, but better to return a dummy value than to # crash print 'wrong position :(', pos1, pos2 return (0, 0), (1, 1) x1, y1 = pos1 x2, y2 = pos2 x1, x2 = sorted([x1, x2]) y1, y2 = sorted([y1, y2]) pos = x1, y1 size = (x2-x1, y2-y1) return pos, size class RectangleTool(Tool): """ Interactively reveal a rectangle of the map """ rect = None origin = None def get_button(self, touch): # on Android we don't have buttons, we assume it's left, i.e. the # default return getattr(touch, 'button', 'left') def on_touch_down(self, fog, touch): if not fog.collide_point(*touch.pos) or self.get_button(touch) != 'left': return self.origin = touch.pos self.rect = RevealRectangle(pos=touch.pos, size=(1, 1), dm=fog.dm, fog=fog) fog.add_widget(self.rect) touch.grab(fog.ids.map) def on_touch_move(self, fog, touch): if (self.rect is None or self.origin is None or self.get_button(touch) != 'left'): return pos, size = bounding_rect(self.origin, touch.pos) self.rect.pos = pos self.rect.size = size def on_touch_up(self, fog, touch): if (self.rect is None or self.origin is None or self.get_button(touch) != 'left'): return if (self.rect and self.rect.width < 5 and self.rect.height < 5): # too small, remove it! fog.remove_widget(self.rect) self.rect = None self.origin = None
true
3eded4c13ea623870b08f0c635fc35c0c2ca225c
Python
fikery/ArticleSpider
/ArticleSpider/tools/crawl_xici_ip.py
UTF-8
3,173
2.734375
3
[]
no_license
import re import requests from scrapy.selector import Selector import pymysql conn=pymysql.connect(host='127.0.0.1',user='root',passwd='mysqlpassword',db='articlcspider',charset='utf8') cursor=conn.cursor() def crawl_ips(): #爬取西刺代理IP headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36', } for i in range(1,20): html=requests.get('http://www.xicidaili.com/nn/{0}'.format(i),headers=headers) selector=Selector(html) trs=selector.css('#ip_list tr') ip_list=[] for tr in trs[1:]: speed_str=tr.css('.bar::attr(title)').extract_first() if speed_str: speed=float(speed_str.replace('秒','')) all_texts=tr.css('td').extract() all_texts=','.join(all_texts) ip=re.findall(r'<td>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>',all_texts)[0] port=re.findall(r'<td>(\d+)</td>',all_texts)[0] ptype=re.findall(r'<td>(HTTPS?)</td>',all_texts)[0] ip_list.append((ip,port,speed,ptype)) for ip_data in ip_list: # cursor.execute( # 'insert into proxy_ip(ip,port,speed,proxy_type) VALUES(%s,%s,%s,%s)',( # ip_data[0],ip_data[1],ip_data[2],ip_data[3]) # ) try: cursor.execute( 'insert into proxy_ip(ip,port,speed,proxy_type) VALUES("{0}","{1}","{2}","{3}")'.format( ip_data[0], ip_data[1], ip_data[2], ip_data[3] ) ) conn.commit() # print('ok') except Exception as e: if 'Duplicate' in str(e): pass class GetIP(): def checkIP(self,ip,port): http_url='http://www.baidu.com' proxy_url='http://{0}:{1}'.format(ip,port) proxy_dict={ 'http':proxy_url, # 'https':proxy_url } try: response=requests.get(http_url,proxies=proxy_dict) except: print('无效ip',ip) self.deleteIP(ip) return False else: code=response.status_code if code>=200 and code<300: print('有效ip') return True else: print('无效ip',ip) self.deleteIP(ip) return False def deleteIP(self,ip): delete_sql='delete from proxy_ip where ip=%s' cursor.execute(delete_sql,ip) conn.commit() def getRandomIP(self): #从数据库中随机取一个ip sql='select ip,port from proxy_ip ORDER BY rand() limit 1' result=cursor.execute(sql) for ips in cursor.fetchall(): ip,port=ips checkres=self.checkIP(ip,port) if checkres: return 'http://{0}:{1}'.format(ip,port) else: return self.getRandomIP() if __name__ == '__main__': crawl_ips() # getip=GetIP() # print(getip.getRandomIP())
true
c05ab7a716aab0b920f66c51382abcc30db7bca7
Python
ahuber950/Euler
/pe004/pe004.py
UTF-8
592
4.125
4
[]
no_license
# Problem 4 # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. def mod4(digits): if type(digits) != int or digits < 1: raise ValueError("The value must be an integer greater than zero") x = 0 for i in range(10 ** (digits - 1), 10 ** (digits)): for j in range(10 ** (digits - 1), 10 ** (digits)): if i * j > x and str(i * j) == str(i * j)[::-1]: x = i * j return x
true
09ca6f1a0ccfcfd70b05d489a04f4ccbaf8024fd
Python
arjunbista/assignment
/Valid.py
UTF-8
1,683
3.59375
4
[]
no_license
'''import sys name=input("Enter your Name: ") for x in range(1,4): if name.isalpha()==True and len(name)>=4 or " " in name: pass break else: print("Invalid name") name = input('enter name again') else: sys.exit("Please follow next Time") age=input("Enter your Age: ") for y in range(1,3): if age.isdecimal()==True and int(age)>=18: pass break else: print("Invalid age details") age=input("Re Enter your age: ") else: sys.exit("Please follow next Time") mob=input("Enter your Mobile number: ") for z in range(1,3): if mob.isdigit()==True and len(mob)==10: pass break else: print("INVALID Mobile number") mob=input("Re Enter your mobile: ") else: sys.exit("Please follow next Time") ''' #CAlculator code starts here from operation view# print("Please choose one of the following operations") print("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Square Root\n6.Square of Number\n7.Cube of Number") choice = input("Choose one Option:") ##user_input == Y## while condition==Y: 1:\ print("You choose Addition Operation") 2:print("You choose Subtraction Operation ") 3:print("") 4:print("") 5:print("") 6:print("") 7:print("") 8:print("") else: print("") input=input("Do you want to continue with program again?\nPress Y/n to continue and press N/n to exit") if input==N or input ==n: sys.exit("Program Exiting.....") elif input !=Y or input!=N or input!=y or input!=y: print("Invalid input") else: input =("aaaaa")
true
6665ca6a973d65c186b314b543a1ed8a25ab580c
Python
axtrace/alisa_sq_color_func
/guess.py
UTF-8
5,939
3.484375
3
[]
no_license
import random def while_or_black(text): whites = ('белый', 'белая', 'белые', 'белое', 'белого') blacks = ( 'черный', 'черная', 'черное', 'черные', 'чёрн', 'черного', 'черн') for c in whites: if c in text: return 'WHITE' for c in blacks: if c in text: return 'BLACK' return '' def square_color(square): file = square[0] rank = int(square[1]) file_num = ord(file.lower()) - ord('a') + 1 if (rank + file_num) % 2 == 0: return 'BLACK' return 'WHITE' def random_square(): files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] rank = random.randint(1, 8) file_index = random.randint(0, 7) return str(files[file_index]) + str(rank) def say_square(square): letters_for_pronunciation = { 'ru': {'a': 'а', 'b': 'бэ', 'c': 'цэ', 'd': 'дэ', 'e': 'е', 'f': 'эф', 'g': 'же', 'h': 'аш'}} if not square: return '' file = square[0] rank = int(square[1]) file_pron = letters_for_pronunciation['ru'].get(file, '') return file_pron + str(rank) def say_color(color): if color == 'WHITE': return 'белого' elif color == 'BLACK': return 'чёрного' return '' def handler(event, context): """ Entry-point for Serverless Function. :param event: request payload. :param context: information about current execution context. :return: response to be serialized as JSON. """ answer = 'Привет! Давай поиграем. Я буду называть клетку шахматной доски, а ты попробуй угадать её цвет. Начинаем?' answer_tts = '' square = '' is_session_end = 'false' count = 0 # if event is not None and event['request']['session']['new']: # Новая сессия if event is not None and 'request' in event and 'original_utterance' in \ event['request'] and len(event['request']['original_utterance']): text = event['request']['command'] intents = {} if 'nlu' in event['request']: if 'intents' in event['request']['nlu']: intents = event['request']['nlu']['intents'] if 'YANDEX.HELP' in intents or 'YANDEX.WHAT_CAN_YOU_DO' in intents: answer = 'Я называю координаты шахматной клетки, а ты угадываешь её цвет. Например, a1 - чёрный, a2 - белый' answer_tts = f'Я называю координаты шахматной клетки, а ты угадываешь её цвет. Например, {say_square("a1")} - чёрный, {say_square("a2")} - белый' elif 'YANDEX.CONFIRM' in intents or 'да' in text or 'начин' in text: square = random_square() color = square_color(square) answer = f'Какого цвета клетка {square}?' answer_tts = f'Какого цвета клетка {say_square(square)}?' elif 'WHITE_WORD' in intents or 'BLACK_WORD' in intents or while_or_black( text.lower()): prev_square = event['state']['session']['square'] count = event['state']['session']['count'] color = square_color(prev_square) user_color = 'BLACK' if 'WHITE_WORD' in intents or while_or_black( text.lower()) == 'WHITE': user_color = 'WHITE' if user_color == color: answer = 'Правильно! ' answer_tts = 'Правильно! ' count += 1 else: answer = f'Неправильно! Клетка {prev_square} {say_color(color)} цвета. Увы, обнуляем счетчик. ' answer_tts = f'Неправильно! Клетка {say_square(prev_square)} {say_color(color)} цвета. Увы, обнуляем счетчик. ' count = 0 if count > 0 and count % 3 == 0: answer += f'У тебя уже {count} правильных ответов подряд. Так держать! ' answer_tts += f'У тебя уже {count} правильных ответов подряд. Так держать! ' square = random_square() answer += f'А теперь скажи, какого цвета клетка {square}?' answer_tts += f'А теперь скажи, какого цвета клетка {say_square(square)}?' else: square = '' if 'state' in event: if 'session' in event['state']: if 'square' in event['state']['session']: square = event['state']['session']['square'] if square: answer = f'Прости. Я не смогла понять твой ответ. Назови цвет клетки {square}: белый или чёрный' answer_tts = f'Прости. Я не смогла понять твой ответ. Назови цвет клетки {say_square(square)}: белый или чёрный' else: answer = f'Прости. Я не смогла понять твой ответ. Начинаем?' answer_tts = f'Прости. Я не смогла понять твой ответ. Начинаем?' if not len(answer_tts): answer_tts = answer return { 'version': event['version'], 'session': event['session'], 'response': { 'text': answer, 'tts': answer_tts, 'end_session': is_session_end }, 'session_state': { 'square': square, 'count': count } }
true
603ca9e3c1b50f264b96b648794cd5ea2f5c7576
Python
shinan0/python2
/约瑟夫环问题.py
UTF-8
1,574
4
4
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[ ]: def move(players,step): #移动step前的元素到列表末尾 #将如何step的元素从列表中删除 num = step - 1 while num > 0: tmp = players.pop(0) players.append(tmp) num = num - 1 return players #根据step做了元素的移动 def play(players,step,alive): """ 模拟约瑟夫问题的函数。 Input: players:参加游戏的人数; step;数到step函数的人数淘汰; alive:幸存人数,即游戏结束。 Output: 返回一个列表,列表中元素为幸存者的编号。 """ #生成一个列表,从[1,...,piayers] list1=[i for i in range(1,players+1)] #进入游戏的循环,每次数到step淘汰,step之前的元素移动到列表末尾 #游戏结束的条件,列表剩余人数小于alive while len(list1) > alive: #移动step前的元素到列表末尾 #将如何step的元素从列表中删除 # num = step - 1 # while num > 0: # tmp = list1.pop(0) # list1.append(tmp) # num = num - 1 list1=move(list1, step) list1.pop(0) #此时的step的元素在列表第一个位置,使用pop(0)从列表中删除 return list1 players_num=int(input("请输入参与游戏的人数 ")) step_num=int(input("请输入淘汰的数字 ")) alive_num=int(input("请输入幸存的人数 ")) alive_list=play(players_num, step_num, alive_num) print(alive_list) # In[ ]:
true
1dd0b9f494a09bc60d8e841405c4436bda8f7b7a
Python
natc79/MENAJobData
/step1_download/src/create_databases.py
UTF-8
7,880
2.875
3
[ "MIT" ]
permissive
""" This code creates key databases for various data that is being downloaded. Author: Natalie Chun Created: November 22, 2018 """ import sqlite3 def update_table(tablename,newtablequery,insertstatement): """Update table""" conn = sqlite3.connect("egyptOLX.db") c = conn.cursor() query ='''PRAGMA table_info({});''' print(c.execute(query.format(tablename)).fetchall()) query = "ALTER TABLE {} RENAME TO {}_temp;" c.execute(query.format(tablename,tablename)) c.execute(newtablequery) query = "INSERT INTO {} ({}) SELECT {} FROM {}_temp;" c.execute(query.format(tablename,insertstatement,insertstatement,tablename)) query ='''PRAGMA table_info({});''' print(c.execute(query.format(tablename)).fetchall()) query = '''DROP TABLE IF EXISTS {}_temp;''' c.execute(query.format(tablename)) temp = c.execute('''SELECT * FROM {};'''.format(tablename)).fetchall() print("Number of entries in converted table {}: {}".format(tablename,len(temp))) conn.commit() conn.close() def reset_tables(): """Reset all of the tables.""" for i, t in enumerate(tables): deletequery = '''DROP TABLE IF EXISTS {};''' c.execute(deletequery.format(table[i])) c.execute(querycreate[t]) query ='''PRAGMA table_info({});''' print(c.execute(query.format(table[i])).fetchall()) conn.commit() conn.close() def get_olx_table_schema(): """Set schema for relevant OLX tables.""" # in sqlite the only option to convert table is to rename temporary table, create new table, and then drop old tables = {} tables['regionadcounts'] = '''CREATE TABLE IF NOT EXISTS regionadcounts ( downloaddate DATE, downloadtime VARCHAR(5), country VARCHAR(15), region VARCHAR(50), freg VARCHAR(50), subregion VARCHAR(50), fsubreg VARCHAR(50), totalregposts INTEGER, subposts INTEGER, PRIMARY KEY(downloaddate,region,subregion));''' tables['regionjobadcounts']= '''CREATE TABLE IF NOT EXISTS regionjobadcounts (downloaddate DATE, downloadtime VARCHAR(5), country VARCHAR(15), region VARCHAR(50), freg VARCHAR(50), subregion VARCHAR(50), fsubreg VARCHAR(50), sector VARCHAR(50), urlregsector VARCHAR(50), totalposts INTEGER, PRIMARY KEY(downloaddate,region,subregion,sector));''' tables['jobadpageurls'] = '''CREATE TABLE IF NOT EXISTS jobadpageurls ( country VARCHAR(15), region VARCHAR(50), freg VARCHAR(50), subregion VARCHAR(50), fsubreg VARCHAR(50), jobsector VARCHAR(50), postdate DATE, uid INTEGER, i_photo INTEGER, i_featured INTEGER, href VARCHAR(50), PRIMARY KEY(uid,postdate));''' tables['jobadpage'] = '''CREATE TABLE IF NOT EXISTS jobadpage ( downloaddate DATE, downloadtime VARCHAR(5), country VARCHAR(15), uid INTEGER, postdate DATE, posttime VARCHAR(5), pageviews INTEGER, title VARCHAR(70), experiencelevel VARCHAR(50), educationlevel VARCHAR(50), type VARCHAR(50), employtype VARCHAR(50), compensation INTEGER, description VARCHAR(5000), textlanguage VARCHAR(2), userhref VARCHAR(30), username VARCHAR(50), userjoinyear INTEGER, userjoinmt VARCHAR(3), emailavail INTEGER, phoneavail INTEGER, stat VARCHAR(10), PRIMARY KEY(downloaddate,uid,postdate));''' return(tables) def get_wuzzuf_table_schema(): """Set schema for relevant Wuzzuf tables.""" tables = {} tables['jobadpageurls']='''CREATE TABLE IF NOT EXISTS jobadpageurls ( country VARCHAR(20), uid INTEGER, href VARCHAR(200), postdatetime VARCHAR(100), postdate DATE, PRIMARY KEY(uid,postdate));''' tables['jobadpage']='''CREATE TABLE IF NOT EXISTS jobadpage ( country VARCHAR(20), uid INTEGER, postdate DATE, posttime VARCHAR(5), downloaddate DATE, downloadtime VARCHAR(5), stat VARCHAR(10), jobtitle VARCHAR(50), company VARCHAR(50), location VARCHAR(50), num_applicants INTEGER, num_vacancies INTEGER, num_seen INTEGER, num_shortlisted INTEGER, num_rejected INTEGER, experience_needed VARCHAR(50), career_level VARCHAR(50), job_type VARCHAR(50), salary VARCHAR(50), education_level VARCHAR(50), gender VARCHAR(10), travel_frequency VARCHAR(20), languages VARCHAR(30), vacancies VARCHAR(15), roles VARCHAR(300), keywords VARCHAR(100), requirements VARCHAR(5000), industries VARCHAR(100), PRIMARY KEY(uid,postdate,downloaddate)); ''' return(tables) def get_tanqeeb_table_schema(): tables = {} tables['mainurls'] = """CREATE TABLE IF NOT EXISTS mainurls ( downloaddate DATE, country VARCHAR(15), topic VARCHAR(15), cat VARCHAR(25), href VARCHAR(30), img VARCHAR(100), PRIMARY KEY(country, href)); """ tables['categoryurls'] = """CREATE TABLE IF NOT EXISTS categoryurls ( downloaddate DATE, country VARCHAR(15), cat VARCHAR(25), subcat VARCHAR(20), href VARCHAR(100), PRIMARY KEY(country, href)); """ tables['jobadpageurls'] = """CREATE TABLE IF NOT EXISTS jobadpageurls ( country VARCHAR(15), cat VARCHAR(15), subcat VARCHAR(15), uniqueid VARCHAR(50), dataid INTEGER, i_featured INTEGER, postdate VARCHAR(10), title VARCHAR(25), href VARCHAR(100), description VARCHAR(500), PRIMARY KEY (uniqueid, postdate));""" tables['jobadpage'] = """CREATE TABLE IF NOT EXISTS jobadpage ( country VARCHAR(15), uniqueid VARCHAR(50), postdate VARCHAR(10), location VARCHAR(20), jobtype VARCHAR(10), company VARCHAR(20), reqexp VARCHAR(10), salary VARCHAR(10), education VARCHAR(20), title VARCHAR(25), pubimg VARCHAR(50), description VARCHAR(5000), PRIMARY KEY (country, uniqueid, postdate)); """ tables['translation'] = """CREATE TABLE IF NOT EXISTS translation ( country VARCHAR(15), uniqueid VARCHAR(50), description_en VARCHAR(5000), PRIMARY KEY(country, uniqueid)); """ return(tables) def get_tanqeebcv_table_schema(): tables = {} tables['resumelinks'] = """CREATE TABLE IF NOT EXISTS resumelinks ( id INTEGER, srchtitle VARCHAR(50), srchcountry VARCHAR(15), name VARCHAR(50), jobtitle VARCHAR(50), jobstatid INTEGER, country VARCHAR(20), region VARCHAR(20), PRIMARY KEY(id, srchtitle, country), FOREIGN KEY(jobstatid) REFERENCES jobstatmap(id) ); """ tables['jobstatmap'] = """CREATE TABLE IF NOT EXISTS jobstatmap ( id INTEGER, jobstat VARCHAR(50), PRIMARY KEY(id) ); """ tables['translation'] = """CREATE TABLE IF NOT EXISTS translation ( id INTEGER, downloaddate VARCHAR(10), column1 VARCHAR(20), column2 VARCHAR(20), listnum INTEGER, translation_en VARCHAR(5000), PRIMARY KEY(id, downloaddate, column1, column2, listnum) ); """ tables['no_translation'] = """CREATE TABLE IF NOT EXISTS no_translation ( id INTEGER, downloaddate VARCHAR(10), PRIMARY KEY(id, downloaddate) ); """ return(tables) if __name__ == "__main__": pass
true
a9f47126e318efddba8b8c9ae55af3467e701e98
Python
ValentunSergeev/FinTechFinal
/constants.py
UTF-8
2,129
2.703125
3
[]
no_license
from emoji import emojize labels = {1: 'Акции', 2: 'Блокировка карты', 3: 'Вам звонили', 4: 'Вклад', 5: 'Действующий кредит', 6: 'Денежные переводы', 7: 'Задолженность', 8: 'Интернет банк', 9: 'Карты', 10: 'Кредит', 11: 'Кредитные карты', 12: 'Курс доллара', 13: 'Курс евро', 14: 'Курсы валют', 15: 'Мобильный банк', 16: 'Не работает банкомат', 17: 'Обслуживание вкладов', 18: 'Обслуживание карт', 19: 'Обслуживание кредитных карт', 20: 'Открыте вклада', 21: 'Перевод на оператора', 22: 'Платежное поручение', 23: 'Получение карты', 24: 'Получения кредита', 25: 'Пос терминал', 26: 'Претензии', 27: 'Приветствие', 28: 'Продажа кредитных карт', 29: 'Процентные ставки', 30: 'Расчетно кассовое обслуживание', 31: 'Расчетный счет', 32: 'Реквизиты банка', 33: 'Физические лица', 34: 'Эквайринг', 35: 'Юридические лица', 0: 'Адреса офисов и банкоматов'} common_requests = {12: "Ткущий курс долара: 65 рублей. ", 13: "Текущий курс евро: 70 рублей. ", "курс доллара": "Текущий курс долара: 65 рублей. ", "курс евро": "Текущий курс евро: 70 рублей. "} non_fin_words = ['нет', 'да', 'хорошо', "ну это"] cake = emojize(":cake:", use_aliases=True) right_ans = ['да', "конечно", "ага", "угадал", "точно", "верно"] wrong_ans = ['нет', 'никакая из этих тем не подходит', "неа", "не", "ошибаешься", "ошибка"] remind_time = 30 off_time = 210
true
3008cda72a7d6faf50f5a191068445ee419e1dd7
Python
JudahDoupe/MachineLearning
/NeuralNet/NetworkOptimizer.py
UTF-8
3,612
3.03125
3
[]
no_license
from NeuralNet.NeuralNetwork import * import operator import matplotlib.patches as mpatches from NeuralNet.NormalizedData import * class NetworkOptimizer: def __init__(self, fileName, fileDelimter=',', debug=False): self.data = NormalizedData(fileName, fileDelimiter) self.numDataSets = len(self.data.inputs) self.trainingIn, self.trainingOut = self.trainingData() self.crossValidationIn, self.crossValidationOut = self.crossValidationData() self.testingIn, self.testingOut = self.testingData() self.debug = debug def trainingData(self): return self.data.inputs[:math.floor(self.numDataSets * 0.8)], \ self.data.outputs[:math.floor(self.numDataSets * 0.8)] def crossValidationData(self): return self.data.inputs[math.floor(self.numDataSets * 0.8):math.floor(self.numDataSets * 0.9)], \ self.data.outputs[math.floor(self.numDataSets * 0.8):math.floor(self.numDataSets * 0.9)] def testingData(self): return self.data.inputs[math.floor(self.numDataSets * 0.9):], \ self.data.outputs[math.floor(self.numDataSets * 0.9):] def NFoldCrossValidation(self, N, learningRates, hiddenLayers, nodesPerLayer): networkConfigs = [] totalIters = len(learningRates) * len(hiddenLayers) * len(nodesPerLayer) countIter = 1 for learningRate in learningRates: for hiddenLayer in hiddenLayers: for nodes in nodesPerLayer: print("Training: {0}th out of {1}".format(countIter, totalIters)) net = Network(self.data.numFeatures, self.data.numClassifications, hiddenLayer, nodes, learningRate) net.debug = self.debug net.train(self.trainingIn, self.trainingOut) accuracy = net.test(self.crossValidationIn, self.crossValidationOut) networkConfigs.append( {'hiddenLayers': hiddenLayer, 'nodesPerLayer': nodes, 'learningRate': learningRate, 'accuracy': accuracy, 'network': net}) countIter += 1 networkConfigs.sort(key=operator.itemgetter('accuracy')) NBestConfigs = networkConfigs[0:N] countIter = 1 for config in NBestConfigs: print("Testing: {0}th out of {1}".format(countIter, N)) config['accuracy'] = config['network'].test(self.testingIn, self.testingOut) self.exportCostGraph(config) countIter += 1 return NBestConfigs def exportCostGraph(self, config): x = np.array(config["network"].costsXAxis) y = np.array(config["network"].costs) costFigure, costAxes = plt.subplots() costAxes.plot(x, y, color='blue') costLine = mpatches.Patch(color='blue', label='Cost') costFigure.legend(handles=[costLine]) costAxes.set_xlabel('Training Iterations') costAxes.set_ylabel('Average Cost') costFigure.suptitle('LearningRate:{0} HiddenLayers:{1} NodesPerLayer:{2}\nAccuracy:{3}'.format( config['learningRate'], config['hiddenLayers'], config['nodesPerLayer'], config['accuracy'])) costFigure.savefig('CostGraphs/LR:{0}_HL:{1}_NPL:{2}.png'.format( config['learningRate'], config['hiddenLayers'], config['nodesPerLayer'])) plt.close(costFigure) if __name__ == "__main__": fileName = 'fishersIris.txt' fileDelimiter = ',' tester = NetworkOptimizer(fileName) tester.NFoldCrossValidation(48, [1,.1,.01,.001], [1, 2, 3], [3, 4, 5, 6])
true
8516113dff141c2142a37483ddc3f23dfbfedc22
Python
vaishali59/CrackingTheCodingInterview
/Sorting_Searching/Peak_Valleys_mysol.py
UTF-8
816
3.265625
3
[]
no_license
def peakValleys(arr): up = False down = False for k in range(len(arr)-1): if not up and not down: if arr[k]>arr[k+1]: up = not up elif arr[k]<arr[k+1]: down = not down else: return -1 elif down: if arr[k]==arr[k+1]: return -1 if arr[k] < arr[k+1]: arr[k],arr[k+1]=arr[k+1],arr[k] up = not up down = not down elif up: if arr[k]==arr[k+1]: return -1 if arr[k] > arr[k+1]: arr[k],arr[k+1]=arr[k+1],arr[k] down = not down up = not up else: return -1 return arr arr = [3,5,5,7,8] print(peakValleys(arr))
true
25c8c5a3d31ce42582fccd31c530b59df7128f53
Python
NainAcero/mineria
/informe01.py
UTF-8
2,114
3.078125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Mar 11 13:35:50 2021 @author: NAIN """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.svm import SVR from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, f1_score, confusion_matrix, accuracy_score, mean_absolute_error, mean_squared_error #IMPORTAMOS EL DATASET #----------------------------------------------------------------------------------------------------------------- df_customer = pd.read_csv('dataset/Ecommerce Customers.csv') df_customer.drop(columns=['Email', 'Address', 'Avatar'], inplace=True) #DIVIDIMOS EN TRAIN Y TEST #----------------------------------------------------------------------------------------------------------------- train = df_customer.drop(columns=['Yearly Amount Spent']) test = df_customer['Yearly Amount Spent'] X_train, X_test, y_train, y_test = train_test_split(train, test, test_size=0.2) #REALIZAMOS EL ALGORITMO Y COMPROBAMOS RESULTADOS #----------------------------------------------------------------------------------------------------------------- #Instanciamos el algoritmo svr_2 = SVR(kernel='linear', C=10, cache_size=800, ) #Entrenamos svr_2.fit(X_train, y_train) #Predecimos train_preds = svr_2.predict(X_train) test_preds = svr_2.predict(X_test) #Vemos el error del algoritmo a la hora de predecir, para comprobar si a ajustado bien. print('MAE in train:', mean_absolute_error(train_preds, y_train)) print('RMSE in train:', np.sqrt(mean_squared_error(train_preds, y_train))) print('MAE in test:', mean_absolute_error(test_preds, y_test)) print('RMSE in test:', np.sqrt(mean_squared_error(test_preds, y_test))) # VEMOS LOS COEFICIENTES DEL ALGORITMO #----------------------------------------------------------------------------------------------------------------- pd.DataFrame(svr_2.coef_, columns=X_train.columns).T print(pd.DataFrame(svr_2.coef_, columns=X_train.columns).T) print() print('DATOS DEL MODELO VECTORES DE SOPORTE REGRESIÓN') print() print('Precisión del modelo:') print(svr_2.score(X_train, y_train))
true
b4837888f4b4d09a6829d58782d75df8c757148b
Python
zhangjiatao/Confidence-Knowledge-Graph
/2-PCRA.py
UTF-8
7,643
2.640625
3
[]
no_license
''' Step 2: Calculate the PCRA confidence of each triples ''' import os,sys import math import random import time in_path = './2-data_with_neg/' # 构建全局容器 ok = {} # ok['h'+'t'][r] = 1 a ={} # a[h][r][t] = 1 # 用于存储dataset三元组 relation2id = {} id2relation = {} relation_num = 0 h_e_p = {} # h_e_p['e1'+'e2'][rel_path] = 可信度(没进行归一化) path_dict = {} # path 2 mount 即统计每个path的数量 作用是统计path对应的频数 path_r_dict = {} # path_r_dict[rel_path+"->" rel] = 数量 ,作用是统计path和rel的共现频数 def map_add(mp, key1,key2, value): ''' 容器操作: mp[key1][key2] += value ''' if (key1 not in mp): mp[key1] = {} if (key2 not in mp[key1]): mp[key1][key2] = 0.0 mp[key1][key2] += value def map_add1(mp,key): ''' 容器操作: mp[key]+=1 ''' if (key not in mp): mp[key] = 0 mp[key]+=1 def load_rel2id(file): ''' load relation2id file ''' global relation2id global id2relation global relation_num # load relation2id f = open(file,"r") for line in f: rel_id, rel_str = line.strip().split('\t') relation2id[rel_str] = int(rel_id) id2relation[int(rel_id)] = rel_str id2relation[int(rel_id)+ relation_num] = "~" + rel_id relation_num += 1 f.close() def load_triples(file): ''' load triples 输入格式(h, r, t) ''' global ok global a # load dataset f = open(file,"r") for line in f: seg = line.strip().split('\t') e1 = seg[0] rel = seg[1] # string e2 = seg[2] # 加入ok if (e1+" "+e2 not in ok): ok[e1+" "+e2] = {} ok[e1+" "+e2][relation2id[rel]] = 1 # e1 e2加入正向边 if (e2+" "+e1 not in ok): ok[e2+" "+e1] = {} ok[e2+" "+e1][relation2id[rel]+relation_num] = 1 # e1 e2加入反向边 # 加入a if (e1 not in a): a[e1]={} if (relation2id[rel] not in a[e1]): a[e1][relation2id[rel]]={} a[e1][relation2id[rel]][e2]=1 # 加入正向边 if (e2 not in a): a[e2]={} if ((relation2id[rel]+relation_num) not in a[e2]): a[e2][relation2id[rel]+relation_num]={} a[e2][relation2id[rel]+relation_num][e1]=1 # 加入反向边 f.close() def generate_path(): ''' search path for triple ''' global h_e_p global path_dict global path_r_dict print('[INFO] 开始进行路径搜索') step = 0 # 进度统计 for e1 in a: # 打印进度 step += 1 if step % 1000 == 0: print('process: %.4lf' % (step / len(a))) # 处理one-hop path:(e1, rel1, e2) for rel1 in a[e1]: e2_set = a[e1][rel1] for e2 in e2_set: map_add1(path_dict, str(rel1)) # e1和e2之间的一跳路径,作用是统计每条路径的出现次数 for key in ok[e1+' '+e2]: map_add1(path_r_dict, str(rel1) + "->" + str(key)) map_add(h_e_p, e1+' '+e2, str(rel1), 1.0 / len(e2_set)) # 处理two-hop path:(e1, rel1, e2)的e2基础上再拓展一层节点e3 for rel1 in a[e1]: e2_set = a[e1][rel1] for e2 in e2_set: if (e2 in a): for rel2 in a[e2]: e3_set = a[e2][rel2] for e3 in e3_set: map_add1(path_dict,str(rel1)+" "+str(rel2)) # 将这个两跳的路径加入,统计出现次数 if (e1+" "+e3 in ok): for key in ok[e1+' '+e3]: map_add1(path_r_dict,str(rel1)+" "+str(rel2)+"->"+str(key)) if (e1+" "+e3 in ok):# and h_e_p[e1+' '+e2][str(rel1)]*1.0/len(e3_set)>0.01): map_add(h_e_p, e1+' '+e3, str(rel1)+' '+str(rel2),h_e_p[e1+' '+e2][str(rel1)]*1.0/len(e3_set)) def proir_path_confidence(in_file, out_file): ''' triple with prior path confidence ''' f = open(in_file, "r") g = open(out_file, "w") for line in f: seg = line.strip().split('\t') e1 = seg[0] rel = relation2id[seg[1]] e2 = seg[2] # 计算正向triple路径 # g.write(str(e1) + ' ' +str(e2) + ' ' + str(rel) + ' ') # triple b = {} a = {} # 计算每条path的可信度 res = 0 # prior path confidence if (e1+' '+e2 in h_e_p): # 可信度的归一化预处理 sum = 0.0 for rel_path in h_e_p[e1+' '+e2]: b[rel_path] = h_e_p[e1+' '+e2][rel_path] sum += b[rel_path] for rel_path in b: b[rel_path]/=sum if b[rel_path]>0.01: a[rel_path] = b[rel_path] # a中存的就是每条路径的可信度rel_path to score # 累加计算 for rel_path in a: if (rel_path in path_dict and rel_path+"->"+str(rel) in path_r_dict): q = path_r_dict[rel_path+"->"+str(rel)] * 1.0 / path_dict[rel_path] r = a[rel_path] # res += q * r res += (0.2 + 0.8 * q) * r g.write(str(res) + '\n') f.close() g.close() def work(in_file, out_file): ''' triple and path with confidence ''' f = open(in_file, "r") g = open(out_file, "w") for line in f: seg = line.strip().split('\t') e1 = seg[0] rel = relation2id[seg[1]] e2 = seg[2] # 计算正向triple路径 g.write(str(e1)+" "+str(e2)+' '+str(rel)+"\n") # triple b = {} a = {} if (e1+' '+e2 in h_e_p): sum = 0.0 # 计算总分,为了进行归一化 for rel_path in h_e_p[e1+' '+e2]: b[rel_path] = h_e_p[e1+' '+e2][rel_path] sum += b[rel_path] # 对每条路径score进行归一化 for rel_path in b: b[rel_path]/=sum if b[rel_path]>0.01: a[rel_path] = b[rel_path] # a中存的就是每条路径的可信度rel_path to score g.write(str(len(a))) # 路径数量 for rel_path in a: g.write(" "+str(len(rel_path.split()))+" "+rel_path+" "+str(a[rel_path])) # 每条路径信息 g.write("\n") # 计算反向triple路径 g.write(str(e2)+" "+str(e1)+' '+str(rel+relation_num)+"\n") e1 = seg[1] e2 = seg[0] b = {} a = {} if (e1+' '+e2 in h_e_p): sum = 0.0 for rel_path in h_e_p[e1+' '+e2]: b[rel_path] = h_e_p[e1+' '+e2][rel_path] sum += b[rel_path] for rel_path in b: b[rel_path]/=sum if b[rel_path]>0.01: a[rel_path] = b[rel_path] g.write(str(len(a))) for rel_path in a: g.write(" "+str(len(rel_path.split()))+" "+rel_path+" "+str(a[rel_path])) g.write("\n") f.close() g.close() if __name__ == '__main__': print('start') load_rel2id(in_path + 'relation_id.tsv') load_triples(in_path + 'pos_with_neg.tsv') print('[INFO] 数据载入完成') generate_path() proir_path_confidence(in_path + "pos_with_neg.tsv", in_path + "pos_with_neg_PP_conf.txt") # file_confidence work(in_path + "pos_with_neg.tsv", in_path + 'pos_with_neg_pra.txt') # file_pra.txt
true
ec25b487ccd92e281d8f7d31df4e4fe9cf707c0e
Python
thiagorabelo/pycout
/ostream/ostream.py
UTF-8
1,774
3.265625
3
[ "MIT" ]
permissive
""" Módulo que contém uma classe que simula a classe padrão ostream do C++ """ import numbers from sys import stdout from typing import Union, Callable, IO, Text, Any from .base_ostream import PrecicionManip, FillManipulator class OStream(PrecicionManip, FillManipulator): # pylint: disable=useless-object-inheritance def __init__(self, output_stream: IO[Text] = stdout) -> None: self._stream = output_stream def _to_string(self, value: Any) -> Text: return '%s' % value def _proccess(self, value: Text) -> Text: if isinstance(value, numbers.Real) and not isinstance(value, numbers.Integral): value = self._proccess_numbers(value) # TODO: quoted deve vir aqui. if self.width_: return self._fill_str(self._to_string(value)) return self._to_string(value) def __lshift__(self, value: Union[Text, int, float, bool, Callable[['OStream'], 'OStream']]) -> 'OStream': return self.write(value) def write(self, value: Union[Text, int, float, bool, Callable[['OStream'], 'OStream']]) -> 'OStream': if callable(value): return value(self) self._stream.write(self._proccess(value)) return self def put(self, char: Text) -> 'OStream': self._stream.write(self._proccess(char)[0]) return self def flush(self) -> None: self._stream.flush() def endl(stream: OStream) -> OStream: stream << '\n' # pylint: disable=pointless-statement stream.flush() return stream def ends(stream: OStream) -> OStream: stream.write('\0') return stream def flush(stream: OStream) -> OStream: stream.flush() return stream
true
25b3de8decb6d3557f6c86e8991a1790cbe1af0d
Python
Paskal-Dash/university
/3.2/Коваленко/3/K-1(O).py
UTF-8
332
2.921875
3
[]
no_license
n = int(input()) files = dict((lambda x: (x[0], x[1:]))(input().split()) for _ in range(n)) delta = {'execute': 'X', 'read': 'R', 'write': 'W'} for i in range(int(input())): obj = input().split() if any(delta[obj[0]] == file1 for file1 in files[obj[1]]): print('OK') else: print('Access denied')
true
2e9e5552f8642959165315f911f0929ed416833c
Python
SirLegolot/SSP
/Python/hw2_starter/photometry rectangle (Jason1984 KB).py
UTF-8
2,277
2.9375
3
[]
no_license
from __future__ import division import numpy as np import matplotlib.pyplot as plt import math from astropy.io import fits myim = fits.getdata("Average1.fit") # jason1984kb ##plt.imshow(myim, vmin=myim.mean(), vmax=2*myim.mean()) ##plt.gray() ##plt.show() ##starx = input("What is your star x coordinate?" ) ##stary = input("What is your star y coordinate?" ) ##magstar = input("What is your star's magnitude" ) ##blankx = input("What is your blank x coordinate?" ) ##blanky = input("What is your blank y coordinate?" ) ##astrdx = input("What is your asteroid x coordinate?" ) ##astrdy = input("What is your asteroid y coordinate?" ) #Jason's data: starx = 866 stary = 164 magstar = 13.66 blankx = 63 blanky = 910 astrdx = 584 astrdy = 549 print "star box" starbox = myim[stary-7:stary+7, starx-7:starx+7] #extracts a 14 by 14 grid around the given star coordinates print starbox print "total star (star+sky) " # gets the total of all the pixels in the star box totalstar = sum(sum(starbox)) print totalstar print "blank box" blankbox = myim[blanky-7:blanky+7, blankx-7:blankx+7] #extracts a 14 by 14 grid around the given coordinates print blankbox print "total blank " # gets the total of all the pixels in the blank box totalblank = sum(sum(blankbox)) print totalblank print "average blank (avgSky)" # gets the average pixel value in the blank box averageblank = totalblank/(14**2) print averageblank print "signal star" # calculates the signal for star signal = totalstar - (averageblank*(14**2)) print signal print "constant" # gets the value of constant const = magstar + 2.5*math.log10(signal) print const print "asteroid box" astrdbox = myim[astrdy-7:astrdy+7, astrdx-7:astrdx+7] #extracts a 14 by 14 grid around the given asteroid coordinates print astrdbox print "total astrd (star+sky) " # gets the total of all the pixels in the asteroid box totalastrd = sum(sum(astrdbox)) print totalastrd print "signal asteroid" # calculates the signal of asteroid signalastrd = totalastrd - (averageblank*(14**2)) print signalastrd print "magnitude asteroid" # calculates magnitude of the asteroid magastrd = -2.5*math.log10(signalastrd) + const print magastrd
true
5af41bfd1ff9920dbf4f09d97371b719355d247e
Python
devos50/fake-tribler-api
/FakeTriblerAPI/utils/read_torrent_file.py
UTF-8
292
2.984375
3
[]
no_license
str = "" with open("data/random_torrents.dat") as random_torrent_files: content = random_torrent_files.readlines() for random_torrent in content: torrent_parts = random_torrent.split("\t") print torrent_parts[0] str = str + torrent_parts[0] + ", " print str
true
cf2a7b4b3f77a5e15c95ee0c3a374af5b7a26c98
Python
oshadmon/StreamingSQL
/db.py
UTF-8
2,155
3.25
3
[ "MIT" ]
permissive
""" Create connection to the database, and execute SQL commands """ from StreamingSQL.fonts import Colors, Formats import pymysql import warnings warnings.filterwarnings("ignore") def create_connection(host='localhost', port=3306, user='root', password='', db='test')->pymysql.cursors.Cursor: """ Create a connection to the MySQL node Args: host: MySQL connection host port: MySQL connection port user: user connecting to MySQL password: user password db: database name Returns: A connection to the MySQL that can be executed against; otherwise an error is printed """ conn = None try: conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db='test') except pymysql.err.OperationalError as e: error = str(e).replace("(",")").replace('"','').replace(")","").replace(",",":") print(Formats.BOLD+Colors.RED+"Connection Error - "+error+Formats.END+Colors.END) if db is not 'test': cur = conn.cursor() output = execute_command(cur, "CREATE DATABASE IF NOT EXISTS %s;" % db) if output == 1: return output try: conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=db) except pymysql.err.OperationalError as e: error = str(e).replace("(", ")").replace('"', '').replace(")", "").replace(",", ":") print(Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) try: return conn.cursor() except AttributeError: return 1 def execute_command(cur=None, stmt="")->tuple: """ Execute SQL command Args: cur: connection stmt: SQL stmt Returns: (by default) result of the sql execution, otherwise prints an error """ try: cur.execute(stmt) except pymysql.err.ProgrammingError as e: error = str(e).replace("(", ")").replace('"', '').replace(")", "").replace(",", ":") print(Formats.BOLD + Colors.RED + "Connection Error - " + error + Formats.END + Colors.END) else: return cur.fetchall()
true
71c75f3c6c56d529cbfabec0e8bb4e1cdcad1ecb
Python
Jorewang/LeetCode_Solutions
/5. Longest Palindromic Substring.py
UTF-8
808
3.140625
3
[ "Apache-2.0" ]
permissive
class Solution(object): def longestPalindrome(self, s): pass def manacher(self, s): li = [] for char in s: li.append('#') li.append(char) li.append('#') print(li) length = len(li) res = [0]*length mx, id = -1, -1 for i in range(length): if mx > i and 2*id-i-res[2*id-i]+1 != 0: res[i] = min(res[2*id-i], mx-i+1) else: cot = 1 while i+cot < length and i-cot >= 0 and li[i+cot] == li[i-cot]: cot += 1 res[i] = cot id = i mx = id + res[id] - 1 return res if __name__ == '__main__': s = '122122' s2 = 'abbaTNTabcba' print(Solution().manacher(s))
true
b4270dcb3683a682090bc98844f5d4ce00f438be
Python
Sauvikk/practice_questions
/Level4/LinkedLists/Remove Nth Node from List End.py
UTF-8
1,186
4.09375
4
[]
no_license
# Given a linked list, remove the nth node from the end of list and return its head. # # For example, # Given linked list: 1->2->3->4->5, and n = 2. # After removing the second node from the end, the linked list becomes 1->2->3->5. # # Note: # * If n is greater than the size of the list, remove the first node of the list. # Try doing it using constant additional space. # http://yucoding.blogspot.in/2013/04/leetcode-question-82-remove-nth-node.html # http://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/ from Level4.LinkedLists.LinkedList import LinkedList, Node class Solution: @staticmethod def solution(head, n): if head is None: return None temp = head for i in range(n): if temp.next is None: head = head.next return head else: temp = temp.next last = head while temp.next: temp = temp.next last = last.next last.next = last.next.next return head A = LinkedList() A.add(5) A.add(4) A.add(3) A.add(2) A.add(1) A.print() res = Solution.solution(A.get_root(), 2) LinkedList.print_any(res)
true
69a19ea4a5362422c2dbe42f29c62098a055adb4
Python
GuillaumeOj/Mergify-Technical-Test
/tests/test_finder.py
UTF-8
1,358
3.125
3
[]
no_license
from warehouse.finder import Finder from warehouse.box import Box class MockBox: def __init__(self, box_id): self.box_id = list(box_id) class TestFinder: def test_compare_boxes_with_one_different_character_in_same_position( self, monkeypatch ): monkeypatch.setattr("warehouse.box.Box", MockBox) result = Finder().compare_boxes(Box("fghij"), Box("fguij")) assert result def test_compare_boxes_with_no_different_character(self, monkeypatch): monkeypatch.setattr("warehouse.box.Box", MockBox) result = Finder().compare_boxes(Box("fghij"), Box("fghij")) assert not result def test_compare_boxes_with_one_different_character_in_different_positions( self, monkeypatch ): monkeypatch.setattr("warehouse.box.Box", MockBox) result = Finder().compare_boxes(Box("fghij"), Box("fgiuj")) assert not result def test_compare_boxes_with_two_different_characters(self, monkeypatch): monkeypatch.setattr("warehouse.box.Box", MockBox) result = Finder().compare_boxes(Box("fghij"), Box("fguxj")) assert not result def test_common_letters(self, monkeypatch): monkeypatch.setattr("warehouse.box.Box", MockBox) result = Finder().common_letters(Box("fghij"), Box("fguij")) assert result == "fgij"
true