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
b6de5c0eb20ce7dde050e1442cddac661189ac43
Python
axellbrendow/python3-basic-to-advanced
/aula003-str-e-aspas/aula3.py
UTF-8
272
3.421875
3
[ "MIT" ]
permissive
""" str - string """ print("Essa é uma 'string' (str).") print('Essa é uma "string" (str).') print("Essa é uma \"string\" (str).") print('Essa é uma \'string\' (str).') print(r'Essa é uma string bruta (raw) \n (str).') print('Essa é uma quebra de linha \n (str).')
true
88f2d4383e444c83971c9f63e8efd43bc3827fd7
Python
soumilshah1995/Deep-Learning-using-Python-MNIST-Data-using-Stochastic-gradient
/stoch sigmoid dropout.py
UTF-8
6,467
3.359375
3
[]
no_license
''' Using Sigmoid Derivative Function in both layers Thanking you, Soumil Nitin Shah Bachelor in Electronic Engineering Master in Electrical Engineering Master in Computer Engineering Graduate Teaching/Research Assistant Python Developer soushah@my.bridgeport.edu —————————————————— Linkedin: https://www.linkedin.com/in/shah-soumil Github https://github.com/soumilshah1995 Youtube channel https://www.youtube.com/channel/UC_eOodxvwS_H7x2uLQa-svw ------------------------------------------------------ ''' try: # Import library import os import sys import cv2 import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt import time import datetime except: print("Library not found ") now_time = datetime.datetime.now() # Create Time x_data_epoch = [] # Create a list to append Epoch y_data_error = [] # Create a list to append Loss train = np.empty((1000, 28, 28), dtype='float64') # create a Training Data trainY = np.zeros((1000,10, 1)) # Create output Expected test = np.empty((10000, 28, 28), dtype='float64') # Prepare Test Data testY = np.zeros((10000, 10, 1)) # Prepare expected Training Output # --------------------------------------------------------Load in Image-------------------------------------- i = 0 for filename in os.listdir('/Users/soumilshah/IdeaProjects/Deep Learning/MNIST /Training1000'): y = int(filename[0]) trainY[i,y] = 1.0 train[i] = cv2.imread('/Users/soumilshah/IdeaProjects/Deep Learning/MNIST /Training1000/{0}'.format(filename), 0)/255.0 i = i+1 # -------------------------------------------------LOAD TEST IMAGE ------------------------------------------------ i = 0 # read test data for filename in os.listdir('/Users/soumilshah/IdeaProjects/Deep Learning/MNIST /Test10000'): y = int(filename[0]) testY[i, y] = 1.0 test[i] = cv2.imread('/Users/soumilshah/IdeaProjects/Deep Learning/MNIST /Test10000/{0}'.format(filename), 0)/255.0 i = i+1 # --------------------------------------------------------------------------------------------------------------------- trainX = train.reshape(train.shape[0],train.shape[1]*train.shape[2], 1) testX = test.reshape(test.shape[0], test.shape[1] * test.shape[2], 1) # --------------------------------- Neural Network --------------------------------------- numNeuronsLayer1 = 200 # Number of Neuron in Layer 1 numNeuronsLayer2 = 10 # Output Neuron numEpochs = 30 # number of Epoch learningRate = 0.1 # define Learning Rate # Define Weight Matrix Randomly w1 = np.random.uniform(low=-0.1, high=0.1, size=(numNeuronsLayer1, 784)) b1 = np.random.uniform(low=-1, high= 1, size=(numNeuronsLayer1, 1)) w2 = np.random.uniform(low=-0.1, high=0.1, size=(numNeuronsLayer2, numNeuronsLayer1)) b2 = np.random.uniform(low=-0.1, high=0.1, size=(numNeuronsLayer2, 1)) zero_out = np.random.binomial(n=1, p=0.8, size=(numNeuronsLayer1, 1)) / 0.8 for n in range(0, numEpochs): loss = 0 trainX, trainY = shuffle(trainX, trainY) for i in range(trainX.shape[0]): s1 = np.dot(w1, trainX[i]) + b1 # S1 = W.X + B a1 = 1 / (1 + np.exp(-1 * s1)) # A1 = 1 / 1 + EXP(-1 * S1) a1 = np.multiply(zero_out, a1) # A1 = A1 * Zero Out s2 = np.dot(w2, a1) + b2 # S2 = A1.W2 + B2 a2 = 1 / (1 + np.exp(-1 * s2)) # A2 = 1 / (1 + EXP(-1* S2 )) loss += (0.5 * ((a2-trainY[i])*(a2-trainY[i]))).sum() # L = 0.5.(y - a) ^^ 2 # -------------------------------------- BACK Propogate -------------------------------------- error = -1 * (trainY[i] - a2) # E = - (Y - A2) a2_act = np.multiply(a2, (1 - a2)) # A2_act = A2.(1-A2) delta2 = np.multiply(error, a2_act) # Delta2 = - (Y - A2) a1_act = np.multiply(a1, (1 - a1)) # A1_ACT = A1.(1 - A1) a1_act = np.multiply(zero_out, a1_act) # A1_ACT = ZERO OUT * A1_ACT error_2 = np.dot(w2.T, delta2) # E_2 = Delta2 . W2 delta1 = np.multiply(error_2, a1_act) # Delta1 = E_2 . A1 gradw2 = np.dot(delta2, a1.T) # GradW2 = Delta2 . A1 gradw1 = np.dot(delta1, trainX[i].T) # GradW1 = Delta1 . TrainX # gradw1 = np.multiply(gradw1, zero_out) # print(gradw1.shape) gradb2 = delta2 # GRADB2 = Delta2 gradb1 = delta1 # GradB1 = Delta1 w2 = w2 - learningRate * gradw2 # W = W - learning rate . Grad b2 = b2 - learningRate * gradb2 # B = B - learning rate . Grad w1 = w1 - learningRate * gradw1 # W = W - learning rate . Grad b1 = b1 - learningRate * gradb1 # B = B - learning rate . Grad x_data_epoch.append(n) y_data_error.append(loss) print("epoch = " + str(n) + " loss = " + (str(loss))) print("done training , starting testing..") accuracyCount = 0 for i in range(testY.shape[0]): s1 = np.dot(w1, testX[i]) + b1 # S1 = W1.X + B1 a1 = 1/(1+np.exp(-1*s1)) # A1 = 1/ 1+ EXP(S1) s2 = np.dot(w2,a1) + b2 # S2 = A1.W2 + B2 a2 = 1/(1+np.exp(-1*s2)) # A2 = 1/ 1+ EXP(S2) a2index = a2.argmax(axis=0) # Select Max from 10 Neuron if testY[i, a2index] == 1: accuracyCount = accuracyCount + 1 print("Accuracy count = " + str(accuracyCount/10000.0)) end = datetime.datetime.now() t = end-now_time print('time{}'.format(t)) # Print total Time Taken plt.plot(x_data_epoch,y_data_error) plt.xlabel('X axis Neuron {}'.format(numNeuronsLayer1)) plt.ylabel('Loss') plt.title('\n stochastic gradient descent \n Execution Time:{} \n Accuracy Count {}\n Loss :{}'.format(t,accuracyCount,loss)) plt.show()
true
d2199519988b66d262c36f5d6fc2ff78377db87e
Python
see4c/codalab-cli
/codalab/objects/user.py
UTF-8
2,688
2.984375
3
[ "Apache-2.0" ]
permissive
""" User objects representing rows from the user table """ import base64 from codalab.common import UsageError from codalab.model.orm_object import ORMObject from codalab.lib.crypt_util import force_bytes, get_random_string, pbkdf2, constant_time_compare class User(ORMObject): COLUMNS = ('user_id', 'user_name', 'email', 'last_login', 'is_active', 'first_name', 'last_name', 'date_joined', 'is_verified', 'is_superuser', 'password', 'time_quota', 'time_used', 'disk_quota', 'disk_used', 'affiliation', 'url') PASSWORD_MIN_LENGTH = 8 @property def unique_id(self): return self.user_id @property def name(self): return self.user_name @staticmethod def encode_password(password, salt, iterations=30000): """ Encode password using the PBKDF2 algorithm. :param password: raw password string :param salt: salt string :param iterations: number of iterations for algorithm :return: """ assert password is not None assert salt and '$' not in salt hash = pbkdf2(password, salt, iterations) hash = base64.b64encode(hash).decode('ascii').strip() return "%s$%d$%s$%s" % ('pbkdf2_sha256', iterations, salt, hash) @staticmethod def validate_password(password): """ Check if password meets our requirements, raising UsageError if not. Requirements: - minimum length of 8 characters :param password: string password to validate :return: None """ if not all(33 <= ord(c) <= 126 for c in password): raise UsageError("Password must consist of only printable, non-whitespace ASCII characters.") if len(password) < User.PASSWORD_MIN_LENGTH: raise UsageError("Password must contain at least %d characters." % User.PASSWORD_MIN_LENGTH) def set_password(self, password): """ Save password to user. :param password: string of new password :return: None """ self.password = self.encode_password(password, get_random_string()) def check_password(self, password): """ Returns True iff password matches the user's current password. :param password: string of password to check :return: boolean """ if not self.password: return False algorithm, iterations, salt, _ = self.password.split('$', 3) assert algorithm == 'pbkdf2_sha256' encoded = self.encode_password(password, salt, int(iterations)) return constant_time_compare(force_bytes(self.password), force_bytes(encoded))
true
818e4a8f412ea64b692c32cda75330daeea02499
Python
harishannavajjala/GoogleMaps
/route.py
UTF-8
17,580
3.640625
4
[]
no_license
''' 1. Which search algorithm seems to work best for each routing options? Ans - A* algorithm works best for all the routing algorithm. It provides optimal solution for all the options BFS and IDS works also gives optimal solution for segments routing option, but does not give optimal solution for any other option DFS is not optimal, it works really fast but not optimal(or near optimal) 2. Which algorithm is fastest in terms of the amount of computation time required by your program, and by how much, according to your experiments? Ans - In our experiments, DFS turned out to be a winner in terms of computarional time required Algorithm | Time Taken to run 50 iteration(Bloomington to Seattle) BFS | 4.40 s DFS | 2.63 s IDS | Killed after few minutes, obviously the most slowest algorithm in all A* | 12.23 s A* is taking a slightly longer time due to handling missing GPS coordinates for some of the cities/junctions, in order to find the optimal solution A* checks in a loop for all the cities connected to current city with missing gps and adds all neighbors of the city in fringe. 3. Which algorithm requires the least memory, and by how much, according to your experiments? Ans - IDS would require the least amount of memory, as IDS would find solution certainly at lower depth in the graph than DFS, and IDS works in a same manner to DFS, it only holds data till current depth. Hence it would require the least memory 4. Which heuristic function did you use, how good is it, and how might you make it better? Ans - We have used different heuristics for different routing options: All the options uses havershine distance. Havershine distance is distance between two location calculated using their latitude and longitudes. Segments - for segments, we divide the segment with minimum size in entire input with the havershine distance from current city to destination city. This heuristic would find the Distance - we used havershine distance as heuristic for chosing most promising states from state list Time - We used havershine time and maximum speed limit in entire city map. By using maximum speed limit and havershine, we can calculate minimum time from a city to reach the destination Scenic - We calculated havershine distance, and if the speed limit is less than 55 then we deduct current city distance from the havershine else we add it as a cost 5. Supposing you start in Bloomington, which city should you travel to if you want to take the longest possible drive (in miles) that is still the shortest path to that city? (In other words, which city is furthest from Bloomington?) Ans - Skagway,_Alaska is the longest possible drive from Bloomington, Indiana. We found it using dijkstra's algorithm. The abstraction - State - We have used state space as information about city, our state contains of - [city_name] [distance to reach this current city from source city] [time to reach this current city from source city] [segments to reach this current city from source city] Successors - Successors returns all the neighbouring city to input city. We have pruned all visited cities Initial State - Start city with all other fields mentioned in state as 0 Goal State - Goal state gives us total time, total distance, number of segments Cost Function - Cost function varies for different routing options, For segments it segments traversed, For distance, total distance travelled, For time, total time taken to reach the city, For scenic, distance to current city ''' import sys import heapq import math from math import radians, cos, sin, asin, sqrt def read_input(): global max_speed_limit global min_segment_length cities = open("road-segments.txt") for line in cities.readlines(): path = line.strip().split(" ") if int(path[2]) == 0: path[2] = default_distance if path[3].isdigit() == False or int(path[3]) == 0: path[3] = default_speed_limit if path[0] not in city_graph: city_graph[path[0]] = [[path[1]] + [path[2]] + [path[3]] + [path[4]]] else: city_graph[path[0]] += [[path[1]] + [path[2]] + [path[3]] + [path[4]]] if path[1] not in city_graph: city_graph[path[1]] = [[path[0]] + [path[2]] + [path[3]] + [path[4]]] else: city_graph[path[1]] += [[path[0]] + [path[2]] + [path[3]] + [path[4]]] if int(path[2]) < min_segment_length: min_segment_length = int(path[2]) if int(path[3]) > max_speed_limit: max_speed_limit = int(path[3]) cities.close() gps_file = open("city-gps.txt") for line in gps_file.readlines(): data = line.strip().split(" ") city_gps[data[0]] = [data[1]] + [data[2]] gps_file.close() def successors(current_node): return city_graph[current_node[0]] def print_path(visited_parent, current_city): # Machine readable output result_machine_readable = [] result_human_readable = [] city_name = destination while city_name in visited_parent: previous_city = visited_parent[city_name] if previous_city[0] != 'start': time_min = int(math.ceil(float(previous_city[3]) * 60)) time_readable = str(time_min/60) + "h " + str(time_min%60) + "m" result_human_readable.append("Drive from " + str(previous_city[0]) + " to " + str(city_name) + " on " + str( previous_city[4]) + " for " + str(previous_city[1]) + " mile (time: " + time_readable + ")") # Machine readable result_machine_readable.append(city_name) city_name = previous_city[0] result_machine_readable.append(str(round(current_city[2], 3))) result_machine_readable.append(str(current_city[1])) total_time_min = int(math.ceil(float(current_city[2]) * 60)) total_time_readable = str(total_time_min/60) + "h " + str(total_time_min%60) + "m" result_human_readable.append("Your destination is "+str(current_city[1])+" miles away, You will reach you destination in "+ total_time_readable+"\n") while result_human_readable: print str(result_human_readable.pop()) print " " while result_machine_readable: print str(result_machine_readable.pop()) + "", def solve_bfs(routing_option): print "You have chosen BFS as routing option, BFS would only yield optimal solution for 'Segments' routing option" print "BFS may run faster, but it requires a lot of memory to store state list" print "" visited_parent = {} fringe = [[start_city] + [0] + [0] + [0]] visited_parent[start_city] = ['start', '0', '0', '0', '0'] while fringe: current_city = fringe.pop(0) if current_city[0] == destination: print_path(visited_parent, current_city) return for s in successors(current_city): if s[0] not in visited_parent: fringe.append([s[0]] + [int(current_city[1]) + int(s[1])] + [ float(current_city[2]) + (float(s[1]) / float(s[2]))] + [int(current_city[3]) + 1]) visited_parent[s[0]] = [current_city[0]] + [s[1]] + [s[2]] + [float(s[1]) / int(s[2])] + [s[3]] return False def solve_dfs(routing_option): print "You have chosen DFS routing algorithm, DFS is not optimal for any routing option" print "Unless you want to travel entire United States before you reach you destination, please use some other algorithm" print "" visited_parent = {} fringe = [[start_city] + [0] + [0] + [0]] visited_parent[start_city] = ['start', '0', '0', '0', '0'] while fringe: current_city = fringe.pop() if current_city[0] == destination: print_path(visited_parent, current_city) return for s in successors(current_city): if s[0] not in visited_parent: fringe.append([s[0]] + [int(current_city[1]) + int(s[1])] + [ float(current_city[2]) + (float(s[1]) / float(s[2]))] + [int(current_city[3]) + 1]) visited_parent[s[0]] = [current_city[0]] + [s[1]] + [s[2]] + [float(s[1]) / int(s[2])] + [s[3]] return False def solve_ids(routing_option): print "You have chosen IDS as routing algorithm, IDS would only yield optimal solution for 'Segments' routing option" print "IDS may take sometime to find the solution, but memory requirements are lower than BFS" print "" max_level = 0 while True: fringe = [[start_city] + [0] + [0] + [0]] visited_parent = {} visited_level = {} visited_parent[start_city] = ['start', '0', '0', '0', '0'] visited_level[start_city] = 0 while fringe: current_city = fringe.pop() if current_city[0] == destination: print_path(visited_parent, current_city) return if int(current_city[3]) > max_level: continue for s in successors(current_city): if s[0] in visited_parent and (int(visited_level[s[0]]) <= (int(current_city[3]) + 1)): continue fringe.append([s[0]] + [int(current_city[1]) + int(s[1])] + [ float(current_city[2]) + (float(s[1]) / float(s[2]))] + [int(current_city[3]) + 1]) visited_parent[s[0]] = [current_city[0]] + [s[1]] + [s[2]] + [float(s[1]) / int(s[2])] + [s[3]] visited_level[s[0]] = int(current_city[3]) + 1 max_level += 1 print "Failed" def astar(routing_option): options = { 'segments': f_segments, 'distance': f_distance, 'time': f_time, 'scenic': f_scenic } fringe = [] visited_parent = {} visited_level = {} heapq.heappush(fringe, (1, [start_city] + [0] + [0] + [0])) visited_parent[start_city] = ['start', '0', '0', '0', '0'] visited_level[start_city] = 0 lat_destination = float(city_gps[destination][0]) lon_destination = float(city_gps[destination][1]) while fringe: current_city = heapq.heappop(fringe)[1] if current_city[0] == destination: print_path(visited_parent, current_city) return for s in successors(current_city): if s[0] in visited_parent and (int(visited_level[s[0]]) <= (int(current_city[3]) + 1)): continue if s[0] in city_gps: lat_s = float(city_gps[s[0]][0]) lon_s = float(city_gps[s[0]][1]) fx = options[routing_option](current_city, s, lat_s, lon_s, lat_destination, lon_destination) heapq.heappush(fringe, (fx, [s[0]] + [int(current_city[1]) + int(s[1])] + [ float(current_city[2]) + (float(s[1]) / float(s[2]))] + [int(current_city[3]) + 1])) visited_parent[s[0]] = [current_city[0]] + [s[1]] + [s[2]] + [float(s[1]) / int(s[2])] + [s[3]] visited_level[s[0]] = int(current_city[3]) + 1 else: city_no_gps = [[s[0]] + [int(current_city[1]) + int(s[1])] + [ float(current_city[2]) + (float(s[1]) / float(s[2]))] + [int(current_city[3]) + 1]] visited_parent[s[0]] = [current_city[0]] + [s[1]] + [s[2]] + [float(s[1]) / int(s[2])] + [s[3]] visited_level[s[0]] = int(current_city[3]) + 1 while city_no_gps: current_lookahead_city = city_no_gps.pop() for s_lookahead in city_graph[current_lookahead_city[0]]: if s_lookahead[0] in visited_parent and ( int(visited_level[s_lookahead[0]]) <= (int(current_lookahead_city[3]) + 1)): continue if s_lookahead[0] not in city_gps: city_no_gps.append( [s_lookahead[0]] + [int(current_lookahead_city[1]) + int(s_lookahead[1])] + [ float(current_lookahead_city[2]) + ( float(s_lookahead[1]) / float(s_lookahead[2]))] + [ int(current_lookahead_city[3]) + 1]) visited_parent[s_lookahead[0]] = [current_lookahead_city[0]] + [s_lookahead[1]] + [ s_lookahead[2]] + [float(s_lookahead[1]) / float(s_lookahead[2])] + [s_lookahead[3]] visited_level[s_lookahead[0]] = int(current_lookahead_city[3]) + 1 continue lat_s = float(city_gps[s_lookahead[0]][0]) lon_s = float(city_gps[s_lookahead[0]][1]) fx = options[routing_option](current_lookahead_city, s_lookahead, lat_s, lon_s, lat_destination, lon_destination) heapq.heappush(fringe, ( fx, [s_lookahead[0]] + [int(current_lookahead_city[1]) + int(s_lookahead[1])] + [ float(current_lookahead_city[2]) + (float(s_lookahead[1]) / float(s_lookahead[2]))] + [ int(current_lookahead_city[3]) + 1])) visited_parent[s_lookahead[0]] = [current_lookahead_city[0]] + [s_lookahead[1]] + [ s_lookahead[2]] + [float(s_lookahead[1]) / float(s_lookahead[2])] + [s_lookahead[3]] visited_level[s_lookahead[0]] = int(current_lookahead_city[3]) + 1 return False def f_segments(current_city, s, lat_s, lon_s, lat_destination, lon_destination): if (s[0] == destination): return int(current_city[3]) + 1 return int(current_city[3]) + 1 + float(min_segment_length) / haversine(lat_s, lon_s, lat_destination, lon_destination) def f_distance(current_city, s, lat_s, lon_s, lat_destination, lon_destination): return int(current_city[1]) + int(s[1]) + haversine(lat_s, lon_s, lat_destination, lon_destination) def f_time(current_city, s, lat_s, lon_s, lat_destination, lon_destination): return float(current_city[2]) + (float(s[1]) / float(s[2])) + haversine(lat_s, lon_s, lat_destination, lon_destination) / max_speed_limit def f_scenic(current_city, s, lat_s, lon_s, lat_destination, lon_destination): if int(s[2]) < 55: # Not a highway hence subtract current distance from havershine distance return int(current_city[1]) + haversine(lat_s, lon_s, lat_destination, lon_destination) - int(s[1]) else: return int(current_city[1]) + int(s[1]) + haversine(lat_s, lon_s, lat_destination, lon_destination) # This function finds havershine distance between two locations based on latitude and longitude # The function is referenced from http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points # By - Michael Dunn def haversine(lat1, lon1, lat2, lon2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) r = 3959 # Radius of earth in miles return c * r # -------------------------------------Execution starts here------------------------- # Default distance and speed limit, if input does not have those then use this values default_distance = 50 default_speed_limit = 50 # Max speed limit, used to find the minimum time required from a city to destination(havershine distance/max_speed) max_speed_limit = 0 min_segment_length = sys.maxint city_graph = {} city_gps = {} read_input() if len(sys.argv) < 5: print "Please pass [start-city] [end-city] [routing-option] [routing-algorithm] in the arguments" exit() start_city = sys.argv[1] destination = sys.argv[2] if start_city not in city_graph: print "Can not find the city: " + start_city exit() if destination not in city_graph: print "Can not find the city: " + destination exit() if start_city == destination: print "You are already at you destination" exit() if destination not in city_gps: count = 0 lat = 0.0 lon = 0.0 for city in city_graph[destination]: if city[0] in city_gps: count += 1 lat += float(city_gps[city[0]][0]) lon += float(city_gps[city[0]][1]) if count > 0: lat = lat / count lon = lon / count city_gps[destination] = [lat, lon] routing_option = sys.argv[3] routing_algorith = sys.argv[4] algorithms = { 'bfs': solve_bfs, 'dfs': solve_dfs, 'ids': solve_ids, 'astar': astar } algorithms[routing_algorith](routing_option)
true
99d02dbcb19736b18217d63c0ffeca7ee23f29b1
Python
isi-nlp/unitok
/scripts/clean.py
UTF-8
1,706
2.765625
3
[]
no_license
#!/usr/bin/env python3 import argparse import sys import codecs if sys.version_info[0] == 2: from itertools import izip from collections import defaultdict as dd import re import os.path import gzip scriptdir = os.path.dirname(os.path.abspath(__file__)) reader = codecs.getreader('utf8') writer = codecs.getwriter('utf8') def prepfile(fh, code): ret = gzip.open(fh.name, code) if fh.name.endswith(".gz") else fh if sys.version_info[0] == 2: if code.startswith('r'): ret = reader(fh) elif code.startswith('w'): ret = writer(fh) else: sys.stderr.write("I didn't understand code "+code+"\n") sys.exit(1) return ret # TODO # also get rid of empty lines # aprime='\s*'.join(list(a)) # re.match(aprime, b).start(0) # re.match(aprime, b).end(0) # b[7:].isspace() # len(b[7:]) == 0 def clean(line): line = line.strip() if line == "" or line.isspace(): return None return (' '.join(line.split())) def main(): parser = argparse.ArgumentParser(description="remove empty lines and other undesirables", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--infile", "-i", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="input file") parser.add_argument("--outfile", "-o", nargs='?', type=argparse.FileType('w'), default=sys.stdout, help="output file") try: args = parser.parse_args() except IOError as msg: parser.error(str(msg)) infile = prepfile(args.infile, 'r') outfile = prepfile(args.outfile, 'w') for line in infile: line = clean(line) if line is None: continue outfile.write(line+"\n") if __name__ == '__main__': main()
true
104af5463ecb8183cfa9e0773e560a2a435b8e16
Python
ZamanbekNuridinov/-Board-games
/chessEngine(base).py
UTF-8
22,478
2.96875
3
[]
no_license
import random class GameState: def __init__(self): self.map=[ ["","","","","","","","",""], ["","r","k","b","q","g","b","k","r"], ["","p","p","p","p","p","p","p","p"], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","","","","","","","",""], ["","P","P","P","P","P","P","P","P"], ["","R","K","B","Q","G","B","K","R"], ] self.white_to_move = True # self.map[8][1:] # self.L=["R","K","B","Q","G","B","K","R"] # self.l=["r","k","b","q","g","b","k","r"] # self.randomlist = random.sample(range(0, 8), 8) # for i in range(8): # self.map[8][i+1]=self.L[self.randomlist[i]] # self.map[1][i+1]=self.l[self.randomlist[i]] def move(self,sr, sc, er, ec): self.map[er][ec] = self.map[sr][sc] self.map[sr][sc] = "" self.selected = [] self.playerClicks = [] self.white_to_move = not self.white_to_move def getPawnMoves(self,sr,sc,er,ec): if self.white_to_move==True: if sr == 2: if self.map[sr-1][sc]=="" and er==sr-1 and ec==sc: self.move(sr,sc,er,ec) self.map[sr-1][sc]="Q" if self.map[sr-1][sc-1].islower() and self.map[sr-1][sc-1]!="" and er == sr-1 and ec == sc-1: self.move(sr,sc,er,ec) self.map[sr-1][sc-1]="Q" elif self.map[sr-1][sc+1].islower() and self.map[sr-1][sc+1]!="" and er == sr-1 and ec == sc+1: self.move(sr,sc,er,ec) self.map[sr-1][sc+1]="Q" if sr-1 >= 1: if self.map[sr-1][sc]=="" and er == sr-1 and ec == sc: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc-1 >=1: if self.map[sr-1][sc-1].islower() and self.map[sr-1][sc-1]!="" and er == sr-1 and ec == sc-1: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc+1 <=8: if self.map[sr-1][sc+1].islower() and self.map[sr-1][sc+1]!="" and er == sr-1 and ec == sc+1: self.move(sr,sc,er,ec) if sr == 7: for i in range(1,3): if self.map[sr-i][sc]=="" and er == sr-i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr-i][sc]!="": break else: if sr == 7: if self.map[sr+1][sc]=="" and er==sr+1 and ec==sc: self.move(sr,sc,er,ec) self.map[sr+1][sc]="q" if self.map[sr+1][sc+1].isupper() and self.map[sr+1][sc+1]!="" and er == sr+1 and ec == sc+1: self.move(sr,sc,er,ec) self.map[sr+1][sc+1]="q" elif self.map[sr+1][sc-1].isupper() and self.map[sr+1][sc-1]!="" and er == sr+1 and ec == sc-1: self.move(sr,sc,er,ec) self.map[sr+1][sc-1]="q" if sr+1 <= 8: if self.map[sr+1][sc]=="" and er == sr+1 and ec == sc: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc+1 <=8: if self.map[sr+1][sc+1].isupper() and self.map[sr+1][sc+1]!="" and er == sr+1 and ec == sc+1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc-1 >=1: if self.map[sr+1][sc-1].isupper() and self.map[sr+1][sc-1]!="" and er == sr+1 and ec == sc-1: self.move(sr,sc,er,ec) if sr == 2: for i in range(1,3): if self.map[sr+i][sc]=="" and er == sr+i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr+i][sc]!="": break def getPawnWay(self,sr,sc): if self.white_to_move == True: if self.map[sr-1][sc]=="" and sr-1 >= 1: self.map[sr-1][sc]="M" if self.map[sr-1][sc]=="M" and sr-2 >= 1 and self.map[sr-2][sc]=="" and sr==7: self.map[sr-2][sc]="M" else: if self.map[sr+1][sc]=="" and sr+1 <= 8: self.map[sr+1][sc]="M" if self.map[sr+1][sc]=="M" and sr+2 <= 8 and self.map[sr+2][sc]=="" and sr==2: self.map[sr+2][sc]="M" def getRookMoves(self,sr, sc, er, ec): if self.white_to_move == True: for i in range(1,8): if sr-i >= 1: if (self.map[sr-i][sc]=="" or (self.map[sr-i][sc].islower() and self.map[sr-i][sc]!="")) and er == sr-i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr-i][sc]!="": break for i in range(1,8): if sr+i <= 8: if (self.map[sr+i][sc]=="" or (self.map[sr+i][sc].islower() and self.map[sr+i][sc]!="")) and er == sr+i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr+i][sc]!="": break for i in range(1,8): if sc-i >= 1: if (self.map[sr][sc-i]=="" or (self.map[sr][sc-i].islower() and self.map[sr][sc-i]!="")) and er == sr and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr][sc-i]!="": break for i in range(1,8): if sc+i <= 8: if (self.map[sr][sc+i]=="" or (self.map[sr][sc+i].islower() and self.map[sr][sc+i]!="")) and er == sr and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr][sc+i]!="": break else: for i in range(1,8): if sr-i >= 1 and sc >= 1: if (self.map[sr-i][sc]=="" or (self.map[sr-i][sc].isupper() and self.map[sr-i][sc]!="")) and er == sr-i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr-i][sc]!="": break for i in range(1,8): if sr+i <= 8 and sc <= 8: if (self.map[sr+i][sc]=="" or (self.map[sr+i][sc].isupper() and self.map[sr+i][sc]!="")) and er == sr+i and ec == sc: self.move(sr,sc,er,ec) elif self.map[sr+i][sc]!="": break for i in range(1,8): if sr >= 1 and sc-i >= 1: if (self.map[sr][sc-i]=="" or (self.map[sr][sc-i].isupper() and self.map[sr][sc-i]!="")) and er == sr and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr][sc-i]!="": break for i in range(1,8): if sr <= 8 and sc+i <= 8: if (self.map[sr][sc+i]=="" or (self.map[sr][sc+i].isupper() and self.map[sr][sc+i]!="")) and er == sr and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr][sc+i]!="": break def getRookWay(self, sr, sc): for i in range(1,8): if sr-i >= 1: if self.map[sr-i][sc]=="": self.map[sr-i][sc]="M" elif self.map[sr-i][sc]!="": break for i in range(1,8): if sr+i <= 8: if self.map[sr+i][sc]=="": self.map[sr+i][sc]="M" elif self.map[sr+i][sc]!="": break for i in range(1,8): if sc+i <= 8: if self.map[sr][sc+i]=="": self.map[sr][sc+i]="M" elif self.map[sr][sc+i]!="": break for i in range(1,8): if sc-i >= 1: if self.map[sr][sc-i]=="": self.map[sr][sc-i]="M" elif self.map[sr][sc-i]!="": break def getBishopMoves(self,sr, sc, er, ec): if self.white_to_move == True: for i in range(1,8): if sr-i >= 1 and sc+i <= 8: if (self.map[sr-i][sc+i]=="" or (self.map[sr-i][sc+i].islower() and self.map[sr-i][sc+i]!="")) and er == sr-i and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr-i][sc+i]!="": break for i in range(1,8): if sr-i >= 1 and sc-i >= 1: if (self.map[sr-i][sc-i]=="" or (self.map[sr-i][sc-i].islower() and self.map[sr-i][sc-i]!="")) and er == sr-i and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr-i][sc-i]!="": break for i in range(1,8): if sr+i <= 8 and sc+i <= 8: if (self.map[sr+i][sc+i]=="" or (self.map[sr+i][sc+i].islower() and self.map[sr+i][sc+i]!="")) and er == sr+i and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr+i][sc+i]!="": break for i in range(1,8): if sr+i <= 8 and sc-i >= 1: if (self.map[sr+i][sc-i]=="" or (self.map[sr+i][sc-i].islower() and self.map[sr+i][sc-i]!="")) and er == sr+i and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr+i][sc-i]!="": break else: for i in range(1,8): if sr-i >= 1 and sc+i <= 8: if (self.map[sr-i][sc+i]=="" or (self.map[sr-i][sc+i].isupper() and self.map[sr-i][sc+i]!="")) and er == sr-i and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr-i][sc+i]!="": break for i in range(1,8): if sr-i >= 1 and sc-i >= 1: if (self.map[sr-i][sc-i]=="" or (self.map[sr-i][sc-i].isupper() and self.map[sr-i][sc-i]!="")) and er == sr-i and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr-i][sc-i]!="": break for i in range(1,8): if sr+i <= 8 and sc+i <= 8: if (self.map[sr+i][sc+i]=="" or (self.map[sr+i][sc+i].isupper() and self.map[sr+i][sc+i]!="")) and er == sr+i and ec == sc+i: self.move(sr,sc,er,ec) elif self.map[sr+i][sc+i]!="": break for i in range(1,8): if sr+i <= 8 and sc-i >= 1: if (self.map[sr+i][sc-i]=="" or (self.map[sr+i][sc-i].isupper() and self.map[sr+i][sc-i]!="")) and er == sr+i and ec == sc-i: self.move(sr,sc,er,ec) elif self.map[sr+i][sc-i]!="": break def getBishopWay(self, sr, sc): for i in range(1,8): if sr-i >= 1 and sc+i <=8: if self.map[sr-i][sc+i]=="": self.map[sr-i][sc+i]="M" elif self.map[sr-i][sc+i]!="": break for i in range(1,8): if sr+i <= 8 and sc+i <=8: if self.map[sr+i][sc+i]=="": self.map[sr+i][sc+i]="M" elif self.map[sr+i][sc+i]!="": break for i in range(1,8): if sr+i <= 8 and sc-i >=1: if self.map[sr+i][sc-i]=="": self.map[sr+i][sc-i]="M" elif self.map[sr+i][sc-i]!="": break for i in range(1,8): if sr-i >= 1 and sc-i >=1: if self.map[sr-i][sc-i]=="": self.map[sr-i][sc-i]="M" elif self.map[sr-i][sc-i]!="": break def getQueenMoves(self, sr, sc, er, ec): self.getBishopMoves(sr,sc,er,ec) self.getRookMoves(sr,sc,er,ec) def getQueenWay(self, sr, sc): self.getBishopWay(sr,sc) self.getRookWay(sr,sc) def getKnightMoves(self, sr, sc, er, ec): if self.white_to_move == True: if sr-1 >= 1 and sc+2 <= 8: if (self.map[sr-1][sc+2]=="" or (self.map[sr-1][sc+2].islower() and self.map[sr-1][sc+2]!="")) and er == sr-1 and ec == sc+2: self.move(sr,sc,er,ec) if sr-2 >= 1 and sc+1 <= 8: if (self.map[sr-2][sc+1]=="" or (self.map[sr-2][sc+1].islower() and self.map[sr-2][sc+1]!="")) and er == sr-2 and ec == sc+1: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc-2 >= 1: if (self.map[sr-1][sc-2]=="" or (self.map[sr-1][sc-2].islower() and self.map[sr-1][sc-2]!="")) and er == sr-1 and ec == sc-2: self.move(sr,sc,er,ec) if sr-2 >= 1 and sc-1 >= 1: if (self.map[sr-2][sc-1]=="" or (self.map[sr-2][sc-1].islower() and self.map[sr-2][sc-1]!="")) and er == sr-2 and ec == sc-1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc+2 <= 8: if (self.map[sr+1][sc+2]=="" or (self.map[sr+1][sc+2].islower() and self.map[sr+1][sc+2]!="")) and er == sr+1 and ec == sc+2: self.move(sr,sc,er,ec) if sr+2 <= 8 and sc+1 <= 8: if (self.map[sr+2][sc+1]=="" or (self.map[sr+2][sc+1].islower() and self.map[sr+2][sc+1]!="")) and er == sr+2 and ec == sc+1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc-2 >= 1: if (self.map[sr+1][sc-2]=="" or (self.map[sr+1][sc-2].islower() and self.map[sr+1][sc-2]!="")) and er == sr+1 and ec == sc-2: self.move(sr,sc,er,ec) if sr+2 <= 8 and sc-1 >= 1: if (self.map[sr+2][sc-1]=="" or (self.map[sr+2][sc-1].islower() and self.map[sr+2][sc-1]!="")) and er == sr+2 and ec == sc-1: self.move(sr,sc,er,ec) else: if sr-1 >= 1 and sc+2 <= 8: if (self.map[sr-1][sc+2]=="" or (self.map[sr-1][sc+2].isupper() and self.map[sr-1][sc+2]!="")) and er == sr-1 and ec == sc+2: self.move(sr,sc,er,ec) if sr-2 >= 1 and sc+1 <= 8: if (self.map[sr-2][sc+1]=="" or (self.map[sr-2][sc+1].isupper() and self.map[sr-2][sc+1]!="")) and er == sr-2 and ec == sc+1: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc-2 <= 8: if (self.map[sr-1][sc-2]=="" or (self.map[sr-1][sc-2].isupper() and self.map[sr-1][sc-2]!="")) and er == sr-1 and ec == sc-2: self.move(sr,sc,er,ec) if sr-2 >= 1 and sc-1 <= 8: if (self.map[sr-2][sc-1]=="" or (self.map[sr-2][sc-1].isupper() and self.map[sr-2][sc-1]!="")) and er == sr-2 and ec == sc-1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc+2 <= 8: if (self.map[sr+1][sc+2]=="" or (self.map[sr+1][sc+2].isupper() and self.map[sr+1][sc+2]!="")) and er == sr+1 and ec == sc+2: self.move(sr,sc,er,ec) if sr+2 <= 8 and sc+1 <= 8: if (self.map[sr+2][sc+1]=="" or (self.map[sr+2][sc+1].isupper() and self.map[sr+2][sc+1]!="")) and er == sr+2 and ec == sc+1: self.move(sr,sc,er,ec) if sr+1 >= 1 and sc-2 >= 1: if (self.map[sr+1][sc-2]=="" or (self.map[sr+1][sc-2].isupper() and self.map[sr+1][sc-2]!="")) and er == sr+1 and ec == sc-2: self.move(sr,sc,er,ec) if sr+2 <= 8 and sc-1 >= 1: if (self.map[sr+2][sc-1]=="" or (self.map[sr+2][sc-1].isupper() and self.map[sr+2][sc-1]!="")) and er == sr+2 and ec == sc-1: self.move(sr,sc,er,ec) def getKnightWay(self,sr,sc): if sr-1 >= 1 and sc+2 <=8: if self.map[sr-1][sc+2]=="": self.map[sr-1][sc+2]="M" if sr-2 >= 1 and sc+1 <=8: if self.map[sr-2][sc+1]=="": self.map[sr-2][sc+1]="M" if sr-1 >= 1 and sc-2 >=1: if self.map[sr-1][sc-2]=="": self.map[sr-1][sc-2]="M" if sr-2 >= 1 and sc-1 >=1: if self.map[sr-2][sc-1]=="": self.map[sr-2][sc-1]="M" if sr+1 <= 8 and sc+2 <=8: if self.map[sr+1][sc+2]=="": self.map[sr+1][sc+2]="M" if sr+2 <= 8 and sc+1 <=8: if self.map[sr+2][sc+1]=="": self.map[sr+2][sc+1]="M" if sr+1 <= 8 and sc-2 >=1: if self.map[sr+1][sc-2]=="": self.map[sr+1][sc-2]="M" if sr+2 <= 8 and sc-1 >=1: if self.map[sr+2][sc-1]=="": self.map[sr+2][sc-1]="M" def getKingMoves(self,sr,sc,er,ec,cnt): if self.white_to_move == True: if sr-1 >= 1 and sc+1 <= 8: if (self.map[sr-1][sc+1]=="" or (self.map[sr-1][sc+1].islower() and self.map[sr-1][sc+1]!="")) and er == sr-1 and ec == sc+1: self.move(sr,sc,er,ec) if sr-1 >= 1: if (self.map[sr-1][sc]=="" or (self.map[sr-1][sc].islower() and self.map[sr-1][sc]!="")) and er == sr-1 and ec == sc: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc-1 >= 1: if (self.map[sr-1][sc-1]=="" or (self.map[sr-1][sc-1].islower() and self.map[sr-1][sc-1]!="")) and er == sr-1 and ec == sc-1: self.move(sr,sc,er,ec) if sc-1 >= 1: if (self.map[sr][sc-1]=="" or (self.map[sr][sc-1].islower() and self.map[sr][sc-1]!="")) and er == sr and ec == sc-1: self.move(sr,sc,er,ec) if sc+1 <= 8: if (self.map[sr][sc+1]=="" or (self.map[sr][sc+1].islower() and self.map[sr][sc+1]!="")) and er == sr and ec == sc+1: self.move(sr,sc,er,ec) if sr+1 <= 8: if (self.map[sr+1][sc]=="" or (self.map[sr+1][sc].islower() and self.map[sr+1][sc]!="")) and er == sr+1 and ec == sc: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc-1 >= 1: if (self.map[sr+1][sc-1]=="" or (self.map[sr+1][sc-1].islower() and self.map[sr+1][sc-1]!="")) and er == sr+1 and ec == sc-1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc+1 <= 8: if (self.map[sr+1][sc+1]=="" or (self.map[sr+1][sc+1].islower() and self.map[sr+1][sc+1]!="")) and er == sr+1 and ec == sc+1: self.move(sr,sc,er,ec) if sr==8 and sc==5 and cnt==1: if self.map[sr][sc+1]=="" and self.map[sr][sc+2]=="" and self.map[sr][sc+3]=="R" and er == sr and ec == sc+2: self.move(sr,sc,er,ec) self.map[sr][sc+1] = "R" self.map[sr][sc+3] = "" if self.map[sr][sc-1]=="" and self.map[sr][sc-2]=="" and self.map[sr][sc-3]=="" and self.map[sr][sc-4]=="R" and er == sr and ec == sc-2: self.move(sr,sc,er,ec) self.map[sr][sc-1] = "R" self.map[sr][sc-4] = "" else: if sr-1 >= 1 and sc+1 <= 8: if (self.map[sr-1][sc+1]=="" or (self.map[sr-1][sc+1].isupper() and self.map[sr-1][sc+1]!="")) and er == sr-1 and ec == sc+1: self.move(sr,sc,er,ec) if sr-1 >= 1: if (self.map[sr-1][sc]=="" or (self.map[sr-1][sc].isupper() and self.map[sr-1][sc]!="")) and er == sr-1 and ec == sc: self.move(sr,sc,er,ec) if sr-1 >= 1 and sc-1 >= 1: if (self.map[sr-1][sc+1]=="" or (self.map[sr-1][sc-1].isupper() and self.map[sr-1][sc-1]!="")) and er == sr-1 and ec == sc-1: self.move(sr,sc,er,ec) if sc-1 >= 1: if (self.map[sr][sc-1]=="" or (self.map[sr][sc-1].isupper() and self.map[sr][sc-1]!="")) and er == sr and ec == sc-1: self.move(sr,sc,er,ec) if sc+1 <= 8: if (self.map[sr][sc+1]=="" or (self.map[sr][sc+1].isupper() and self.map[sr][sc+1]!="")) and er == sr and ec == sc+1: self.move(sr,sc,er,ec) if sr+1 <= 8: if (self.map[sr+1][sc]=="" or (self.map[sr+1][sc].isupper() and self.map[sr+1][sc]!="")) and er == sr+1 and ec == sc: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc-1 >= 1: if (self.map[sr+1][sc-1]=="" or (self.map[sr+1][sc-1].isupper() and self.map[sr+1][sc-1]!="")) and er == sr+1 and ec == sc-1: self.move(sr,sc,er,ec) if sr+1 <= 8 and sc+1 <= 8: if (self.map[sr+1][sc+1]=="" or (self.map[sr+1][sc+1].isupper() and self.map[sr+1][sc+1]!="")) and er == sr+1 and ec == sc+1: self.move(sr,sc,er,ec) if sr==1 and sc==5 and cnt==1: if self.map[sr][sc+1]=="" and self.map[sr][sc+2]=="" and self.map[sr][sc+3]=="r" and er == sr and ec == sc+2: self.move(sr,sc,er,ec) self.map[sr][sc+1] = "r" self.map[sr][sc+3] = "" if self.map[sr][sc-1]=="" and self.map[sr][sc-2]=="" and self.map[sr][sc-3]=="" and self.map[sr][sc-4]=="r" and er == sr and ec == sc-2: self.move(sr,sc,er,ec) self.map[sr][sc-1] = "r" self.map[sr][sc-4] = "" def getKingWay(self,sr,sc): if sr-1 >= 1 and sc+1 <=8: if self.map[sr-1][sc+1]=="": self.map[sr-1][sc+1]="M" if sr-1 >= 1: if self.map[sr-1][sc]=="": self.map[sr-1][sc]="M" if sr-1 >= 1 and sc-1 >=1: if self.map[sr-1][sc-1]=="": self.map[sr-1][sc-1]="M" if sc-1 >=1: if self.map[sr][sc-1]=="": self.map[sr][sc-1]="M" if sc+1 <=8: if self.map[sr][sc+1]=="": self.map[sr][sc+1]="M" if sr+1 <= 8: if self.map[sr+1][sc]=="": self.map[sr+1][sc]="M" if sr+1 <= 8 and sc-1 >=1: if self.map[sr+1][sc-1]=="": self.map[sr+1][sc-1]="M" if sr+1 <= 8 and sc+1 <=8: if self.map[sr+1][sc+1]=="": self.map[sr+1][sc+1]="M"
true
8a4a3c5dc9e7f844e260dc7471aa4b3380e1de88
Python
ch2ohch2oh/Generative-Adversarial-Networks-Cookbook
/Chapter2/Data-Augmentation/aug_demo.py
UTF-8
1,308
2.953125
3
[ "MIT" ]
permissive
import imgaug as ia from imgaug import augmenters as iaa import numpy as np # This seed can be changed - random seed ia.seed(1) # Example batch of 100 images images = np.array( [ia.quokka(size=(64, 64)) for _ in range(100)], dtype=np.uint8 ) # Create the transformer function by specifying the different augmentations seq = iaa.Sequential([ # Horizontal Flips iaa.Fliplr(0.5), # Random Crops iaa.Crop(percent=(0, 0.1)), # Gaussian blur for 50% of the images iaa.Sometimes(0.5, iaa.GaussianBlur(sigma=(0, 0.5)) ), # Strengthen or weaken the contrast in each image. iaa.ContrastNormalization((0.75, 1.5)), # Add gaussian noise. iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # Make some images brighter and some darker. iaa.Multiply((0.8, 1.2), per_channel=0.2), # Apply affine transformations to each image. iaa.Affine( scale={"x": (0.5, 1.5), "y": (0.5, 1.5)}, translate_percent={"x": (-0.5, 0.5), "y": (-0.5, 0.5)}, rotate=(-10, 10), shear=(-10, 10) ) ], # apply augmenters in random order random_order=True) # This should display a random set of augmentations in a window images_aug = seq.augment_images(images) seq.show_grid(images[0], cols=8, rows=8)
true
f87ea6293b3e9d4924f1ca9414e1279435cc383e
Python
najeex/Competitive-Programming
/44. Dynamic Programming/04. Min Steps to One Bottom Up.py
UTF-8
389
3.015625
3
[]
no_license
import sys LIM=10**3 dp = [0 for i in range(LIM)] def solve(num): global dp for i in range(2,num+1): x = sys.maxsize y = sys.maxsize if i%3==0: x = dp[i//3] if i%2==0: y = dp[i//2] z = dp[i-1] ans = min(x,y,z) dp[i] = ans + 1 return dp[num] num = int(input()) print(solve(num))
true
a40a3b62f10828a34afaa847f2f8441a986c2064
Python
rimarks/automateBoringThings
/guessTheNumber.py
UTF-8
1,386
4.4375
4
[]
no_license
# This is a guess the number game. import random #Import random package so that we can use the randint function secretNumber = random.randint(1, 20) # Generates a random number between 1 and 20 and then assigns to the secretNumber print('I am thinking of a number between 1 and 20.') #prints a prompt for he user #Ask the player to guess 6 times. for guessesTaken in range(1, 7):# Iniates a for loop until it is finally exited they have a total of 6 times print ('Take a guess.') guess = int(input()) # Prompts user to input an integrer, will break if there is a different property, maybe error handling can be built in if guess < secretNumber: #If the guess is lower than the secretNumber, then output print('Your guess is too low.') elif guess > secretNumber: print('Your guess is too high.') #else if the guess is higher then the secretNumber, then output else: break #This condition is the correct guess! #For loops ends here when the correct guess is chosen. For loop also ends if the number of Guesses are more than 6. # if guess == secretNumber: # acts as a win or loss condition. If the resulting guess variable is correct then win condition. else Lost. print('Good Job! You guessed my number in '+ str(guessesTaken) + ' guesses!') else: print ('Nope, The number I was thinking of was ' +str(secretNumber))
true
12a02de52c53e45af62d1e919b600f8ac5a7c115
Python
KenNaNa/Python_learning
/unit.py
UTF-8
417
4.09375
4
[]
no_license
''' 元组 就是像一个括号列表 ''' unit = (0,12,3,445) print(unit)#(0, 12, 3, 445) ''' 可以像数组一样获取他的索引值 ''' print(unit[2])#3 ''' 可以获取元组的长度 ''' print(len(unit))#4 ''' 不可以像数组一样的修改元组的值 ''' # unit[0] = 5 # print(unit) 会报错 TypeError: 'tuple' object does not support item assignment
true
e915cdf4a51b7c70a53a4c539875868d2b80fa38
Python
GongFuXiong/leetcode
/topic13_tree/T95_generateTrees/interview.py
UTF-8
1,856
3.421875
3
[]
no_license
''' 95. 不同的二叉搜索树 II 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。 示例: 输入:3 输出: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 ''' import sys sys.path.append("..") # 这句是为了导入_config from T_tree.Tree import Tree import math class Solution: def generateTrees(self, n): if n == 0: return [] dct = {} def left_right(left, right): if left > right: return [None] if (left, right) in dct: return dct[(left, right)] ret = [] for i in range(left, right+1): left_lst = left_right(left, i-1) right_lst = left_right(i+1, right) for L in left_lst: for R in right_lst: app_Tree = Tree(i) app_Tree.left = L app_Tree.right = R ret.append(app_Tree) dct[(left, right)] = ret return ret return left_right(1, n) # if __name__ == "__main__": # tree = Tree() # solution = Solution() # while 1: # str1 = input() # if str1 != "": # n = int(str1) # res = solution.generateTrees(n) # for r in res: # print(f"层次遍历:{tree.traverse(r.root)}") # else: # break
true
9102b6ec3aaca2082aff49a213b8cb54cdad3731
Python
HappyAndItWillBeFinished/vrpprogram
/ReadExcel.py
UTF-8
1,113
3.109375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Jul 10 08:27:35 2018 @author: 长风振林 """ import xlrd def read(file,sheet_index=0): workbook = xlrd.open_workbook("E:/皓首穷经/大四下/竞赛/京东/车辆智能调度-A榜/input_node.xlsx") # all_sheets_list = workbook.sheet_names() # print("本文件中所有的工作表名称:", all_sheets_list) # 按索引读取工作表 sheet = workbook.sheet_by_index(sheet_index) print("工作表名称:", sheet.name) print("行数:", sheet.nrows) print("列数:", sheet.ncols) # 按工作表名称读取数据 # second_sheet = workbook.sheet_by_name("b") # print("Second sheet Rows:", second_sheet.nrows) # print("Second sheet Cols:", second_sheet.ncols) # 获取单元格的数据 # cell_value = sheet.cell(1, 0).value # print("获取第2行第1列的单元格数据:", cell_value) data = [] for i in range(0, sheet.nrows): data.append(sheet.row_values(i)) return data if __name__ == '__main__': #read函数里面的东西暂时没用 print(read('随便起个名.xlsx'))
true
afd5ac59160bd4d904fbc9d872bbcc69c699bb60
Python
gbiebuyc/stuff
/adventofcode2020/d22.py
UTF-8
1,581
3.359375
3
[]
no_license
#!/usr/bin/env python3 from sys import stdin data = stdin.read() player1, player2 = [[int(x) for x in x.splitlines()[1:]] for x in data.split('\n\n')] def part1(player1, player2): while len(player1) and len(player2): draw1 = player1.pop(0) draw2 = player2.pop(0) if draw1 > draw2: player1 += [draw1, draw2] elif draw2 > draw1: player2 += [draw2, draw1] return player1, player2 def calc_score(deck): return sum((i+1)*score for i, score in enumerate(deck[::-1])) #game=0 def part2(player1, player2): #global game #game+=1 #thisgame=game #print() #print(f'=== Game {thisgame} ===') #round=0 rounds=[] while len(player1) and len(player2): #round+=1 #print(f'-- Round {round} (Game {thisgame}) --') #print(player1) #print(player2) cur_round = str([player1, player2]) if cur_round in rounds: return 1, player1, player2 rounds.append(cur_round) draw1 = player1.pop(0) draw2 = player2.pop(0) winner = 1 if draw1>draw2 else 2 if len(player1) >= draw1 and len(player2) >= draw2: winner, _, _ = part2(player1[:draw1], player2[:draw2]) if winner == 1: player1 += [draw1, draw2] else: player2 += [draw2, draw1] return 1 if len(player1) else 2, player1, player2 result1, result2 = part1(player1[:], player2[:]) print(calc_score(result1+result2)) _, result1, result2 = part2(player1[:], player2[:]) print(calc_score(result1+result2))
true
63aa6985f22e40b56c8f751949da95d6bb86daca
Python
muphy021/Software-Testing
/py_autogui/py_autogui.py
UTF-8
1,070
2.96875
3
[]
no_license
#!/usr/local/bin python3 # -*- encoding: utf-8 -*- ''' 说明: 1. 前置条件 OS X上,执行pip3 install pyobjc-framework-Quartz, pip3 install pyobjc-core, pip3 install pyobjc Linux上,执行pip3 install python3-xlib, apt-get intall scrot, apt-get install python3-tk, apt-get install python3-dev 2. 安装模块 pip install pyautogui 3. 使用模块 import pyautogui 4. 防故障操作 pyautogui.PAUSE=1 pyautogui.FAILSAFE=True 5. python屏幕坐标是左上角开始为(0,0) ''' import pyautogui import time pyautogui.PAUSE=1 pyautogui.FAILSAFE=True # move mouse in 0.1 second # pyautogui.moveTo(200, 324, duration=0.1) width, height = pyautogui.size() print("屏幕分辨率为:("+str(width)+", "+str(height)+")") # print mouse position print("press Ctrl+C to exit") try: while True: x,y = pyautogui.position() pos_str = 'X: '+str(x).rjust(4)+" Y: "+str(y).rjust(4) print(pos_str, end='') time.sleep(1) print('\b' * len(pos_str), end='', flush=True) except KeyboardInterrupt: print('\nDone.')
true
5560e617eb0cf3cee7c9fcc81fc841823cc5b678
Python
Joan93/BigData
/Core/GetTrafficMatrix_on_distance.py
UTF-8
3,123
2.5625
3
[]
no_license
#!/usr/bin/env python #title :GetTrafficMatrix_ondistance.py #description :This script process PReMatrix file to get Adjacent matrix of netwok. #author :Lucia #date :2016-04-28 #version :0.1 #usage :python pyscript.py #notes : #python_version :2.7.6 #============================================================================== # UPC-EETAC MASTEAM 2015-2016 BIGDATA # # Group former by Ana, Lucia, Joan and Rodrigo # #============================================================================== ################################################################################### # # # Obtener la matrix de conectividad en funcion de la distancia entre estaciones # # # ################################################################################### import numpy as np import config as conf def run_main(num): NumberOfStations=465 Matrix=np.zeros((NumberOfStations,NumberOfStations)) InputFile = conf.data_process_file_distancematrix if(num==1000): distance_neigbours = conf.distance_1000 OutputFile= conf.data_process_file_adjacentmatrix_distance_1000 elif(num==300): distance_neigbours = conf.distance_300 OutputFile= conf.data_process_file_adjacentmatrix_distance_300 else: distance_neigbours = conf.distance_1000 OutputFile= conf.data_process_file_adjacentmatrix_distance print OutputFile print num min_neigbours=conf.min_neigbours Distance_matrix = np.loadtxt(InputFile,delimiter=' ',dtype=np.dtype('int32')) nummax_enlaces=0 factor=1 total_enlaces=0 i=0 while(i<NumberOfStations): num_enlaces=0 distance_range=factor*distance_neigbours #print "range: "+str(distance_range) for j in range (0,NumberOfStations): #print Distance_matrix[i,j] if(Distance_matrix[i,j]<(distance_range+1) and i!=j): num_enlaces+=1 Matrix[i,j]=1 Matrix[j,i]=1 if(num_enlaces<(2*min_neigbours+1)): factor=factor*2 #print "["+str(i)+","+str(j)+"] : factor "+str(factor) else: #print "["+str(i)+","+str(j)+"] : enlaces "+str(num_enlaces) if(num_enlaces>nummax_enlaces): nummax_enlaces=num_enlaces factor=1 total_enlaces+=num_enlaces i+=1 print ("Numero enlacesmax: "+str(nummax_enlaces/2)) print ("Numero total: "+str(total_enlaces/2)) print ("Numero medio enlaces: "+str((total_enlaces/2)/NumberOfStations)) # # print("Numero medio de enlaces: "+str(float(media/NumberOfStations))) # print("Numero max de enlaces: "+str(nummax_enlaces)) # print("Numero min de enlaces: "+str(nummin_enlaces)) np.savetxt(OutputFile, Matrix, delimiter=' ',newline='\n',fmt='%i')
true
cb442894d9329fa87a154af3f419fa9cea1a352c
Python
cnanne/pathfinderHelper
/player/models.py
UTF-8
11,863
2.515625
3
[]
no_license
from django.db import models from player.classes.skillsAndAbilities import * from player.classes.effects import * from player.classes.items import * from player.classes.spells import * from player.classes.inventoryAndEquipment import * from player.classes.raceAndClasses import * class Saves: fort = dex = will = 0 def __init__(self, saves): self.fort = saves["fort"] self.will = saves["will"] self.ref = saves["ref"] class PC(models.Model): name = models.CharField(max_length=200, primary_key=True) race = models.OneToOneField(SelectedRace, on_delete=models.CASCADE, blank=True, null=True) equipment = models.OneToOneField(Equipment, on_delete=models.CASCADE, blank=True) inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE, blank=True) abilities = models.ForeignKey(Abilities, on_delete=models.CASCADE) photo = models.ImageField(upload_to="images", blank=True, null=True) activeEffects = models.ManyToManyField(ActiveEffect, blank=True) alignment = models.ForeignKey(Alignment, on_delete=models.SET_NULL, null=True) gender = models.CharField(max_length=50, default="Male") weight = models.IntegerField(blank=True, default=0, null=True) age = models.IntegerField(blank=True, default=0, null=True) hair = models.CharField(max_length=100, blank=True, default="Blonde", null=True) eyes = models.CharField(max_length=100, blank=True, default="Green", null=True) def getAC(self): ac = 10 ac += self.equipment.AC() for activeEffect in self.activeEffects.all(): ac += activeEffect.effect.ac abilities = self.getAbilitiesScoresAndModifiers ac += abilities["DEX"]["mod"] return ac def firstSave(self): location = Location() location.name = self.name location.save() inv = Inventory() inv.location = location inv.save() self.inventory = inv equipment = Equipment() equipment.save() self.equipment = equipment self.save() def save(self, *args, **kwargs): self.abilities.save() self.abilities = self.abilities self.race.save() self.race = self.race super().save(*args, **kwargs) def getLevels(self): playerClassLevels = self.playerclasslevel_set.all() playerClasses = [] finalClassLevels = {} levels = "" for playerClassLevel in playerClassLevels: if playerClassLevel.classLevel.gameClass not in playerClasses: playerClasses.append(playerClassLevel.classLevel.gameClass) finalClassLevels[playerClassLevel.classLevel.gameClass.name] = playerClassLevel else: if playerClassLevel > finalClassLevels[playerClassLevel.playerClassLevel.classLevel.gameClass.name]: finalClassLevels[playerClassLevel.classLevel.gameClass.name] = playerClassLevel for playerClassLevel in finalClassLevels.values(): levels += playerClassLevel.classLevel.name return levels def __str__(self): return self.name # TODO: need to implement def maxWeight(self): pass def equipItem(self, item, area): if self.maxWeight < item.getWeight() + self.maxWeight: return "Item is to heavy to be equipped" elif item.canBeWielded() or item.canBeWorn(): return self.equipment.equipItem(item, area) else: return "Item cannot be equipped" def carryItem(self, item): if self.maxWeight < item.getWeight() + self.maxWeight: return "Item is to heavy to carry" else: return self.equipment.carryItem(item) def getStrength(self): return self.abilities.strength def getAlignment(self): return self.alignment.alignment def getBab(self): classLevels = self.classLevels bab = [0, 0, 0, 0] for classLevel in classLevels.all(): bab[0] += classLevel.classLevel.bab1 bab[1] += classLevel.classLevel.bab2 bab[2] += classLevel.classLevel.bab3 bab[3] += classLevel.classLevel.bab4 activeEffectsAttack = 0 activeEffectsAttack += self.activeEffectsAttackBonus() bab[0] += activeEffectsAttack if bab[1] > 0: bab[1] += activeEffectsAttack if bab[2] > 0: bab[2] += activeEffectsAttack if bab[3] > 0: bab[3] += activeEffectsAttack return bab def getSize(self): return self.race.race.size def getRaceName(self): return self.race.race.name def getSpeed(self): return self.race.race.speed def activeEffectsAttackBonus(self): activeEffects = self.activeEffects attack = 0 for activeEffect in activeEffects.all(): attack += activeEffect.attackBonus return attack def getSkills(self): skills = {} skillRanks = self.skillRanks.all() abilities = self.getAbilitiesSocresAndModifiers classSkills = self.getClassSkills() for skill in skillRanks: name = skill.skill.name ranks = skill.ranks ranks += abilities[skill.skill.ability]["mod"] for classSkill in classSkills: if skill.skill.name == classSkill.name: ranks += 3 break skills[name] = SkillRank.create(skill.skill, ranks) for effect in self.activeEffects.all(): for skillRank in effect.effectskillrank_set.all(): if skillRank.skill.name in skills.keys(): skills[skillRank.skill.name].ranks += skillRank.ranks else: skill = SkillRank() skill.skill = skillRank.skill skill.ranks = skillRank.ranks skills[skillRank.skill.name] = skill return skills @property def getAbilitiesMap(self): return self.getAbilitiesSocresAndModifiers @property def getAbilitiesScoresAndModifiers(self): abilities = self.getAbilities() return abilities.makeDictionary() def getAbilities(self): abilities = Abilities() abilities += self.abilities abilities += self.race.appliedAbilities for effect in self.activeEffects.all(): abilities += effect.abilities return abilities def getClassSkills(self): classLevels = self.classLevels classSkills = [] for classLevel in classLevels.all(): skills = classLevel.gameClass.classSkills for skill in skills.all(): if skill.name not in classSkills: classSkills.append(skill) return classSkills def getSaves(self): ref = 0 fort = 0 will = 0 classes = self.classLevels.all() for classLevel in classes: ref = ref + classLevel.ref fort += classLevel.fort will += classLevel.will activeEffects = self.activeEffects.all() for activeEffect in activeEffects: ref = activeEffect.effect.ref fort = activeEffect.effect.fort will = activeEffect.effect.will ref += self.race.race.ref will += self.race.race.will fort += self.race.race.fort saves = Saves({"ref": ref, "will": will, "fort": fort}) return saves def getAttacks(self): bab = self.getBab() rh = self.equipment.rightHand lh = self.equipment.leftHand def availableClassesForNewLevel(self): levels = [] if self.playerclasslevel_set.count() == 0: classes = Class.objects.all() for gameClass in classes: classLevel: Class = gameClass classLevel = classLevel.classlevel_set.first() classLevel = classLevel.getLevel(1) levels.append(classLevel) else: for classLevel in self.playerclasslevel_set.all(): levels.append(classLevel.getNextLevel()) for gameClass in Class.objects.all(): for level in levels: if ClassLevel(level).gameClass.name == gameClass.name: continue classLevel = gameClass.objects.first() classLevel = classLevel.getLevel(1) levels.append(classLevel) return levels def getClassSkills(self): classSkills = [] for playerClassLevel in self.classLevels.all(): for skill in playerClassLevel.classLevel.gameClass.classSkills.all(): if skill.name not in classSkills: classSkills.append(skill.name) return classSkills def addLevel(self, classLevel, hp): playerClassLevel = PlayerClassLevel() playerClassLevel.pc = self playerClassLevel.classLevel = classLevel playerClassLevel.hp = hp playerClassLevel.save() def addSkillRanks(self, skills): skillRanks = [] for skill in skills: skill: str if skill.endswith('*'): skill = skill[0:len(skill) - 1] skillFound = False for pcSkillRank in self.skillRanks.all(): if pcSkillRank.skill.name == skill: pcSkillRank.addRank() skillFound = True if not skillFound: pcSkillRank = PCSkillRank() pcSkillRank.pc = self try: skillObj = Skill.objects.get(pk=skill) except: continue pcSkillRank.skill = skillObj pcSkillRank.ranks = 1 skillRanks.append(pcSkillRank) return skillRanks class PCSkillRank(SkillRank): pc = models.ForeignKey(PC, on_delete=models.CASCADE, related_name="skillRanks") def __str__(self): return self.pc.name + "'s " + self.skill.name @property def totalRanks(self): abilities = self.pc.abilities self.skill.ability class PlayerClassLevel(models.Model): classLevel = models.ForeignKey(ClassLevel, on_delete=models.CASCADE, null=True) hp = models.IntegerField() pc = models.ForeignKey(PC, on_delete=models.CASCADE, null=True) def __str__(self): return self.pc.name + ":" + self.classLevel.gameClass.shortHand + str(self.level) def __gt__(self, other): if self.sameClassLevel(other): if self.classLevel.level > other.classLevel.level: return True return False def sameClassLevel(self, playerClassLevel): if self.classLevel is playerClassLevel.classLevel: return True else: return False def getLevel(self, level): try: return ClassLevel.objects.get(name=self.classLevel.gameClass.shortHand + str(level)) except: return None def getNextLevel(self): nextLevel = self.getLevel(self.classLevel.level + 1) if nextLevel is None: return self.classLevel return nextLevel def getPrevLevel(self): if self.level - 1 <= 0: return self.classLevel return self.getLevel(self.classLevel.level - 1) def save(self, *args, **kwargs): name = self.pc.name name += ":" name += self.classLevel.gameClass.shortHand name += str(self.classLevel.level) level = self.level self.name = name super().save(*args, **kwargs) @property def level(self): return self.classLevel.level
true
badd0dce4235c305ded659f866843998f7100f47
Python
brandonhaynes100/data_structures_and_algorithms
/data_structures/linked-list/linked_list.py
UTF-8
3,148
3.8125
4
[ "MIT" ]
permissive
from node import Node from typing import Any, Iterable class LinkedList(object): def __init__(self, input_iterable=None) -> Node: """ """ self.head = None self._len = 0 if input_iterable is Iterable: for val in input_iterable: pass def __len__(self): return self._len def __str__(self): return 'Head: {head} | Length: {length}'.format(head=self.head, length=self._len) def __repr__(self): return '<Linked List | Head: {head} | Length: {length}'.format(head=self.head, length=self._len) def __iter__(self): return Node(self.head.val, self.head._next) # Type annotations (python3.6+) # expected return value -> Any # defines output for intellisense def insert(self, val: Any) -> Any: """ Takes any value as an argument and adds that value to the head of the list with an O(1) Time performance. """ self.head = Node(val, self.head) self._len += 1 return self.head.val # expected return value -> bool def includes(self, val: Any) -> bool: """ """ current = self.head while current is not None: if current.val == val: return True current = current._next return False # Code Challenge 06 def append(self, val): """Adds a new node with the given value to the end of the list """ current = self.head if not current: self.head = Node(val) return self while current._next is not None: current = current._next current._next = Node(val) def insert_before(self, val, new_val): """Adds a new node with the given new_val immediately before the first val node """ current = self.head if not current: self.head = Node(val) return self while current._next is not None: if current._next.val == val: new_node = Node(new_val, current._next) current._next = new_node return self # reaching here means the value was not in the linked list return self def insert_after(self, val, new_val): """Adds a new node with the given new_val immediately after the first val node """ current = self.head if not current: self.head = Node(val) return self while current is not None: if current.val == val: new_node = Node(new_val, current._next) current._next = new_node return self # reaching here means the value was not in the linked list return self def kth_from_end(self, k): """ Takes a number k, as a parameter, and returns the node that is k from the end of the linked list. """ current = self.head a = [] while current is not None: a += [current.val] current = current._next return a[-(k+1)]
true
11e112842eb185a7f63e56d91ad997a5df07e405
Python
linmenggui/Udacity-Project-3-Data-Wrangling
/project_code_repository/update_pin_code.py
UTF-8
1,411
3.171875
3
[]
no_license
# this code is written in python 3 import re def pin_validator(pin): """ Return a pin if pin code is 6 digit valid pin. Else append invalid pin codes to a list. """ pin_validator = re.compile(r'^[1-9][0-9]{5}$') match = pin_validator.search(pin) if match: correct_pin = pin return correct_pin invalid_pins.append(pin) #return pin def simple_pin_code_fix(pin_code): """ Return a corrected pin code if a wrong pin code is found. Else return just the pin code. This is not a generalized solution. It fixes only the wrong pin codes of this dataset. """ pin = list(pin_code) if len(pin) > 6 and pin_code.count("0") > 3: pin.remove("0") correct_pin = "".join(pin) return correct_pin elif len(pin) > 6 and pin_code.count(" ") > 0: correct_pin = "".join(pin_code.strip().split()) return correct_pin elif pin_code.startswith("10", 0, 2): correct_pin = re.sub(r"^10", "11", pin_code) return correct_pin elif pin_code.endswith("0", -1) and pin_code.startswith("2", 0) and len(pin) > 6: del pin[-1] correct_pin = "".join(pin) return correct_pin return pin_code def is_pin_code(elem): """Return True if the value of two operands are equal. Return False otherwise.""" return elem.attrib["k"] == "addr:postcode"
true
ea30d84a26ec5e0061cf124b78f9d0c13f8af90a
Python
SocialCars/COPS-public
/parking/runtime/communication.py
UTF-8
2,276
3.703125
4
[ "MIT" ]
permissive
from collections import deque def mark_neighbours(vehicles, distance): """ Discovers neighbors for a vehicles and saves them internally into vehicle objects. Has complexity of approx O(len(vehicles)**2/2). Args: vehicles (list): A list with vehicle object whose neighbors should be discovered. distance (float): Maximum distance between two vehicles such that they can be considered neighbors. Manhattan distance is used for faster computation. """ # Reset previous neighbors for v in vehicles: v.connected_neighbors = [] # loop over vehicles but in inner loop don't check vehicles that went # through first loop because connections are symmetric for veh_idx, veh in list(enumerate(vehicles))[:-1]: for other in vehicles[veh_idx + 1:]: veh_x, veh_y = veh.position oth_x, oth_y = other.position if (abs(veh_x - oth_x) + abs(veh_y - oth_y)) < distance: veh.connected_neighbors.append(other) other.connected_neighbors.append(veh) def communication_groups(vehicles): """ Creates groups of vehicles that are connected at specific time step with an assumption that communication is instantaneous. For example if vehicle_0 is connected to vehicle_1 and vehicle_1 is connected to vehicle_2 then all 3 vehicles share same knowledge about parking spaces. Args: vehicles (list): A list with vehicle objects. Returns: list(list): A list of list where each inner list is a group of vehicles that share the same knowledge at that time instance """ vehicles = vehicles[:] groups = [] while vehicles: group = [] veh_queue = deque([vehicles[0]]) while veh_queue: veh = veh_queue.pop() group.append(veh) # don't add to queue vehicles that are already in the group or are # already in the queue filtered = (v for v in veh.connected_neighbors if (v not in group) and (v not in veh_queue)) veh_queue.extend(filtered) if vehicles: vehicles.remove(veh) groups.append(group) return groups
true
af1cef264a52bd639cfc9fcbec6ce5b7e1eb35f8
Python
smaje99/Contactos-Flask-React
/backend/src/app.py
UTF-8
2,572
2.84375
3
[]
no_license
from flask import Flask, jsonify, request from flask_pymongo import PyMongo, ObjectId from flask_cors import CORS app = Flask(__name__) app.config['MONGO_URI'] = 'mongodb://localhost/pythonreactdb' mongo = PyMongo(app) CORS(app) db = mongo.db.users @app.route('/users', methods=['POST']) def createUser(): '''Recibe un usuario nuevo, lo registra en la base de datos y devuelve el id en la base de datos del nuevo usuario. Returns: str: id en la base de datos del nuevo usuario ''' user = request.json result = db.insert_one({ 'name': user['name'], 'email': user['email'], 'password': user['password'], }) return jsonify(str(result.inserted_id)) @app.route('/users', methods=['GET']) def getUsers(): '''Lista a todos los usuarios registrados en la base de datos con su respectivos datos. Returns: list: todos los usuarios con su datos ''' return jsonify([{ '_id': str(ObjectId(user['_id'])), 'name': user['name'], 'email': user['email'], 'password': user['password'] } for user in db.find()]) @app.route('/users/<id>', methods=['GET']) def getUser(id): '''Información de un usuario en especifico de la base de datos según su id. Args: id (str): id del usuario Returns: set: información del usuario ''' user = db.find_one({'_id': ObjectId(id)}) return jsonify( _id=str(ObjectId(user['_id'])), name=user['name'], email=user['email'], password=user['password'] ) @app.route('/users/<id>', methods=['DELETE']) def deleteUser(id): '''Eliminar un usuario en especifico registrado en la base de datos según su id. Args: id (str): id del usuario Returns: bool: confirmación ''' user = db.delete_one({'_id': ObjectId(id)}) return jsonify( deleted=bool(user.deleted_count) ) @app.route('/users/<id>', methods=['PUT']) def updateUser(id): '''Actualiza los datos de un usario en especifico de la base de datos. Args: id (str): id del usuario Returns: bool: confirmación ''' user = request.json update = db.update_one( filter={'_id': ObjectId(id)}, update={'$set':{ 'name': user['name'], 'email': user['email'], 'password': user['password'] }} ) return jsonify( updated=bool(update.modified_count) ) if __name__ == "__main__": app.run(debug=True)
true
ac84a4c3723efc891c87396ac6673689f14a3eaa
Python
Frostmander/Visual-Studio
/Python/bucles.py
UTF-8
125
3.296875
3
[]
no_license
print("Bucle while") contador=0 while contador <= 6: contador+=1 print(contador) if(contador==3): break
true
c3d412df40eb8785461d1e41648a198b70df9790
Python
metamorph-inc/meta-core
/meta/DesignDataPackage/doc/ClassDiagrams/genFiguresCode.py
UTF-8
503
2.53125
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
__author__ = 'adam' import glob for pdf in glob.glob("*.pdf"): nameroot = pdf.replace('.pdf','') print '\\begin{figure}[h!]' print '\\fbox{\includegraphics[width=\\textwidth]{ClassDiagrams/' + nameroot + '.pdf}}' if nameroot.find('_') >= 0: print '\\caption{' + nameroot.split('_')[0].replace('-','.') + ' Namespace: ' + nameroot.split('_')[1] + ' diagram}' else: print '\\caption{' + nameroot.replace('-','.') + ' Namespace}' print '\\end{figure}' print ''
true
b7d751ac903760db7dea1ddb2c7f4f79b9226436
Python
ArthurSko/mandelbrot
/mb.py
UTF-8
2,845
3.25
3
[]
no_license
import pygame import time class Mandelbrot: def __init__(self, window, color, backgroundColor, size, coords, zoomfactor): self.window = window self.width, self.height = size self.xmin, self.xmax, self.ymin, self.ymax = coords self.zoomfactor = zoomfactor self.backgroundColor = backgroundColor # -------------------- self.color = color self.max_iteration = 50 # -------------------------------------------------------------- def draw(self): n = 0 progression = 0 time_ = time.time() for x in range(self.width): for y in range(self.height): i = 0 n += 1 if n % ((self.width * self.height) // 100) == 0: progression += 1 print(f"Loading... {progression}%") cx = self.complex_transform(x, self.width, self.xmax, self.xmin) cy = self.complex_transform(y, self.width, self.ymax, self.ymin) c = complex(cx, cy) z = 0 while (z.imag**2 + z.real**2 < 4) and i < self.max_iteration: z = z**2 + c i+=1 if i == self.max_iteration: self.window.set_at((x, y), self.color) else: self.window.set_at((x, y), ( i * self.backgroundColor[0] / self.max_iteration, i * self.backgroundColor[1] / self.max_iteration, i * self.backgroundColor[2] / self.max_iteration) ) print(f"Mandelbrot fractal successfully generated in {round(time.time() - time_, 2)}s") # -------------------------------------------------------------- def zoom(self, pos, zoomtype): mouseRealPart = self.complex_transform(pos[0], self.width, self.xmax, self.xmin) mouseImaginaryPart = self.complex_transform(pos[1], self.height, self.ymax, self.ymin) self.xmin = self.interpolate(mouseRealPart, self.xmin, self.set_interpolation(zoomtype)) self.xmax = self.interpolate(mouseRealPart, self.xmax, self.set_interpolation(zoomtype)) self.ymin = self.interpolate(mouseImaginaryPart, self.ymin, self.set_interpolation(zoomtype)) self.ymax = self.interpolate(mouseImaginaryPart, self.ymax, self.set_interpolation(zoomtype)) self.draw() # ---------- Util functions ----------------------------------- def complex_transform(self, grid_position, size, max, min): return min + (grid_position * ((max - min) / size)) def interpolate(self, start, end, interpolation): return start + ((end - start) * interpolation) def set_interpolation(self, zoomtype): return (1.0 / self.zoomfactor) if zoomtype == 1 else (1.0 * self.zoomfactor)
true
0a0c66300e5555db618fd533b19b5bf7463eef29
Python
jperezig/GeoService
/geoservice_ingester.py
UTF-8
1,725
2.984375
3
[]
no_license
""" Ingestion Module """ import json import logging from pymongo import GEO2D from pymongo.errors import ServerSelectionTimeoutError class Ingester: """ This class is in charge og ingesting from CSV file to Mongo, using a 2D euclidean index. """ def __init__(self, collection, index_name): self.logger = logging.getLogger(__name__) self.collection = collection self.index_name = index_name def create_index(self): """ Create 'loc' index to speedup geospatial searches """ self.collection.create_index([(self.index_name, GEO2D)]) def _build_document(self, loc, attributes): document = json.loads(json.dumps(attributes)) document[self.index_name] = [loc.x, loc.y] return document def bulk_ingest(self, data): """ Insert into Mongo in bulk mode """ docs = [self._build_document(loc, atts) for loc, atts in data] try: document_ids = self.collection.insert_many(docs).inserted_ids self.logger.debug('Inserted batch of documents size: %s %s', len( document_ids), document_ids) return document_ids except ServerSelectionTimeoutError: self.logger.error('Cannot connect to collection') return -1 def ingest(self, loc, attributes): """ Insert into Mongo """ try: document_id = self.collection.insert_one( self._build_document(loc, attributes)).inserted_id self.logger.debug('Inserted document: %s', document_id) return document_id except ServerSelectionTimeoutError: self.logger.error('Cannot connect to collection') return -1
true
cd5ba359153bf02332fccd8d65da845e47725f9e
Python
fsload/algorithm
/SWEA/어디에 단어가 들어갈 수 있을까.py
UTF-8
1,171
2.796875
3
[]
no_license
TC = int(input()) for t in range(TC): line, size = input().split() line = int(line) size = int(size) arr = [] for i in range(line): li = [] li = list(map(int, input().split())) arr.append(li) result = 0 for i in range(line): count = 0 for j in range(line): if arr[i][j] == 1: count += 1 else: count = 0 try: if count == size and arr[i][j+1] == 0: result += 1 except IndexError: result += 1 # if count == size: # result += 1 arr = list(map(list, zip(*arr))) for i in range(line): count = 0 for j in range(line): if arr[i][j] == 1: count += 1 else: count = 0 try: if count == size and arr[i][j+1] == 0: result += 1 except IndexError: if count == size: result += 1 # if count == size: # result += 1 print('#'+ str(t+1), result)
true
16b61a1791bfcaedd0e10ed162bed49714c5114e
Python
Planheat/Planheat-Tool
/planning_and_simulation_modules/dhcoptimizerplanheat/optimizer/automatic_design/ad_network_optimization.py
UTF-8
46,240
2.59375
3
[ "MIT" ]
permissive
# general import logging import os import sys import time import configparser import math import scipy.optimize as opt from scipy.spatial import ConvexHull from copy import deepcopy from itertools import combinations # graph import networkx as nx import geonetworkx as gnx # data import pandas as pd # optimization import julia # config from .. import config from ...exception_utils import DHCOptimizerException from .NLP.data_regressions import * from PyQt5.QtWidgets import QMessageBox from ....python_julia_interface import JuliaQgisInterface class ADNetworkOptimizer: """Network optimizer in automatic design mode. Given a 'networkx' network having costs, capacities, demand and production attributes, the optimize method trying to find the minimal fixed cost network supplying the given objective. """ def __init__(self, optimization_graph=None, **kwargs): self.logger = logging.getLogger(__name__) self.optimization_graph = optimization_graph self.network_objective = kwargs.get('network_objective', None) self.solution_graph = None self.connected = False self.connected_buildings = None self.old_capacity = {} self.conf = {} os.makedirs(os.path.join(os.environ["LOCALAPPDATA"], "QGIS\\QGIS3\\planheat_data\\tmp"), exist_ok=True) self.solver_log_file = os.path.join(os.environ["LOCALAPPDATA"], "QGIS\\QGIS3\\planheat_data\\tmp\\output.log") self.energy = None self.consumption_file_path = os.path.join(os.path.dirname(__file__),'NLP','consumption_data.csv') self.conf_path = os.path.join(os.path.dirname(__file__),'NLP','conf.ini') def check_is_ready(self): """Check that all necessary inputs have been set.""" self.logger.info("Checking optimization inputs for automatic design.") if self.optimization_graph is None: raise RuntimeError("The optimization graph needs to be defined in order to optimize the network.") if self.network_objective is None: raise RuntimeError("A network objective has to be set (in MW).") def check_infeasibility(self, graph, objective): self.logger.info("Checking infeasibility for automatic design.") ccs = list(nx.connected_components(graph.to_undirected())) productions = nx.get_node_attributes(graph, config.SUPPLY_POWER_CAPACITY_KEY) heat_demand = nx.get_node_attributes(graph, config.BUILDING_CONSUMPTION_KEY) total_residual_connections = 0.0 # print([e for e in graph.edges()]) for cc in ccs: #print('!!', cc) residual_production = sum(productions[n] for n in cc if n in productions) residual_consumption = sum(heat_demand[n] for n in cc if n in heat_demand) residual_maximum_connection = min(residual_production, residual_consumption) total_residual_connections += residual_maximum_connection if total_residual_connections < objective - 1e-8: raise DHCOptimizerException("Problem is inconsistent: total production capacity is lower than coverage" " objective (taking into account connected components): " "reachable consumption is %f" " and total objective is %f" % (total_residual_connections, objective)) def optimize(self): """Run the optimization with the selected method :return: flows : dict. Flow on each edge. :return: obj_val: float. Solution cost. """ self.logger.info("Solving with Dynamic Slope Scaling Procedure in Julia :") optimization_start = time.time() # 1. Preprocess for old network graph if self.old_network_graph is not None: # DSSP on old network old_network_obj = sum(list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values()))-1e-5 try: self.check_infeasibility(self.old_network_graph, old_network_obj) except DHCOptimizerException as e: e.data = "Invalid existing network: " + e.data raise e flows, obj_val = self.optimize_with_dssp_julia(self.old_network_graph, old_network_obj, set()) self.logger.info("Optimization phase time: %.2fs" % (time.time() - optimization_start)) solution_old_graph = self.build_solution_graph(self.old_network_graph, flows) if self.modify_old_network: # Add max capacity on old edges self.old_capacity = deepcopy(flows) old_buildings = list(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).values()) for key in flows: if (key[1],key[0],0) not in self.old_capacity and key[1] not in old_buildings: self.old_capacity[(key[1],key[0],0)] = self.old_capacity[key] # Add Imaginary edges for edge in self.old_capacity: if self.optimization_graph.has_edge(*edge): # add nodes if not self.optimization_graph.has_node(config.IM_PREFIX+edge[0]): self.optimization_graph.add_node(config.IM_PREFIX+edge[0]) self.optimization_graph.nodes[config.IM_PREFIX+edge[0]][config.GPD_GEO_KEY] = \ self.optimization_graph.nodes[edge[0]][config.GPD_GEO_KEY] if not self.optimization_graph.has_node(config.IM_PREFIX+edge[1]): self.optimization_graph.add_node(config.IM_PREFIX+edge[1]) self.optimization_graph.nodes[config.IM_PREFIX+edge[1]][config.GPD_GEO_KEY] = \ self.optimization_graph.nodes[edge[1]][config.GPD_GEO_KEY] # add edges if not self.optimization_graph.has_edge(edge[0],config.IM_PREFIX+edge[0]): self.optimization_graph.add_edge(edge[0],config.IM_PREFIX+edge[0]) if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1]): self.optimization_graph.add_edge(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1]) if not self.optimization_graph.has_edge(config.IM_PREFIX+edge[1],edge[1]): self.optimization_graph.add_edge(config.IM_PREFIX+edge[1],edge[1]) # put cost self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY] = \ self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY] self.optimization_graph.edges[(edge[0],edge[1],0)][config.EDGE_COST_KEY] = 1e-5 self.optimization_graph.edges[(edge[0],config.IM_PREFIX+edge[0],0)][config.EDGE_COST_KEY] = 1e-5 self.optimization_graph.edges[(config.IM_PREFIX+edge[1],edge[1],0)][config.EDGE_COST_KEY] = 1e-5 else: # if we don't modify the old network, we have to change the capacity of the supplies already_consummed = {} for edge in solution_old_graph.edges(): if solution_old_graph.nodes[edge[0]].get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE: already_consummed[edge[0]] = already_consummed.get(edge[0], 0) + \ solution_old_graph.edges[edge][config.SOLUTION_POWER_FLOW_KEY] for source in already_consummed: if already_consummed[source] <= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY]: self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] -= already_consummed[source] self.network_objective -= already_consummed[source] else: self.network_objective -= self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] = 0 # Remove edges from old network edges_to_remove = set() for e in self.optimization_graph.edges(): if self.old_network_graph.has_edge(*e) or self.old_network_graph.has_edge(e[1],e[0]): edges_to_remove.add(e) self.optimization_graph.remove_edges_from(edges_to_remove) # Remove isolated buildings of optimization graph isolated_to_remove = set() for e in self.old_network_graph.edges(): if e[0] in self.old_network_graph.nodes() and \ self.optimization_graph.nodes[e[1]].get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE: isolated_to_remove.add(e) self.optimization_graph.remove_edges_from(isolated_to_remove) # Remove buildings from old network for n, data in self.old_network_graph.nodes(data=True): if data.get(config.NODE_TYPE_KEY) == config.BUILDING_NODE_TYPE: self.optimization_graph.remove_node(n) # Re-link sources sources = set() for n, data in self.optimization_graph.nodes(data=True): if data.get(config.NODE_TYPE_KEY) == config.SUPPLY_NODE_TYPE: sources.add(n) source_graph = self.optimization_graph.subgraph(sources).copy() self.optimization_graph.remove_nodes_from(sources) gnx.remove_isolates(self.optimization_graph) node_filter = lambda n: self.optimization_graph.nodes.get(n,{}).get(config.NODE_TYPE_KEY) != config.BUILDING_NODE_TYPE gnx.spatial_points_merge(self.optimization_graph, source_graph.nodes_to_gdf(), node_filter=node_filter, inplace=True) # fill missing information gnx.fill_edges_missing_geometry_attributes(self.optimization_graph) gnx.fill_length_attribute(self.optimization_graph, config.EDGE_LENGTH_KEY, only_missing=True) gnx.fill_length_attribute(self.optimization_graph, config.EDGE_COST_KEY, only_missing=True) for e in self.optimization_graph.edges(keys=True): self.optimization_graph.edges[e][config.LEASTCOST_COEF_KEY] = \ self.optimization_graph.edges[e].get(config.LEASTCOST_COEF_KEY,0) # 2. Process the DSSP on optimization graph self.check_is_ready() self.check_infeasibility(self.optimization_graph, self.network_objective) if self.old_network_graph is not None and self.modify_old_network: old_buildings = set(nx.get_node_attributes(self.old_network_graph, config.BUILDING_CONSUMPTION_KEY).keys()) else: old_buildings = set() flows, obj_val = self.optimize_with_dssp_julia(self.optimization_graph, self.network_objective, old_buildings,postprocess= (not self.modify_old_network)) self.logger.info("Optimization phase time: %.2fs" % (time.time() - optimization_start)) self.solution_graph = self.build_solution_graph(self.optimization_graph, flows, self.connected) # 3. Postprocess for old network graph if self.old_network_graph is not None: if self.modify_old_network: # Put the right supply capacity and cost for edge in self.old_capacity: if self.solution_graph.has_edge(edge[0],edge[1]): self.solution_graph.edges[(edge[0],edge[1])][config.EDGE_COST_KEY] = \ self.optimization_graph.edges[(config.IM_PREFIX+edge[0],config.IM_PREFIX+edge[1],0)][config.EDGE_COST_KEY] # Remove imaginary edges imaginary_nodes_to_remove = set() nodes_to_relabel = {} for edge in self.solution_graph.edges(): if str(edge[0]).startswith(config.IM_PREFIX) and str(edge[1]).startswith(config.IM_PREFIX): real_edge = edge[0][len(config.IM_PREFIX):],edge[1][len(config.IM_PREFIX):] self.old_capacity[(real_edge[0], real_edge[1], 0)] = pd.np.inf self.old_capacity[(real_edge[1], real_edge[0], 0)] = pd.np.inf if not self.solution_graph.has_edge(*real_edge): for i in range(2): nodes_to_relabel[edge[i]] = real_edge[i] else: self.solution_graph.edges[real_edge[0],real_edge[1]][config.SOLUTION_POWER_FLOW_KEY] += \ self.solution_graph.edges[edge].get(config.SOLUTION_POWER_FLOW_KEY,0) imaginary_nodes_to_remove.add(edge[0]) imaginary_nodes_to_remove.add(edge[1]) elif str(edge[0]).startswith(config.IM_PREFIX): imaginary_nodes_to_remove.add(edge[0]) elif str(edge[1]).startswith(config.IM_PREFIX): imaginary_nodes_to_remove.add(edge[1]) nx.relabel_nodes(self.solution_graph, nodes_to_relabel, copy=False) self.solution_graph.remove_nodes_from(list(imaginary_nodes_to_remove)) for node in nodes_to_relabel.values(): if self.solution_graph.has_edge(node, node): self.solution_graph.remove_edge(node, node) else: for source in nx.get_node_attributes(self.solution_graph, config.SUPPLY_POWER_CAPACITY_KEY): self.solution_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0) self.optimization_graph.nodes[source][config.SUPPLY_POWER_CAPACITY_KEY] += already_consummed.get(source,0) return flows, obj_val def optimize_NLP(self, only_preprocess=False): ''' solve the NLP problem of the optimal size of the pipes knowing the route i.e. the selected streets 1. Load parameters 2. Preprocess to satisfy the heat demand at any time of the year 3. Solve the problem with Ipopt or Knitro on the graph 4. Add velocity, pressure and costs information on solution graph's edges if the status of the optimizer is "Optimal" ''' self.logger.info("Start pipe size optimization") # 1. Load parameters self.load_conf() consumption_data, capacity_data = self.get_consumption_and_capacities_from_csv(self.solution_graph, self.consumption_file_path) # 2. Preprocess NLP if self.old_network_graph is not None and self.modify_old_network: max_capacity = self.old_capacity else: max_capacity = {} lb_flow = self.preprocess(self.solution_graph, consumption_data, capacity_data, max_capacity) # Conversion MW flow to diameter lb_diam = {} a_vel, b_vel = self.conf["A_MAX_VELOCITY"], self.conf["B_MAX_VELOCITY"] for edge in lb_flow: mass_flow = self.convert_power_to_mass_flow(lb_flow[edge]) # mass flow = v * pi*(D/2)**2 = (A*D+B) * pi*(D/2)**2 (in mm) f = lambda x : x**3 *a_vel + x**2*b_vel - 4*mass_flow/math.pi/self.conf["RHO"]*1e6 a, b = 0, 500 while b-a>0.1: c = (a+b)/2 if f(a)*f(c) <= 0 : b = c else: a = c lb_diam[edge] = a/10 # (in cm) if only_preprocess: self.fill_edges_with_NLP({'Diameter': lb_diam}) self.logger.info("Pipe size optimization completed") return True # 3. peak_consumption = self.get_annual_peak_consumption(consumption_data) NLP_Output, status = self.optimize_pipe_size(self.solution_graph, lb_diam, peak_consumption, max_capacity) if status == "Optimal": # "Optimal", "Unbounded", "Infeasible", "UserLimit", "Error" or "NotSolved" self.logger.info("Pipe size optimization completed") self.logger.info("Collecting the NLP solution" ) self.fill_edges_with_NLP(NLP_Output) return True else: self.logger.warning("NLP optimization exits with status: %s" % str(status)) self.fill_edges_with_NLP({'Diameter': lb_diam}) return False def build_solution_graph(self, graph, flows, connecting_graph=False): """Create the solution with the optimization results. Keep only the edges with non negative flow.""" self.logger.info("Building solution graph") self.clean_flow_cycles(flows) edges_to_keep = [e for e, flow in flows.items() if flow > 0] solution_graph_mdg = graph.edge_subgraph(edges_to_keep) if connecting_graph: # We add the edges to connect edges_to_keep = edges_to_keep + self.connecting_graph(solution_graph_mdg) # We rebuild the graph solution_graph_mdg = graph.edge_subgraph(edges_to_keep) # We add the flow attribute for e in edges_to_keep: solution_graph_mdg.edges[(e[0], e[1], 0)][config.SOLUTION_POWER_FLOW_KEY] = flows[e] # We convert it in GeoDiGraph solution_graph_mdg.crs = self.optimization_graph.crs solution_graph = gnx.GeoDiGraph(solution_graph_mdg, crs=solution_graph_mdg.crs) gnx.remove_isolates(solution_graph) solution_graph.name = "solution_graph" return solution_graph def preprocess(self, solution_graph, consumption_data, capacity_data, max_capacity={}): ''' calculate the lower bound for flow. 1. Simplify the graph until having no end nodes 2. If there is no crossing nodes, the preprocess is ended. 3. 1) we calculate for each edge the surplus and the need 2) we deduced the lower bounds''' self.logger.info('start preprocess') lb_flow = {} # Graph copy to directed graph G = nx.DiGraph(nx.Graph(solution_graph)) # check dimensions assert len(consumption_data) == len(capacity_data), "Dimension of consumption_data and capacity_data much match" start_time = time.time() # 1. simplify the graph and calculate the lower bounds end_nodes = set([x for x in G.nodes() \ if len(set(G.predecessors(x)).union(set(G.successors(x))))==1\ and G.node[x].get(config.NODE_TYPE_KEY,config.SUPPLY_NODE_TYPE) != config.SUPPLY_NODE_TYPE]) finished = self.calculate_consumption_predecessors_nodes(G, consumption_data, capacity_data, lb_flow, end_nodes) if finished: return lb_flow # 3. source_nodes = set([n for n in G.nodes() if G.node[n].get(config.NODE_TYPE_KEY,None) == config.SUPPLY_NODE_TYPE]) needs_data, surplus_data = {}, {} for node in source_nodes: for edge in G.out_edges(node): self.find_needs(G, edge, needs_data, consumption_data, source_nodes, max_capacity) for edge in G.edges(): self.find_surplus(G, edge, surplus_data, consumption_data, capacity_data, set(), max_capacity) for edge in set(surplus_data.keys()).intersection(set(needs_data.keys())): if type(surplus_data[edge]) != int and type(needs_data[edge]) != int: lb_flow[edge] = max(lb_flow.get(edge,0), max(pd.concat([surplus_data[edge],needs_data[edge]], axis=1).min(axis=1))) lb_flow[(edge[1], edge[0], *edge[2:])] = max( lb_flow.get((edge[1], edge[0], *edge[2:]),0), lb_flow[edge] ) self.logger.info('end preprocess in ' + str(time.time() - start_time) + ' s') return lb_flow def connecting_graph(self, solution_graph, weight='cost', ignore_sources=False): """Return the list of edges to add to have a connected graph 1. find the groups of sources isolated from each others 2. calculate for each group of sources the convex hull 3. find the smallest path between each pair of groups The key idea is to add to the graph edges of weight 0 between all nodes on the convex hull and then run a dijkstra between one random node of group1 to one random node of group2. To have the "real" path, we just have to remove 0-weigth edges 4. Do a minimum spanning tree with the aggregated graph (nodes are the different groups and edges are the path found just before) """ debut = time.time() self.logger.info('start connecting graph') # we need an undirected graph undirected_solution_graph = solution_graph.to_undirected() if self.old_network_graph is not None and self.modify_old_network: undirected_solution_graph = nx.compose(nx.MultiGraph(self.old_network_graph), undirected_solution_graph) # if already connected if nx.is_connected(undirected_solution_graph) == True: self.logger.info("the solution graph is already connected") return [] # Computing the minimum sources in each component and all junction nodes in the solution graph nodetype = nx.get_node_attributes(undirected_solution_graph, config.NODE_TYPE_KEY) list_sources = [node for node in nodetype if nodetype[node] == config.SUPPLY_NODE_TYPE] # 1. Search of all connected subgraphs if not ignore_sources: reduced_list_sources = [] while len(list_sources) > 0: source, is_isolated = list_sources.pop(0), True for i in range(len(list_sources)): is_isolated = is_isolated and not (nx.has_path(undirected_solution_graph, source, list_sources[i])) if is_isolated: reduced_list_sources.append(source) else: reduced_list_sources = [list(n)[0] for n in nx.connected_components(undirected_solution_graph)] # 2. Creation of all convex hulls for each source in reduced_list_sources hulls = {} for source in reduced_list_sources: coord_compo = {} nodes_connecting_source = nx.node_connected_component(undirected_solution_graph, source) for node in nodes_connecting_source: xy = tuple(self.optimization_graph.get_node_coordinates(node)) coord_compo[xy] = node if len(coord_compo) > 2: convexhull = ConvexHull(list(coord_compo.keys())).points else: convexhull = list(coord_compo.keys()) hulls[source] = [coord_compo[tuple(coord)] for coord in convexhull] # 3. Create list of possible list_edges_to_add list_edges_to_add = {} # list of {(S1, S2):(length_of_SP, edges_to_add)} for S1, S2 in combinations(reduced_list_sources, 2): # change weight of edges for i in range(len(hulls[S1])-1): u,v = hulls[S1][i], hulls[S1][i+1] self.optimization_graph.add_edge(u,v,key=-1,weight=0) self.optimization_graph.add_edge(hulls[S1][-1],hulls[S1][0],key=-1,weight=0) for i in range(len(hulls[S2])-1): u,v = hulls[S2][i], hulls[S2][i+1] self.optimization_graph.add_edge(u,v,key=-1,weight=0) self.optimization_graph.add_edge(hulls[S2][-1],hulls[S2][0],key=-1,weight=0) # find the shortest path source, target = hulls[S1][0], hulls[S2][0] # it's a choice to take 0, but no matter try: length, path = nx.single_source_dijkstra(self.optimization_graph, source, target=target, weight=weight) except nx.NetworkXNoPath: self.logger.info("Source " + str(S1) + " and source " + str(S2) + " can't be connected") return [] list_weights = nx.get_edge_attributes(self.optimization_graph, weight) # edges to add to connect S1 and S2 edges_to_add = [] for i in range(len(path) - 1): u, v = path[i], path[i + 1] # if the edge between (u,v) is not artificial, we add it if list_weights.get((u, v, -1), None) != 0 and list_weights.get((u, v, 0), None) is not None: edges_to_add.append((u, v, 0)) if list_weights.get((v, u, -1), None) != 0 and list_weights.get((v, u, 0), None) is not None: edges_to_add.append((v, u, 0)) list_edges_to_add[(S1, S2)] = (length, edges_to_add) # change weight of edges for i in range(len(hulls[S1])-1): u,v = hulls[S1][i], hulls[S1][i+1] self.optimization_graph.remove_edge(u,v,key=-1) self.optimization_graph.remove_edge(hulls[S1][-1],hulls[S1][0],key=-1) for i in range(len(hulls[S2])-1): u,v = hulls[S2][i], hulls[S2][i+1] self.optimization_graph.remove_edge(u,v,key=-1) self.optimization_graph.remove_edge(hulls[S2][-1],hulls[S2][0],key=-1) # 4. choice of best edges to add (Kruskal) G = nx.Graph() for (S1, S2) in list_edges_to_add: (length, _) = list_edges_to_add[(S1, S2)] if not G.has_node(S1): G.add_node(S1) if not G.has_node(S2): G.add_node(S2) G.add_edge(S1, S2, weight=length) reduced_list_edges_to_add = set() T = nx.minimum_spanning_tree(G) for u, v in T.edges: if (u, v) in list_edges_to_add: reduced_list_edges_to_add = reduced_list_edges_to_add.union(set(list_edges_to_add[(u, v)][1])) if (v, u) in list_edges_to_add: reduced_list_edges_to_add = reduced_list_edges_to_add.union(set(list_edges_to_add[(v, u)][1])) self.logger.info('end connecting graph in ' + str(time.time() - debut) + ' s') return list(reduced_list_edges_to_add) @staticmethod def clean_flow_cycles(flows: dict): """Remove the sub-optimal flow cycles allowed with the flow conservation. Flows dictionnary is modified inplace.""" for e, flow in flows.items(): if flow > 0: reversed_e = (e[1], e[0], *e[2:]) if reversed_e in flows and flows[reversed_e] > 0: reversed_flow = flows[reversed_e] cycle_flow = min(flow, reversed_flow) flows[e] -= cycle_flow flows[reversed_e] -= cycle_flow # -------------- NLP methods def load_conf(self): """ loads the parameters defined in the config.ini in self.conf to prepare the NLP optimization""" conf = configparser.ConfigParser() conf.read(self.conf_path) params = self.conf for s in conf.sections(): for p in conf[s]: params[p.upper()] = eval(conf.get(s,p)) self.conf = params if self.energy == "Heating": T = self.conf['SUPPLY_HEAT_TEMPERATURE'] if self.energy == "Cooling": T = self.conf['SUPPLY_COOL_TEMPERATURE'] # piecewise linear functions self.conf['CP'] = CP(T) self.conf['RHO'] = RHO(T) # REGRESSIONS if self.energy == "Heating": self.conf['A_HEAT_TRANSIT_COEF'], self.conf['B_HEAT_TRANSIT_COEF'] = \ HEAT_LOSS_COST((self.conf['SUPPLY_HEAT_TEMPERATURE']+self.conf['RETURN_HEAT_TEMPERATURE'])/2) if self.energy == "Cooling": self.conf['A_COOL_TRANSIT_COEF'], self.conf['B_COOL_TRANSIT_COEF'] = \ HEAT_LOSS_COST((self.conf['SUPPLY_COOL_TEMPERATURE']+self.conf['RETURN_COOL_TEMPERATURE'])/2) self.conf['A_LINEAR_COST'], self.conf['B_LINEAR_COST'] = CONSTRUCTION_COST() self.conf['A_MAX_VELOCITY'], self.conf['B_MAX_VELOCITY'] = MAX_VELOCITY() def convert_power_to_mass_flow(self, power_mw): if self.energy == "Heating": mass_flow = (power_mw * 1e6) / (self.conf['CP']\ * (self.conf['SUPPLY_HEAT_TEMPERATURE'] - self.conf['RETURN_HEAT_TEMPERATURE'])) if self.energy == "Cooling": mass_flow = (power_mw * 1e6) / (self.conf['CP']\ * (self.conf['RETURN_COOL_TEMPERATURE'] - self.conf['SUPPLY_COOL_TEMPERATURE'])) return mass_flow def convert_mass_flow_to_power(self, mass_flow): if self.energy == "Heating": power_mw = mass_flow * 1e-6 * self.conf['CP'] * \ (self.conf['SUPPLY_HEAT_TEMPERATURE'] - self.conf['RETURN_HEAT_TEMPERATURE']) if self.energy == "Cooling": power_mw = mass_flow * 1e-6 * self.conf['CP'] * \ (self.conf['RETURN_COOL_TEMPERATURE'] - self.conf['SUPPLY_COOL_TEMPERATURE']) return power_mw def get_params(self, network_frame, peak_consumption): lengths = nx.get_edge_attributes(network_frame, config.EDGE_LENGTH_KEY) Length, Outflow, Supply_Max_Inflow = {}, {}, {} sources = set(n for n,d in network_frame.nodes(data = True) if \ config.NODE_TYPE_KEY in d and d[config.NODE_TYPE_KEY] == config.SUPPLY_NODE_TYPE) connected_buildings = set(n for n,d in network_frame.nodes(data =True) if \ config.NODE_TYPE_KEY in d and d[config.NODE_TYPE_KEY] == config.BUILDING_NODE_TYPE) # IMPORTANT : edges between a source and a junction must have the form (source, junction) # edges between a building and junction must have the form (junction, building) for key in lengths: u, v = key[0], key[1] if (v,u) not in Length: if v in sources: Length[(v,u)] = max(lengths[key],1e-5) # we don't want a length of zero else: Length[(u,v)] = max(lengths[key],1e-5) for s in sources: Supply_Max_Inflow[s] = self.convert_power_to_mass_flow(network_frame.nodes[s][config.SUPPLY_POWER_CAPACITY_KEY]) for b in connected_buildings: if self.energy == "Heating": Outflow[b] = self.convert_power_to_mass_flow(peak_consumption[b]) if self.energy == "Cooling": Outflow[b] = self.convert_power_to_mass_flow(peak_consumption[b]) GraphParam = {} GraphParam["LENGTH"] = Length GraphParam["ELEVATION"] = nx.get_node_attributes(network_frame, config.NODE_ELEVATION_KEY) GraphParam["OUTFLOW"] = Outflow GraphParam["SUPPLY_MAX_INFLOW"] = Supply_Max_Inflow return GraphParam def get_consumption_and_capacities_from_csv(self, graph, csv_file): consumption_data, capacity_data = pd.DataFrame(), pd.DataFrame() csv_data = pd.read_csv(csv_file, sep=";",decimal=',') L = len(csv_data) for n, data in graph.nodes(data=True): if data.get(config.NODE_TYPE_KEY,None) == config.BUILDING_NODE_TYPE: consumption_data[n] = data[config.BUILDING_CONSUMPTION_KEY]/max(csv_data[data[config.BUILDING_USE_KEY]])*csv_data[data[config.BUILDING_USE_KEY]] if data.get(config.NODE_TYPE_KEY,None) == config.SUPPLY_NODE_TYPE: capacity_data[n] = pd.Series([data[config.SUPPLY_POWER_CAPACITY_KEY]]*L) return consumption_data.dropna(), capacity_data.dropna() def get_annual_peak_consumption(self, consumption_data): index_tot_consumption = pd.concat([consumption_data[n] for n in consumption_data], axis=1).sum(axis=1).idxmax(axis=0) return {n:consumption_data[n].loc[index_tot_consumption] for n in consumption_data} def fill_edges_with_NLP(self, NLP_Output): Diameter = NLP_Output.get("Diameter", {}) Velocity = NLP_Output.get("Velocity", {}) Pressure = NLP_Output.get("Pressure", {}) MassFlow = NLP_Output.get("MassFlow", {}) PressureFriction = NLP_Output.get("PressureFriction", {}) #print(PressureFriction) ConstructionCost = NLP_Output.get("ConstructionCost", {}) if self.energy == "Heating": HeatLossCost = NLP_Output.get("HeatLossCost", {}) if self.energy == "Cooling": CoolLossCost = NLP_Output.get("CoolLossCost", {}) PumpingCost = NLP_Output.get("PumpingCost", {}) for u,v in self.solution_graph.edges: if self.solution_graph.edges[u, v][config.EDGE_LENGTH_KEY] > 0: # fill diameter if (u, v) in Diameter: self.solution_graph.edges[u, v][config.PIPE_DIAMETER_KEY] = round(Diameter[(u, v)]*10)/10 elif (v, u) in Diameter: self.solution_graph.edges[u, v][config.PIPE_DIAMETER_KEY] = round(Diameter[(v, u)]*10)/10 else: self.solution_graph.edges[u, v][config.PIPE_DIAMETER_KEY] = 0 # fill velocity if (u, v) in Velocity: self.solution_graph.edges[u, v][config.VELOCITY_KEY] = Velocity[(u, v)] elif (v, u) in Velocity: self.solution_graph.edges[u, v][config.VELOCITY_KEY] = -Velocity[(v, u)] else: self.solution_graph.edges[u, v][config.VELOCITY_KEY] = 0 # fill construction and heat/cool loss costs if (u, v) in ConstructionCost: self.solution_graph.edges[u, v][config.CONSTRUCTION_COST_KEY] = ConstructionCost[(u, v)] elif (v, u) in ConstructionCost: self.solution_graph.edges[u, v][config.CONSTRUCTION_COST_KEY] = ConstructionCost[(v, u)] else: self.solution_graph.edges[u, v][config.CONSTRUCTION_COST_KEY] = 0 if self.energy == "Heating": if (u, v) in HeatLossCost: self.solution_graph.edges[u, v][config.HEAT_LOSS_COST_KEY] = HeatLossCost[(u, v)] elif (v, u) in HeatLossCost: self.solution_graph.edges[u, v][config.HEAT_LOSS_COST_KEY] = HeatLossCost[(v, u)] else: self.solution_graph.edges[u, v][config.HEAT_LOSS_COST_KEY] = 0 if self.energy == "Cooling": if (u, v) in CoolLossCost: self.solution_graph.edges[u, v][config.COOL_LOSS_COST_KEY] = CoolLossCost[(u, v)] elif (v, u) in CoolLossCost: self.solution_graph.edges[u, v][config.COOL_LOSS_COST_KEY] = CoolLossCost[(v, u)] else: self.solution_graph.edges[u, v][config.COOL_LOSS_COST_KEY] = 0 # fill average pressure if (u, v) in Pressure: self.solution_graph.edges[u, v][config.AVERAGE_PRESSURE_KEY] = Pressure[(u, v)] elif (v, u) in Pressure: self.solution_graph.edges[u, v][config.AVERAGE_PRESSURE_KEY] = Pressure[(v, u)] else: self.solution_graph.edges[u, v][config.AVERAGE_PRESSURE_KEY] = 0 # fill pumping costs if u in PumpingCost: self.solution_graph.edges[u, v][config.PUMPING_COST_KEY] = PumpingCost[u] elif v in PumpingCost: self.solution_graph.edges[u, v][config.PUMPING_COST_KEY] = PumpingCost[v] else: self.solution_graph.edges[u, v][config.PUMPING_COST_KEY] = 0 # actualize flow values if (u, v) in MassFlow: self.solution_graph.edges[u, v][config.SOLUTION_POWER_FLOW_KEY] = \ self.convert_mass_flow_to_power(MassFlow[(u, v)]) elif (v, u) in MassFlow: self.solution_graph.edges[u, v][config.SOLUTION_POWER_FLOW_KEY] = \ -self.convert_mass_flow_to_power(MassFlow[(v, u)]) else: self.solution_graph.edges[u, v][config.SOLUTION_POWER_FLOW_KEY] = 0 # -------------- Preprocess NLP methods def calculate_consumption_predecessors_nodes(self, G, consumption_data, capacity_data, lb_flow, end_nodes): ''' simplify all the simple final branches until having no end nodes. ''' #draw_graph(G, pos) # terminal case if len(end_nodes) == 0: for n in G.nodes(): if G.node[n].get(config.NODE_TYPE_KEY,None) != config.SUPPLY_NODE_TYPE: return False return True else: pre_end_nodes = set() # calculate all the terminal branches {pre_end_nodes: {end_node1, end_node2}} for n in end_nodes: p = list(set(G.predecessors(n)).union(set(G.successors(n))))[0] # update consumption data consumption_data[p] = consumption_data.get(p,0) + consumption_data.get(n,0) # the flow lb is the max over the time of the consumption lb_flow[(p,n)] = max(consumption_data.get(n,[0])) # remove the terminal node G.remove_node(n) # compute pre_end_nodes = next end nodes if len(set(G.predecessors(p)).union(set(G.successors(p))))==1: if G.node[p].get(config.NODE_TYPE_KEY) != config.SUPPLY_NODE_TYPE: pre_end_nodes.add(p) # continue to simplify the graph self.calculate_consumption_predecessors_nodes(G, consumption_data, capacity_data, lb_flow, pre_end_nodes) def find_needs(self, G, edge, needs_data, consumption_data, forbidden_nodes, max_capacity={}): forbidden_nodes.add(edge[0]) if edge not in needs_data: successors = set(G.successors(edge[1])) reduced_successors = successors.difference(forbidden_nodes) val = consumption_data.get(edge[1],0) if len(reduced_successors) > 0: for s in reduced_successors: val = val + self.find_needs(G, (edge[1],s), needs_data, consumption_data, deepcopy(forbidden_nodes), max_capacity) if type(val) != int: needs_data[edge] = pd.concat([val, pd.Series([max_capacity.get((*edge,0), pd.np.inf)]*len(val))],axis=1).min(axis=1) else: needs_data[edge] = val return needs_data[edge] def find_surplus(self, G, edge, surplus_data, consumption_data, capacity_data, forbidden_nodes, max_capacity={}): forbidden_nodes.add(edge[1]) if edge not in surplus_data: predecessors = set(G.predecessors(edge[0])) reduced_predecessors = predecessors.difference(forbidden_nodes) if G.node[edge[0]].get(config.NODE_TYPE_KEY,None) == config.SUPPLY_NODE_TYPE: val = capacity_data[edge[0]] else: val = - consumption_data.get(edge[0],0) if len(reduced_predecessors) > 0: for p in reduced_predecessors: val = val + self.find_surplus(G, (p,edge[0]), surplus_data, consumption_data, capacity_data, deepcopy(forbidden_nodes), max_capacity) if type(val) != int: surplus_data[edge] = pd.concat([val, pd.Series([max_capacity.get((*edge,0), pd.np.inf)]*len(val))],axis=1).min(axis=1) else: surplus_data[edge] = val return surplus_data[edge] # ============================================= Optimization methods =============================================== def optimize_with_dssp_julia(self, graph, network_objective, old_buildings, postprocess=True): """Solve the Fixed Charge Network Flow Problem using the Dynamic Slope Scaling Procedure from Dukwon Kim, Panos M. Pardalos in "A solution approach to the fixed charge network flow problem using a dynamic slope scaling procedure" (1998). The model and the procedure is defined in the Julia language in the file 'DSSP.jl'. We use here the python library PyJulia to call julia and to wrap input and output variables. :return: tuple containing : flows : dict. Values of the flow on each edge. obj_val : float. Value of the optimization objective, i.e. the total cost of the network. """ # === Start data initialization data_init_start = time.time() # === Start the algorithm all_nodes = set(graph.nodes()) costs = nx.get_edge_attributes(graph, config.EDGE_COST_KEY) heat_demand = nx.get_node_attributes(graph, config.BUILDING_CONSUMPTION_KEY) production = nx.get_node_attributes(graph, config.SUPPLY_POWER_CAPACITY_KEY) capacities = {} #print(costs) #print(heat_demand) #print(production) if self.old_network_graph is not None and self.modify_old_network: for e,c in self.old_capacity.items(): if e in graph.edges(keys=True): capacities[e] = c+1e-5 elif (e[1],e[0],e[2]) in graph.edges(keys=True): capacities[(e[1],e[0],e[2])] = c+1e-5 self.logger.info("\tData initialization time: %.2fs" % (time.time() - data_init_start)) # === Set up instance of julia : self.logger.info("Setting up julia call...") julia_instantiate_start = time.time() optimizer_directory = os.path.dirname(os.path.realpath(__file__)) with JuliaQgisInterface() as j: j.include(os.path.join(optimizer_directory, "DSSP.jl")) j.using("Main.DSSP: optimize_with_DSSP") assert (hasattr(j, "optimize_with_DSSP")) self.logger.info("\tJulia instantiating time: %.2fs" % (time.time() - julia_instantiate_start)) dssp_start = time.time() #print("old_buildings", old_buildings) best_solution, best_cost = j.optimize_with_DSSP(network_objective, all_nodes, costs, heat_demand, production, capacities, old_buildings, self.logger.info, postprocess) self.logger.info("\tDSSP run time: %.2fs" % (time.time() - dssp_start)) return best_solution, best_cost def optimize_pipe_size(self, network_frame, lb_diam, peak_consumption, max_capacity={}): """Optimize the diameter layout of the network's main line based on connected building's consumption during the peak. Non linear and nonconvex problem to be solved with Artelys KNITRO or open-source solver Ipopt. Techno-economic optimization: we minimize annualised costs of construction, heat loss and pumping. The model and the procedure is defined in the Julia language in the file 'NLP_variable_flows.jl'""" # Start data initialization GraphParam = self.get_params(network_frame, peak_consumption) GraphParam['LB_DIAM'] = lb_diam # In case of old network if len(max_capacity) > 0: GraphParam['MAX_CAPACITY'] = {} for e, val in max_capacity.items(): GraphParam['MAX_CAPACITY'][(e[0],e[1])] = val else: GraphParam['MAX_CAPACITY'] = {} # Start the algorithm # Use NLP module optimizer_directory = os.path.dirname(os.path.realpath(__file__)) with JuliaQgisInterface() as j: j.include(os.path.join(optimizer_directory, "NLP", "NLP_variable_flows.jl")) j.using("Main.NLP: find_optimal_physical_parameters") assert (hasattr(j, "find_optimal_physical_parameters")) nlp_start = time.time() NLP_Output, status = j.find_optimal_physical_parameters(GraphParam, self.conf, self.solver_log_file, self.energy, self.logger.info) nlp_end = time.time() self.logger.info("nlp time: %s" % str(nlp_end - nlp_start)) return NLP_Output, status if __name__ == "__main__": results_dir = "optimizer/automatic_design/results/" # Load optimization graph optimization_graph = nx.read_gpickle(os.path.join(results_dir, "optimization_graph.gpickle")) supplies = nx.get_node_attributes(optimization_graph, config.SUPPLY_POWER_CAPACITY_KEY) for s in supplies: optimization_graph.nodes[s][config.SUPPLY_POWER_CAPACITY_KEY] *= 1000 self = ADNetworkOptimizer(optimization_graph) self.logger.setLevel(logging.INFO) stream_handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s') stream_handler.setFormatter(formatter) stream_handler.setLevel(logging.DEBUG) self.logger.addHandler(stream_handler) consumptions = nx.get_node_attributes(optimization_graph, config.BUILDING_CONSUMPTION_KEY) total_consumption = sum(consumptions.values()) self.network_objective = total_consumption * 0.8 assert (sum( nx.get_node_attributes(optimization_graph, config.SUPPLY_POWER_CAPACITY_KEY).values()) > self.network_objective) self.optimize() # gnx.export_graph_as_shape_file(self.solution_graph, results_dir, fiona_cast=True)
true
6f81cc4436f10f52c6bc60572e6400e241bb714e
Python
spbgithub/projecteuler
/pe139.py
UTF-8
1,022
3.9375
4
[]
no_license
'''Pythagorean tiles Problem 139 Let (a, b, c) represent the three sides of a right angle triangle with integral length sides. It is possible to place four such triangles together to form a square with length c. For example, (3, 4, 5) triangles can be placed together to form a 5 by 5 square with a 1 by 1 hole in the middle and it can be seen that the 5 by 5 square can be tiled with twenty-five 1 by 1 squares. However, if (5, 12, 13) triangles were used then the hole would measure 7 by 7 and these could not be used to tile the 13 by 13 square. Given that the perimeter of the right triangle is less than one-hundred million, how many Pythagorean triangles would allow such a tiling to take place?''' from math import sqrt from fractions import gcd MAX_PER = 100000000.0 MAX_SQRT = int(sqrt(MAX_PER/2.0)+1) pythag = [(j,k) for j in range(2, MAX_SQRT) for k in range(1,j) if gcd(j,k) == 1 if (j - k) % 2 != 0 if (j*j + k*k) % (j*j - k*k - 2*j*k) == 0] print(sum([int(MAX_PER)//(2*j*(j+k)) for (j,k) in pythag]))
true
6700a1df268e7d4bfc4a4c9fb272dbe97d8ca260
Python
wzy810103882/DLCV_Final_Project
/SinGAN/ui.py
UTF-8
5,397
2.921875
3
[]
no_license
import pygame, sys from PIL import Image import os import argparse pygame.init() def displayImage(screen, px, topleft, prior): # ensure that the rect always has positive width, height x, y = topleft width = pygame.mouse.get_pos()[0] - topleft[0] height = pygame.mouse.get_pos()[1] - topleft[1] if width < 0: x += width width = abs(width) if height < 0: y += height height = abs(height) # eliminate redundant drawing cycles (when mouse isn't moving) current = x, y, width, height if not (width and height): return current if current == prior: return current # draw transparent box and blit it onto canvas screen.blit(px, px.get_rect()) im = pygame.Surface((width, height)) im.fill((128, 128, 128)) pygame.draw.rect(im, (32, 32, 32), im.get_rect(), 1) im.set_alpha(128) screen.blit(im, (x, y)) pygame.display.flip() # return current box extents return (x, y, width, height) def setup(path): px = pygame.image.load(path) screen = pygame.display.set_mode( px.get_rect()[2:] ) screen.blit(px, px.get_rect()) pygame.display.flip() return screen, px def mainLoop(screen, px): topleft = bottomright = prior = None n=0 while n!=1: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: if not topleft: topleft = event.pos else: bottomright = event.pos n=1 if event.type == pygame.QUIT: n = 1 #pygame.display.quit() #pygame.quit() #quit() if topleft: prior = displayImage(screen, px, topleft, prior) return ( topleft + bottomright ) if __name__ == "__main__": parser = argparse.ArgumentParser() # get default parameter (config.py) # input image and harmonization mask image parser.add_argument('--background_dir', help='background image dir', required=True) parser.add_argument('--insert_dir', help='insert image dir', required=True) parser.add_argument('--output_dir', help='output image dir',default = 'Input/Harmonization') #parser.add_argument('--width', help='width to be rescaled',required=True) #parser.add_argument('--height', help='height to be rescaled',required=True) #parser.add_argument('--output_dir', help='output dir, default to input_dir (WARNING: replaces input_dir)') opt = parser.parse_args() img = Image.open(opt.insert_dir) #print(os.getcwd()) #background_loc = 'Input/Images/background_001_500.png' #human_loc = 'Input/Insert/human_001.png' background_loc = opt.background_dir human_loc = opt.insert_dir screen, px = setup(background_loc) left, upper, right, lower = mainLoop(screen, px) if right < left: left, right = right, left if lower < upper: lower, upper = upper, lower print("crop height" + str(abs(upper -lower))) print("crop width" + str(abs(left-right))) background = Image.open(background_loc) print("bg height" + str(background.size[1])) print("bg width" + str(background.size[0])) human = Image.open(human_loc) real = background.copy() #print(upper) #print(lower) human_background_ratio = abs(upper - lower) / background.size[1] scale = background.size[1] * human_background_ratio / human.size[1] width, height = int(human.size[0] * scale), int(human.size[1] * scale) #print(width) #print(height) human = human.resize((width, height), Image.ANTIALIAS) print("human height" + str(human.size[1])) print("human width" + str(human.size[0])) #human.show() bg_width, bg_height = background.size x = left y = upper #x_ratio = 0.7 #y_ratio = 0.7 #x = int(x_ratio * bg_width) #y = int(y_ratio * bg_height) background.paste(human, (x, y), human) #background.save("SinGAN/Input/Harmonization/human.png") #background.show() ref = background.copy() background = Image.new('RGB', (bg_width, bg_height)) human_width, human_height = human.size human_mask = Image.new('RGBA', (human_width,human_height), (0, 0, 0, 0)) for i in range(human_width): for j in range(human_height): _,_,_,a = human.getpixel((i,j)) if a != 0: human_mask.putpixel((i,j), (255,255,255,255)) #human_mask.show() background.paste(human_mask, (x, y), human_mask) mask = background.copy() #background.show() #background.save("SinGAN/Input/Harmonization/human_mask.png") # ensure output rect always has positive width, height #im = im.crop(( left, upper, right, lower)) pygame.display.quit() output_dir = opt.output_dir #ref_loc = 'Input/Harmonization/human.png' #real_loc = 'Data/harmonization/real.png' # background #mask_loc = 'Input/Harmonization/human_mask.png' counter = 1 ref_loc = output_dir + "/" + "human{}.png" while os.path.isfile(ref_loc.format(counter)): counter += 1 ref_loc = ref_loc.format(counter) #ref_loc = output_dir + '/human.png' mask_loc = ref_loc[:-4] + "_mask" + ".png" print(ref_loc) print(mask_loc) ref.save(ref_loc) #real.save(real_loc) mask.save(mask_loc)
true
f400a4d34527928c5df4626236702430f2a89fda
Python
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/paul_jurek/lesson04/file_lab.py
UTF-8
1,545
4
4
[]
no_license
# Activity 2: File Lab # Goal: # Get a little bit of practice with handling files and parsing simple text. # Paths and File Processing # Write a program which prints the full path for all files in the current directory, one per line # import pathlib pth = pathlib.Path('./') for f in pth.iterdir(): print(f) # Write a program which copies a file from a source, to a destination (without using shutil, or the OS copy command). # we will copy lesson 3 file to lesson 4 for this # Advanced: make it work for any size file: i.e. don’t read the entire contents of the file into memory at once. # This should work for any kind of file, so you need to open the files in binary mode: open(filename, 'rb') (or 'wb' for writing). Note that for binary files, you can’t use readline() – lines don’t have any meaning for binary files. # Test it with both text and binary files (maybe jpeg or something of your chosing). def copy_file(old_file, new_file): """does content copy of files from old file to new""" with open(old_file, 'rb') as infile, open(new_file, 'wb') as outfile: while True: line = infile.read(1000) if not line: break outfile.write(line) # testing this script original_file = '../lesson03/slicing_lab.py' new_file = 'slicing_lab_copy2.py' copy_file(old_file=original_file, new_file=new_file) # testing this script with picture original_file = 'example_picture.png' new_file = 'copied_picture.png' copy_file(old_file=original_file, new_file=new_file)
true
455c88491969c2fd67ea6cd638f09967130ba041
Python
LazyCrazyFirst/NeuroPy
/static/bin/C#/ConsoleApp1/ConsoleApp1/bin/Debug/netcoreapp3.1/test.py
UTF-8
667
3.453125
3
[]
no_license
import os from Writing_And_Output_From_A_File import writing_to_a_file, reading_from_a_file # Переменные var1 = 'hello' var2 = 4 var3 = 'Лох' # Словарь с переменными для записи в файл variables = ['var1', 'var2', 'var3', 'Raschet', 'Demo'] # Запись имён value = [var1, var2, var3, 'Method', 'Method'] # Запись значений # Вызов функции добавления переменных в файл writing_to_a_file(variables, value) # Вызов функции чтения переменных # print(reading_from_a_file()) # Запуск C# файла # os.system('ConsoleApp1.exe')
true
e53a05a0361439a258a1b09b7f611a0daf73e3ce
Python
bioexcel/biobb_common
/biobb_common/tools/file_utils.py
UTF-8
26,024
2.90625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
"""Tools to work with files """ import difflib import functools import logging import os import errno import pathlib import re import shutil import uuid import warnings import zipfile from sys import platform from pathlib import Path import typing import sys def create_unique_file_path(parent_dir: str = None, extension: str = None) -> str: if not parent_dir: parent_dir = Path.cwd() if not extension: extension = '' while True: name = str(uuid.uuid4())+extension file_path = Path.joinpath(Path(parent_dir).resolve(), name) if not file_path.exists(): return str(file_path) def create_dir(dir_path: str) -> str: """Returns the directory **dir_path** and create it if path does not exist. Args: dir_path (str): Path to the directory that will be created. Returns: str: Directory dir path. """ if not Path(dir_path).exists(): Path(dir_path).mkdir(exist_ok=True, parents=True) return str(Path(dir_path)) def create_stdin_file(intput_string: str) -> str: file_path = create_unique_file_path(extension='.stdin') with open(file_path, 'w') as file_handler: file_handler.write(intput_string) return file_path def create_unique_dir(path: str = '', prefix: str = '', number_attempts: int = 10, out_log: logging.Logger = None) -> str: """Create a directory with a prefix + computed unique name. If the computed name collides with an existing file name it attemps **number_attempts** times to create another unique id and create the directory with the new name. Args: path (str): ('') Parent path of the new directory. prefix (str): ('') String to be added before the computed unique dir name. number_attempts (int): (10) number of times creating the directory if there's a name conflict. out_log (logger): (None) Python logger object. Returns: str: Directory dir path. """ new_dir = prefix + str(uuid.uuid4()) if path: new_dir = str(Path(path).joinpath(new_dir)) for i in range(number_attempts): try: oldumask = os.umask(0) Path(new_dir).mkdir(mode=0o777, parents=True, exist_ok=False) if out_log: out_log.info('%s directory successfully created' % new_dir) os.umask(oldumask) return new_dir except OSError: if out_log: out_log.info(new_dir + ' Already exists') out_log.info('Retrying %i times more' % (number_attempts - i)) new_dir = prefix + str(uuid.uuid4().hex) if path: new_dir = str(Path(path).joinpath(new_dir)) if out_log: out_log.info('Trying with: ' + new_dir) raise FileExistsError def get_working_dir_path(working_dir_path: str = None, restart: bool = False) -> str: """Return the directory **working_dir_path** and create it if working_dir_path does not exist. If **working_dir_path** exists a consecutive numerical suffix is added to the end of the **working_dir_path** and is returned. Args: working_dir_path (str): Path to the workflow results. restart (bool): If step result exists do not execute the step again. Returns: str: Path to the workflow results directory. """ if not working_dir_path: return str(Path.cwd().resolve()) working_dir_path = str(Path(working_dir_path).resolve()) if (not Path(working_dir_path).exists()) or restart: return str(Path(working_dir_path)) cont = 1 while Path(working_dir_path).exists(): working_dir_path = re.split(r"_[0-9]+$", str(working_dir_path))[0] + '_' + str(cont) cont += 1 return str(working_dir_path) def zip_list(zip_file: str, file_list: typing.Iterable[str], out_log: logging.Logger = None): """ Compress all files listed in **file_list** into **zip_file** zip file. Args: zip_file (str): Output compressed zip file. file_list (:obj:`list` of :obj:`str`): Input list of files to be compressed. out_log (:obj:`logging.Logger`): Input log object. """ file_list.sort() Path(zip_file).parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(zip_file, 'w') as zip_f: inserted = [] for index, f in enumerate(file_list): base_name = Path(f).name if base_name in inserted: base_name = 'file_' + str(index) + '_' + base_name inserted.append(base_name) zip_f.write(f, arcname=base_name) if out_log: out_log.info("Adding:") out_log.info(str(file_list)) out_log.info("to: " + str(Path(zip_file).resolve())) def unzip_list(zip_file: str, dest_dir: str = None, out_log: logging.Logger = None) -> typing.List[str]: """ Extract all files in the zipball file and return a list containing the absolute path of the extracted files. Args: zip_file (str): Input compressed zip file. dest_dir (str): Path to directory where the files will be extracted. out_log (:obj:`logging.Logger`): Input log object. Returns: :obj:`list` of :obj:`str`: List of paths of the extracted files. """ with zipfile.ZipFile(zip_file, 'r') as zip_f: zip_f.extractall(path=dest_dir) file_list = [str(Path(dest_dir).joinpath(f)) for f in zip_f.namelist()] if out_log: out_log.info("Extracting: " + str(Path(zip_file).resolve())) out_log.info("to:") out_log.info(str(file_list)) return file_list def search_topology_files(top_file: str, out_log: logging.Logger = None) -> typing.List[str]: """ Search the top and itp files to create a list of the topology files Args: top_file (str): Topology GROMACS top file. out_log (:obj:`logging.Logger`): Input log object. Returns: :obj:`list` of :obj:`str`: List of paths of the extracted files. """ top_dir_name = str(Path(top_file).parent) file_list = [] pattern = re.compile(r"#include\s+\"(.+)\"") if Path(top_file).exists(): with open(top_file) as tf: for line in tf: include_file = pattern.match(line.strip()) if include_file: found_file = str(Path(top_dir_name).joinpath(include_file.group(1))) file_list += search_topology_files(found_file, out_log) else: if out_log: out_log.info("Ignored file %s" % top_file) return file_list return file_list + [top_file] def zip_top(zip_file: str, top_file: str, out_log: logging.Logger = None, remove_original_files: bool = True) -> typing.List[str]: """ Compress all *.itp and *.top files in the cwd into **zip_file** zip file. Args: zip_file (str): Output compressed zip file. top_file (str): Topology TOP GROMACS file. out_log (:obj:`logging.Logger`): Input log object. Returns: :obj:`list` of :obj:`str`: List of compressed paths. """ file_list = search_topology_files(top_file, out_log) zip_list(zip_file, file_list, out_log) if remove_original_files: rm_file_list(file_list, out_log) return file_list def unzip_top(zip_file: str, out_log: logging.Logger = None, unique_dir: typing.Union[pathlib.Path, str] = None) -> str: """ Extract all files in the zip_file and copy the file extracted ".top" file to top_file. Args: zip_file (str): Input topology zipball file path. out_log (:obj:`logging.Logger`): Input log object. unique_dir (str): Directory where the topology will be extracted. Returns: str: Path to the extracted ".top" file. """ unique_dir = unique_dir or create_unique_dir() top_list = unzip_list(zip_file, unique_dir, out_log) top_file = next(name for name in top_list if name.endswith(".top")) if out_log: out_log.info('Unzipping: ') out_log.info(zip_file) out_log.info('To: ') for file_name in top_list: out_log.info(file_name) return top_file def get_logs_prefix(): return 4 * ' ' def get_logs(path: str = None, prefix: str = None, step: str = None, can_write_console: bool = True, level: str = 'INFO', light_format: bool = False) -> typing.Tuple[logging.Logger, logging.Logger]: """ Get the error and and out Python Logger objects. Args: path (str): (current working directory) Path to the log file directory. prefix (str): Prefix added to the name of the log file. step (str): String added between the **prefix** arg and the name of the log file. can_write_console (bool): (False) If True, show log in the execution terminal. level (str): ('INFO') Set Logging level. ['CRITICAL','ERROR','WARNING','INFO','DEBUG','NOTSET'] light_format (bool): (False) Minimalist log format. Returns: :obj:`tuple` of :obj:`logging.Logger` and :obj:`logging.Logger`: Out and err Logger objects. """ prefix = prefix if prefix else '' step = step if step else '' path = path if path else str(Path.cwd()) out_log_path = create_name(path=path, prefix=prefix, step=step, name='log.out') err_log_path = create_name(path=path, prefix=prefix, step=step, name='log.err') # If logfile exists create a new one adding a number at the end if Path(out_log_path).exists(): name = 'log.out' cont = 1 while Path(out_log_path).exists(): name = name.split('.')[0].rstrip('\\/0123456789_') + str(cont) + '.out' out_log_path = create_name(path=path, prefix=prefix, step=step, name=name) cont += 1 if Path(err_log_path).exists(): name = 'log.err' cont = 1 while Path(err_log_path).exists(): name = name.split('.')[0].rstrip('\\/0123456789_') + str(cont) + '.err' err_log_path = create_name(path=path, prefix=prefix, step=step, name=name) cont += 1 # Create dir if it not exists create_dir(str(Path(out_log_path).resolve().parent)) # Create logging format logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") if light_format: logFormatter = logging.Formatter("%(asctime)s %(message)s", "%H:%M:%S") # Create logging objects out_Logger = logging.getLogger(out_log_path) err_Logger = logging.getLogger(err_log_path) # Create FileHandler out_fileHandler = logging.FileHandler(out_log_path, mode='a', encoding=None, delay=False) err_fileHandler = logging.FileHandler(err_log_path, mode='a', encoding=None, delay=False) # Asign format to FileHandler out_fileHandler.setFormatter(logFormatter) err_fileHandler.setFormatter(logFormatter) # Assign FileHandler to logging object if not len(out_Logger.handlers): out_Logger.addHandler(out_fileHandler) err_Logger.addHandler(err_fileHandler) # Create consoleHandler consoleHandler = logging.StreamHandler(stream=sys.stdout) # Assign format to consoleHandler consoleHandler.setFormatter(logFormatter) # Assign consoleHandler to logging objects as aditional output if can_write_console and len(out_Logger.handlers) < 2: out_Logger.addHandler(consoleHandler) err_Logger.addHandler(consoleHandler) # Set logging level level out_Logger.setLevel(level) err_Logger.setLevel(level) return out_Logger, err_Logger def launchlogger(func): @functools.wraps(func) def wrapper_log(*args, **kwargs): args[0].out_log, args[0].err_log = get_logs(path=args[0].path, prefix=args[0].prefix, step=args[0].step, can_write_console=args[0].can_write_console_log) value = func(*args, **kwargs) handlers = args[0].out_log.handlers[:] # Create a copy [:] of the handler list to be able to modify it while we are iterating for handler in handlers: handler.close() args[0].out_log.removeHandler(handler) handlers = args[0].err_log.handlers[:] # Create a copy [:] of the handler list to be able to modify it while we are iterating for handler in handlers: handler.close() args[0].err_log.removeHandler(handler) return value return wrapper_log def log(string: str, local_log: logging.Logger = None, global_log: logging.Logger = None): """Checks if log exists Args: string (str): Message to log. local_log (:obj:`logging.Logger`): local log object. global_log (:obj:`logging.Logger`): global log object. """ if local_log: local_log.info(string) if global_log: global_log.info(get_logs_prefix() + string) def human_readable_time(time_ps: int) -> str: """Transform **time_ps** to a human readable string. Args: time_ps (int): Time in pico seconds. Returns: str: Human readable time. """ time_units = ['femto seconds', 'pico seconds', 'nano seconds', 'micro seconds', 'mili seconds'] t = time_ps * 1000 for tu in time_units: if t < 1000: return str(t) + ' ' + tu t /= 1000 return str(time_ps) def check_properties(obj: object, properties: dict, reserved_properties: dict = None): if not reserved_properties: reserved_properties = [] reserved_properties = set(["system", "working_dir_path"] + reserved_properties) error_properties = set([prop for prop in properties.keys() if prop not in obj.__dict__.keys()]) error_properties -= reserved_properties for error_property in error_properties: close_property = difflib.get_close_matches(error_property, obj.__dict__.keys(), n=1, cutoff=0.01) close_property = close_property[0] if close_property else "" warnings.warn("Warning: %s is not a recognized property. The most similar property is: %s" % ( error_property, close_property)) def create_name(path: str = None, prefix: str = None, step: str = None, name: str = None) -> str: """ Return file name. Args: path (str): Path to the file directory. prefix (str): Prefix added to the name of the file. step (str): String added between the **prefix** arg and the **name** arg of the file. name (str): Name of the file. Returns: str: Composed file name. """ name = '' if name is None else name.strip() if step: if name: name = step + '_' + name else: name = step if prefix: prefix = prefix.replace("/", "_") if name: name = prefix + '_' + name else: name = prefix if path: if name: name = str(Path(path).joinpath(name)) else: name = path return name def write_failed_output(file_name: str): with open(file_name, 'w') as f: f.write('Error\n') def rm(file_name: str) -> str: try: file_path = pathlib.Path(file_name) if file_path.exists(): if file_path.is_dir(): shutil.rmtree(file_name) return file_name if file_path.is_file(): Path(file_name).unlink() return file_name except Exception: pass return None def rm_file_list(file_list: typing.Iterable[str], out_log: logging.Logger = None) -> typing.List[str]: removed_files = [f for f in file_list if rm(f)] if out_log: log('Removed: %s' % str(removed_files), out_log) return removed_files def check_complete_files(output_file_list: typing.Iterable[str]) -> bool: for output_file in filter(None, output_file_list): if not (Path(output_file).is_file() and Path(output_file).stat().st_size > 0): return False return True def copy_to_container(container_path: str, container_volume_path: str, io_dict: typing.Mapping, out_log: logging.Logger = None) -> dict: if not container_path: return io_dict unique_dir = str(Path(create_unique_dir()).resolve()) container_io_dict = {"in": {}, "out": {}, "unique_dir": unique_dir} # IN files COPY and assign INTERNAL PATH for file_ref, file_path in io_dict["in"].items(): if file_path: if Path(file_path).exists(): shutil.copy2(file_path, unique_dir) log(f'Copy: {file_path} to {unique_dir}') container_io_dict["in"][file_ref] = str(Path(container_volume_path).joinpath(Path(file_path).name)) else: # Default files in GMXLIB path like gmx_solvate -> input_solvent_gro_path (spc216.gro) container_io_dict["in"][file_ref] = file_path # OUT files assign INTERNAL PATH for file_ref, file_path in io_dict["out"].items(): if file_path: container_io_dict["out"][file_ref] = str(Path(container_volume_path).joinpath(Path(file_path).name)) return container_io_dict def copy_to_host(container_path: str, container_io_dict: dict, io_dict: dict): if not container_path: return # OUT files COPY for file_ref, file_path in container_io_dict["out"].items(): if file_path: container_file_path = str(Path(container_io_dict["unique_dir"]).joinpath(Path(file_path).name)) if Path(container_file_path).exists(): shutil.copy2(container_file_path, io_dict["out"][file_ref]) def create_cmd_line(cmd: typing.Iterable[str], container_path: str = '', host_volume: str = None, container_volume: str = None, container_working_dir: str = None, container_user_uid: str = None, container_shell_path: str = None, container_image: str = None, out_log: logging.Logger = None, global_log: logging.Logger = None) -> typing.List[str]: container_path = container_path or '' if container_path.endswith('singularity'): log('Using Singularity image %s' % container_image, out_log, global_log) if not Path(container_image).exists(): log(f"{container_image} does not exist trying to pull it", out_log, global_log) container_image_name = str(Path(container_image).with_suffix('.sif').name) singularity_pull_cmd = [container_path, 'pull', '--name', container_image_name, container_image] try: from biobb_common.command_wrapper import cmd_wrapper cmd_wrapper.CmdWrapper(singularity_pull_cmd, out_log).launch() if Path(container_image_name).exists(): container_image = container_image_name else: raise FileNotFoundError except FileNotFoundError: log(f"{' '.join(singularity_pull_cmd)} not found", out_log, global_log) raise FileNotFoundError singularity_cmd = [container_path, 'exec', '-e', '--bind', host_volume + ':' + container_volume, container_image] # If we are working on a mac remove -e option because is still no available if platform == "darwin": if '-e' in singularity_cmd: singularity_cmd.remove('-e') cmd = ['"' + " ".join(cmd) + '"'] singularity_cmd.extend([container_shell_path, '-c']) return singularity_cmd + cmd elif container_path.endswith('docker'): log('Using Docker image %s' % container_image, out_log, global_log) docker_cmd = [container_path, 'run'] if container_working_dir: docker_cmd.append('-w') docker_cmd.append(container_working_dir) if container_volume: docker_cmd.append('-v') docker_cmd.append(host_volume + ':' + container_volume) if container_user_uid: docker_cmd.append('--user') docker_cmd.append(container_user_uid) docker_cmd.append(container_image) cmd = ['"' + " ".join(cmd) + '"'] docker_cmd.extend([container_shell_path, '-c']) return docker_cmd + cmd elif container_path.endswith('pcocc'): # pcocc run -I racov56:pmx cli.py mutate -h log('Using pcocc image %s' % container_image, out_log, global_log) pcocc_cmd = [container_path, 'run', '-I', container_image] if container_working_dir: pcocc_cmd.append('--cwd') pcocc_cmd.append(container_working_dir) if container_volume: pcocc_cmd.append('--mount') pcocc_cmd.append(host_volume + ':' + container_volume) if container_user_uid: pcocc_cmd.append('--user') pcocc_cmd.append(container_user_uid) cmd = ['\\"' + " ".join(cmd) + '\\"'] pcocc_cmd.extend([container_shell_path, '-c']) return pcocc_cmd + cmd else: # log('Not using any container', out_log, global_log) return cmd def get_doc_dicts(doc: str): regex_argument = re.compile(r'(?P<argument>\w*)\ *(?:\()(?P<type>\w*)(?:\)):?\ *(?P<optional>\(\w*\):)?\ *(?P<description>.*?)(?:\.)\ *(?:File type:\ *)(?P<input_output>\w+)\.\ *(\`(?:.+)\<(?P<sample_file>.*?)\>\`\_\.)?\ *(?:Accepted formats:\ *)(?P<formats>.+)(?:\.)?') regex_argument_formats = re.compile(r"(?P<extension>\w*)\ *(\(\ *)\ *edam\ *:\ *(?P<edam>\w*)") regex_property = re.compile(r"(?:\*\ *\*\*)(?P<property>.*?)(?:\*\*)\ *(?:\(\*)(?P<type>\w*)(?:\*\))\ *\-\ ?(?:\()(?P<default_value>.*?)(?:\))\ *(?:(?:\[)(?P<wf_property>WF property)(?:\]))?\ *(?:(?:\[)(?P<range_start>[\-]?\d+(?:\.\d+)?)\~(?P<range_stop>[\-]?\d+(?:\.\d+)?)(?:\|)?(?P<range_step>\d+(?:\.\d+)?)?(?:\]))?\ *(?:(?:\[)(.*?)(?:\]))?\ *(?P<description>.*)") regex_property_value = re.compile(r"(?P<value>\w*)\ *(?:(?:\()(?P<description>.*?)?(?:\)))?") doc_lines = list(map(str.strip, filter(lambda line: line.strip(), doc.splitlines()))) args_index = doc_lines.index(next(filter(lambda line: line.lower().startswith('args'), doc_lines))) properties_index = doc_lines.index(next(filter(lambda line: line.lower().startswith('properties'), doc_lines))) examples_index = doc_lines.index(next(filter(lambda line: line.lower().startswith('examples'), doc_lines))) arguments_lines_list = doc_lines[args_index+1:properties_index] properties_lines_list = doc_lines[properties_index+1:examples_index] doc_arguments_dict = {} for argument_line in arguments_lines_list: argument_dict = regex_argument.match(argument_line).groupdict() argument_dict['formats'] = {match.group('extension'): match.group('edam') for match in regex_argument_formats.finditer(argument_dict['formats'])} doc_arguments_dict[argument_dict.pop("argument")] = argument_dict doc_properties_dict = {} for property_line in properties_lines_list: property_dict = regex_property.match(property_line).groupdict() property_dict['values'] = None if "Values:" in property_dict['description']: property_dict['description'], property_dict['values'] = property_dict['description'].split('Values:') property_dict['values'] = {match.group('value'): match.group('description') for match in regex_property_value.finditer(property_dict['values']) if match.group('value')} doc_properties_dict[property_dict.pop("property")] = property_dict return doc_arguments_dict, doc_properties_dict def check_argument(path: pathlib.Path, argument: str, optional: bool, module_name: str, input_output: str = None, output_files_created: bool = False, extension_list: typing.List[str] = None, raise_exception: bool = True, check_extensions: bool = True, out_log: logging.Logger = None) -> None: if optional and not path: return None if input_output in ['in', 'input']: input_file = True elif input_output in ['out', 'output']: input_file = False else: unable_to_determine_string = f"{module_name} {argument}: Unable to determine if input or output file." log(unable_to_determine_string, out_log) if raise_exception: raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), unable_to_determine_string) warnings.warn(unable_to_determine_string) if input_file or output_files_created: not_found_error_string = f"Path {path} --- {module_name}: Unexisting {argument} file." if not path.exists(): log(not_found_error_string, out_log) if raise_exception: raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), not_found_error_string) warnings.warn(not_found_error_string) # else: # if not path.parent.exists(): # not_found_dir_error_string = f"Path {path.parent} --- {module_name}: Unexisting {argument} directory." # log(not_found_dir_error_string, out_log) # if raise_exception: # raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), not_found_dir_error_string) # warnings.warn(not_found_dir_error_string) if check_extensions and extension_list: no_extension_error_string = f"{module_name} {argument}: {path} has no extension. If you want to suppress this message, please set the check_extensions property to False" if not path.suffix: log(no_extension_error_string) warnings.warn(no_extension_error_string) else: not_valid_extension_error_string = f"{module_name} {argument}: {path} extension is not in the valid extensions list: {extension_list}. If you want to suppress this message, please set the check_extensions property to False" if not path.suffix[1:].lower() in extension_list: log(not_valid_extension_error_string) warnings.warn(not_valid_extension_error_string)
true
a9860eddd8dfcba31cf19101e9ef7f05e874d202
Python
MarlonIC/demo-clean-architecture-projects-tasks
/tests/application/repositories/test_task_repository.py
UTF-8
3,756
2.734375
3
[ "MIT" ]
permissive
from pytest import fixture, raises from taskit.application.models.task import Task from taskit.application.repositories.errors import EntityNotFoundError from taskit.application.repositories.task_repository import ( TaskRepository, MemoryTaskRepository) def test_task_repository_methods() -> None: abstract_methods = TaskRepository.__abstractmethods__ # type: ignore assert 'add' in abstract_methods assert 'get' in abstract_methods assert 'update' in abstract_methods assert 'delete' in abstract_methods def test_task_repository_memory_implementation() -> None: assert issubclass(MemoryTaskRepository, TaskRepository) def test_memory_task_repository_load() -> None: memory_task_repository = MemoryTaskRepository() tasks_dict = { 'T-1': Task("Buy the milk") } memory_task_repository.load(tasks_dict) assert memory_task_repository.tasks == tasks_dict @fixture def memory_task_repository() -> MemoryTaskRepository: memory_task_repository = MemoryTaskRepository() tasks_dict = { 'T-1': Task("Buy the milk"), 'T-2': Task("Make conference presentation"), 'T-3': Task("Clean the kitchen") } memory_task_repository.sequence = 4 memory_task_repository.load(tasks_dict) return memory_task_repository def test_memory_task_repository_get( memory_task_repository: MemoryTaskRepository) -> None: task = memory_task_repository.get('T-3') assert task.name == "Clean the kitchen" def test_memory_task_repository_get_not_found( memory_task_repository: MemoryTaskRepository) -> None: with raises(EntityNotFoundError): memory_task_repository.get('MISSING') def test_memory_task_repository_add( memory_task_repository: MemoryTaskRepository) -> None: task = Task("Improve the repository") memory_task_repository.add(task) assert len(memory_task_repository.tasks) == 4 assert memory_task_repository.tasks['T-4'] == task assert memory_task_repository.sequence == 5 def test_memory_task_repository_add_with_uid( memory_task_repository: MemoryTaskRepository) -> None: task = Task("Improve the repository") task.uid = "ABC123" memory_task_repository.add(task) assert len(memory_task_repository.tasks) == 4 assert memory_task_repository.tasks['ABC123'] == task assert memory_task_repository.sequence == 5 def test_memory_task_repository_update( memory_task_repository: MemoryTaskRepository) -> None: task = Task("Buy the milk and the eggs") task.uid = 'T-1' assert memory_task_repository.tasks['T-1'].name == "Buy the milk" memory_task_repository.update(task) assert len(memory_task_repository.tasks) == 3 assert memory_task_repository.tasks['T-1'].name == ( "Buy the milk and the eggs") def test_memory_task_repository_update_not_found( memory_task_repository: MemoryTaskRepository) -> None: task = Task("Fix my bike") task.uid = 'T-MISSING' with raises(EntityNotFoundError): memory_task_repository.update(task) assert len(memory_task_repository.tasks) == 3 def test_memory_task_repository_delete( memory_task_repository: MemoryTaskRepository) -> None: task = memory_task_repository.tasks['T-1'] task.uid = 'T-1' memory_task_repository.delete(task) assert len(memory_task_repository.tasks) == 2 assert memory_task_repository.tasks.get('T-1') is None def test_memory_task_repository_delete_not_found( memory_task_repository: MemoryTaskRepository) -> None: task = Task("Fix my bike") task.uid = 'T-MISSING' with raises(EntityNotFoundError): memory_task_repository.delete(task) assert len(memory_task_repository.tasks) == 3
true
9e4d32e4b2144edc307879631f3eaa238e4b35b4
Python
niteshsurtani/Personal_Assistant
/preprocessing_tools/category_disambiguator/date_disambiguator.py
UTF-8
11,867
2.53125
3
[]
no_license
import os import nltk import re from PATH_CONSTANTS import * def normalizeParse(extendedNERAnalyzedParse): fl = 0 for key,tokenInfoDict in extendedNERAnalyzedParse.iteritems(): if(tokenInfoDict["NER"] == "DATE" and fl == 0): fl = 1 elif(tokenInfoDict["NER"] == "DATE" and fl == 1): tokenInfoDict["NER"] = "0" tokenInfoDict["NormalizedNER"] = "0" else: fl = 0 return extendedNERAnalyzedParse def getNumberOfDates(NERAnalyzedParse,chunkedParse): dateList = {} rangeIdentifiers = loadSeedlist(DISAMBIGUATOR_DATE_RANGE_PREPOSITIONS) # Return tokens of dates that are in range NERAnalyzedParse = normalizeParse(NERAnalyzedParse) rangeDateKeys = getRangeDates(rangeIdentifiers,NERAnalyzedParse,dateList,chunkedParse) # print "List ============ " # print dateList # All other dates are exact dates getExactDates(NERAnalyzedParse,dateList,rangeDateKeys) # print "List ============ " # print dateList return dateList def loadSeedlist(fileName): seedlist = [] with open(fileName) as f: line = f.readline().strip() seedlist = line.split(",") return seedlist def getRangeDates(rangeIdentifiers,NERAnalyzedParse,dateList,chunkedParse): dateKeys = [] for key,tokenInfoDict in NERAnalyzedParse.iteritems(): for word in rangeIdentifiers: if(tokenInfoDict["word"] == word): # Check if next NNP is Date if(isNextNPDate(key,NERAnalyzedParse,chunkedParse)): # Pick next two dates as range rangeDates = getNextTwoRangeDates(key,NERAnalyzedParse,dateKeys) # Simple comparison of dates dateListLength = len(dateList) dateRange = {"range":{'min':"",'max':""},"exact":""} dateList[dateListLength] = dateRange if(rangeDates[0] < rangeDates[1]): dateList[dateListLength]['range']['min'] = rangeDates[0] dateList[dateListLength]['range']['max'] = rangeDates[1] else: dateList[dateListLength]['range']['min'] = rangeDates[1] dateList[dateListLength]['range']['max'] = rangeDates[0] return dateKeys def getNextTwoRangeDates(key,NERAnalyzedParse,dateKeys): dateList = [] count = 0 parseLength = len(NERAnalyzedParse) dateFlag = 0 for index in range(key+1,parseLength+1): if(NERAnalyzedParse[index]["NER"] == "DATE"): if(dateFlag == 0): dateFlag = 1 date = NERAnalyzedParse[index]["NormalizedNER"] else: if(dateFlag == 1): dateList.append(date) dateKeys.append(index-1) count += 1 if(count == 2): break dateFlag = 0 return dateList def getNextNPChunkKeys(key,chunkedParse): # Reaching key token count = 0 chunk_start = 0 chunk_end = 0 matchedIndex = 0 tokens = chunkedParse.split() tokens_size = len(tokens) for index in range(0,tokens_size): token = tokens[index] if (token[0]!='('): count += 1; if(count == key): matchedIndex = index break # Find next NP chunk in_brak = 0 start = 0 # Start matching the in_brak when first NP matched flag = 0 for index in range(matchedIndex+1, tokens_size): token = tokens[index] if(start == 1 and token[0] == '('): in_brak += 1 elif(start == 1 and token[len(token)-1] == ')'): # If token[0] == ')', it is considered as a word and not parse ). for i in range(1,len(token)): if(token[i] == ')'): in_brak -= 1 if(in_brak == 0): flag = 1 chunk_end = index break if(start == 0 and token in ("(NP","(NP-TMP")): if(tokens[index + 1] in ("(NP","(NP-TMP")): continue chunk_start = index start = 1 in_brak += 1 if(flag == 1): break # Map chunk_start, chunk_end to token index token_start = 1 token_end = 1 count = 0 mapper = 0 flag = 0 for index in range(0,tokens_size): token = tokens[index] if (token[0]!='('): mapper += 1; if(flag == 0 and count >= chunk_start): token_start = mapper flag = 1 elif(flag == 1 and count >= chunk_end): token_end = mapper break count += 1 return token_start, token_end def isNextNPDate(key,NERAnalyzedParse,chunkedParse): chunk_start, chunk_end = getNextNPChunkKeys(key,chunkedParse) # print "Chunk = ", # print chunk_start, chunk_end parseLength = len(NERAnalyzedParse) for index in range(chunk_start,chunk_end+1): if(NERAnalyzedParse[index]["NER"] == "DATE"): return 1 else: return 0 def getExactDates(NERAnalyzedParse,dateList,dateKeys): for key,tokenInfoDict in NERAnalyzedParse.iteritems(): if(tokenInfoDict["NER"] == "DATE"): if key not in dateKeys: dateListLength = len(dateList) if type(tokenInfoDict["NormalizedNER"]) == dict: dateList[dateListLength] = tokenInfoDict["NormalizedNER"] else: dateRange = {"range":"","exact":""} dateList[dateListLength] = dateRange dateList[dateListLength]['exact'] = tokenInfoDict["NormalizedNER"] def disambiguateDates(dateList,numDates,chunkedParse): dateDF = {} if(numDates == 2): dateComparison = [] if(dateList[0]['exact'] == ""): dateComparison.append(dateList[0]['range']['min']) else: dateComparison.append(dateList[0]['exact']) if(dateList[1]['exact'] == ""): dateComparison.append(dateList[1]['range']['min']) else: dateComparison.append(dateList[1]['exact']) if (dateComparison[0] <= dateComparison[1]): dateDF['start_date'] = dateList[0] dateDF['end_date'] = dateList[1] else: dateDF['start_date'] = dateList[1] dateDF['end_date'] = dateList[0] return dateDF ''' elif(numDates == 1): start_date = "" end_date = "" prepositionChunkList = getDatePPChunks(dateList,chunkedParse) print prepositionChunkList for chunk in prepositionChunkList: prep = extractPrepositionFromChunk(chunk) date = extractDateFromChunk(chunk) if(checkPrepositionSource(prep)): start_date = date dateDF["start_date"] = start_date elif(checkPrepositionDestination(prep)): end_date = date dateDF["end_date"] = end_date if(len(dateDF) == numDates): # print "Rule 1 applied" return dateDF # Step 2. If no information from step 1, then use verbs verbInflected = "" verbChunkList = getDateVPChunks(dateList,chunkedParse) # print "Chunk List" # print verbChunkList for chunk in verbChunkList: verbInflected = extractVerbFromChunk(chunk) if(verbInflected != ""): verbInflected = verbInflected.lower() verb = extractRootForm(verbInflected,extendedNERAnalyzedParse) # print "Root verb form = " + verb date = extractDateFromChunk(chunk) # print "Date = "+date if(checkVerbSource(verb)): start_date = date dateDF["start_date"] = start_date elif(checkVerbDestination(verb)): end_date = date dateDF["end_date"] = end_date if(len(dateDF) == numDates): # print "Rule 2 applied" return dateDF # Step 3. If no verb matched, find SOURCE and DESTINATION keywords in the query. start_datePosition = 0 end_datePosition = 0 start_datePosition = findSourcePosition(extendedNERAnalyzedParse,DISAMBIGUATOR_DATE_SOURCE_KEYWORDS) end_datePosition = findDestinationPosition(extendedNERAnalyzedParse,DISAMBIGUATOR_DATE_DESTINATION_KEYWORDS) if(start_datePosition !=0 and end_datePosition != 0): if(start_datePosition < end_datePosition): start_date = dateList[0] end_date = dateList[1] dateDF["start_date"] = start_date dateDF["end_date"] = end_date else: start_date = dateList[1] end_date = dateList[0] dateDF["start_date"] = start_date dateDF["end_date"] = end_date elif(start_datePosition !=0 and end_datePosition == 0): # Pick date from dateList not in dateDF['end_date'] if(numDates == 1): dateDF["start_date"] = dateList[0] elif(numDates == 2): dateDestination = dateDF["end_date"] for loc in dateList: if(loc!=dateDestination): start_date = loc dateDF["start_date"] = start_date elif(start_datePosition ==0 and end_datePosition != 0): if(numDates == 1): dateDF["end_date"] = dateList[0] elif(numDates == 2): dateSource = dateDF["start_date"] for loc in dateList: if(loc!=dateSource): end_date = loc dateDF["end_date"] = end_date if(len(dateDF) == numDates): # print "Rule 3 applied" return dateDF # Step 4. Treat first date as Source and second date as Destination. if(len(dateDF) == 1): if(start_date == ""): dateDestination = dateDF["end_date"] for loc in dateList: if(loc!=dateDestination): start_date = loc dateDF["start_date"] = start_date elif(end_date == ""): dateSource = dateDF["start_date"] for loc in dateList: if(loc!=dateSource): end_date = loc dateDF["end_date"] = end_date else: start_date = dateList[0] dateDF["start_date"] = start_date if(numDates == 2): end_date = dateList[1] dateDF["end_date"] = end_date # print "Rule 4 applied" return dateDF def checkInList(word,fileName): seedlist = [] with open(fileName) as f: line = f.readline().strip() seedlist = line.split(",") if word in seedlist: return 1 return 0 def getDatePPChunks(dateList,parse): parse = re.sub(r'\(',"",parse) parse = re.sub(r'\)',"",parse) parse = parse.split(' ') print parse indexesPP = [] indexesDate = [] datePPChunks=[] for index, postag in enumerate(parse): if postag == 'PP' : indexesPP.append(index) if postag in dateList: indexesDate.append(index) resultIndexes = sorted(indexesPP + indexesDate) print resultIndexes for index, position in enumerate(resultIndexes): if position in indexesDate: datePPChunks.append(parse[resultIndexes[index-1]:(resultIndexes[index]+1)]) return datePPChunks def extractPrepositionFromChunk(chunk): for index, postag in enumerate(chunk): if postag == 'IN' or postag == 'TO': return chunk[index+1] def extractDateFromChunk(chunk): for index, postag in enumerate(chunk): if postag == 'NNP': return chunk[index+1] def checkPrepositionSource(preposition): return checkInList(preposition,DISAMBIGUATOR_DATE_SOURCE_PREPOSITIONS) def checkPrepositionDestination(preposition): return checkInList(preposition,DISAMBIGUATOR_DATE_DESTINATION_PREPOSITIONS) def getDateVPChunks(dateList,parse): parse = re.sub(r'\(',"",parse) parse = re.sub(r'\)',"",parse) parse = parse.split(' ') indexesVP = [] indexesDate = [] dateVPChunks=[] for index, postag in enumerate(parse): if postag == 'VP' : indexesVP.append(index) if postag in dateList: indexesDate.append(index) resultIndexes = sorted(indexesVP + indexesDate) for index, position in enumerate(resultIndexes): if position in indexesDate: dateVPChunks.append(parse[resultIndexes[index-1]:(resultIndexes[index]+1)]) return dateVPChunks def extractVerbFromChunk(chunk): for index, postag in enumerate(chunk): if(postag[:2] == "VB"): return chunk[index+1] return "" def extractRootForm(verbInflected,extendedNERAnalyzedParse): for key,tokenInfoDict in extendedNERAnalyzedParse.iteritems(): if(tokenInfoDict["word"].lower() == verbInflected): return tokenInfoDict["lemma"].lower() def checkVerbSource(verb): return checkInList(verb,DISAMBIGUATOR_DATE_SOURCE_VERB) def checkVerbDestination(verb): return checkInList(verb,DISAMBIGUATOR_DATE_DESTINATION_VERB) def loadSeedlist(fileName): seedlist = [] with open(fileName) as f: line = f.readline().strip() seedlist = line.split(",") return seedlist def findPosition(seedlist,extendedNERAnalyzedParse): for key,tokenInfoDict in extendedNERAnalyzedParse.iteritems(): for word in seedlist: if(tokenInfoDict["word"].lower() == word): return key return 0 def findSourcePosition(extendedNERAnalyzedParse,fileName): sourceList = loadSeedlist(fileName) return findPosition(sourceList,extendedNERAnalyzedParse) def findDestinationPosition(extendedNERAnalyzedParse,fileName): destinationList = loadSeedlist(fileName) return findPosition(destinationList,extendedNERAnalyzedParse) '''
true
42b39d2ed1edb328b8ecf1bcae7b71e68824ba34
Python
wurijie/mnist-check
/check.py
UTF-8
1,228
2.734375
3
[]
no_license
#--*-- encoding: UTF-8 --*-- import torch from PIL import Image import numpy as np from flask import Flask, request, render_template import base64 from my_mnist import CNN #-------下面部分为web容器代码------- app = Flask(__name__) #用于接收手写的图片 @app.route('/cnn', methods=["POST"]) def test(): imgdata = base64.b64decode(request.form['img'][22:]) with open('temp.png', 'wb') as fd: fd.write(imgdata) # 通过之前的模型识别用户手写的图片 return transfer() #返回index.html,用户书写数字页面 @app.route('/') def index(): return render_template( 'index.html' ) #-------下面部分为神经网络验证部分---------- #使用my_mnist中定义的神经网络 cnn = CNN() cnn.load_state_dict(torch.load('net_params.pkl')) #加载训练的模型结果 def transfer(): #将网页手写的图片转换成28*28,并转成单通道灰度图片 np_data = np.array(Image.open('./temp.png').resize((28, 28),Image.ANTIALIAS).convert('L')) t_data = torch.from_numpy(np_data).unsqueeze(dim=0).unsqueeze(dim=0).type(torch.FloatTensor)/255.0 predict = cnn(t_data) num = torch.max(predict, 1)[1].numpy() return str(num[0])
true
7d7d383f90c35f33ccd9ab8aba22b6e1d89308dd
Python
ricardosilva1998/pythonBeginnerCourse
/cicloFor.py
UTF-8
60
4.03125
4
[]
no_license
for x in range(0,5): print("Valor de x é: ",x)
true
66f704736e80b36014fbb8f6655fb65c4ced9efe
Python
jlehenbauer/python-projects-public
/chess/main.py
UTF-8
482
3.234375
3
[]
no_license
from chess import Board def main(): c = Board() c.set_standard() while True: print(c) if c.TURN: print("White, it's your turn.") # TODO: create verification for chess notation c.move(input("Enter your move: ")) else: print("Black, it's your turn.") # TODO: create verification for chess notation c.move(input("Enter your move: ")) if __name__ == "__main__": main()
true
a936d7678d62da4bcc536950023d57e372af5f6f
Python
onedayatatime0923/Cycle_Mcd_Gan
/src/visualizer/train_visualizer.py
UTF-8
1,607
2.9375
3
[]
no_license
from visualizer.base_visualizer import BaseVisualizer class TrainVisualizer(BaseVisualizer): def __init__(self, opt, dataset): super(TrainVisualizer, self).__init__(opt.batchSize, len(dataset), opt.logPath, opt.displayWidth) # init argument: stepSize, totalSize, displayWidth, logPath): def __call__(self, name, epoch, data= []): message = '\x1b[2K\r' message += '{} Epoch:{}|[{}/{} ({:.0f}%)]|'.format( name, epoch , self.nStep * self.stepSize, self.totalSize, 100. * self.nStep * self.stepSize / self.totalSize) for i in data: name = i.replace('loss','') self.data[name] += data[i] message += ' {}:{:.4f}'.format(name, data[i]) self.nStep += 1 message += '|Time: {}'.format( self.timer(self.nStep * self.stepSize / self.totalSize)) print(message, end = '', flush = True) def end(self, name, epoch, data): message = '\x1b[2K\r' message += '{} Epoch:{}|[{}/{} ({:.0f}%)]|Time: {}\n'.format( name, epoch , self.totalSize, self.totalSize, 100., self.timer(1)) message += 'Loss:\n' for name in self.data: message += '{:>25}: {:.4f}\n'.format(name, self.data[name]/ self.nStep) if len(data) > 0: message += 'Accu, mIOU:\n' for i in data: name = i.replace('miou','') message += '{:>25}: Accu: {:>8.4f}% | mIOU: {:>8.4f}\n'.format(name, *data[i]) print(message) self.reset()
true
3c922a6b68a7521e99dceb1a3dd930c024c4d93d
Python
dragonsun7/dsPyLib
/dsPyLib/sound/sound.py
UTF-8
2,249
3.171875
3
[ "MIT" ]
permissive
# -*- coding:utf-8 -*- __author__ = 'Dragon Sun' __date__ = '2019-08-23 14:26:29' import threading import wave import pyaudio def play_wav(file: str): """ 同步播放WAV文件 (需要引用pyaudio) :param file: WAV文件名 """ # define stream chunk chunk = 1024 # open a wav format music wf = wave.open(file, 'rb') # instantiate PyAudio p = pyaudio.PyAudio() # open stream (output=True表示音频输出) fmt = p.get_format_from_width(wf.getsampwidth()) channels = wf.getnchannels() rate = wf.getframerate() # print(f'format: {fmt}\nchannels: {channels}\nrate: {rate}') stream = p.open(format=fmt, channels=channels, rate=rate, frames_per_buffer=chunk, output=True) # read data & play stream data = wf.readframes(chunk) while data: stream.write(data) data = wf.readframes(chunk) # stop stream stream.stop_stream() stream.close() # close PyAudio p.terminate() g_playing_thread = None # 拼音播放线程(同时只能播放一个音频) def play_wav_async(file: str) -> threading.Thread: """ 异步播放WAV文件 (需要引用pyaudio) 注意:同时只能播放一段声音,开始调用前需要等待前一次播放完成 :param file: WAV文件名 :return 播放线程对象 """ def play(): global g_playing_thread if g_playing_thread and g_playing_thread.is_alive(): g_playing_thread.join() g_playing_thread = threading.Thread(target=play_wav, args=(file,)) # 异步播放 g_playing_thread.start() thread = threading.Thread(target=play) thread.start() return thread if __name__ == '__main__': import os filename = os.path.join(os.path.dirname(__file__), '../res/notice.wav') print(f'播放文件:{filename}') print('开始同步播放...') play_wav(filename) print('同步播放完成!\n') print('开始异步播放1...') t1 = play_wav_async(filename) print('异步播放1调用完成!') print('开始异步播放2...') t2 = play_wav_async(filename) print('异步播放2调用完成!')
true
c25945321fc9bc3903ff215eed9368a1acafd776
Python
kamyu104/LeetCode-Solutions
/Python/design-a-number-container-system.py
UTF-8
939
3.421875
3
[ "MIT" ]
permissive
# Time: ctor: O(1) # change: O(logn) # find: O(1) # Space: O(n) from sortedcontainers import SortedList # sorted list class NumberContainers(object): def __init__(self): self.__idx_to_num = {} self.__num_to_idxs = collections.defaultdict(SortedList) def change(self, index, number): """ :type index: int :type number: int :rtype: None """ if index in self.__idx_to_num: self.__num_to_idxs[self.__idx_to_num[index]].remove(index) if not self.__num_to_idxs[self.__idx_to_num[index]]: del self.__num_to_idxs[self.__idx_to_num[index]] self.__idx_to_num[index] = number self.__num_to_idxs[number].add(index) def find(self, number): """ :type number: int :rtype: int """ return self.__num_to_idxs[number][0] if number in self.__num_to_idxs else -1
true
89035942f5c54284b6b67ed26fb5910e455a6a8c
Python
pongo/rapturebot
/src/dayof/valentine_day/date_checker.py
UTF-8
520
3.453125
3
[ "MIT" ]
permissive
from datetime import datetime def is_day_active() -> bool: """ Сегодня 14-е фев? """ return datetime.today().strftime( "%m-%d") == '02-14' # месяц-день. Первое января будет: 01-01 def is_today_ending() -> bool: """ Сегодня 15-е фев? """ return datetime.today().strftime("%m-%d") == '02-15' def is_morning() -> bool: """ Сейчас утро? """ hour = datetime.now().hour return hour == 9 or hour == 10
true
90f7c13a5aad8c0ba1b7de3cd02bee280d7a20d0
Python
JamesRobEaston/ForestFireSimulator
/Tree.py
UTF-8
993
3.71875
4
[]
no_license
class Tree: def __init__(self, isDestroyed, isOnFire): self.isDestroyed = isDestroyed self.isOnFire = isOnFire #Sets isOnFire to value of boolean #Precondition : boolean is a boolean #Postcondition : isOnFire will be equivalent to boolean def setIsOnFire(self, boolean): if not self.isDestroyed: boolean = bool(boolean) self.isOnFire = boolean #Sets isDestroyed to value of boolean #Precondition : boolean is a boolean #Postcondition : isDestroyed will be equivalent to boolean def setIsDestroyed(self, boolean): if self.isOnFire: boolean = bool(boolean) self.isDestroyed = boolean self.isOnFire = False def toString(self): returnString = "" if self.isDestroyed: returnString = "|D|" elif self.isOnFire: returnString ="|F|" else: returnString = "|T|" return returnString
true
e017097b15977c837e0a0342232ae97b65a9da66
Python
zhangjianyu1979/netsoft-2021-paper
/conformance-checker/flows.py
UTF-8
1,793
2.671875
3
[]
no_license
import re class FlowLog: def __init__(self, timestamp, deviceId): self.timestamp = timestamp self.deviceId = deviceId class EthPacket: def __init__(self, src, dst): self.src = ":".join(re.findall("([0-9a-fA-F]{2})",src)) self.dst = ":".join(re.findall("([0-9a-fA-F]{2})",dst)) class OutputFlowLog(FlowLog): def __init__(self, timestamp, deviceId, dl_src, dl_dst, output_action,to_host): super().__init__(timestamp, deviceId) self.dl_src = dl_src self.dl_dst = dl_dst self.output_action = output_action self.to_host=to_host def __str__(self): return "%s-%s -> %s" % (self.dl_src,self.dl_dst,self.output_action) def get_next_device(self,dl_src,dl_dst): if self.dl_src==dl_src and self.dl_dst==dl_dst: return self.output_action elif self.dl_src==dl_src and self.dl_dst is None: return self.output_action else: return None class DropFlowLog(FlowLog): def __init__(self, timestamp, deviceId, dl_src, dl_dst, output_action): super().__init__(timestamp, deviceId) self.dl_src = dl_src self.dl_dst = dl_dst self.output_action = output_action def __str__(self): ret = "" if (self.dl_src is not None): ret += "src= %s " % self.dl_src if (self.dl_dst is not None): ret += "dst= %s " % self.dl_dst ret += " DROP" return ret def isDropping(self, packet): same_src = (self.dl_src == packet.src) same_dst = (self.dl_dst == packet.dst) if self.dl_src is None: return same_dst if self.dl_dst is None: return same_src else: return same_dst and same_src
true
16a02cb80cf4d2f856905a69287426d542dc4243
Python
hyperrixel/aaion
/python/simple_command_line.py
UTF-8
8,256
2.828125
3
[ "Apache-2.0" ]
permissive
from datetime import datetime, timedelta from time import sleep from typing import Optional def createshiftplan(hours_to_shift: int, days_to_shift: int, align_to_end: Optional[bool] = True) -> list: result = [] if hours_to_shift < days_to_shift: pass else: daily_average_floor = int(hours_to_shift / days_to_shift) rest_hours = hours_to_shift % days_to_shift: if rest_hours == 0: for i in range(days_to_shift): result.append(daily_average_floor) else: if align_to_end: for i in range(days_to_shift): if i >= days_to_shift - rest_hours: result.append(daily_average_floor + 1) else: result.append(daily_average_floor) else: for i in range(days_to_shift): if i < rest_hours: result.append(daily_average_floor + 1) else: result.append(daily_average_floor) return result def changeday(date: int, daycount: int) -> int: return datetime.timestamp(datetime.fromtimestamp(date) + timedelta(days=daycount)) def getmidnight(date: int) -> int: return datetime.timestamp(datetime.combine(datetime.fromtimestamp(date), datetime.min.time())) def inttotimeunits(date: int) -> dict: timeunits = {} timeunits['days'] = int(date // 86400) date -= timeunits['days'] * 86400 timeunits['hours'] = int(date // 3600) date -= timeunits['hours'] * 3600 timeunits['minutes'] = int(date // 60) date -= timeunits['minutes'] * 60 timeunits['seconds'] = int(date) return timeunits now = int(datetime.timestamp(datetime.today())) today = getmidnight(now) ############# # TIMEZONES # ############# time_success = False while not time_success: print('Input current timezone GMT +/- hours:') time_success = True answer = input('[?] ') try: personal_from = int(answer) except Exception: time_success = False print('[!] Failed to convert your input to GMT difference.') if personal_from > 12 or personal_from < -12: time_success = False print('[!] GMT difference must be between +/- 12.') time_success = False while not time_success: print('Input target timezone GMT +/- hours:') time_success = True answer = input('[?] ') try: personal_to = int(answer) except Exception: time_success = False print('[!] Failed to convert your input to GMT difference.') if personal_from > 12 or personal_from < -12: time_success = False print('[!] GMT difference must be between +/- 12.') shift_hours_to_shift = personal_to - personal_from if shift_hours_to_shift > 12 or shift_hours_to_shift < -12: print('[!] Your shift is {} hours.'.format(shift_hours_to_shift)) if shift_hours_to_shift > 12: temp_shift = -24 + shift_hours_to_shift else: temp_shift = 24 + shift_hours_to_shift answer = '' while answer not in ['Y', 'N']: print('Would you prefer to shift {} hours instead? [Y]/[N]'.format(temp_shift)) answer = input('[?] ') answer = answer.upper() if answer == 'Y': shift_hours_to_shift = temp_shift print('[.] Your shift is {} hours.'.format(shift_hours_to_shift)) ########## # TRAVEL # ########## time_success = False while not time_success: print('Please enter date of departure of your travel in your time zone in format MM/DD/YYYY HH:MM') answer = input('[?] ') time_success = True try: travel_departure_time = int(datetime.timestamp(datetime.strptime(answer, r'%m/%d/%Y %H:%M'))) except Exception: time_success = False print('[!] Failed to convert your input to time.') if travel_departure_time <= now: time_success = False print('[!] Departure should be in the future.') time_success = False while not time_success: print('Please enter date of arrival of your travel in your time zone in format MM/DD/YYYY HH:MM') answer = input('[?] ') time_success = True try: travel_arrival_time = int(datetime.timestamp(datetime.strptime(answer, r'%m/%d/%Y %H:%M'))) except Exception: time_success = False print('[!] Failed to convert your input to time.') if travel_arrival_time <= travel_departure_time: time_success = False print('[!] Arrival should be at least a second later than departure.') ############### # SLEEP HOURS # ############### time_success = False while not time_success: print('Input the hour of day when you usually go to sleep [0-23]:') time_success = True answer = input('[?] ') try: sleep_from = int(answer) except Exception: time_success = False print('[!] Failed to convert your input to hours.') if sleep_from > 23 or sleep_from < 0: time_success = False print('[!] Hours must be between 0 and 23.') time_success = False while not time_success: print('Input the hour of day when you usually wake up [0-23]:') time_success = True answer = input('[?] ') try: sleep_to = int(answer) except Exception: time_success = False print('[!] Failed to convert your input to GMT difference.') if sleep_to > 23 or sleep_to < 0: time_success = False print('[!] Hours must be between 0 and 23.') sleep_duration = sleep_to - sleep_from if sleep_duration < 0: sleep_duration += 24 print('[.] You used to sleep {} hour(s) daily.'.format(sleep_duration)) ################ # SHIFT PERIOD # ################ answer = '' shift_before = False while answer not in ['Y', 'N']: print('Would you like to shift your sleep before the travel? [Y]/[N]') answer = input('[?] ') answer = answer.upper() if answer == 'Y': shift_before = True if shift_before: time_success = False while not time_success: print('Please enter date of the beginning of your shift period MM/DD/YYYY') answer = input('[?] ') time_success = True try: shift_begin_time = int(datetime.timestamp(datetime.strptime(answer, r'%m/%d/%Y'))) except Exception: time_success = False print('[!] Failed to convert your input to time.') if shift_begin_time < today or shift_begin_time >= getmidnight(travel_departure_time): time_success = False print('[!] Shift should begin not earlier than today.') shift_end_time = getmidnight(travel_departure_time) else: time_success = False while not time_success: print('Please enter date of the end of your shift period MM/DD/YYYY') answer = input('[?] ') time_success = True try: shift_end_time = int(datetime.timestamp(datetime.strptime(answer, r'%m/%d/%Y'))) except Exception: time_success = False print('[!] Failed to convert your input to time.') if shift_end_time <= travel_arrival_time: time_success = False print('[!] Shift should begin not earlier than the end of your travel.') shift_begin_time = getmidnight(travel_arrival_time) shift_duration = shift_end_time - shift_begin_time shift_dict = inttotimeunits(shift_duration) print('[.] Your shift period is {} seconds long, it means:'.format(shift_duration), end='') for key, value in shift_dict.items(): if value > 0: print(' {} {}'.format(value, key), end='') print('.') shift_plan = createshiftplan(shift_hours_to_shift, shift_dict['days']) if shift_hours_to_shift > 0: print('[.] You have a FORWARD shift plan:') else: print('[.] You have a BACKWARD shift plan:') for i, row in enumerate(shift_plan, 1): print('--- Day {}, {} hours.'.format(i, row)) # Megkérdezni, akar-e kihagyni alvást.
true
d4909ed738be3152ab8b7a8daab095c613734f35
Python
Harryharries/pythonlearningnote
/Nagel_Schreckenberg.py
UTF-8
2,992
3.34375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Oct 17 16:34:25 2018 @author: js """ import matplotlib.pyplot as plt import numpy as np L = 100 # number of cells steps = 100 # number of time steps density = 0.5 # density of cars vmax = 5 p = 0.3 stepsize = int(1/density) gammaLR=0.0 gammaRL=1 # create initial state; -1 represents an empty site; 0,1,2,3,4,5 velocities a=np.zeros((steps,L))-1 b= np.zeros((steps,L))-1 i=0 while i < L: a[0,i] = 1 b[0, i] = 1 i += stepsize for i in range(1,steps): for j in range(L): if a[i-1,j] > -1: # found a car # current velocity of car velocity = a[i-1,j] # measure number of empty cells in front of car dist = 1 while a[i-1,(j + dist) % L] < 0: dist += 1 # update velocity: increase by one but not more than distance to next car and not more than vmax velupdate = min(velocity+1, dist - 1, vmax) # bring in random variations in speed if np.random.randint(0,101) < p*100: v = max(velupdate - 1, 0) else: v= velupdate # move all cars forward according to their velocity a[i,int(j + v) % L] = v if b[i-1,j] > -1: # found a car # current velocity of car velocity = b[i-1,j] # measure number of empty cells in front of car dist = 1 while b[i-1,(j + dist) % L] < 0: dist += 1 # update velocity: increase by one but not more than distance to next car and not more than vmax velupdate = min(velocity+1, dist - 1, vmax) # bring in random variations in speed if np.random.randint(0,101) < p*100: v = max(velupdate - 1, 0) else: v= velupdate # move all cars forward according to their velocity b[i,int(j + v) % L] = v for j in range(L): if a[i-1,j] == -1 and b[i-1,j] > -1: if np.random.randint(0, 101) < gammaRL * 100: a[i-1,j] = b[i-1,j] b[i - 1, j] = -1 elif b[i-1,j] == -1 and a[i-1,j] > -1: if np.random.randint(0, 101) < gammaLR * 100: b[i - 1, j] = a[i-1,j] a[i - 1, j] = -1 # Prints car positions for i in range(steps): for j in range(L): if a[i,j]== -1: print(".",end='') else: print(int(a[i,j]),end='') print("\n") for j in range(L): if b[i,j]== -1: print(".",end='') else: print(int(b[i,j]),end='') print("\n\n-------------------------------------------------------------------------------------------\n\n") # showing image plt.figure(figsize=(10,10)) plt.title("LIFT") plt.imshow(a, cmap='PuBu_r') plt.show() plt.figure(figsize=(10,10)) plt.title("RIGHT") plt.imshow(b, cmap='PuBu_r') plt.show()
true
9eebab7d45cc971f06a26aadb2eae202056c73d4
Python
samheckle/rapid-pie-movement
/game/scenes/tutorial_scene.py
UTF-8
1,005
2.8125
3
[ "MIT" ]
permissive
import pygame from . import * class TutorialScene(BaseScene): def __init__(self, context): # Create scene and make transparent box over the 'x' BaseScene.__init__(self, context) self.btn = pygame.Surface((50,50), pygame.SRCALPHA, 32) self.btn.convert_alpha() context.screen.blit(self.context.tutorial, (0,0)) self.b = context.screen.blit(self.btn, (1120,25)) def handle_inputs(self, events): for event in events: if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.context.scene = TitleScene(self.context) elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = pygame.mouse.get_pos() if self.b.collidepoint(pos): self.context.scene = TitleScene(self.context) def render_scene(self): pygame.display.flip()
true
def97dbae2829fc40aec4eede644c772684376c1
Python
TosinJia/pythonFiles
/pythonic/c3.py
UTF-8
527
4.21875
4
[]
no_license
a = [1, 2, 3, 4, 5, 6, 7, 8] # a列表中每个元素平方 # 1.for循环 # 2.高阶函数 map # 3.列表推导式 b1 = [i*i for i in a] b2 = [i**2 for i in a] print(b1, b2) # 有选择性地对a列表中筛选出的元素进行平方,推荐使用列表推导式 # 1. map filter 稍复杂些 b3 = [i**2 for i in a if i > 5] print(b3) # set集合推导式 a = {1, 2, 3, 4, 5, 6, 7, 8} b1 = {i**2 for i in a if i > 5} print(b1) # 元组也可以推导 a = (1, 2, 3, 4, 5, 6, 7, 8) b1 = [i**2 for i in a if i > 5] print(b1)
true
67e261ffb27822f7657f17c1d5a61f2d8d515126
Python
juan083/algorithm_learn
/src/python/substring/longest_substring.py
UTF-8
1,089
3.9375
4
[]
no_license
#!/usr/bin/python3 # -*- coding:UTF-8 -*- ''' https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 3. 无重复字符的最长子串 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 思路: 使用滑动窗口的算法 利用i in string 判断是否有重复字符 重点:滑动窗口移动的大小,这个步骤是关键,容易出错的地方 ''' class Solution: def lengthOfLongestSubstring(self, s: str) -> int: strlen = len(s) if strlen <= 1: return strlen max = 0 sub = '' for i in s: if i in sub: max = max if max > len(sub) else len(sub) sub = sub[sub.index(i) + 1:] #print(sub) sub += i print(sub) max = max if max > len(sub) else len(sub) # print(max) return max s = 'abcabcbb' # 3 s = 'bbtablud' # 6 s = 'pwwkew' # 3 s = 'au' # 2 s = 'dvdf' # 3 solution = Solution() ret = solution.lengthOfLongestSubstring(s) print(ret)
true
111503ab68dd199d58d91665e1628623bf1592ed
Python
hillala/hack-rank-solutions
/algorithms/find_digit.py
UTF-8
270
2.734375
3
[]
no_license
#!/bin/python import sys t = int(raw_input().strip()) for a0 in xrange(t): n = int(raw_input().strip()) d=str(n) counter=0 for i in d: if int(i)>0: if n % int(i) ==0: counter=counter+1 print(counter)
true
7de11d6bdc5df6c0eae4d988290094c9916c9b3a
Python
VinuthnaGangula/261714_Py_DailyCommits
/seven_segment_display.py
UTF-8
1,043
3.4375
3
[]
no_license
# To display numbers in as a number in seven segment display list_ = list(map(int, input("Enter number: "))) num_list_1 = ["***", "*", "***", "***", "* *", "***", "***", "***", "***", "***"] num_list_2 = ["* *", "*", " *", " *", "* *", "* ", "* ", " *", "* *", "* *"] num_list_3 = ["* *", "*", "***", "***", "***", "***", "***", " *", "***", "***"] num_list_4 = ["* *", "*", "* ", " *", " *", " *", "* *", " *", "* *", " *"] num_list_5 = ["***", "*", "***", "***", " *", "***", "***", " *", "***", "***"] for i in list_: print(num_list_1[i], end=" ") print() for i in list_: print(num_list_2[i], end=" ") print() for i in list_: print(num_list_3[i], end=" ") print() for i in list_: print(num_list_4[i], end=" ") print() for i in list_: print(num_list_5[i], end=" ") # Sample Input # 1234567890 # Output # * *** *** * * *** *** *** *** *** *** # * * * * * * * * * * * * * * # * *** *** *** *** *** * *** *** * * # * * * * * * * * * * * * * # * *** *** * *** *** * *** *** ***
true
ff170a04db91297bae9c8ae9a7c2c8dc7caf5dda
Python
zopefoundation/zc.i18n
/src/zc/i18n/date.py
UTF-8
3,273
2.765625
3
[ "ZPL-2.1" ]
permissive
############################################################################# # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """ $Id: date.py 2041 2005-06-16 18:34:44Z fred $ """ import datetime import pytz from zope.interface.common.idatetime import ITZInfo def now(request): return datetime.datetime.now(ITZInfo(request)) def format(request, dt=None): if dt is None: dt = now(request) formatter = request.locale.dates.getFormatter( 'dateTime', 'medium') return formatter.format(dt) def normalize(request, dt): """this method normalizes datetime instances by converting them to utc, daylight saving times are also taken into account. This method requires an adapter to get the tzinfo from the request. >>> from zope import component, interface >>> import pytz >>> from zope.interface.common.idatetime import ITZInfo >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> from zope.publisher.browser import TestRequest >>> requestTZ = pytz.timezone('Europe/Vienna') >>> @interface.implementer(ITZInfo) ... @component.adapter(IBrowserRequest) ... def tzinfo(request): ... return requestTZ >>> component.provideAdapter(tzinfo) >>> dt = datetime.datetime(2006,5,1,12) >>> request = TestRequest() The Vienna timezone has a 2 hour offset to utc at this date. >>> normalize(request,dt) datetime.datetime(2006, 5, 1, 10, 0, tzinfo=<UTC>) At this date the timezone has only a one hour offset. >>> dt = datetime.datetime(2006,2,1,12) >>> normalize(request,dt) datetime.datetime(2006, 2, 1, 11, 0, tzinfo=<UTC>) Normalizing UTC to UTC should work also >>> dt = datetime.datetime(2006,5,1,12,tzinfo=pytz.UTC) >>> normalize(request,dt) datetime.datetime(2006, 5, 1, 12, 0, tzinfo=<UTC>) This way too UTC to UTC >>> requestTZ = pytz.UTC >>> dt = datetime.datetime(2006,5,1,12) >>> normalize(request,dt) datetime.datetime(2006, 5, 1, 12, 0, tzinfo=<UTC>) Just so you would know that these are possible - The time that does not exist (defaulting to is_dst=False will raise an index error in this case): >>> requestTZ = pytz.timezone('Europe/Vilnius') >>> dt = datetime.datetime(2006,3,26,3,30) >>> normalize(request,dt) Traceback (most recent call last): ... NonExistentTimeError: 2006-03-26 03:30:00 An ambiguous time: >>> dt = datetime.datetime(2006,10,29,3,30) >>> normalize(request,dt) Traceback (most recent call last): ... AmbiguousTimeError: 2006-10-29 03:30:00 """ if dt.tzinfo is None: tzinfo = ITZInfo(request) dt = tzinfo.localize(dt, is_dst=None) return dt.astimezone(pytz.utc)
true
4c801ddd839dd5adbdd5bddd1abd906c05b11bcd
Python
XiaoyuCong/leetcode
/minPriceFlihts.py
UTF-8
1,534
3.015625
3
[]
no_license
def findCheapestPrice(n, flights, src, dst, K): """ :type n: int :type flights: List[List[int]] :type src: int :type dst: int :type K: int :rtype: int """ dict = {}; for f in flights: if f[0] not in dict: dict[f[0]] = [(f[1],f[2])]; else: dict[f[0]].append((f[1],f[2])); minPrice = [100000000] * n; minPrice[src] = 0; queue = [src]; i = 0; to_update = []; while i <= K and queue: for e in to_update: if minPrice[e[0]] > e[1]: minPrice[e[0]] = e[1]; del to_update; to_update = []; next_queue = []; for q in queue: if q in dict: for e in dict[q]: if minPrice[q] + e[1] < minPrice[e[0]]: if e[0] not in queue: minPrice[e[0]] = minPrice[q] + e[1]; else: to_update.append((e[0], minPrice[q] + e[1])); if e[0] not in next_queue: next_queue.append(e[0]); del queue; queue = next_queue; i = i + 1; for e in to_update: if minPrice[e[0]] > e[1]: minPrice[e[0]] = e[1]; if minPrice[dst] < 100000000: return minPrice[dst]; else: return -1; flights = [[0,1,500],[1,2,300],[0,2,1000],[0,3,200],[1,4,100],[1,5,100],[3,2,400],[2,6,200],[6,7,200]]; print(findCheapestPrice(8,flights,0,5,2));
true
982da6904fc278d9066debd6e7b064ba46c2865d
Python
Karthik-Sankar/ML
/Simple Linear Regression/Cricketchirps vs Temprature/cricchirpsvstemp.py
UTF-8
911
3.296875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 11 21:03:14 2018 @author: kay """ #Cricket Chirps vs Temprature dataset import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_excel("cricket.xls", sheetname=0) #matrix of feature cricket_chirps = dataset.iloc[:,1:2].values #dependent vector temp = dataset.iloc[:,-1].values #test train split from sklearn.cross_validation import train_test_split Xtrain, Xtest, ytrain, ytest = train_test_split(cricket_chirps, temp, test_size=0.2) #Model creation from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(Xtrain,ytrain) ypred = regressor.predict(Xtest) #model visualisation plt.plot(Xtrain,regressor.predict(Xtrain),color='black') plt.scatter(Xtrain,ytrain,color='red') plt.scatter(Xtest,ytest,color='green') plt.xlabel("Cricket Chirps") plt.ylabel("Temprature")
true
3f0cf1bbdd0ce32ee44e5518df37d6f4937d86b9
Python
STARTFURRY0937/-
/싹수봇.py
UTF-8
5,265
2.90625
3
[]
no_license
import discord import openpyxl import datetime import os client = discord.Client() @client.event async def on_ready(): print(client.user.id) print("ready") game = discord.Game("기다리고 있는중") await client.change_presence(status=discord.Status.online) @client.event async def on_message(message): if message.author.bot: return None if message.content.startswith("{싹수야 도움말"): await message.channel.send("무슨 도움말을 할까요?") await message.channel.send("https://cdn.discordapp.com/attachments/714377816421957663/716943029298266123/21cf9b2c60bdb65b.png") if message.content.startswith("{싹수야?"): await message.channel.send("네?") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716935341822443520/6ed0b344b1b53351.png") if message.content.startswith("{싹수야 아잉아잉"): await message.channel.send("그거 저두 할수 있어요!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716936060004859965/8eeefe382170c0d0.png") if message.content.startswith("{싹수야 빙글뱅글"): await message.channel.send("으어어 새상이 돈드아@@@") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716938451832012840/d78d73a147eec6cd.png") if message.content.startswith("{싹수야 싸가지 없네"): await message.channel.send("저 아직 싹이 없어요!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716938679439982632/6f23d3b66b38d556.png") if message.content.startswith("{싹수야 철좀 들어"): await message.channel.send("저 철 들어 올립니다!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716938958734622760/8816e73502778769.png") if message.content.startswith("{싹수야 안녕"): await message.channel.send("안녕하세요!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716939473212145684/7c3066eb17612b3d.png") if message.content.startswith("{싹수야 칼"): await message.channel.send("난 칼을 들고있다. 무섭지?") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716939637666349096/67bd543e530e4074.png") if message.content.startswith("{싹수야 함수"): await message.channel.send("우웨 너한테 함수 냄새나 ;;") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716957373629202432/0d0cf5c9aeb72e5a.png") if message.content.startswith("{싹수야 ㅋㅋㅋ"): await message.channel.send("하하하!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716959751128481862/4a4edfeda586e5d8.png") if message.content.startswith("{싹수야 코스프레 함수"): await message.channel.send("나는 함수다!") await message.channel.send("https://cdn.discordapp.com/attachments/716541654848503890/716960211382042625/87ae8bf9a5d6e494.png") if message.content.startswith("{싹수야 프로필"): date = datetime.datetime.utcfromtimestamp(((int(message.author.id) >> 22) + 1420070400000) / 1000) embed = discord.Embed(color=0x00ff00) embed.add_field(name="사용자 이름", value=message.author.name, inline=True) embed.add_field(name="서버 사용자 이름", value=message.author.display_name, inline=True) embed.add_field(name="가입 날짜", value=str(date.year) + "년" + str(date.month) + "월" + str(date.day) + "일", inline=True) embed.add_field(name="사용자 ID", value=message.author.id, inline=True) embed.set_thumbnail(url=message.author.avatar_url) await message.channel.send(embed=embed) if message.content.startswith(""): file = openpyxl.load_workbook("호감도.xlsx") sheet = file.active exp = [50, 150, 400, 800, 1300, 2000, 2800, 3700, 4800, 6000, 7300, 9200, 11500, 13000] i = 1 while True: if sheet["A" + str(i)].value == str(message.author.id): sheet["B" + str(i)].value = sheet["B" + str(i)].value + 5 if sheet["B" + str(i)].value >= exp[sheet["C" + str(i)].value - 1]: sheet["C" + str(i)].value = sheet["C" + str(i)].value + 1 await message.channel.send("싹수와의 호감도가 올랐습니다.\n현재 호감도 : " + str(sheet["C" + str(i)].value) + "\n경험치 : " + str(sheet["B" + str(i)].value)) file.save("호감도.xlsx") break if sheet["A" + str(i)].value == None: sheet["A" + str(i)].value = str(message.author.id) sheet["B" + str(i)].value = 0 sheet["C" + str(i)].value = 1 file.save("호감도.xlsx") break i += 1 acces_token = os.environ["BOT_TOKEN"] client.run("acces_token")
true
d9e8c02b622de124afce3ff22f63e6a4090de585
Python
WestonMJones/Coursework
/RPI-CSCI-1100 Computer Science I/lecture/Lecture 10 Exercises/Lecture 10 Ex 3.py
UTF-8
314
3.1875
3
[]
no_license
co2_levels = [ 320.03, 322.16, 328.07, 333.91, 341.47, \ 348.92, 357.29, 363.77, 371.51, 382.47, 392.95 ] average = sum(co2_levels)/len(co2_levels) counter = 0 for v in co2_levels: if v>average: counter += 1 print("Average:",round(average,2)) print("Num above average:",counter)
true
dbb2a7545844105cec6ef7ff63310711c1bd01ba
Python
lozdan/oj
/HakerRank/contests/revised_russian_roulette.py
UTF-8
519
3.171875
3
[]
no_license
# author: Daniel Lozano # source: HackerRank ( https://www.hackerrank.com ) # problem name: Contests > Revised Russian Roulette # problem url: https://www.hackerrank.com/contests/w36/challenges/revised-russian-roulette n = int(input()) doors = input().split() max_oper = 0 min_oper = 0 i = 0 while i < n: if doors[i] == '1': min_oper += 1 max_oper += 1 if i < n - 1 and doors[i + 1] == '1': max_oper += 1 i += 2 continue i += 1 print(min_oper, max_oper)
true
e09daa67e208f675be32046ab4ee7cd1c2658ce1
Python
Rishav159/neural-network
/generator.py
UTF-8
974
3.015625
3
[ "MIT" ]
permissive
import random def get_y(x1,x2,x3): a = x1*x1*3 + x2*5 + x3 + 9 b = 30*30*3 + 150*5 + 554 + 9 if a < b: return 1 else: return 0 train = 10000 test = 5000 train_features = open('dataset/train.txt','w') train_target = open('dataset/train_Target.txt','w') test_features = open('dataset/test.txt','w') test_target = open('dataset/test_target.txt','w') for i in range(train): x1 = random.randrange(1,150,1) x2 = random.randrange(1,150,1) x3 = random.randrange(1,150,1) y = get_y(x1,x2,x3) train_features.write(str(x1) + " " +str(x2)+ " "+str(x3)+"\n") train_target.write(str(y)+"\n") for i in range(test): x1 = random.randrange(1,150,1) x2 = random.randrange(1,150,1) x3 = random.randrange(1,150,1) y = get_y(x1,x2,x3) test_features.write(str(x1) + " " +str(x2)+ " "+str(x3)+"\n") test_target.write(str(y)+"\n") train_features.close() train_target.close() test_features.close() test_target.close()
true
3243cd337bb11112d1abe659b81d0127d2878a5d
Python
dipsuji/coding_pyhton
/coding/remove_duplicate_num.py
UTF-8
854
4.03125
4
[ "Apache-2.0" ]
permissive
def remove_duplicate_num(my_arr): """ Remove duplicate number from an array INPUT - [2, 3, 4, 4, 5, 6, 2] OUTPUT - [2, 3, 4, 5, 6] """ # making a empty array result_array = [] # making a dictionary, key is number and value is occurrence of number num_dic = {} for num_element in my_arr: # check number in num_dic if num_element in num_dic: # if num_element already in num_dic then increase counting but in intial there are no any element num_dic[num_element] += 1 else: # if num_element not in num_dic then put its counting as 1 num_dic[num_element] = 1 # and that character append in array result_array.append(num_element) # print num_dic print(result_array) remove_duplicate_num([2, 3, 4, 4, 5, 6, 1, 2])
true
a720c7867bb2100f7cf906f08ae008e6519ea601
Python
andrecamilo/pln
/lab01/comandos.py
UTF-8
868
2.796875
3
[]
no_license
# # # # # # # # # # lab01 # # # # # # # # # # # # # # conteudo = open("avaliacoes.json").read() import json avaliacoes = json.loads(conteudo) avaliacoes from similares import inverte print(json.dumps(inverte(avaliacoes), indent=3)) from similares import sim_euclidiana sim_euclidiana(avaliacoes, "Rubens V. Martins", "Denis E. Barreto") from similares import top_similares top_similares(avaliacoes, "Rubens V. Martins", 2, sim_euclidiana) top_similares(inverte(avaliacoes), "Scarface", 2, sim_euclidiana) from similares import sim_manhattan sim_manhattan(avaliacoes, "Adriano K. Lopes", "Denis E. Barreto") top_similares(avaliacoes, "Adriano K. Lopes", 2, sim_manhattan) from similares import sim_pearson sim_pearson(inverte(avaliacoes), "A Princesa e o Plebeu", "Os Bons Companheiros") top_similares(inverte(avaliacoes), "A Princesa e o Plebeu", 2, sim_pearson) # # # # # # # # # # lab02 # # # # # # # # # # # # # #
true
25b3d1a728932483ed4553398cdd1c8d1075ade5
Python
dgrant/project-euler
/python/euler06.py
UTF-8
140
2.921875
3
[]
no_license
a=[i for i in xrange(1,101)] sum=0 for i,val1 in enumerate(a): for j,val2 in enumerate(a[i+1:]): sum += val1 * val2 print sum*2
true
47b8794128a6c67dbf0274cdf53aa0306d73e55e
Python
csteamengine/project_koh
/koh_api/util.py
UTF-8
1,404
3.671875
4
[ "BSD-3-Clause" ]
permissive
def write_new(first, last, id_num): """ Create a new entry in the storage text file. :param first: the first name :param last: the last name :param id_num: id number :return: None """ with open("database.txt", "a") as f: f.write("{}, {}, {}\n".format(first, last, id_num)) def get_id(first_name, last_name): """ :param first_name: The first_name to search for. :param last_name: The last_name to search for. :return: The id number for the given first/last name, otherwise None. """ with open("database.txt", "r") as file: for line in file: line = line.rstrip() if not line: continue first, last, _id = line.split(", ") if first_name == first and last_name == last: return _id return None def get_name(id_num): """ Return the first and last name associated with an ID. :param id_num: the id number to search for :return: a tuple of the (first_name, last_name), or (None, None) if not found """ with open("database.txt", "r") as f: for line in f: line = line.rstrip() id_num_string = str(id_num) if not line: continue first, last, _id = line.split(", ") if id_num_string == _id: return first, last return None, None
true
5f994830519f05118a42ab5e512b2f517ed4cfa1
Python
belkiskara/protenus-assessment
/Python/pingSite.py
UTF-8
634
3.1875
3
[]
no_license
import sys import threading import time import requests #Routine for call site periodically def CallSite(): while 1: print (sys.argv[1]) if sys.argv[1].startswith('http'): r = requests.get(sys.argv[1]) print(f'Call For : {sys.argv[1]} Result : {r.status_code} ') else: print('Request Schema not valid...') time.sleep(60) CallSite() t1 = threading.Thread(target=CallSite) #Background thread will finish with the main program t1.setDaemon(True) #Start CallSite() in a separate thread as Background worker t1.start() if __name__ == "__main__": CallSite()
true
afec77db5b0802f3aab364342f0cfa5e32e8c387
Python
carlohamalainen/playground
/python/beautiful_soup_4/tocom_kobetu_prices.py
UTF-8
1,719
3.0625
3
[]
no_license
import bs4 import requests import pandas URLS = [ "https://www.tocom.or.jp/market/kobetu/east_base_elec.html", "https://www.tocom.or.jp/market/kobetu/west_base_elec.html", "https://www.tocom.or.jp/market/kobetu/east_peak_elec.html", "https://www.tocom.or.jp/market/kobetu/west_peak_elec.html", ] def parse_html_table_with_header(t): rows = [] for bits in t: x = parse_rows(bits) if x != []: rows += x header = [h.text.strip() for h in t.find('thead').find_all('th')] return (header, rows) def parse_rows(x): rows = [] if hasattr(x, 'find_all'): for row in x.find_all('tr'): cols = row.find_all('td') cols = [c.text.strip() for c in cols] this_row = [c for c in cols if c != []] if cols: rows.append(this_row) return rows def scrape(url): tables = {} soup = bs4.BeautifulSoup(requests.get(url).content, features='html.parser') h3 = soup.find('h3') while h3 is not None: name = h3.contents[0].strip() table0 = h3.find_next_sibling('table') table1 = table0.find_next_sibling('table') tables[name] = [parse_rows(table0), parse_html_table_with_header(table1)] h3 = h3.find_next_sibling('h3') for (name, [t0, t1]) in tables.items(): [[session, _, prices_in]] = t0 (header, rows) = t1 df = pandas.DataFrame(data=rows, columns=header) print(url) print() print(name) print(session) print(prices_in) print() print(df) print() print() if __name__ == '__main__': for url in URLS: scrape(url)
true
da5e2b46c0c021a58c00c7eb6dc8a536ff9d8791
Python
richarddeng88/Python
/0. social meida analysis/2. parse twitter search page.py
UTF-8
2,537
3.203125
3
[]
no_license
import re from re import sub import time import cookielib from cookielib import CookieJar import urllib2 from urllib2 import urlopen import difflib cj = CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders = [('User-agent','Mozilla/5.0')] ## i think this is http header that send out to twitter. keyword = 'obama' link = 'https://twitter.com/search/realtime?q=' def main(): oldTweet = [] newTweet = [] ## create a list howArray = [0.5,0.5,0.5,0.5,0.5] while 1<2: try: source_code = opener.open(link + keyword+ '&src=hash&lang=en').read() ## get this link's HTML source code split = re.findall(r'<p class="TweetTextSize js-tweet-text tweet-text" lang="en" data-aria-label-part="0">(.*?)</p>',source_code) # <p class="TweetTextSize js-tweet-text tweet-text" lang="en" data-aria-label-part="0"> # >>>> above is the begining of tag of html for each tweet print 'the number of tweets we downloaded is: ',len(split), '\n' for item in split: # print type(item),len(item), item, '\n' aTweet = re.sub(r'<.*?>','',item) ## Here a is the actual tweets. print len(aTweet), aTweet newTweet.append(aTweet) # it is a list comparison = difflib.SequenceMatcher(None,newTweet, oldTweet) how = comparison.ratio() ## calculate the ratio of matched items. howArray.append(how) howArray.remove(howArray[0]) avg = reduce(lambda x,y : x+y, howArray)/ len(howArray) # Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce # the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates # ((((1+2)+3)+4)+5). print "#######" print 'the number of tweets we downloaded is: ', len(split), '\n' print "this session is ", how, ' similar to the past' oldTweet = [None] for i in newTweet: oldTweet.append(i) newTweet = [None] print howArray print "tha average ratio is ", avg time.sleep(avg*10) except Exception, e: print str(e) print 'errored in the main try' time.sleep(555) # The method sleep() suspends execution for the given number of seconds main()
true
fec4b52c1a72ed3badbb9009a7db2e3fe7aa5dac
Python
Nispanu78/list-of-Selenium-tests
/test_assert_not_equal.py
UTF-8
232
3.046875
3
[]
no_license
import unittest class TestAssertIsNotEqual(unittest.TestCase): def test_is_not_equal(self): num=7 num2=8 self.assertNotEqual(num, num2, "Numbers do match") if __name__ == '__main__': unittest.main()
true
d7b515d3b4bd15fa2f071c07871c8d9d63415c68
Python
alexjercan/algorithms
/old/leetcode/problems/longest-substring-without-repeating-characters.py
UTF-8
864
3.390625
3
[]
no_license
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: charSet = set() res, l = 0, 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res, r - l + 1) return res # abcabcbb # I1: r = 0, s[r] = 'a', l = 0, charSet = {'a'}, res = 1 # I2: r = 1, s[r] = 'b', l = 0, charSet = {'a', 'b'}, res = 2 # I3: r = 2, s[r] = 'c', l = 0, charSet = {'a', 'b', 'c'}, res = 3 # I4: r = 3, s[r] = 'a', l = 1, charSet = {'b', 'c', 'a'}, res = 3 # I5: r = 4, s[r] = 'b', l = 2, charSet = {'c', 'a', 'b'}, res = 3 # I6: r = 5, s[r] = 'c', l = 3, charSet = {'a', 'b', 'c'}, res = 3 # I7: r = 6, s[r] = 'b', l = 4, charSet = {'a', 'c', 'b'}, res = 3 # I8: r = 7, s[r] = 'b', l = 5, charSet = {'a', 'c', 'b'}, res = 3
true
a09c877d567c3e82168de0d3f8f11065a38c6b14
Python
Amsterdam/stadsarchief-machine-learning
/src/processing/transform.py
UTF-8
217
2.65625
3
[]
no_license
def transform_aanvraag_labels(labels): """ # Convert all labels to either "aanvraag" or "other" :param labels: :return: """ return ['aanvraag' if x == 'aanvraag' else 'other' for x in labels]
true
f17708cf1b771955323d25f68b8daef548c40a32
Python
dahsser/hacks
/orceBruteForce.py
UTF-8
1,195
2.65625
3
[]
no_license
import requests import threading import time total = 50 found = False threads = 0 password = 200000 headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'keep-alive' } def testPassword(codigo, password): global threads global found threads += 1 data = { "tipo": "acceso", "codUni": codigo, "clave": password } try: r = requests.post('http://www.academico.uni.pe/intranet/public/alumno/entrar', data=data, headers=headers, allow_redirects=False) if r.headers["location"]!="http://www.academico.uni.pe/intranet/public/alumno/entrar": print("Password found", password) threads-=1 found = True file = open("password.txt","w") file.write(password) file.close() return else: threads-=1 return except ValueError: time.sleep(3) threads-=1 return testPassword(codigo, password) codigo = '20140417F' print("Codigo", codigo) while not found: if(threads < total): if(password %1000==0): print("testing", password) t = threading.Thread(target=testPassword, args=(codigo, str(password))) #threads.append(t) t.start() password+=1
true
efdcba2e7d1e9e1a4675e36f6a8eb76ffc9a4269
Python
marianac99/Mision-04
/areaRectangulos.py
UTF-8
1,870
4.5
4
[]
no_license
#Mariana Caballero Cabrera A01376544 # Calcular área y perímetro de 2 rectangulos, determinar cuál tiene mayor área # Calcular área del rectángulo 1 def calcularArea1 (base1,altura1): area1 = base1*altura1 return area1 #calcular el área del rectángulo 2 def calcularArea2 (base2,altura2): area2 = base2*altura2 return area2 #Calcular el perímetro del rectángulo 1 def calcularPerimetro1 ( base1,altura1): perimetro1 = (base1*2)+(altura1*2) return perimetro1 #Calcular el perímtro del rectángulo 2 def calcularPerimetro2 (base2, altura2): perimetro2 = (base2 * 2) + (altura2 * 2) return perimetro2 # función principal def main(): base1 = int(input("Teclea el tamaño de la base del primer rectángulo: ")) altura1 = int(input("Teclea el tamaño de la altura del primer rectángulo: ")) base2 = int(input("Teclea el tamaño de la base del segundo rectángulo: ")) altura2 = int(input("Teclea el tamaño de la altura del segundo ractángulo: ")) area1 = calcularArea1 (base1,altura1) area2 = calcularArea2 (base2,altura2) print ("---------------------------------------------------") if area1 < area2: print("El ractángulo 2 es mayor con: ", area2, "cm2") print("El ractángulo 1 es menor con: ", area1, "cm2") else: print("El ractángulo 1 es mayor con: ", area1, "cm2") print("El ractángulo 2 es menor con: ", area2, "cm2") perimetro1 = calcularPerimetro1 (base1, altura1) perimetro2 = calcularPerimetro2 (base2,altura2) print ("------------------------------------------------------------------") print ("El perímetro del rectángulo 1 es: ", perimetro1, "cm") print("El perímetro del rectángulo 2 es: ", perimetro2, "cm") #llamamos a la función principal main()
true
9f744ae452db69610b0cff56bdf8865d43a813ad
Python
thorvaldurs19/Tile-traveller
/tile_traveller.py
UTF-8
2,783
4.25
4
[]
no_license
import math # tökum kommuna út úr tile´unum þ.a. td. 3,2 er 32.. # ..Ef farið er í norður/suður þá +/- 1 því tile fyrir ofan/neðan eru 1 meira eða minna... # ..Ef farið er í vestur/austur þá +/- 10 því tile fyrir hliðin á eru 10 meira eða minna... def direction_(direction_inp,tile): if direction_inp=="e": tile=tile+10 if direction_inp=="w": tile=tile-10 if direction_inp=="n": tile=tile+1 if direction_inp=="s": tile=tile-1 return tile borderW="valid" borderN="valid" borderE="valid" borderS="valid" # Þurfum að skilgreina í hvaða stefnu má ekki fara í ef maður er staðsettur á X tile´i.. # Ef borderX = "not_valid" þá má ekki fara í þá átt í völundarhúsinu.. def border_e(tile): borderE="valid" if tile==11: borderE="not_valid" if tile==22: borderE="not_valid" if tile==21: borderE="not_valid" if tile==33 or tile==32: borderE="not_valid" return borderE def border_n(tile): borderN="valid" if tile==22: borderN="not_valid" if tile==13 or tile==23 or tile==33: borderN="not_valid" return borderN def border_w(tile): borderW="valid" if tile==21: borderW="not_valid" if tile==32: borderW="not_valid" if tile==13 or tile==12 or tile==11: borderW="not_valid" return borderW def border_s(tile): borderS="valid" if tile==23: borderS="not_valid" if tile==11 or tile==21: borderS="not_valid" return borderS tile=11 #Búum til while setningu til þess að koma í veg fyrir að "or" komi fremst fram í you can travel: " " ... while tile!=31: out="" count=0 borderS=border_s(tile) borderN=border_n(tile) borderW=border_w(tile) borderE=border_e(tile) if borderN=="valid": out =out+"(N)orth" count+=1 if borderE=="valid": if count>0: out=out+" or " out=out+"(E)ast" count+=1 if borderS=="valid": if count>0: out=out+" or " out=out+"(S)outh" count+=1 if borderW=="valid": if count>0: out=out+" or " out=out+"(W)est" count+=1 print("You can travel: "+out+".") direction_inp=input("Direction: ") direction=str.lower(direction_inp) if direction=="w"and borderW=="not_valid": print("Not a valid direction!") elif direction=="s"and borderS=="not_valid": print("Not a valid direction!") elif direction=="n"and borderN=="not_valid": print("Not a valid direction!") elif direction=="e"and borderE=="not_valid": print("Not a valid direction!") else: tile=direction_(direction,tile) print("Victory!")
true
870b0c30f78ec6355ccb023db60dfa726399785e
Python
Aasthaengg/IBMdataset
/Python_codes/p02584/s480385741.py
UTF-8
221
2.90625
3
[]
no_license
if __name__ == "__main__": X, K, D = map(lambda x: abs(int(x)), input().split()) if X - K*D >= 0: print(X - K*D) else: xdd = X // D k = xdd + (K - xdd) % 2 print(abs(X - k*D))
true
f92eb29a5d9ab84027c320e04a5194a672b48f97
Python
biggod-ck/python
/变量.py
UTF-8
540
3.4375
3
[]
no_license
a = 100 b = 12.345 c = 1 + 5j d = 'hello, world' e = True print(type(a)) # <class 'int'> print(type(b)) # <class 'float'> print(type(c)) # <class 'complex'> print(type(d)) # <class 'str'> print(type(e)) # <class 'bool'> a1 = int('123') print(a) a2 =float('1') print(a2) a3 = str('123aasd') print(a3) flag0 = 1 == 1 flag1 = 3 > 2 flag2 = 2 < 1 flag3 = flag1 and flag2 flag4 = flag1 or flag2 flag5 = not(1 != 2) print(flag0,flag1,flag2,flag3,flag4,flag5) bool1 = True bool2 = False print(bool1 and bool2,bool1 or bool2)
true
8c99f9322583492d848a667184aea4596ff79bb2
Python
xindiguo/challengeutils
/tests/test_utils.py
UTF-8
3,890
2.515625
3
[]
no_license
import mock import pytest import re import challengeutils.utils import synapseclient from synapseclient.annotations import to_submission_status_annotations syn = mock.create_autospec(synapseclient.Synapse) def test_raiseerror__switch_annotation_permission(): ''' Test that annotations permission isn't switched ''' add_annotations = {'test': 2, 'test2': 2} existing_annotations = {'test': 1} error_message = ( "You are trying to change the ACL of these annotation key(s): " "test. Either change the annotation key or specify " "force_change_annotation_acl=True") # Must use re.escape() because match accepts regex with pytest.raises(ValueError, match=re.escape(error_message)): challengeutils.utils._switch_annotation_permission( add_annotations, existing_annotations) def test_filter__switch_annotation_permission(): ''' Test filtering out of switched annotations ''' add_annotations = {'test': 2, 'test2': 2} existing_annotations = {'test': 1} existing = challengeutils.utils._switch_annotation_permission( add_annotations, existing_annotations, force_change_annotation_acl=True) assert existing == {} def test_nooverlap__switch_annotation_permission(): ''' Test no overlap of annotations to add and existing annotations ''' add_annotations = {'test': 2, 'test2': 2} existing_annotations = {'test3': 1} existing = challengeutils.utils._switch_annotation_permission( add_annotations, existing_annotations, force_change_annotation_acl=True) assert existing == existing_annotations def test_append_update_single_submission_status(): ''' Test appending new annotation (dict) ''' existing = {"test": "foo", "test1": "d", "test2": 5, "test3": 2.2} existing = to_submission_status_annotations(existing) status = {'annotations': existing} add_annotations = {"test4": 5} new_status = challengeutils.utils.update_single_submission_status( status, add_annotations) status['annotations']['longAnnos'].append( {'key': 'test4', 'value': 5, 'isPrivate': True} ) assert new_status == status def test_update_update_single_submission_status(): ''' Test updating new annotation to change type (dict) ''' existing = {"test": "foo"} existing = to_submission_status_annotations(existing) status = {'annotations': existing} add_annotations = {"test": 5} new_status = challengeutils.utils.update_single_submission_status( status, add_annotations) new_annots = synapseclient.annotations.to_submission_status_annotations( add_annotations) expected_status = {'annotations': new_annots} assert new_status == expected_status def test_substatus_update_single_submission_status(): ''' Test passing in submission annotation format ''' existing = {"test": 5} existing = to_submission_status_annotations(existing) status = {'annotations': existing} add_annotations = to_submission_status_annotations({"test": 2.4}) expected_status = {'annotations': add_annotations} new_status = challengeutils.utils.update_single_submission_status( status, add_annotations) assert new_status == expected_status def test_topublic_update_single_submission_status(): ''' Test topublic flag. By default when a dict is passed in the annotation is set to private, but you can change that flag ''' status = {'annotations': {}} add_annotations = {"test": 2.4} new_status = challengeutils.utils.update_single_submission_status( status, add_annotations, to_public=True) expected_annot = to_submission_status_annotations( add_annotations, is_private=False) expected_status = {'annotations': expected_annot} assert new_status == expected_status
true
9c62484645c8e3629ca85cd4f350dabccdd7658c
Python
rachitdev/ugMDSCode
/makeDF.py
UTF-8
376
2.765625
3
[]
no_license
import pandas as pd import sys,ast input_list = [['c1','c2','c3'],[1,2,3],[4,5,6],[7,8,9]] data = {input_list[0][0]:[input_list[1][0], input_list[2][0], input_list[3][0]], input_list[0][1]:[input_list[1][1], input_list[2][1], input_list[3][1]], input_list[0][2]:[input_list[1][2], input_list[2][2], input_list[3][2]]} df = pd.DataFrame(data) #print(df) print(df.describe())
true
290b3f51b060338cac36fb6e4e6f8a534efc8d99
Python
ben-mcginty/Ben-McGinty-Software
/convex_hull_problem.py
UTF-8
3,848
3.59375
4
[ "MIT" ]
permissive
#Copyright © 2020 Benjamin McGinty #Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from collections import namedtuple import matplotlib.pyplot as plt import random Point = namedtuple('Point', 'x y') class ConvexHull(object): _points = [] _hull_points = [] def __init__(self): pass def add(self, point): self._points.append(point) def _get_orientation(self, origin, p1, p2): ''' Returns the orientation of the Point p1 with regards to Point p2 using origin. Negative if p1 is clockwise of p2. :param p1: :param p2: :return: integer ''' difference = ( ((p2.x - origin.x) * (p1.y - origin.y)) - ((p1.x - origin.x) * (p2.y - origin.y)) ) return difference def compute_hull(self): ''' Computes the points that make up the convex hull. :return: ''' points = self._points # get leftmost point start = points[0] min_x = start.x for p in points[1:]: if p.x < min_x: min_x = p.x start = p point = start self._hull_points.append(start) far_point = None while far_point is not start: # get the first point (initial max) to use to compare with others p1 = None for p in points: if p is point: continue else: p1 = p break far_point = p1 for p2 in points: # ensure we aren't comparing to self or pivot point if p2 is point or p2 is p1: continue else: direction = self._get_orientation(point, far_point, p2) if direction > 0: far_point = p2 self._hull_points.append(far_point) point = far_point def get_hull_points(self): if self._points and not self._hull_points: self.compute_hull() return self._hull_points def display(self): # all points x = [p.x for p in self._points] y = [p.y for p in self._points] plt.plot(x, y, marker='D', linestyle='None') # hull points hx = [p.x for p in self._hull_points] hy = [p.y for p in self._hull_points] plt.plot(hx, hy) plt.title('Convex Hull') plt.show() def main(): ch = ConvexHull() for _ in range(2500): ch.add(Point(random.randint(0, 5000), random.randint(0, 5000))) print("Points on hull:", ch.get_hull_points()) ch.display() if __name__ == '__main__': main()
true
b78857ce9ff4e5fff9e94404f75baa78da19f90d
Python
Anjualbin/workdirectory
/programs fundamental/sumofnumbers.py
UTF-8
113
3.9375
4
[]
no_license
num=int(input("Enter the number:")) sum=0 for i in range(num): sum=sum+i print("The sum of numbers is:",sum)
true
337b87ed23e58d133298485049e0f6d96d4d8de3
Python
EsauloffLev/GoToProject
/бот.py
UTF-8
4,417
2.59375
3
[]
no_license
import telebot token = "642787161:AAH9ETHpiLfTrxI0HjIRHDEMIqIel2RbbfE" # Обходим блокировку с помощью прокси telebot.apihelper.proxy = {'https': 'socks5://tvorogme:TyhoRuiGhj1874@tvorog.me:6666'} # подключаемся к телеграму bot = telebot.TeleBot(token=token) state = 'waiting' ADMIN_ID = 560733832 users = set() bets_right = {} bets_left = {} sum_left = 0 sum_right = 0 who_win = 0 id_bets_left = set() id_bets_right = set() bet_amount = 0 left_player = "" right_player = "" @bot.message_handler(commands=['start']) def start(message): bot.send_message(message.chat.id, "HEllo") if message.chat.id != ADMIN_ID: users.add(message.chat.id) else: bot.send_message(message.chat.id, "Вы дядя админ") # content_types=['text'] - сработает, если нам прислали текстовое сообщение @bot.message_handler(content_types=['text']) def process(message): global state global users global bets_left global left_player global right_player global bets_right global sum_left global sum_right global bet_amount global id_bets_lest global id_bets_right if message.chat.id == ADMIN_ID: if state == 'waiting': # TODO: понять из сообщения кто сражается left_player = "" right_player = "" action_name = "" list = message.text.split('-') if len(list) >= 2: our_text = list[2] + ": " + list[0] + " vs " + list[1] for user in users: # TODO: .... bot.send_message(user, our_text) state = 'taking' if state == 'taking': state = 'playing' if state == 'playing': state = 'waiting' if message == '1': who_win = 1 elif message == '2': who_win = 2 else: bot.send_message(message.chat.id, "Пожалуйста, напишите результат матча") #TODO: Разослать всем, кто че выиграл for user in users: if who_win == 1: if user in id_bets_left: win_bet = str(bets_left[user] * (sum_left + sum_right) / sum_left) result = "Поздравляем, Ваш выигрыш составляет " + win_bet bot.send_message(user, result) else: bot.send_message(user, "В следующий раз повезет") elif who_win == 2: if user in id_bets_right: win_bet = str(bets_right[user] * (sum_left + sum_right) / sum_right) result = "Поздравляем, Ваш выигрыш составляет " + win_bet bot.send_message(user, result) else: bot.send_message(user, "В сдедующий раз повезет") else: if state == 'waiting': bot.send_message(message.chat.id, "Пока ждем") if state == 'taking': #TODO: сделать ставку if message == '1': bot.send_message(message.chat.id, "Введите размер вашей ставки") bet_amount = int(message) sum_left+= bet_amount bets_right[message.chat.id] = bet_amount id_bets_left.add(message.chat.id) elif message == '2': bot.send_message(message.chat.id, "Введите размер вашей ставки") bet_amount = int(message) sum_right+= bet_amount bets_left[message.chat.id] = bet_amount id_bets_right.add(message.chat.id) else: bot.send_message(message.chat.id, "Sorry, Я Вас не понимать") bot.send_message(message.chat.id, "Ставка принята") if state == 'playing': bot.send_message(message.chat.id, "Игра идет") # поллинг - вечный цикл с обновлением входящих сообщений bot.polling(none_stop=True)
true
b4ceb5bfb296acde8b52b10a3bb14fe1505ce8ac
Python
JanGonzales/Treasure_Island
/Love_Score.py
UTF-8
785
4.21875
4
[]
no_license
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 # Write your code below this line 👇 Combined = name1 + name2 Name_lower = Combined.lower() Var_True = Name_lower.count("t") + Name_lower.count("r") + Name_lower.count("u") + Name_lower.count("e") Var_Love = Name_lower.count("l") + Name_lower.count("o") + Name_lower.count("v") + Name_lower.count("e") score = int(str(Var_True) + str(Var_Love)) if score <= 10 or score >= 90: print(f"Your score is {score}, you go together like coke and mentos.") elif 40 <= score <= 50: print(f"Your score is {score}, you are alright together.") else: print(f"Your score is {score}")
true
b35131529316f0f8b4bd1f4d9e088ef3a3dc7c1a
Python
FelipeRossoni/Exercicios_LP_1B
/Ex4.py
UTF-8
156
3.953125
4
[ "MIT" ]
permissive
n1 = int(input("Digite o primeiro número: ")) n2 = int(input("Digite o segundo número: ")) print("O resultado da soma dos dois números é de: ", n1 + n2)
true
6009e1159428460a031ae37f3d41000535d064ae
Python
antonmolchanov90/5.Test-Automation-Python
/UI_Tests/Python_Selenium (Facebook LogIn)/FacebookLogin_UI_Test.py
UTF-8
2,035
2.578125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- from selenium import webdriver from FacebookLogin_Locators import* from FacebookLogin_Credentials import* from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument('--disable-gpu') # POSITIVE CASE - SIMPLE VERIFICATION # Open browser, enter Facebook driver = webdriver.Chrome("/opt/chromedriver", options=chrome_options) driver.get("https://www.facebook.com") # Locate elements, pass email & password (both empty), click Log In button driver.find_element_by_id(email).send_keys(emailAddress) driver.find_element_by_id(passWord).send_keys(passwordAccess) driver.find_element_by_id(loginButton).click() # Assert successful login if driver.title == 'Facebook': print('Passed!') else: print('Failed!') # Close browser driver.quit() # NEGATIVE CASE 1 # Open browser, enter Facebook driver = webdriver.Chrome("/opt/chromedriver") driver.get("https://www.facebook.com") # Locate elements, pass email & password (both empty), click Log In button driver.find_element_by_id(email).send_keys("") driver.find_element_by_id(passWord).send_keys("") driver.find_element_by_id(loginButton).click() # Assert unsuccessful login if driver.title == 'Log into Facebook | Facebook': print('Passed!') else: print('Failed!') # Close browser driver.quit() # NEGATIVE CASE 2 # Open browser, enter Facebook driver = webdriver.Chrome("/opt/chromedriver") driver.get("https://www.facebook.com") # Locate elements, pass email & password (both empty), click Log In button driver.find_element_by_id(email).send_keys(emailAddress) driver.find_element_by_id(passWord).send_keys("") driver.find_element_by_id(loginButton).click() # Assert unsuccessful login if driver.title == 'Log into Facebook | Facebook': print('Passed!') else: print('Failed!') # Close browser driver.quit()
true
e3df00f987785d3490da1c2787b3d9049d4ea221
Python
Amangeldy-Bibars/FPGA_KazNU
/Raspberry/reconnect.py
UTF-8
793
2.65625
3
[]
no_license
import bluetooth from time import sleep bd_addr = "00:21:13:05:C3:5E" port = 1 data = "" k = 0 def connect(): not_connected = True while not_connected: try: sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect((bd_addr, port)) not_connected = False except: sleep(1) pass return sock sock = connect() while 1: try: data += sock.recv(1024).decode() data_end = data.find('\n') if data_end != -1: rec = data[:data_end] print(rec) data = data[data_end+1:] except KeyboardInterrupt: break except bluetooth.btcommon.BluetoothError: sleep(2) sock = connect() pass sock.close()
true
ceef47a20e9554837fcf602b805ede4af6038ef3
Python
harmslab/pytc-gui
/pytc_gui/widgets/experiment_box/experiment_dialog/global_dialog.py
UTF-8
2,569
2.828125
3
[ "Unlicense" ]
permissive
__description__ = \ """ Dialog that pops up when user wants to create a new global variable. """ __author__ = "Michael J. Harms" __date__ = "2017-06-06" from PyQt5 import QtWidgets as QW class AddGlobalDialog(QW.QDialog): """ Dialog box for adding a new global variable. """ def __init__(self,parent,fit,experiment,fit_param): """ parent: parent widget instance fit: FitContainer instance experiment: pytc.ITCExperiment instance holding fit parameter fit_param: pytc.FitParam instance holding fittable parameter """ super().__init__() self._parent = parent self._fit = fit self._experiment = experiment self._p = fit_param self.layout() def layout(self): """ Populate the window. """ self._main_layout = QW.QVBoxLayout(self) self._form_layout = QW.QFormLayout() # Input box holding name self._global_var_input = QW.QLineEdit(self) self._global_var_input.setText("global") self._global_var_input.editingFinished.connect(self._check_name) # Final OK button self._OK_button = QW.QPushButton("OK", self) self._OK_button.clicked.connect(self._ok_button_handler) # Add to form self._form_layout.addRow(QW.QLabel("New Global Variable:"), self._global_var_input) # add to main layout self._main_layout.addLayout(self._form_layout) self._main_layout.addWidget(self._OK_button) self.setWindowTitle("Add new global variable") def _check_name(self): """ Turn bad name pink. """ value = self._global_var_input.text() value = value.strip() color = "#FFFFFF" if value.strip() == "": color = "#FFB6C1" if value in self._fit.global_param.keys(): color = "#FFB6C1" self._global_var_input.setStyleSheet("QLineEdit {{ background-color: {} }}".format(color)) def _ok_button_handler(self): """ Handle OK button. """ self._check_name() value = self._global_var_input.text() value = value.strip() if value.strip() == "": return if value in self._fit.global_param.keys(): warn = "{} already defined.".format(value) err = QW.QMessageBox.warning(self, "warning", warn, QW.QMessageBox.Ok) return self._fit.link_to_global(self._experiment,self._p.name,value) self.accept()
true
9c33956de1ca70d01017c05c52eeeb59c75f6969
Python
Nishi1499/Assignment
/New folder/AssignmentTwo.4.py
UTF-8
96
3.3125
3
[]
no_license
for i in range(1,100): if(i%2==0): List = [i] print("Even numbers",i)
true
6545b97798fcc671d1e1871ed3e52eac0f3166f0
Python
Gabriel979aps/Checkpoint3_MachineLearning_RM87010_RM89369
/checkpoint3_MachineLearning_RM87010_RM89369.py
UTF-8
2,271
3.3125
3
[]
no_license
''' FIAP Defesa Cibernética - 1TDCF - 2021 Development e Coding for Security Prof. Ms. Fábio H. Cabrini Atividade: Check Point 3 Alunos Gabriel Anselmo Pires Dos Santos - RM87010 Vinicius Fernandes - RM89369 ''' from sklearn import tree #importa o módulo "tree" do Sklearn Árvore de Decisão features = [99, 139, 199], [89, 120, 160], [70, 110, 110], [65, 90, 90], [50, 80, 100], [40, 119, 170], [90, 100, 100], [60, 129, 159], [67, 124, 125],[97, 132, 109], [110, 150, 199], [100, 140, 180], [120, 145, 170], [121, 160, 198], [124, 180, 90], [126, 190, 100], [100, 169, 190], [111, 157, 113], [121, 190, 170], [105, 168, 192], [126, 200, 200], [190, 290, 248], [312, 241, 410], [431, 234, 210], [129, 265, 205], [137, 280, 341], [290, 345, 211], [138, 231, 230], [127, 201, 230], [154, 214, 294] #labels = [Jejum, Pós_Sobrecarga, Casual] #Glicose normal: 0 Tolerância à glicose diminuída: 1 Diagnóstico de Diabetes Mellitus: 2 labels = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] classif = tree.DecisionTreeClassifier() #Classificador classif.fit(features, labels) Jejum = float(input("\n \033[1;32mDigite o valor da glicemia do paciente em jejum: ")) Pós_Sobrecarga = float(input("\033[1;33m Digite o valor da glicemia do paciente Pós-Sobrecarga: ")) Casual = float(input("\033[1;4;31m Digite o valor da glicema casual do paciente: ")) x = classif.predict([[Jejum, Pós_Sobrecarga, Casual]]) if x== 0: print ("\033[1;34m=-=" *14) print("\033[1;32mSua glicemia está normal!") print ("\033[1;34m=-=" *14) print('\033[1;4;31;43mAtenção! O diagnóstico apresentado não é definitivo, não deixe de consultar o seu médico!\033[m') elif x== 1: print ("\033[1;34m=-=" *14) print("\033[1;33mVocê possui tolerância à glicose diminuída.") print("\033[1;34m=-=" *14) print('\033[1;4;31;43mAtenção! O diagnóstico apresentado não é definitivo, não deixe de consultar o seu médico!\033[m') elif x== 2: print ("\033[1;34m=-=-=" *10) print("\033[1;4;31mVocê apresenta um diagnóstico de Diabetes Mellitus.") print ("\033[1;34m=-=-=" *10) print('\033[1;4;31;43mAtenção! O diagnóstico apresentado não é definitivo, não deixe de consultar o seu médico!\033[m')
true
06bdb0207213b8abf256ba322aaf2b6613d34c1c
Python
dkosaty/Whispering-gallery-waves
/tests/the waves of whispering gallery/whispering_gallery_waves.py
UTF-8
1,454
2.9375
3
[]
no_license
# the solution of the whispering gallery equation import matplotlib.pyplot as plt from airy_funcs import * from Y import * import script_2 import script_3 class FAnother(script_2.F): def initialize_consts(self): self.N = 160 self.p = 1 self.p_prime = 1 - self.p ** 3 Lambda = 0.1 # Lambda = 10 # Lambda = 1 k0 = script_3.compute_k0(Lambda) m = script_3.compute_m(k0) # N0 = 1e-6 N0 = 5 * 1e-6 h = 50 self.y0 = Y0(m, self.p, N0) self.y2 = Y2(k0, h, m, self.p) self.y1 = Y1(self.y0.wave_2, self.y2.wave_2) def get_roots(self): all_roots = np.roots(self.coefficients) # for root in all_roots: # print(root, np.abs(self.model(root))) return self.sample_roots(all_roots, eps=0.7) roots = property(get_roots) def W(self, i, t=0): t_1 = self.p ** 2 * t - self.y2.wave_1 t_2 = t - self.y1.wave_2 if i == 1: return w(t_1) * v(t_2) elif i == 2: return dw(t_1) * v(t_2) elif i == 3: return w(t_1) * dv(t_2) elif i == 4: return dw(t_1) * dv(t_2) else: raise IndexError def display(roots): x = np.real(roots) y = np.imag(roots) plt.plot(x, y, '.') plt.show() if __name__ == '__main__': f = FAnother() print(f.roots) display(f.roots)
true
ab47623f7853e27a20484dc1ee45b61c27fa1057
Python
chudasamajd/Sudoku-Solver
/Test.py
UTF-8
5,318
2.875
3
[]
no_license
# from keras.models import Sequential # from keras.layers import Dense # from keras.layers import Dropout # from keras.layers import Flatten # from keras.layers.convolutional import Conv2D, MaxPooling2D # from sklearn.model_selection import train_test_split # from keras.utils import np_utils import cv2 import numpy as np import matplotlib.pyplot as plt import operator def pre_process_image(img, skip_dilate=False): """Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image.""" # Gaussian blur with a kernal size (height, width) of 9. # Note that kernal sizes must be positive and odd and the kernel must be square. proc = cv2.GaussianBlur(img.copy(), (9, 9), 0) # Adaptive threshold using 11 nearest neighbour pixels proc = cv2.adaptiveThreshold(proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Invert colours, so gridlines have non-zero pixel values. # Necessary to dilate the image, otherwise will look like erosion instead. proc = cv2.bitwise_not(proc) if not skip_dilate: # Dilate the image to increase the size of the grid lines. kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]], np.uint8) proc = cv2.dilate(proc, kernel) #plt.imshow(proc, cmap='gray') #plt.title('pre_process_image') #plt.show() return proc def find_corners_of_largest_polygon(img): """Finds the 4 extreme corners of the largest contour in the image.""" contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours #for c in contours: # if cv2.contourArea(c) > 700: #cv2.drawContours(original, contours, -1, (0, 255, 255), 2) #cv2.imshow('res', original) #cv2.waitKey(0) contours = sorted(contours, key=cv2.contourArea, reverse=True) # Sort by area, descending #cv2.drawContours(original, contours, -1, (0, 255, 255), 2) #cv2.imshow('res', original) #cv2.waitKey(0) #print(contours) polygon = contours[0] # Largest image #cv2.drawContours(original, polygon, -1, (0, 255, 255), 2) #cv2.imshow('res', original) #cv2.waitKey(0) #x,y,w,h = cv2.boundingRect(polygon) #cv2.circle(original,(x,y),5,(0,0,255),-1) #cv2.imshow('res', original) #cv2.waitKey(0) # Use of `operator.itemgetter` with `max` and `min` allows us to get the index of the point # Each point is an array of 1 coordinate, hence the [0] getter, then [0] or [1] used to get x and y respectively. # Bottom-right point has the largest (x + y) value # Top-left has point smallest (x + y) value # Bottom-left point has smallest (x - y) value # Top-right point has largest (x - y) value bottom_right, _ = max(enumerate([pt[0][0] + pt[0][1] for pt in polygon]),key=operator.itemgetter(1)) top_left, _ = min(enumerate([pt[0][0] + pt[0][1] for pt in polygon]),key=operator.itemgetter(1)) bottom_left, _ = min(enumerate([pt[0][0] - pt[0][1] for pt in polygon]),key=operator.itemgetter(1)) top_right, _ = max(enumerate([pt[0][0] - pt[0][1] for pt in polygon]),key=operator.itemgetter(1)) #print(polygon[top_left][0]) #cv2.circle(original,(229,19),5,(0,255,255),3) #cv2.imshow('res', original) #cv2.waitKey(0) # Return an array of all 4 points using the indices # Each point is in its own array of one coordinate return [polygon[top_left][0], polygon[top_right][0], polygon[bottom_right][0], polygon[bottom_left][0]] def distance_between(p1,p2): a = p2[0] - p1[0] b = p2[1] - p1[1] return np.sqrt((a ** 2) + (b ** 2)) def crop_and_warp(img, crop_rect): """Crops and warps a rectangular section from an image into a square of similar size.""" # Rectangle described by top left, top right, bottom right and bottom left points top_left, top_right, bottom_right, bottom_left = crop_rect[0], crop_rect[1], crop_rect[2], crop_rect[3] # Explicitly set the data type to float32 or `getPerspectiveTransform` will throw an error src = np.array([top_left, top_right, bottom_right, bottom_left], dtype='float32') #print(src) # Get the longest side in the rectangle side = max([ distance_between(bottom_right, top_right), distance_between(top_left, bottom_left), distance_between(bottom_right, bottom_left), distance_between(top_left, top_right) ]) # Describe a square with side of the calculated length, this is the new perspective we want to warp to dst = np.array([[0, 0], [side - 1, 0], [side - 1, side - 1], [0, side - 1]], dtype='float32') # Gets the transformation matrix for skewing the image to fit a square by comparing the 4 before and after points m = cv2.getPerspectiveTransform(src, dst) # Performs the transformation on the original image warp = cv2.warpPerspective(img, m, (int(side), int(side))) plt.imshow(warp, cmap='gray') plt.title('warp_image') plt.show() return warp original = cv2.imread('qrcode.jpeg',1) img = cv2.imread('qrcode.jpeg',0) img = pre_process_image(img) crop_rect = find_corners_of_largest_polygon(img) crop_and_warp(img,crop_rect)
true
77336a7535bd6d4d21ccc1637c4d21d41c5cd001
Python
JingkaiTang/github-play
/first_eye_and_point/hand_and_eye/good_place/life.py
UTF-8
237
2.734375
3
[]
no_license
#! /usr/bin/env python def try_next_person_to_place(str_arg): new_world(str_arg) print('way_or_eye') def new_world(str_arg): print(str_arg) if __name__ == '__main__': try_next_person_to_place('call_old_fact_by_time')
true
0dbc5dc47d47b1c151f28fb76143296c6d9f9c1e
Python
HBinhCT/Q-project
/hackerearth/Algorithms/Mittal wants to go to play!/solution.py
UTF-8
1,425
3.484375
3
[ "MIT" ]
permissive
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here from collections import defaultdict from heapq import heappop, heappush from sys import stdin def dijkstra(start, adj): distances = {i: float('inf') for i in adj} distances[start] = 0 visited = set() heap = [(0, start)] while heap: total, node = heappop(heap) if node not in visited: visited.add(node) for neighbor, cost in adj[node]: new_cost = total + cost if distances[neighbor] > new_cost: distances[neighbor] = new_cost heappush(heap, (new_cost, neighbor)) return distances t = int(stdin.readline()) for _ in range(t): n, m = map(int, stdin.readline().strip().split()) road = defaultdict(list) for _ in range(m): x, y, c = map(int, stdin.readline().strip().split()) road[x].append((y, c)) road[y].append((x, c)) dist = dijkstra(1, road) q = int(stdin.readline()) for _ in range(q): a, k = map(int, stdin.readline().strip().split()) spend = dist[a] * 2 if spend >= k: print(0) else: print(k - spend)
true
22cb04c28a3c1fa23986f5b28dfced810254c72f
Python
kapil87/Object-Oriented-Python-Code
/Chapter_4/BankOOP6_UsingExceptions/Main_Bank_Version6.py
UTF-8
1,294
3.96875
4
[ "BSD-2-Clause" ]
permissive
# Main program for controlling a Bank made up of Accounts from Bank import * # Create an instance of the Bank oBank = Bank('9 to 5', '123 Main Street, Anytown, USA', '(650) 555-1212') #Main code while True: print() print('To get an account balance, press b') print('To close an account, press c') print('To make a deposit, press d') print('To get bank information, press i') print('To open a new account, press o') print('To quit, press q') print('To show all accounts, press s') print('To make a withdrawal, press w ') print() action = input('What do you want to do? ') action = action.lower() action = action[0] # grab the first letter print() try: if action == 'b': oBank.balance() elif action == 'c': oBank.closeAccount() elif action == 'd': oBank.deposit() elif action == 'i': oBank.getInfo() elif action == 'o': oBank.openAccount() elif action == 'q': break elif action == 's': oBank.show() elif action == 'w': oBank.withdraw() except AbortTransaction as error: # Print out the text of the error message print(error) print('Done')
true
8032f37d69bd3299c6913e241eb978a501952555
Python
ActuallyAcey/ClodhoppersBot
/cogs/moderation.py
UTF-8
1,856
2.796875
3
[]
no_license
import discord from discord.ext import commands class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.guild_only() @commands.has_permissions(kick_members = True) async def delete(self, ctx, amount: int=1): """Delete an amount of messages""" await ctx.message.delete() await ctx.message.channel.purge(limit=amount) await ctx.send(f"Deleted {amount} messages.", delete_after=3) @commands.command() @commands.guild_only() @commands.has_permissions(kick_members = True) async def kick(self, ctx, member: discord.Member, for_, *, args: str): if member.dm_channel == None: await member.create_dm() reason = '' for word in args: if word.isspace(): reason += ' ' else: reason += word await member.dm_channel.send(f'You were kicked from **{ctx.guild.name}** for {reason}') await ctx.send(f'**{member.name}** was kicked for {reason}') await member.kick() @commands.command() @commands.guild_only() @commands.has_permissions(ban_members = True) async def ban(self, ctx, member: discord.Member, for_, *, args: str): if member.dm_channel == None: await member.create_dm() reason = '' for word in args: if word.isspace(): # Some black magic done on 9:30 PM at 23rd February, 2019. reason += ' ' else: reason += word await member.dm_channel.send(f'You were banned from **{ctx.guild.name}** for **{reason}**.') await ctx.send(f'**{member.name}** was banned for **{reason}**.') await member.ban() def setup(bot): bot.add_cog(Moderation(bot))
true
1c546d2cc4f8648b374447ab55c4b8c2b154a739
Python
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/4330e069667243979ba5d3bf4a7421af.py
UTF-8
426
3.359375
3
[]
no_license
def hey(msg): if is_blank(msg): return 'Fine. Be that way!' if is_yelling(msg): return 'Whoa, chill out!' if is_question(msg): return 'Sure.' return 'Whatever.' def is_question(msg): # avoid reaching out of bounds in empty array with msg[-1] return len(msg) > 0 and msg[-1] == '?' def is_yelling(msg): return msg.isupper() def is_blank(msg): return msg.strip() == ''
true
569c5993b9a2cae36e692c5204e650b9f27fd83e
Python
dataandyou/covid19
/python/plotInfectedAggregate.py
UTF-8
1,609
3.03125
3
[]
no_license
# Plotting trends on infections # Author : Sandip Pal # Start Date: 06/06/2020 # How to use this script: TBD import plotly.figure_factory as ff import matplotlib.pyplot as plt import matplotlib.pyplot as plt1 import numpy as np import pandas as pd key_name = 'China' df_sample = pd.read_csv('../data/csejhudump/COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv', index_col="Country/Region") lastDays=20 # Trend for the last how many days #Debug prints #print(df_sample) oneRow = df_sample.loc[key_name] #Debug prints #print(oneRow.index[len(oneRow)-lastDays:]) #print(oneRow.values[len(oneRow)-lastDays:]) print(oneRow) aggOneRow = oneRow.groupby('Country/Region').sum() print("Debug: After Groupby Sum") print(aggOneRow) print(aggOneRow.index) res = [aggOneRow.values[i + 1] - aggOneRow.values[i] for i in range(len(aggOneRow.values)-1)] print("Debug: After subtraction") print(res) plt1.figure(figsize=(24, 8)) plt1.bar(aggOneRow.index[len(aggOneRow)-lastDays:], res[len(res)-lastDays:]) plt1.xlabel(f'Last {lastDays} days') plt1.ylabel(key_name) # zip joins x and y coordinates in pairs for x,y in zip(aggOneRow.index[len(aggOneRow)-lastDays:], res[len(res)-lastDays:]): label = "{:.2f}".format(y) plt1.annotate(label, # this is the text (x,y), # this is the point to label textcoords="offset points", # how to position the text xytext=(0,10), # distance from text to points (x,y) ha='center') # horizontal alignment can be left, right or center plt1.show()
true
b9b5adb19a3a1a9b328cfd3b94fbe4d7f36466b9
Python
avontd2868/6.00.1x
/exercises/l3_p9.py
UTF-8
1,125
4.6875
5
[]
no_license
# Lecture 3 Problem 9 ''' Ask user to guess a number between 0 and 100. Guess secret_number with user hints and bisection search: low = 0 high = 100 guess = (high + low) / 2 print guess prompt user for hint: 'h' - guess too high 'l' - guess too low 'c' - guess is correct loop: if 'h': guess is the new high end elif 'l': guess is the new low end elif 'c': game over; break and print guess bisect (guess = (high + low) / 2) print guess ''' low = 0 high = 100 guess = (high + low) / 2 print "Please think of a number between 0 and 100!" while True: print "Is your secret number " + str(guess) + "?" print "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is to low. Enter 'c' to indicate I guessed correctly.", hint = raw_input() if hint == 'h': high = guess elif hint == 'l': low = guess elif hint == 'c': print "Game over. Your secret number was: " + str(guess) break else: print "Sorry, I did not understand your input." continue guess = (high + low) / 2
true
1400ae4f4a2c2d3eb0e7ad8f844b0741ac733ebb
Python
geekcomputers/Python
/Sorting Algorithms/Merge-sort.py
UTF-8
1,426
4.21875
4
[ "LicenseRef-scancode-unknown", "GPL-1.0-or-later", "MIT" ]
permissive
# merge sort lst = [] # declaring list l n = int(input("Enter number of elements in the list: ")) # taking value from user for i in range(n): temp = int(input("Enter element" + str(i + 1) + ": ")) lst.append(temp) def merge(ori_lst, left, mid, right): L, R = [], [] # PREPARE TWO TEMPORARY LIST TO HOLD ELEMENTS for i in range(left, mid): # LOADING L.append(ori_lst[i]) for i in range(mid, right): # LOADING R.append(ori_lst[i]) base = left # FILL ELEMENTS BACK TO ORIGINAL LIST START FROM INDEX LEFT # EVERY LOOP CHOOSE A SMALLER ELEMENT FROM EITHER LIST while len(L) > 0 and len(R) > 0: if L[0] < R[0]: ori_lst[base] = L[0] L.remove(L[0]) else: ori_lst[base] = R[0] R.remove(R[0]) base += 1 # UNLOAD THE REMAINER while len(L) > 0: ori_lst[base] = L[0] L.remove(L[0]) base += 1 while len(R) > 0: ori_lst[base] = R[0] R.remove(R[0]) base += 1 # ORIGINAL LIST SHOULD BE SORTED FROM INDEX LEFT TO INDEX RIGHT def merge_sort(L, left, right): if left + 1 >= right: # ESCAPE CONDITION return mid = left + (right - left) // 2 merge_sort(L, left, mid) # LEFT merge_sort(L, mid, right) # RIGHT merge(L, left, mid, right) # MERGE print("UNSORTED -> ", lst) merge_sort(lst, 0, n) print("SORTED -> ", lst)
true
12a98260e881b8397eb81d420043eafef17501bd
Python
wwtang/code02
/findpermuataion.py
UTF-8
1,465
3.5625
4
[]
no_license
""" the example of find permutaion """ # prefix ="" . cool why we need the prefix def getPermutations(string, storage, prefix=""): if len(string) ==1: # here is prefix + ""stirng"", not "string[i]", each time update the prefix storage.append(prefix+string) else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) #print "***", prefix+string[i], "***" return storage def getPermutations1(string, prefix=""): if len(string) ==1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations1(string[:i]+string[i+1:], prefix+string[i]): yield perm # without a accumulator def getPermutations2(string, prefix=""): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations2(string[:i]+string[i+1:], prefix+string[i]): yield string[i]+perm def main(): print "Version 1 *******" storage = [] getPermutations("abc", storage) for permutation in storage: print permutation print "Version 2 *******" p1 = getPermutations1("abc") for item in p1: print item print p1 print "Version 3 *******" p2 = getPermutations2("abc") for item in p2: print item print p2 if __name__ =="__main__": main()
true
07acbf5f0321e2b8ff6ebf10e6dfdd127db6615a
Python
COMP0031VRProject/Framework
/example.py
UTF-8
2,653
2.953125
3
[]
no_license
import numpy as np from Bot import * from World import * from Utils import * # Generate the three Meshes n = 20 virtual = generate_embedded_polygon_mesh(n, 5, 2, (0,0)) homogeneous_scaling_k_real = virtual.copy() center = homogeneous_scaling_k_real.verts[0] k = 2 for i,v in enumerate(homogeneous_scaling_k_real.verts): # Move all vertices towards center homogeneous_scaling_k_real.verts[i] = np.array([(v[0] - center[0]) / k + center[0], (v[1] - center[1]) / k + center[1]]) warped = homogeneous_scaling_k_real.copy() center = warped.verts[0] for i in range(1, n + 1): # Move vertices of inner circle away from center v = warped.verts[i] warped.verts[i] = np.array([(v[0] - center[0]) * k + center[0], (v[1] - center[1]) * k + center[1]]) # Initialize the Bot bot = Bot(speed=0.1) # Initial Virtual Position of the Bot start_position = np.array([-5.0,5.0]) # Goals / Flags for the Bot targets = [[5.0,5.0], [5.0,-5.0], [-5.0,-5.0], [-5.0,5.0]] targets = [np.array(t) for t in targets] # Initialize the world for homogeneous scaling homo_world = World(virtual, homogeneous_scaling_k_real, start_position, bot, targets) homo_rRecord, homo_vRecord = homo_world.simulate() # Initialize the world for area of interest (Choi's method) aoi_world = World(virtual, warped, start_position, bot, targets) aoi_rRecord, aoi_vRecord = aoi_world.simulate() # Visualize all fig, axs = plt.subplots(2,2) # Real World Trajectory for homogeneous scaling axs[0][0].set_xlim((-10, 10)) axs[0][0].set_ylim((-10, 10)) axs[0][0].set_aspect('equal') axs[0][0].set_title('Real World Trajectory for homogeneous scaling') visualize_records(axs[0][0], homo_rRecord) visualize_mesh(axs[0][0], homogeneous_scaling_k_real) # Virtual World Trajectory for homogeneous scaling axs[0][1].set_xlim((-10, 10)) axs[0][1].set_ylim((-10, 10)) axs[0][1].set_aspect('equal') axs[0][1].set_title('Virtual World Trajectory for homogeneous scaling') visualize_records(axs[0][1], homo_vRecord) visualize_mesh(axs[0][1], virtual) visualize_targets(axs[0][1], targets) # Real World Trajectory for Choi's method axs[1][0].set_xlim((-10, 10)) axs[1][0].set_ylim((-10, 10)) axs[1][0].set_aspect('equal') axs[1][0].set_title('Real World Trajectory for Choi\'s method') visualize_records(axs[1][0], aoi_rRecord) visualize_mesh(axs[1][0], warped) # Virtual World Trajectory for Choi's method axs[1][1].set_xlim((-10, 10)) axs[1][1].set_ylim((-10, 10)) axs[1][1].set_aspect('equal') axs[1][1].set_title('Virtual World Trajectory for Choi\'s method') visualize_records(axs[1][1], aoi_vRecord) visualize_mesh(axs[1][1], virtual) visualize_targets(axs[1][1], targets) plt.show()
true
e3adc3b02b6c20381eff7f0f625bf48d192d71bb
Python
PythonFunProj/games
/final/parcour_client_2.1.py
UTF-8
11,953
2.515625
3
[]
no_license
import pygame from pygame.locals import * from queue import Queue, Empty import websocket import _thread import os from levelsdata import wallsforlevel, killrectsforlevel, winrectsforlevel, spawnforlevel, backgroundforlevel, fakewallsforlevel # sets the location of the .py file as the working directory abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) print(websocket.__version__) q = Queue() online = True colors = [(255, 0, 0), (0, 255, 0), (255, 255, 0)] pygame.mixer.init() s = 'sound' jumpsound = pygame.mixer.Sound('sounds/SFX_Jump_09.wav') hurtsound = pygame.mixer.Sound('sounds/SFX_Jump_50.wav') wintouch = pygame.mixer.Sound('sounds/coin10.wav') def ws_message(ws, message): # print('Enqueued ' + message) q.put(message) def ws_open(ws): ws.send('{"event":"subscribe", "subscription":{"name":"trade"}, "pair":["XBT/USD","XRP/USD"]}') def ws_thread(*args): ws.run_forever() ws = websocket.WebSocketApp("ws:///", on_open=ws_open, on_message=ws_message) # Start a new thread for the WebSocket interface _thread.start_new_thread(ws_thread, ()) # controller pygame.joystick.init() class Game: def __init__(self): print("init game") self.collision = False self.moveLeft, self.moveRight, self.moveUp, self.jump = False, False, False, False self.player = pygame.Rect(300, 600, 25, 25) self.MOVESPEED = 15 self.MOVESPEEDy = 0 # self.click = 0 self.friend = [[-25, -25], [-25, -25], [-25, -25]] self.elevator = 0 self.walls = [] self.joy = False self.joysticks = False if pygame.joystick.get_count() > 0: # self.joystick = pygame.joystick.Joystick(0).init() self.joy = True pygame.joystick.init() self.joysticks = pygame.joystick.Joystick(0) def run_logic(self, winrects, killrects, level): self.collision = False """move/collision left""" if self.moveLeft and self.player.left > 0: self.player.left -= self.MOVESPEED for wall in self.walls[:]: if self.player.colliderect(wall) and wall.right <= self.player.left+self.MOVESPEED: #print("oui") self.player.left = wall.right self.collision = True if self.player.left < 0: self.player.left = 0 for player1 in self.friend: x = self.player x1 = int(player1[0]) y1 = int(player1[1]) if y1-25 < x.top < y1+25 and x1-25 < x.left < x1+25: self.player.left = x1+25 self.collision = True """move/collision right""" if self.moveRight and self.player.right < 800: self.player.right += self.MOVESPEED for wall in self.walls[:]: if self.player.colliderect(wall) and wall.left >= self.player.right-self.MOVESPEED: #print("oui") self.player.right = wall.left self.collision = True for player1 in self.friend: x = self.player x1 = int(player1[0]) y1 = int(player1[1]) if y1-25 < x.top < y1+25 and x.right > x1 and x.left < x1 + 25: self.player.right = x1 self.collision = True """fall""" self.player.bottom -= self.MOVESPEEDy self.MOVESPEEDy -= 1 for wall in self.walls[:]: if self.player.colliderect(wall) and not self.jump: self.player.bottom = wall.top #print(wall) self.MOVESPEEDy = 0 self.collision = True for player1 in self.friend: x = self.player.left y = self.player.top x1 = int(player1[0]) y1 = int(player1[1]) if x-25 < x1 < x + 25 and y + abs(self.MOVESPEED) > y1 >= y: self.player.bottom = y1 self.MOVESPEEDy = 0 self.collision = True """jump""" if self.jump and self.MOVESPEEDy == 0: self.jump = False if self.moveUp and self.collision and not self.jump: self.jump = True pygame.mixer.Sound.play(jumpsound) self.MOVESPEEDy = 15 """collision at the Top of the player""" for wall in self.walls[:]: if self.player.colliderect(wall) and self.jump: self.jump = False self.player.top = wall.bottom self.MOVESPEEDy = 0 if self.friend: for player1 in self.friend: x = self.player.left y = self.player.top x1 = int(player1[0]) y1 = int(player1[1]) if x-25 < x1 < x + 25 and self.jump and y1+25 == y: self.jump = False self.player.top = y1+25 self.MOVESPEEDy = 0 """collision with killrect""" for kr in killrects[:]: if self.player.colliderect(kr): print("ouch") pygame.mixer.Sound.play(hurtsound)###################################"" self.player.left = int(spawnforlevel(level)[0]) self.player.top = int(spawnforlevel(level)[1]) """collision with winrect""" win = False for wr in winrects[:]: if self.player.colliderect(wr): pygame.mixer.Sound.play(wintouch) level += 1 print('win') self.player.left = int(spawnforlevel(level)[0]) self.player.top = int(spawnforlevel(level)[1]) win = True return win, level def process_events(self): for event in pygame.event.get(): if event.type == QUIT: return True keys = pygame.key.get_pressed() self.moveLeft, self.moveRight, self.moveUp = False, False, False if keys[pygame.K_LEFT] \ or (self.joy and self.joysticks.get_axis(0) < -0.1): self.moveLeft = True self.moveRight = False if keys[pygame.K_RIGHT] \ or (self.joy and self.joysticks.get_axis(0) > 0.1): self.moveRight = True self.moveLeft = False if keys[pygame.K_UP] \ or (self.joy and self.joysticks.get_button(0)): self.moveUp = True return False class Elevators: # elevator = Elevators(660, 600, 30, 750, 500) def __init__(self, xbutton, ybutton, xelevator, yelevator, maxheight): self.xbutton = xbutton self.ybutton = ybutton self.xelevator = xelevator self.yelevator = yelevator self.maxheight = maxheight self.buttonOF = False self.height = 0 def button(self, posx, posy, friend): self.buttonOF = False if posy == self.ybutton-25 and self.xbutton+15 < posx < self.xbutton + 115: self.buttonOF = True else: for i in range(3): if int(friend[i][1]) == self.ybutton-25 and self.xbutton+15 < int(friend[i][0]) < self.xbutton + 115: self.buttonOF = True def elevator(self): if self.height < self.maxheight and self.buttonOF: self.height += 1 if self.height > 0 and not self.buttonOF: self.height -= 1 def display_frame(friend, colors, screen, walls, xbutton, ybutton, height, player, xelevator, yelevator, killrects, winrects,fakewalls, background, image): screen.fill((35, 35, 60)) screen.blit(background, [0, 0]) # friend: for i in range(3): pygame.draw.rect(screen, colors[i], pygame.Rect(int(friend[i][0]), int(friend[i][1]), 25, 25)) screen.blit(image, (int(friend[i][0]), int(friend[i][1]))) # walls: for wall in walls: pygame.draw.rect(screen, (0, 0, 0), wall) for kr in killrects: pygame.draw.rect(screen, (200, 0, 0), kr) for wr in winrects: pygame.draw.rect(screen, (200, 200, 0), wr) for fw in fakewalls: pygame.draw.rect(screen,(0,0,0),fw) # button: pygame.draw.rect(screen, (50, 50, 50), pygame.Rect(xbutton, ybutton, 105, 8)) pygame.draw.rect(screen, (150, 0, 0), pygame.Rect(xbutton+15, ybutton-3, 75, 7)) # elevator pygame.draw.rect(screen, (20, 20, 20), pygame.Rect(xelevator, yelevator-height, 100, height)) # player: pygame.draw.rect(screen, (0, 0, 255), player) screen.blit(image, (player.left, player.top)) pygame.display.update() def updatelevel(level, game): game.walls = wallsforlevel(level) killrects = killrectsforlevel(level) winrects = winrectsforlevel(level) spawn = spawnforlevel(level) fakewalls = fakewallsforlevel(level) background = backgroundforlevel(level) game.player.left = (int(spawn[0])) game.player.top = (int(spawn[1])) return killrects, winrects, background, fakewalls def main(): level = 1 pygame.init() image1 = pygame.image.load(r'images/character.png') image1 = pygame.transform.scale(image1, (25, 25)) # Create an instance of the Game class game = Game() # elevator = Elevators(660, 600, 30, 750, 500) elevator = Elevators(-100, -600, -30, -750, 500) updatelevel(level, game) clock = pygame.time.Clock() # pygame.key.set_repeat(10, 100) screen = pygame.display.set_mode((800, 800), 0, 32) pygame.display.set_caption("client") pygame.mouse.set_visible(False) killrects, winrects, background, fakewalls = updatelevel(level, game) done = False # Main game loop while not done: # Process events (keystrokes, mouse clicks, etc) done = game.process_events() # Update object positions, check for collisions win, level = game.run_logic(winrects, killrects, level) if win: killrects, winrects, background, fakewalls= updatelevel(level, game) elevator.button(game.player.left, game.player.top, game.friend) elevator.elevator() try: while True: data = q.get(False) # If `False`, the program is not blocked. `Queue.Empty` is thrown if # the queue is empty if data[0] == "p": # data => p 'x' / 'y' 'player' e = int(data[len(data)-1]) f = len(game.friend) pos1 = data.find('/') game.friend[e][0] = int(data[1:pos1]) game.friend[e][1] = data[pos1 + 1:len(data)-1] else: #print(data[0]) pass except Empty: data = 0 # send coordinates try: ws.send("p" + str(game.player.left) + "/" + str(game.player.top)) online = True except: online = False # Draw the current frame display_frame(game.friend, colors, screen, game.walls, elevator.xbutton, elevator.ybutton, elevator.height, game.player, elevator.xelevator, elevator.yelevator, killrects, winrects, fakewalls, background, image1) # Pause for the next frame clock.tick(60) # Close window and exit pygame.quit() # Call the main function, start up the game main()
true
1d7ab987b3718914917eab0a00025ad114e4ac63
Python
Aasthaengg/IBMdataset
/Python_codes/p03041/s982160667.py
UTF-8
100
2.796875
3
[]
no_license
n,k = map(int,input().split()) S = input() s = list(S) s[k-1] = str.lower(s[k-1]) print(''.join(s))
true
fefeacbb704597b0d536989e62a27ad5dc45c06b
Python
ravindraved/pyflask_demoapp
/rest-apps-section1_to_4/security.py
UTF-8
652
2.78125
3
[ "MIT" ]
permissive
from dobj.user_do import UserDo from werkzeug.security import safe_str_cmp # safe string compare to account for unicode characters.. mostly for python versions 2 userslist = [ UserDo(1, "ravi", "ravi1"), UserDo(2, "aditya", "aditya1") ] username_mapping = {u.username: u for u in userslist} userid_mapping = {u.id: u for u in userslist} def authenticate(username, password): user = username_mapping.get(username, None) if user and safe_str_cmp(user.password, password): return user def identity(payload): user_id = payload['identity'] return userid_mapping.get(user_id, None) print(authenticate('ravi','rav1'))
true
2adac39067dff8f4ce7f50a15fd401011218a20f
Python
oscarcontreras24/Python-Baseball
/stats/defense.py
UTF-8
2,192
3.1875
3
[ "MIT" ]
permissive
import pandas as pd import matplotlib.pyplot as plt from frames import games, info, events plays = games.query("type == 'play' & event != 'NP'") plays.columns = ['type', 'inning', 'team', 'player', 'count', 'pitches', 'event', 'game_id', 'year'] #print(plays.head()) #ensurng that consecutive player appearneces aren't duplicated but kept to one index per player pa = plays.loc[plays['player'].shift() != plays['player'], ['year', 'game_id', 'inning', 'team', 'player']] #print(pa.head()) pa = pa.groupby(['year', 'game_id', 'team']).size().reset_index(name = 'PA') #print(events.head()) #makes the columns origianlly asigned to the data frame the indexes for the data frame events = events.set_index(['year', 'game_id', 'team', 'event_type']) #print(events.head()) #making a data frame that takes the values of a multi-index and makes the element in a column, into a column and making each row indexed like before events = events.unstack().fillna(0).reset_index() events.columns = events.columns.droplevel() #print(events.head()) events.columns = ['year', 'game_id', 'team', 'BB', 'E', 'H', 'HBP', 'HR', 'ROE', 'SO'] #ensures the index name is not evemnt_types and on the sme axis as the other column headers events = events.rename_axis('None', axis = 'columns') #print(events.head()) #performing an outer merge wuth pa and events events_plus_pa = pd.merge(events, pa, how = 'outer', left_on = ['year', 'game_id', 'team'], right_on = ['year', 'game_id', 'team']) #print(events_plus_pa.head()) #merging info and event plus data frame to attachleague info defense = pd.merge(events_plus_pa, info) #assigning the DER to the DER column defense.loc[:, 'DER'] = 1 - ((defense['H'] + defense['ROE']) / (defense['PA'] - defense['BB'] - defense['SO'] - defense['HBP'] - defense['HR'])) #need in order to plot defense['year'] = pd.to_numeric(defense.loc[:, 'year']) #print(defense.head()) #new data frame with columns of interest der = defense.loc[defense['year'] >= 1978, ['year', 'defense', 'DER']] #arranges data in a plottable format der = der.pivot(index = 'year', columns = 'defense', values = 'DER') der.plot(x_compat = True, xticks = range(1978, 2018, 4), rot = 45) plt.show()
true
9d70d46472653ac35758ce99060dadb10a56672c
Python
umichczn/final_proj
/final.py
UTF-8
5,843
2.875
3
[]
no_license
from bs4 import BeautifulSoup import requests import json import secrets import time import sqlite3 import random from decimal import Decimal HOTELS_URL = 'https://www.latlong.net/category/hotels-236-57.html' BASE_URL = 'https://api.yelp.com' SEARCH_PATH = '/v3/businesses/search' CACHE_DICT = {} CACHE_FILE_NAME = 'cache.json' API_KEY = secrets.API_KEY def creat_db(): '''create a database connection to the SQLite database specified by "Final_Project.db". And create two tables in the db. Parameters ---------- None Returns ------- None ''' connection = sqlite3.connect("Final_Project.db") cursor = connection.cursor() query1 = '''CREATE TABLE IF NOT EXISTS Hotels ( Id INTEGER NOT NULL, HotelName TEXT, HotelCity TEXT, HotelState TEXT, Latitude TEXT, Longitude TEXT, PRIMARY KEY(Id)); ''' cursor.execute(query1) connection.commit() query2 = '''CREATE TABLE IF NOT EXISTS Restaurants ( Id INTEGER NOT NULL, Name TEXT, HotelId INTEGER, Rating TEXT, AvgPrice TEXT, Distance REAL, Link TEXT, FOREIGN KEY(HotelId) REFERENCES Hotels(Id)); ''' cursor.execute(query2) connection.commit() connection.close() #--------Scraping a web page and store data into sqlite--------# def get_hotels_list(url): '''scraping a web page and get each hotel information into a list. Parameters ---------- url: string the url we are going to scrape. Returns ------- list all the hotel stored in a list. ''' #cache CACHE_DICT = load_cache() url_text = make_url_request_using_cache(url, CACHE_DICT) hotels_list = [] soup = BeautifulSoup(url_text, 'html.parser') hotels = soup.find_all("tr")[1:] for hotel in hotels: title = hotel.find('a')['title'] hotel_name = title.split(',')[0].strip() hotel_city = title.split(',')[1].strip() hotel_state = title.split(',')[2].strip() latitude = hotel.find_all('td')[1].string longitude = hotel.find_all('td')[2].string hotels_list.append((hotel_name, hotel_city, hotel_state, latitude, longitude)) return hotels_list def insert_hotels_database(hotels_list): '''insert hotel attribute into sqlite database. Parameters ---------- hotels_list: list the list with all hotel info Returns ------- None ''' connection = sqlite3.connect("Final_Project.db") cursor = connection.cursor() i = 1 for hotel in hotels_list: query = f'''INSERT INTO Hotels (Id, HotelName, HotelCity, HotelState, Latitude, Longitude) VALUES ({i}, "{hotel[0]}", "{hotel[1]}", "{hotel[2]}", "{hotel[3]}", "{hotel[4]}") ''' cursor.execute(query) i += 1 connection.commit() connection.close() #--------Request from Yelp Api and store data into sqlite-------# def get_nearby_restaurants(hotel_id): '''with specific hotel id get 20 nearby restaurants from yelp api. Parameters ---------- hotels_id: int the id of the hotel Returns ------- dict: the dict type of returned data. ''' connection = sqlite3.connect("Final_Project.db") cursor = connection.cursor() lat = Decimal(cursor.execute(f'SELECT * FROM Hotels WHERE Id={hotel_id}').fetchall()[0][-2]) log = Decimal(cursor.execute(f'SELECT * FROM Hotels WHERE Id={hotel_id}').fetchall()[0][-1]) connection.close() resource_url = BASE_URL + SEARCH_PATH headers = {'Authorization': 'Bearer %s' % API_KEY} params = { 'term' : 'restaurants', 'latitude' : lat, 'longitude' : log, 'sort_by' : 'best_match' } response = requests.get(resource_url, headers=headers, params=params) return response.json() def load_cache(): try: cache_file = open(CACHE_FILE_NAME, 'r') cache_file_contents = cache_file.read() cache = json.loads(cache_file_contents) cache_file.close() except: cache = {} return cache def save_cache(cache): cache_file = open(CACHE_FILE_NAME, 'w') contents_to_write = json.dumps(cache) cache_file.write(contents_to_write) cache_file.close() def make_url_request_using_cache(url, cache): if (url in cache.keys()): print("Using cache") return cache[url] else: print("Fetching") time.sleep(1) response = requests.get(url) cache[url] = response.text save_cache(cache) return cache[url] def insert_restaurants_database(id): '''insert restaurants attribute into sqlite database with specific hotel id. Parameters ---------- hotels_id: int the id of the hotel Returns ------- None ''' rest_dict = get_nearby_restaurants(id) connection = sqlite3.connect("Final_Project.db") cursor = connection.cursor() i = 1 for rest in rest_dict['businesses']: name = rest['name'] hotel_id = id rating = rest['rating'] if 'rating' in rest else 'unclear' price = rest['price'] if 'price' in rest else 'unclear' dist = rest['distance'] if 'distance' in rest else 'unclear' link = rest['url'] if 'url' in rest else 'unclear' query = f'''INSERT INTO Restaurants (Id, Name, HotelId, Rating, AvgPrice, Distance, Link) VALUES ({i}, "{name}", {hotel_id}, "{rating}", "{price}", "{dist}", "{link}") ''' cursor.execute(query) i += 1 connection.commit() connection.close() if __name__ == "__main__": creat_db() hotels_list = get_hotels_list(HOTELS_URL) insert_hotels_database(hotels_list) for i in range(1, len(hotels_list) + 1): insert_restaurants_database(i)
true