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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d7c7fa637a169ca06cf885ae5c49d206b9443f07 | Python | SiChiTong/micro_mouse_final | /control_mousebot/scripts/Controller.py | UTF-8 | 7,898 | 3.25 | 3 | [] | no_license | #!/usr/bin/env python3
""" objective - control the robot at a very very high level"""
from Graph import Graph2
from MoveComputer import MoveComputer2
from DriveStep import DriveStep
from PathPlanner import PathPlanner
import rospy
import time
import numpy as np
class Controller(object):
def __init__(self):
# params for driving
self.regular_speed = 0.3
self.speedrun_speed = 1.3
#unit_length = 0.195 #For regular runs
unit_length = 0.188 #For speed runs
# positions
self.pos = (0,0)
self.target_list = [(7, 7), (7, 8), (8, 7), (8, 8)]
# circular buffer for nodes visited
self.len_nodes_visited = 5
self.nodes_visited = [0]*self.len_nodes_visited
self.pointer = 0
# initializing objects
self.MoveComputer = MoveComputer2()
self.graph = Graph2()
self.driver = DriveStep(self.pos, unit_length=unit_length)
self.planner = PathPlanner()
self.previous_graph = None # dictionary, not graph object.
self.save = False # for saving the graph
self.step = False # steps vs continuous drive
def run_advanced(self):
""" blocking code while loop for mousebot reach center """
walls = self.driver.return_walls(first=True) # compute first walls before movement
print('walls returned first: ', walls)
pos = self.pos
while (pos not in self.target_list) and not rospy.is_shutdown():
print('movement!=======================================================================')
self.graph.update_graph(pos, walls)
next_pos = self.MoveComputer.compute_next_move(self.graph, pos)
print("Moving to: ", next_pos)
walls = self.driver.drive_advanced(next_pos, self.regular_speed) # updates walls, position
pos = next_pos
# self.nodes_visited[self.pointer] = pos
# counter = 0
# for visited in self.nodes_visited:
# if visited == self.nodes_visited[self.pointer]:
# counter += 1
# if counter >=3:
# print("you're in a back and forth loop, altering MoveComputer2 code")
# self.pointer = (self.pointer+1)%self.len_nodes_visited
print(' ')
if self.step:
time.sleep(.3)
# do some final updates
self.pos = pos
self.graph.update_graph(pos, walls) # final graph update with destination.
print("reached center")
def run(self):
""" blocking code while loop for mousebot reach center """
walls = self.driver.return_walls(first=True) # compute first walls before movement
print('walls returned first: ', walls)
pos = self.pos
while (pos not in self.target_list) and not rospy.is_shutdown():
print('movement!=======================================================================')
self.graph.update_graph(pos, walls)
next_pos = self.MoveComputer.compute_next_move(self.graph, pos)
print("Moving to: ", next_pos)
walls = self.driver.drive(next_pos, self.regular_speed) # updates walls, position
pos = next_pos
self.nodes_visited[self.pointer] = pos
counter = 0
for visited in self.nodes_visited:
if visited == self.nodes_visited[self.pointer]:
counter += 1
if counter >=3:
print("you're in a back and forth loop, altering MoveComputer2 code")
self.pointer = (self.pointer+1)%self.len_nodes_visited
print(' ')
if self.step:
time.sleep(.3)
# do some final updates
self.pos = pos
self.graph.update_graph(pos, walls) # final graph update with destination.
print("reached center")
# save dictionary
if self.save:
time.sleep(5)
print("should be complete graph, saving ... ", self.graph.graph)
np.save('mazes/graph.npy', self.graph.graph)
def test_speedrun(self):
target = (8,8)
pos = self.pos
self.previous_graph = np.load('mazes/graph.npy',allow_pickle='TRUE').item()
path_to_center = self.planner.a_star(self.previous_graph, start=pos, target=target)
print("path to center: ", path_to_center)
optimized_path = self.planner.consolidate_path(path_to_center)
print("optimized path: ", optimized_path)
while not rospy.is_shutdown():
for position in optimized_path:
print('movement!=======================================================================')
print("Moving to: ", position)
self.driver.drive_speedrun(position, self.speedrun_speed) # updates walls, position
pos = position
print(' ')
if self.step:
time.sleep(.3)
break
print("At Center.")
self.pos = pos
def test_pathplanning(self):
"""test pathplanning code with imported maze graph"""
target = (8,8)
pos = self.pos
self.previous_graph = np.load('mazes/graph.npy',allow_pickle='TRUE').item()
print("prev graph: ", self.previous_graph)
path_to_center = self.planner.a_star(self.previous_graph, start=pos, target=target)
while not rospy.is_shutdown():
for position in path_to_center:
print('movement!=======================================================================')
print("Moving to: ", position)
walls = self.driver.drive(position, self.regular_speed) # updates walls, position
pos = position
print(' ')
if self.step:
time.sleep(.3)
break
print("At Center.")
def run_with_astar(self, target):
# code for mousebot to reverse track back to starting point
pos = self.pos
path_to_home = self.planner.a_star(self.graph.graph, start=pos, target=target)
print(path_to_home)
while not rospy.is_shutdown():
for position in path_to_home:
print('movement!=======================================================================')
print("Moving to: ", position)
walls = self.driver.drive(position, self.regular_speed) # updates walls, position
pos = position
print(' ')
if self.step:
time.sleep(.3)
break
self.pos = pos
print("Back home.")
def speedrun(self, target):
pos = self.pos
self.previous_graph = np.load('mazes/graph.npy',allow_pickle='TRUE').item()
path_to_center = self.planner.a_star(self.previous_graph, start=pos, target=target)
print("path to center: ", path_to_center)
optimized_path = self.planner.consolidate_path(path_to_center)
print("optimized path: ", optimized_path)
while not rospy.is_shutdown():
for position in optimized_path:
print('movement!=======================================================================')
print("Moving to: ", position)
self.driver.drive_speedrun(position, self.speedrun_speed) # updates walls, position
pos = position
print(' ')
if self.step:
time.sleep(.3)
break
print("At target.")
if __name__ == '__main__':
control = Controller()
# control.test_pathplanning()
control.run()
# control.run_advanced()
#control.run_with_astar(target=(0,0))
# control.speedrun(target = (8,8))
# control.test_speedrun()
| true |
4a4db97774cb4c878fa370eb21560ed7f696091b | Python | CaiqueSobral/PyLearning | /Code Day 1 - 10/Code Day 9 Dictionaries and Nesting/1_Day 9 First Steps/2_Grades_Exercise.py | UTF-8 | 579 | 3.625 | 4 | [] | no_license | studentScores = {
"Harry": 81,
"Ron": 78,
"Hermione": 99,
"Draco": 74,
"Neville": 62,
}
#ToDo-1: Create an empty dictionary called student_grades.
studentGrades = {}
#ToDo-2: Write your code below to add the grades to student_grades.👇
for key in studentScores:
if studentScores[key] > 90:
studentGrades[key] = "Outstanding"
elif studentScores[key] > 80:
studentGrades[key] = "Exceeds Expectations"
elif studentScores[key] > 70:
studentGrades[key] = "Acceptable"
else:
studentGrades[key] = "Fail"
print(studentGrades) | true |
40238bccb1145ebe43f2b71f57fde668b6a9c0e7 | Python | Kefkius/txsc | /txsc/txscript/script_parser.py | UTF-8 | 8,824 | 2.765625 | 3 | [] | no_license | import ast
from ply import lex, yacc
import lexer
class ScriptParser(object):
tokens = lexer.tokens
precedence = lexer.precedence
def __init__(self, **kwargs):
self.debug = False
for k, v in kwargs.items():
setattr(self, k, v)
self.lexer = lex.lex(module=lexer)
self.parser = yacc.yacc(module=self, debug=self.debug)
def parse(self, s):
return self.parser.parse(s, lexer=self.lexer, tracking=True)
def get_bin_op(self, s):
"""Get the BinOp class for s."""
op = None
if s == '+':
op = ast.Add()
elif s == '-':
op = ast.Sub()
elif s == '*':
op = ast.Mult()
elif s == '/':
op = ast.Div()
elif s == '%':
op = ast.Mod()
elif s == '<<':
op = ast.LShift()
elif s == '>>':
op = ast.RShift()
elif s == '&':
op = ast.BitAnd()
elif s == '^':
op = ast.BitXor()
elif s == '|':
op = ast.BitOr()
return op
def p_error(self, p):
raise SyntaxError('Syntax error: %s' % p)
def p_module(self, p):
'''module : statement
| module statement
'''
p[1].lineno = p.lineno(1)
if isinstance(p[1], ast.Module):
p[0] = p[1]
else:
p[0] = ast.Module(body=[p[1]])
p[0].lineno = p.lineno(1)
if len(p) == 3:
p[2].lineno = p.lineno(2)
p[0].body.append(p[2])
def p_ifbody(self, p):
'''ifbody : module
|
'''
if len(p) == 1:
module = ast.Module(body=[])
else:
module = p[1]
p[0] = module
def p_conditional(self, p):
'''statement : IF expr LBRACE ifbody RBRACE
| IF expr LBRACE ifbody RBRACE ELSE LBRACE ifbody RBRACE
'''
test = p[2]
iftrue = p[4]
iftrue.lineno = p.lineno(4)
iffalse = []
if len(p) > 6:
iffalse = p[8]
iffalse.lineno = p.lineno(8)
p[0] = ast.If(test=test, body=iftrue, orelse=iffalse)
def p_declaration(self, p):
'''statement : LET NAME EQUALS expr SEMICOLON
| LET MUTABLE NAME EQUALS expr SEMICOLON
'''
if p[2] == 'mutable':
name = p[3]
value = p[5]
mutable = True
else:
name = p[2]
value = p[4]
mutable = False
p[0] = ast.Assign(targets=[
ast.Name(id=name, ctx=ast.Store()),
], value=value)
p[0].mutable = mutable
p[0].declaration = True
def p_aug_assignment_op(self, p):
'''augassign : PLUSEQUALS
| MINUSEQUALS
| TIMESEQUALS
| DIVIDEEQUALS
| MODEQUALS
| LSHIFTEQUALS
| RSHIFTEQUALS
| AMPERSANDEQUALS
| CARETEQUALS
| PIPEEQUALS
'''
op = p[1]
base_op = op[:-1]
bin_op = self.get_bin_op(base_op)
p[0] = bin_op
def p_unary_aug_assignment_op(self, p):
'''unaryaugassign : INCREMENT
| DECREMENT
'''
op = p[1]
bin_op = ast.BinOp()
bin_op.right = ast.Num(1)
if op == '++':
bin_op.op = ast.Add()
elif op == '--':
bin_op.op = ast.Sub()
p[0] = bin_op
def p_statement_unary_aug_assign(self, p):
'''statement : NAME unaryaugassign SEMICOLON'''
bin_op = p[2]
bin_op.left = ast.Name(id=p[1], ctx=ast.Load())
p[0] = ast.AugAssign(target=ast.Name(id=p[1], ctx=ast.Store()),
op=bin_op.op,
value=bin_op.right)
def p_statement_assign(self, p):
'''statement : NAME EQUALS expr SEMICOLON
| NAME augassign expr SEMICOLON
'''
name = p[1]
value = p[3]
target = ast.Name(id=name, ctx=ast.Store())
if p[2] == '=':
p[0] = ast.Assign(targets=[
target,
], value=value)
else:
p[0] = ast.AugAssign(target=target,
op=p[2],
value=value)
p[0].declaration = False
def p_function_args(self, p):
'''args : expr
| args COMMA expr
|
'''
args = []
if len(p) > 1:
args = [p[1]]
if getattr(p[1], 'is_arguments', False):
args = p[1].elts
if len(p) > 2:
args.append(p[3])
p[0] = ast.List(elts=args, ctx=ast.Store())
p[0].is_arguments = True
def p_function_define(self, p):
'''statement : FUNC TYPENAME NAME LPAREN args RPAREN LBRACE module RBRACE'''
func_name = p[3]
args = p[5]
body = p[8].body
p[0] = ast.FunctionDef(name=func_name, args=ast.arguments(args=args), body=body)
p[0].type_name = p[2]
def p_assume(self, p):
'''statement : ASSUME args SEMICOLON'''
if not all(isinstance(i, ast.Name) for i in p[2].elts):
raise Exception('Assumptions can only be assigned to names.')
p[0] = ast.Assign(targets=[ast.Name(id='_stack', ctx=ast.Store())], value=p[2])
p[0].mutable = False
p[0].declaration = True
def p_return(self, p):
'''statement : RETURN expr SEMICOLON'''
p[0] = ast.Return(p[2])
def p_function_call(self, p):
'''expr : NAME LPAREN args RPAREN
| TYPENAME LPAREN args RPAREN
'''
p[0] = ast.Call(func=ast.Name(id=p[1], ctx=ast.Load()),
args=p[3].elts,
keywords=[])
def p_boolop(self, p):
'''expr : expr AND expr
| expr OR expr
'''
op = ast.And() if p[2] == 'and' else ast.Or()
p[0] = ast.BoolOp(op=op, values=[p[1], p[3]])
def p_expr_unaryop(self, p):
'''expr : MINUS expr %prec UNARYOP
| TILDE expr %prec UNARYOP
| NOT expr %prec UNARYOP
'''
op = None
if p[1] == '-':
op = ast.USub()
elif p[1] == '~':
op = ast.Invert()
elif p[1] == 'not':
op = ast.Not()
p[0] = ast.UnaryOp(op=op, operand=p[2])
def p_verify(self, p):
'''expr : VERIFY expr'''
p[0] = ast.Assert(test=p[2], msg=None)
def p_expr_binop(self, p):
'''expr : expr PLUS expr
| expr MINUS expr
| expr TIMES expr
| expr DIVIDE expr
| expr MOD expr
| expr LSHIFT expr
| expr RSHIFT expr
| expr AMPERSAND expr
| expr CARET expr
| expr PIPE expr
'''
op = self.get_bin_op(p[2])
p[0] = ast.BinOp(left=p[1], op=op, right=p[3])
def p_expr_compare(self, p):
'''expr : expr EQUALITY expr
| expr INEQUALITY expr
| expr LESSTHAN expr
| expr GREATERTHAN expr
| expr LESSTHANOREQUAL expr
| expr GREATERTHANOREQUAL expr
'''
op = None
if p[2] == '==':
op = ast.Eq()
elif p[2] == '!=':
op = ast.NotEq()
elif p[2] == '<':
op = ast.Lt()
elif p[2] == '>':
op = ast.Gt()
elif p[2] == '<=':
op = ast.LtE()
elif p[2] == '>=':
op = ast.GtE()
p[0] = ast.Compare(left=p[1], ops=[op], comparators=[p[3]])
def p_expr_hexstr(self, p):
'''expr : HEXSTR'''
s = p[1].replace('\'','')
try:
_ = int(s, 16)
except ValueError:
raise Exception('Invalid hex literal.')
byte_arr = [s[i:i+2] for i in range(0, len(s), 2)]
p[0] = ast.List(elts=byte_arr, ctx=ast.Store())
def p_expr_str(self, p):
'''expr : STR'''
p[0] = ast.Str(p[1][1:-1])
def p_expr_name(self, p):
'''expr : NAME'''
p[0] = ast.Name(id=p[1], ctx=ast.Load())
def p_expr_group(self, p):
'''expr : LPAREN expr RPAREN'''
p[0] = p[2]
def p_expr_number(self, p):
'''expr : NUMBER'''
p[0] = ast.Num(n=p[1])
def p_statement_expr(self, p):
'''statement : expr SEMICOLON
| PUSH expr SEMICOLON
'''
if len(p) == 3:
p[0] = p[1]
else:
p[0] = ast.Call(func=ast.Name(id='_push', ctx=ast.Load()),
args=[p[2]],
keywords=[])
| true |
4aa29a617ae3bd105b54ade9890003f2b2fb9f6b | Python | Anseik/algorithm | /study/정올/Beginner_Coder/j_1338_문자삼각형1.py | UTF-8 | 413 | 3.359375 | 3 | [] | no_license | import sys
for line in sys.stdin:
n = int(line.rstrip())
# print(n)
arr = [[' '] * n for _ in range(n)]
# print(arr)
num = ord('A')
for i in range(n):
k = n - 1
for j in range(i, n):
if num > ord('Z'):
num = ord('A')
arr[j][k] = chr(num)
num += 1
k -= 1
# print(arr)
for a in arr:
print(*a)
| true |
4b6b96a25388bb1a646b1c16343a2921c8018ac6 | Python | MatejBabis/CS-GO-Fantasy-Calculator | /pandas_style.py | UTF-8 | 518 | 3.171875 | 3 | [] | no_license | def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
def highlight_event_winner(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: gold' if v else '' for v in is_max]
def bold(s):
'''
Make the output bold
'''
return 'font-weight: bold'
| true |
0051152f95ff5ca3b2b3818e846b52e6862a3aba | Python | Janardan-latchumanan/NumberGuessingGame-Pro-97 | /numberGuessingGame( Project 97 ).py | UTF-8 | 489 | 4.28125 | 4 | [] | no_license | import random
print("Number Guessing Game")
print("Guess the number between 1 and 9")
# A.I statements required in this project
guessNumber = random.randint(1,9)
guessChances = 5
userGuess = input("Enter your Guess : ")
# conditional statements required in this project
if (guessChances <= 5):
print(userGuess)
if (userGuess == guessNumber & guessChances <= 5):
print("Congrats you answered it Right !!!")
else:
print("You were Wrong , try again later ")
| true |
de7d8fc2d8c25418f0dabda49e5fb3c94a16565c | Python | JackInTaiwan/DLCV2018SPRING | /hw1/notes.py | UTF-8 | 223 | 2.984375 | 3 | [] | no_license | import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9]])
y = np.array([[0], [0], [1]])
print (np.matmul(x, y))
a = np.array([1,2,3,4]).reshape(-1, 1)
b = np.array([0,1,2,2]).reshape(-1, 1)
print (np.sum((a-b) ** 2)) | true |
c7903afb3c6c58fa835037f2f7e33d6e46ce4335 | Python | Sandeep8447/interview_puzzles | /src/test/python/com/skalicky/python/interviewpuzzles/test_sum_2_binary_numbers_without_converting_to_integer.py | UTF-8 | 1,041 | 3.203125 | 3 | [] | no_license | from unittest import TestCase
from src.main.python.com.skalicky.python.interviewpuzzles.sum_2_binary_numbers_without_converting_to_integer import \
sum_2_binary_numbers_without_converting_to_integer
class Test(TestCase):
def test_sum_2_binary_numbers_without_converting_to_integer__when_0_plus_0__then_result_is_0(self):
self.assertEqual('0', sum_2_binary_numbers_without_converting_to_integer('0', '0'))
def test_sum_2_binary_numbers_without_converting_to_integer__when_0_plus_1__then_result_is_1(self):
self.assertEqual('1', sum_2_binary_numbers_without_converting_to_integer('0', '1'))
def test_sum_2_binary_numbers_without_converting_to_integer__when_1_plus_1__then_result_is_10(self):
self.assertEqual('10', sum_2_binary_numbers_without_converting_to_integer('1', '1'))
def test_sum_2_binary_numbers_without_converting_to_integer__when_11101_plus_1011__then_result_is_101000(self):
self.assertEqual('101000', sum_2_binary_numbers_without_converting_to_integer('11101', '1011'))
| true |
706a40aaa1446e0f555afa2c3e490852bcdf74e9 | Python | xiaolongjia/techTrees | /Python/98_授课/Algorithm development/01_String/02_string_container/sc.py | UTF-8 | 1,616 | 4.0625 | 4 | [] | no_license | #!C:\Python\Python
import array
'''
string container: string a "BNDWDAQWDC", string b "ABA",
please write code to check if all characters in string b are contained in string a
let us asume length of a is n, length of b is m
time complexity: O(n)
space complexity: O(1)
'''
# Brute-force
# T(n) = O(n*m)
def strContainer (strA, strB):
if len(strA) < len(strB):
(strA, strB) = (strB, strA)
for srcIdx in range(len(strB)):
flag = False
for dstIdx in range(len(strA)):
if strA[dstIdx] == strB[srcIdx]:
flag = True
if flag == False:
return False
return True
# Permit to sort string a and b
# T(n) = O(n*logn) + O(m*logm) + O(n+m)
def strContainerSort (strA, strB):
if len(strA) < len(strB):
(strA, strB) = (strB, strA)
strA.sort() # O(n*logn)
strB.sort() # O(m*logm)
print("sorted A is ", strA)
print("sorted B is ", strB)
'''
newA = sorted(strA)
newB = sorted(strB)
'''
idxA = 0
idxB = 0
while(idxB < len(strB)):
while ((idxA < len(strA)) and (strA[idxA] < strB[idxB])):
idxA += 1
if (idxA >= len(strA)) or (strA[idxA] > strB[idxB]):
return False
idxB += 1
return True
#myStrA = array.array("u", ["B", "N", "W", "D", "A", "Q", "W", "D", "C"])
#myStrB = array.array("u", ["A", "B", "A"])
#myStrA = array.array("u", list("BNDWDAQWDC"))
#myStrB = array.array("u", list("ABA"))
myStrA = list("BNDWDAQWDC")
myStrB = list("ABA")
#print(strContainer(myStrA, myStrB))
print(strContainerSort(myStrA, myStrB))
| true |
9c876f973c7f283bbebef4c3f6ea07ea4c4c567c | Python | TheBlackParrot/icecast-stats-python | /icestats.py | UTF-8 | 1,901 | 2.65625 | 3 | [] | no_license | import urllib.request;
import json;
import mimetypes;
import time;
import datetime;
class Stream():
def __init__(self, data):
self.bitrate = None;
if "bitrate" in data:
self.bitrate = int(data["bitrate"]) * 1024;
self.mimetype = None;
if "server_type" in data:
if data["server_type"]:
self.mimetype = data["server_type"];
if not self.mimetype:
self.mimetype = mimetypes.guess_type(data["listenurl"]);
self.timestamp = None;
if "stream_start" in data:
self.timestamp = int(time.mktime(datetime.datetime.strptime(data["stream_start"], "%a, %d %b %Y %H:%M:%S %z").timetuple()));
self.title = data["server_name"] if "server_name" in data else None;
self.description = data["server_description"] if "server_description" in data else None;
self.genre = data["genre"] if "genre" in data else None;
self.listeners = int(data["listeners"]);
self.listener_peak = int(data["listener_peak"]);
self.stream_url = data["listenurl"];
self.server_url = data["server_url"] if "server_url" in data else None;
self.playing = data["title"] if "title" in data else None;
def __str__(self):
return self.stream_url;
def __int__(self):
return self.listeners;
class IcecastStats():
def __init__(self, url, user_agent="Mozilla/5.0 (Windows NT 6.1; WOW64)"):
req = urllib.request.Request(
url + "/status-json.xsl",
data=None,
headers={
'User-Agent': user_agent
}
);
data = json.loads(urllib.request.urlopen(req).read().decode('utf-8'));
self.data = data["icestats"];
self.streams = [];
for i in range(0, len(self.data["source"])):
self.streams.append(Stream(self.data["source"][i]));
def getOverallListenerCount(self):
count = 0;
for i in range(0, len(self.streams)):
count += int(self.streams[i]);
return count;
def __len__(self):
return len(self.streams);
def __getitem__(self, value):
return self.streams[value]; | true |
2bfd071e42d513e24acc054179c815acff9d93dc | Python | raad1masum/ParrotNAV | /controller/correct_horizontal.py | UTF-8 | 2,995 | 2.8125 | 3 | [
"MIT"
] | permissive | import matplotlib.pyplot as plt
import random
from time import sleep
from datetime import datetime
from PID.pid_controller import *
from simulation.sim import *
from states.states import *
from controls import controls
# set constants & gains
kp = horizontal_kp
setpoint = horizontal_setpoint
delay = 0
# data for plotting
horizontal_data = []
# set current date & time
current_datetime = datetime.now()
# translate left
def translate_left(correction_rate):
for i in range(correction_rate):
control(controls.translate_left)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
sleep(delay)
for i in range(correction_rate):
control(controls.translate_right)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
# translate right
def translate_right(correction_rate):
for i in range(correction_rate):
control(controls.translate_right)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
sleep(delay)
for i in range(correction_rate):
control(controls.translate_left)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
# single incrementation
def increment_single():
if float(get_info(y_range_state).rstrip(' m')) < setpoint:
control(controls.translate_right)
sleep(delay)
control(controls.translate_left)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
if float(get_info(y_range_state).rstrip(' m')) > setpoint:
control(controls.translate_left)
sleep(delay)
control(controls.translate_right)
horizontal_data.append(float(get_info(y_range_state).rstrip(' m')))
# return if on setpoint
def is_correct():
if abs(kp * float(get_info(y_range_state).rstrip(' m'))) == setpoint:
return True
else:
return False
# return error
def get_horizontal_error():
return abs(kp * float(get_info(y_range_state).rstrip(' m')))
# plot data
def plot_data():
plt.plot(horizontal_data, color='m', label="horizontal")
plt.style.use('seaborn-bright')
plt.axhline(linewidth=4, color='b')
plt.title('Vehicle Error in Degrees Over Time in Seconds', fontsize=14)
plt.legend(loc='upper right')
plt.xlabel('Time (seconds)')
plt.ylabel('Error (°)')
plt.grid()
plt.savefig(f'data/plots/data_{current_datetime.strftime("%d-%m-%Y_%H:%M:%S")}.png')
# run correction loop
def run():
while int(abs(kp * float(get_info(y_range_state).rstrip(' m')))) >= 1 or int(abs(kp * float(get_info(y_range_state).rstrip(' m')))) <= -1:
if float(get_info(y_range_state).rstrip(' m')) < setpoint:
translate_right(int(abs(kp * float(get_info(y_range_state).rstrip(' m')))))
if float(get_info(y_range_state).rstrip(' m')) > setpoint:
translate_left(int(abs(kp * float(get_info(y_range_state).rstrip(' m'))))) | true |
d4d5530c63237ec9e8a54d2d8a3cd71cc90a18ec | Python | DQder/WHN-Codefest-2020 | /code/Problem 13.py | UTF-8 | 117 | 4.09375 | 4 | [] | no_license | Tf = float(input("Enter fahrenheit value: "))
Tc = (Tf - 32) / 1.8
print(Tf, "fahrenheit is equal to", Tc, "celsius") | true |
5dd0aa04ff9c1f207927f63accfc9d01476c29a6 | Python | jorgemira/euler-py | /p003.py | UTF-8 | 288 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | '''Problem 3 from project Euler: Largest prime factor
https://projecteuler.net/problem=3'''
from utils import prime_factors
RESULT = 6857
def solve():
'''Main function'''
num = 600851475143
return max(prime_factors(num))
if __name__ == '__main__':
print solve()
| true |
b729baa2f985f8e4bfd26b091d524a301e1fe879 | Python | sidharth-potdar/dynamic-bus | /events/request_event.py | UTF-8 | 1,245 | 2.671875 | 3 | [] | no_license | from .event import Event
from .schedule_event import ScheduleEvent
import time
class RequestEvent(Event):
def __init__(self, origin_node, destination_node, ts=None, current_ts=None,priority=1):
super(RequestEvent, self).__init__(ts=ts)
self.origin_node = origin_node
self.destination_node = destination_node
def execute(self):
'''
Executes the ride request event by calling the scheduler
'''
# print(f"Executing ride request event {self._id} at {self.getExecutionPoint()} from {self.origin_node} to {self.destination_node}")
schedule_event = ScheduleEvent(ts=self.getExecutionPoint(), ride_id=self._id, origin_node=self.origin_node, destination_node=self.destination_node)
return_dict = {
"events": [schedule_event],
"scheduler_calls": [
{
"function": "request_ride",
"*args": (self._id,),
"**kwargs" : {
"uuid": self._id,
"type": type(self),
"time": self.getExecutionPoint()
}
}
]
}
return return_dict
| true |
0604f7752b9ec3fcff716e8e7e9dae64231df8c3 | Python | shanekang/Push-up_Algorithm_study | /Stack(Eval_Postfix).py | UTF-8 | 5,392 | 4.5625 | 5 | [] | no_license | class Stack:
def __init__(self):
self.items = list()
def is_empty(self): # 현재 스택이 비었는지 확인하는 함수
return True if len(self.items) == 0 else False
def push(self, item): # 스택에 item을 추가하는 함수
self.items.append(item)
def pop(self): # 스택의 마지막 item을 빼고 그 값을 반환하는 함수
if not self.is_empty(): return self.items.pop()
def peek(self): # 스택의 마지막 item을 반환하는 함수
if not self.is_empty(): return self.items[-1]
# 1. 중위 표기법을 후위 표기법으로 바꾸는 함수입니다.
def infix_to_postfix(string):
stack = Stack() # 연산할 우선순위를 저장할 스택
# -> 우선순위가 낮을수록 스택의 밑에 저장
# -> 우선순위가 높을수록 스택의 위에 저장
ret = list() # 최종적으로 반환할 요소를 저장하는 리스트
for elem in string.split():
if elem.isnumeric(): # 숫자라면 무조건 결과 리스트에 추가
ret.append(elem)
continue # 다음 iteration 진행(밑의 코드 실행x, 다음 elem으로 진행)
if elem == '(': stack.push(elem) # 여는 괄호는 일단 스택에 저장
elif elem in ['+', '-']: # 사칙연산 중 가장 우선순위가 낮음( '+-' < '*/' )
tmp = stack.peek() # 일단 스택 가장 위의 요소를 보고,
while not stack.is_empty() and tmp != '(': # 만약 스택이 비어있지 않고 괄호가 아니면,
ret.append(stack.pop()) # 스택의 가장 위인 연산자가 우선순위가 높으므로 먼저 ret에 추가
tmp = stack.peek() # 다음 stack에 남은 요소를 확인, 스택이 비어있거나 '('이라면 while 문 종료!
stack.push(elem) # + 또는 - 연산보다 우선순위가 높은 연산자를 다 뺐으니 이제 + 또는 - 를 ret에 추가
elif elem in ['*', '/']: # 사칙연산 중 가장 우선순위가 높음
tmp = stack.peek() # 스택의 가장 위의 요소를 보고,
if tmp in ['*', '/']: ret.append(stack.pop()) # 만약 동일한 순위일 경우,
# 순서에 따라 연산을 해야하므로 앞에 있는 연산 먼저 빼고 ret에 추가
stack.push(elem) # 그 다음 stack에 저장
elif elem == ')': # 괄호의 마지막이 오면 무조건 이전 괄호 이전의 모든 연산을 후위표기법으로 넣어야 하므로
while stack.peek() != '(': # 여는 괄호가 올때까지
ret.append(stack.pop()) # 모든 연산자를 ret에 추가하면서 stack에 뺀다.
stack.pop() # 여는 괄호는 아직 stack에 남아있으므로 한번 더 pop!
while not stack.is_empty(): # 아직 더 stack에 남은 연산이 없을때 까지
ret.append(stack.pop()) # pop하면서 나온 값들을 ret에 추가
return ' '.join(ret) # 빈칸을 사이에 두고 join한 string을 반환
# 2. 후위 표기법을 사칙연산으로 계산값을 return하는 함수입니다. - 힌트
def eval_postfix(string):
stack = Stack()
for elem in string.split(): # 빈칸을 기준으로 나눕니다.
if elem.isnumeric(): # 숫자가 맞다면, stack에 push!
stack.push(int(elem)) # 사칙연산을 위해 미리 정수형으로 변환!
continue
num2 = stack.pop() # 가장 위의 원소를 pop!
num1 = stack.pop()
return stack.peek()
def expr_test(infix):
postfix = infix_to_postfix(infix)
result = eval_postfix(postfix)
print("'%s' => '%s' = %.2f" % (infix, postfix, result))
def expr_test2(postfix):
result = eval_postfix(postfix)
print("'%s' = %.2f" % (postfix, result))
# 숫자는 여러 자리 숫자가 올 수도 있어요. 대신 연산자와 피 연산자는 공백문자로 나누어집니다.
# 괄호는 '(' 또는 ')'만 주어진다고 가정하며 숫자/연산자 및 괄호 이외의 문자는 주어지지 않습니다.
if __name__ == '__main__':
test_type = input("테스트 방식: A / B => ")
if test_type == "A": # A 방식: 중위식 -> 후위식 -> 계산까지 모든 함수를 작성한 경우
expr_test("14 + 3 - 2")
expr_test("4 + 23 - 4 / 2")
expr_test("1 + 2 * 43 - 4 * ( 2 / ( 4 - ( 5 + 2 ) ) )")
expr_test("( 1 + 2 ) * 10 - 4 * ( 2 / ( 4 - ( 5 + 2 ) ) )")
expr_test("( 150 + 60 / 2 * 2 + ( ( 78 - 20 ) + ( 60 / 3 ) ) + 15 )")
else: # B 방식: 후위식 -> 계산 까지의 함수만 작성한 경우
# 밑의 문자열들은 중위표현식을 후위표현식으로 바꾼 후의 상태 입니다.
input_string = """14 3 + 2 -\n4 23 + 4 2 / -\n1 2 43 * + 4 2 4 5 2 + - / * -\n1 2 + 10 * 4 2 4 5 2 + - / * -\n150 60 2 / 2 * + 78 20 - 60 3 / + + 15 +"""
for cases in input_string.split("\n"): expr_test2(cases) | true |
9f933980a146980d3dfe97bcbd57a2a61ff9e04b | Python | kunalkumar37/allpython---Copy | /ex23.py | UTF-8 | 75 | 3.015625 | 3 | [] | no_license | fruits=["apple","abanana","cherry"]
x,y,z=fruits
print(x)
print(y)
print(z) | true |
85137a6087a856cadb0d3dd4a53ffd6575cafb08 | Python | kebab-mai-haddi/zcash_service_status_library | /src/zcash_service_status/communities_and_forums_response_time.py | UTF-8 | 945 | 2.578125 | 3 | [
"MIT"
] | permissive | import requests
import urllib3
urllib3.disable_warnings()
def get_response_time(url):
try:
return(requests.get(url, verify=False).elapsed.total_seconds())
except requests.exceptions.ConnectionError as e:
print(e)
return -1
communities = {
'chat.zcashcommunity.com': {'url': 'https://chat.zcashcommunity.com/home'},
'forum.zcashcommunity.com': {'url': 'https://forum.zcashcommunity.com/'},
'zcashcommunity.com': {'url': 'https://www.zcashcommunity.com/'},
'z.cash': {'url': 'https://z.cash/'},
'zfnd.org': {'url': 'https://www.zfnd.org/'}
}
def communities_and_forums_response_time():
response_time_list = []
for community in communities.keys():
community_url = communities[community]['url']
response_time = get_response_time(community_url)
response_time_list.append((community,response_time))
return response_time_list
| true |
7d8c7963639380ec1a1963f7828bd8d1a3f53481 | Python | mcjcode/number-theory | /utilities.py | UTF-8 | 14,253 | 3.421875 | 3 | [] | no_license | #!/usr/bin/env python -i
# -*- coding: utf-8 -*-
"""
General purpose, factorization and modular
arithmetic routines.
"""
import time
import itertools
import functools
import operator
import random
import math
from math import sqrt
def prod(xs, start=1):
"""
:param xs: a sequence of elements to multiply
:param start: the value to return if xs is empty
:return: the product of the xs
"""
return functools.reduce(operator.mul, xs, start)
def timeit(f):
"""
:param f: a function
:return: a function with the side effect of printing the time it takes to run f
A decorator to wrap around functions when we
want to measure the run time.
"""
def g(*args):
t0 = time.time()
retval = f(*args)
t1 = time.time()
print('%.3f seconds' % (t1-t0))
return retval
return g
def memoize(f):
"""
:param f: a function
:return: a memoized version of f.
"""
fhash = {}
def g(*args):
targs = tuple(args)
if targs in fhash:
retval = fhash[targs]
else:
retval = f(*targs)
fhash[targs] = retval
return retval
return g
def mymod(n, m):
"""
:param n: an integer
:param m: an integer, the modulus
:return: :math:`n(mod m)`, if m != 0, otherwise n.
(Kind of what I'd want '%' to do in the first place.)
"""
return n % m if m else n
def sqrtInt(n):
"""
:param n: a non-negative integer
:return: the largest integer smaller than the square root of n
Note that this depends on `math.sqrt`, and its double precision
accuracy means that this function should not be trusted for n on
the order of :math:`10^{52}` and up.
"""
sqrtn = int(sqrt(n))
if (sqrtn+1)**2 <= n:
sqrtn += 1
return sqrtn
def cbrtInt(n):
"""
:param n: a non-negative integer
:return: the largest integer smaller than the cube root of n
Note that this depends on `math.sqrt`, and its double precision
accuracy means that this function should not be trusted for n on
the order of :math:`10^{52}` and up.
"""
cbrtn = int(n**(1./3.))
if (cbrtn+1)**3 <= n:
cbrtn += 1
return cbrtn
def multiplicities(xs):
"""
:param xs: a list of elements
:return: the list of unique items in xs and how often they appear in xs
"""
items = sorted(list(set(xs)))
counts = []
for item in items:
counts.append(len([xx for xx in xs if xx == item]))
return items, counts
def symmetric_function(k, xs, zero=0, one=1):
"""
:param k: the degree of the symmetric function
:param xs: the list of elements
:param zero: the zero of the elements
:param one: the 'one' of the elements
:return: the value of the kth symmetric function evaluated on xs
"""
retval = zero
for comb in itertools.combinations(xs, k):
term = one
for elt in comb:
term = term * elt
retval = retval + term
return retval
def isprime(p):
"""
:param p: an integer
:return: a boolean saying whether p is a prime number
"""
if type(p) != int:
raise TypeError('%s is %s, but should be int' % (p, type(p)))
if p < 0:
p = -p
if p == 0 or p == 1:
return False
sqrtp = sqrtInt(p)
trdiv = 2
while trdiv <= sqrtp:
if p % trdiv == 0:
return False
trdiv += 1
return True
def is_miller_rabin_witness(p, a):
"""
:param p: an odd number >= 3 whose primality we are testing
:param a: the potential 'witness' a
"""
s = 0
d = p-1
while d%2==0:
s += 1
d //= 2
assert p-1 == 2**s * d
assert d%2 == 1
ad = pow(a, d, p)
if ad==1 or ad==p-1:
return False
for _ in range(s-1):
ad *= ad
ad %= p
if ad==p-1:
return False
return True
def isprime_miller_rabin(p):
if p<=1:
return False
if p==2:
return True
if p%2==0:
return False
# p is now an odd number >= 3.
for a in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]:
if a >= p:
break
if is_miller_rabin_witness(p, a):
return False
return True
def lucas(n, nattempts=5, factoring_steps=0):
if n==1:
return False, None, '1 is a unit'
if n==2:
return True, 1, 'Found a primitive root'
assert n>2
try:
f = list(factorize2(n-1, factoring_steps))
except Exception as e:
return 'Maybe', None, f'Too hard to factor n-1={n-1}'
for _ in range(nattempts):
a = random.randint(1, n)
g = gcd(a, n)
if g>1 and g!=n:
return False, g, 'Found a factor'
if pow(a, n-1, n) != 1:
return False, a, 'Fermat fails'
if all(pow(a, (n-1)//p, n)!=1 for p, _ in f):
return True, a, 'Found a primitive root'
return 'Maybe', None, 'Test inconclusive'
def issq(nn):
"""
:param nn: an integer
:return: a boolean telling whether nn is a square
"""
return nn >= 0 and nn == int(sqrt(nn)) ** 2
def factorize(n):
"""
:param n: a positive integer
:return: a non-decreasing list of primes whose product is n.
"""
if n == 1:
return []
q = 2
while q * q <= n:
if n % q == 0:
return [q] + factorize(n//q)
q += 1
return [n]
_wheel = [ 1, 6, 5, 4, 3, 2,
1, 4, 3, 2, 1, 2,
1, 4, 3, 2, 1, 2,
1, 4, 3, 2, 1, 6,
5, 4, 3, 2, 1, 2 ]
def pollard_p_minus_1(n, B):
a = 2
for p in _ps:
if p>B:
break
k = int(math.log(B)/math.log(p))
a = pow(a, p**k, n)
g = gcd(a-1, n)
if 1<g<n:
return g
return False
def trial_division(n, ntrials=0):
"""
:param n: a positive integer
:return: yields a sequence of (prime, exponent) pairs where the
primes are distinct and in increasing order giving
the prime factorization of n.
"""
itrial = 0
for p in _ps:
if p*p > n:
if n>1:
yield n, 1
return
e = 0
while n%p == 0:
e += 1
n //= p
if e:
yield p, e
itrial += 1
if ntrials and itrial==ntrials:
raise Exception(f'Exceeded {ntrials} trial divisions. Giving up.')
q = _ps[-1]+2
while q*q <= n:
e = 0
while n%q == 0:
e += 1
n //= q
if e:
yield q, e
q += _wheel[q%30]
itrial += 1
if ntrials and itrial==ntrials:
raise Exception(f'Exceeded {ntrials} trial divisions. Giving up.')
if n > 1:
yield n, 1
factorize2 = trial_division
def factors(f):
"""
Given a factorization `f` of an integer `n`, return
a list of all of the factors of `n`
"""
retval = [1]
for p, e in f:
xs = [b*p**ee for b in retval for ee in range(1, e+1)]
retval += xs
return retval
def squarefree(mm):
"""
:param mm: a positive integer
:return: True if mm is square free, False otherwise.
"""
factors = factorize(abs(mm))
for i in range(len(factors) - 1):
if factors[i] == factors[i + 1]:
return False
return True
def order(a, p):
"""
:param a: an integer relatively prime to p
:param p: a positive integer
:return: the order of a in the multiplicative group :math:`(Z/pZ)^*`.
"""
one = type(a)(1)
cnt = 1
b = a % p
while not b == one:
b = (b * a) % p
cnt += 1
return cnt
def primitive_root(p):
"""
:param p: a prime number
:return: a generator of the (cyclic) multiplicative group :math:`(Z/pZ)^*`.
"""
facts = list(factorize2(p-1))
a = 2
while a < p:
ok = True
for q, e in facts:
if pow(a, (p-1)//q, p)==1:
ok = False
break
if ok:
return a
a += 1
def modpow(a, k, p):
"""
:param a: the base
:param k: the exponent (a positive integer)
:param p: the modulus
:return: :math:`a^k(p)`.
a can be of any type that has a multiplicative
identity and supports multiplication and modding.
"""
retval = type(a)(1)
cnt = 0
while cnt < k:
retval = (retval * a) % p
cnt += 1
return retval
def powerset(xs):
"""
:param xs: a list of elements
:return: a generator iterating over all of subsets of
xs, starting with the smallest and ending with
the largest subsets
"""
lengths = range(len(xs)+1)
return itertools.chain(*[itertools.combinations(xs, nn) for nn in lengths])
def fastpow(a, k, mul, one):
"""
:param a: the base
:param k: the exponent (a positive integer)
:param mul: the binary multiplication operator
:param one: the multiplicative identity for mul
:return: :math:`a^k`.
"""
retval = one
while k: # k != 0
if k % 2: # k odd
retval = mul(retval, a)
a = mul(a, a)
k = k >> 1
return retval
def modpow2(a, k, p):
"""
:param a: the base
:param k: the exponent (a positive integer)
:param p: the modulus
:return: :math:`a^k(p)`.
a can be of any type that has a multiplicative
identity and supports multiplication and modding.
O(log(k))-time algorithm
"""
retval = 1 % p
while k: # k != 0
if k % 2: # k odd
retval = retval*a % p
a = a*a % p
k = k >> 1
return retval
def legendre_ch(p):
"""
:param p: an odd prime
:return: the mod p Legendre character
"""
if not isprime(p) or p == 2:
raise ValueError("%d is not an odd prime." % (p, ))
def ch(a):
if a % p == 0:
return 0
rr = pow(a, (p-1)//2, p)
return (-1) if (rr == p - 1) else +1
return ch
def gcd(a, b):
"""
:param a: an integer
:param b: an integer
:return: the greatest common divisor of a and b.
Uses the Euclidean algorithm.
"""
if a == 0 or b == 0:
return abs(a + b)
while a % b != 0:
a, b = b, a % b
return abs(b)
def bezout(a:int, b:int) -> (int, int):
"""
:param a: an integer
:param b: an integer
:return: x, y such that :math:`xa + yb = gcd(a, b)`.
"""
sa = sign(a)
sb = sign(b)
a = abs(a)
b = abs(b)
if b == 0:
return sa, 0
x0, y0 = 1, 0 # x0*a + y0*b = a
x1, y1 = 0, 1 # x1*a + y1*b = b
q, r = divmod(a, b) # now r = a - q*b
while r:
a, b = b, r
(x0, y0), (x1, y1) = (x1, y1), (x0 - q*x1, y0 - q*y1)
q, r = divmod(a, b)
return x1*sa, y1*sb
def modinv(m:int, a:int) -> int:
"""
:param m: a positive integer
:param a: an integer, with (m,a)==1
:return: the multiplicative inverse of a(mod m)
"""
x, y = bezout(m, a)
if x*m + y*a != 1:
raise ValueError(f'{a} is not relatively prime to {m}')
#
# now we have xp+ya=1
#
return y % m
def crt(r1, m1, r2, m2):
"""
:param r1: the first residue
:param m1: the first modulus
:param r2: the second residue
:param m2: the second modulus
:return: the smallest positive simultaneous solution 'x' to the congruences
x = r1 (mod m1)
x = r2 (mod m2)
Raises a ValueError if no solution exists.
Note that we do *not* require m1 and m2 to be
relatively prime.
"""
c1, c2 = bezout(m1, m2)
g = c1*m1+c2*m2
q, r = divmod(r1-r2, g)
if r != 0: # no solution
raise ValueError()
else:
x = r1 - q*(c1*m1)
return x % (m1*m2//g)
def ea3(a, b, c):
"""
:param a: an integer
:param b: an integer
:param c: an integer
:return: x, y, z such that :math:`xa + yb + zc = gcd(a, b, c)`.
Uses the Euclidean algorithm twice.
"""
x, y = bezout(a, b)
assert x*a + y*b == gcd(a, b)
s, t = bezout(gcd(a, b), c)
return s*x, s*y, t
def digitsum(n,base=10):
"""
:param n: a non-negative integer
:return: the sum of all the digits of n in the given base
"""
retval = 0
while n:
k = n % base
retval += k
n = (n-k)//base
return retval
def digits(n, base=10):
"""
:param n: an integer
:return: a list ds so that the base^i digit of n is ds[i]
"""
while n:
n, d = divmod(n, base)
yield d
def num_from_digits(ds, base=10):
"""
:param ds: a list of integers from [0,base)
:return: the integer whose base^i digit is ds[i]
"""
n = 0
a = 1
for d in ds:
n += a*d
a *= base
return n
def sign(x):
"""
:param a: an integer
:return: the sign of a (+1,-1, or 0)
"""
if x < 0:
return -1
if x > 0:
return +1
return 0
def step_modp_pascal(row, p):
"""
:param row: a row of Pascal's triangle mod p, in compressed form
:param p: the modulus, not necessary prime
:return: the next row of Pascal's triangle mod p, in compressed form
compressed mod p pascal's triangle generation.
Given the nth row of pascal's triangle, generate the
(n+1)st row, where both are represented in compressed
form enumerating just the non-zero entries.
e.g. row=[(0,1),(1,1),(4,1),(5,1)] is the 5th row
of the mod 2 triangle, then the result would be
[(0,1),(2,1),(4,1),(6,1)], the 6th row.
"""
new_row = [(0,1)]
for k in range(len(row)-1):
if row[k][0]+1 == row[k+1][0]:
newval = (row[k][1] + row[k+1][1]) % p
if newval:
new_row.append((row[k+1][0], newval)) # if p=2, you never land here
else:
new_row.append((row[k][0]+1,row[k][1]))
new_row.append((row[k+1][0],row[k+1][1]))
new_row.append((row[-1][0]+1,1))
return new_row
from prime_sieve import segmented_sieve
_ps = list(segmented_sieve(10**6))
| true |
90b581fab2014010d7398201ddf9847cef6a0d84 | Python | adarsh0610/python-codes | /evenodd.py | UTF-8 | 131 | 3.21875 | 3 | [] | no_license | n=int(input("enter a number"))
def evenodd():
if n%2==0:
print("the no is even")
else:
print("the number is odd")
evenodd()
| true |
032674fd1d2385459e9fdc31bdb4077875f8722e | Python | ezeqzim/tleng | /tp/calculoLambda/Asserts.py | UTF-8 | 2,170 | 3.5625 | 4 | [] | no_license | from .Type import *
from .Types import *
import copy
class ExpressionMustBeBool(Exception):
pass
class ExpressionMustBeNat(Exception):
pass
class ExpressionMustBeLambda(Exception):
pass
class ExpressionsMustHaveEqualType(Exception):
pass
class ExpressionMustBeApplicable(Exception):
pass
class FreeVariable(Exception):
pass
def assertTypeBool(expression):
if (not (expression.getType() == Bool())):
message = 'La expresion (' + expression.printString() + ' : ' + expression.printType() + ') debe ser de tipo Bool'
raise ExpressionMustBeBool(message)
def assertTypeNat(expression):
if (not (expression.getType() == Nat())):
message = 'La expresion (' + expression.printString() + ' : ' + expression.printType() + ') debe ser de tipo Nat'
raise ExpressionMustBeNat(message)
def assertTypeArrow(expression):
if (expression.getType() == Bool() or expression.getType() == Nat()):
message = 'La expresion (' + expression.printString() + ' : ' + expression.printType() + ') debe ser de tipo Arrow'
raise ExpressionMustBeLambda(message)
def assertSameType(expression1, expression2):
if (not (expression1.getType() == expression2.getType())):
message = 'Las expresiones (' + expression1.printString() + ' : ' + expression1.printType() + ') y (' + expression2.printString() + ' : ' + expression2.printType() + ') deben ser del mismo tipo'
raise ExpressionsMustHaveEqualType(message)
def assertTypeNonVar(expression):
if (expression.getType() is None):
message = 'La variable ' + expression.getValue() + ' esta libre'
raise FreeVariable(message)
def assertNotHasFreeVariables(expression, context):
hasFreeVariables = expression.hasFreeVariables(context)
if (hasFreeVariables[0]):
assertTypeNonVar(hasFreeVariables[1])
def assertIsApplicable(expression1, expression2):
if (not (expression1.getType().getParam() == expression2.getType())):
message = 'La expresion (' + expression2.printString() + ' : ' + expression2.printType() + ') no tiene el tipo correcto para aplicarse a (' + expression1.printString() + ' : ' + expression1.printType() + ')'
raise ExpressionMustBeApplicable(message)
| true |
9103890ca3c33c2b08716e7c7caee22eb060ea3a | Python | Aliendood/pairmaker | /pairmaker.py | UTF-8 | 5,780 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
DEBUG = False
import sys
# Usage message.
USAGE = '''
Usage:
{program} [OPTIONS]
Example:
{program} 0426 Pairs for 04/26
{program} today Pairs for today
{program} help Usage message
Notes:
- Looks for students.txt in directory where script running from
- File students.txt must contain student names one per line
'''.format(program=sys.argv[0]).strip()
STUDENTS = [
'Dan',
'Jayaradha',
'Jillian',
'Lilly',
'Roy',
'Shylaja',
]
STUDENTS_FILE_NAME = 'students.txt'
import os, re,sys
import datetime as dt
# Reference Monday
MONDAY1_2016 = dt.datetime(2016,1,4)
def date_to_non_weekend(date):
date_weekday = date.weekday()
if date_weekday <= 4:
return date
days_since_friday = date_weekday - 4
return date - dt.timedelta(days_since_friday)
def date_to_workday_count(date):
'Workdays between date and Mon 2016/1/4'
start = MONDAY1_2016
date = date_to_non_weekend(date)
delta = date - start
days = delta.days
weeks = days / 7
weekends = weeks * 2
workday_count = days - weekends
return workday_count
def workday_count_to_shift(workday_count, student_count):
cycle_length = student_count - 1
return workday_count % cycle_length
def test_date_to_workday_count():
assert 0 == date_to_workday_count(dt.datetime(2016,1,4))
assert 1 == date_to_workday_count(dt.datetime(2016,1,5))
assert 2 == date_to_workday_count(dt.datetime(2016,1,6))
assert 3 == date_to_workday_count(dt.datetime(2016,1,7))
assert 4 == date_to_workday_count(dt.datetime(2016,1,8))
assert 4 == date_to_workday_count(dt.datetime(2016,1,9))
assert 4 == date_to_workday_count(dt.datetime(2016,1,10))
assert 5 == date_to_workday_count(dt.datetime(2016,1,11))
assert 6 == date_to_workday_count(dt.datetime(2016,1,12))
assert 7 == date_to_workday_count(dt.datetime(2016,1,13))
def right_shift(l,n):
n = n % len(l)
return l[-n:] + l[:-n]
def students_to_even_students(students):
# If odd append empty string as student
if len(students) % 2 == 1:
return students + [""]
return students
def students_to_count(students):
return len(students)
def count_to_index(count):
return range(count)
def index_to_rotated_index(index,shift):
# First student is fixed point
index = index[:1] + right_shift(index[1:],shift)
return index
def index_to_index_pairs(index):
row_length = len(index) / 2
row1 = index[:row_length]
row2 = index[row_length:]
row2.reverse()
pairs = []
for i in xrange(row_length):
pair = [row1[i],row2[i]]
pairs.append(pair)
return pairs
def index_pairs_to_student_pairs(index_pairs,students):
student_pairs = []
for index_pair in index_pairs:
index0 = index_pair[0]
index1 = index_pair[1]
student_pair = [students[index0],students[index1]]
student_pairs.append(student_pair)
return student_pairs
def student_pairs_to_output_str(student_pairs):
max_width = student_pairs_to_max_width(student_pairs)
output_str = ''
format_str = '%-{0}s <--> %s\n'.format(max_width)
for student_pair in student_pairs:
output_str += format_str % tuple(student_pair)
return output_str
def student_pairs_to_max_width(student_pairs):
if len(student_pairs) == 0: return 0
pair_to_first = lambda pair: pair[0]
str_to_len = lambda s: len(s)
first_students = map(pair_to_first, student_pairs)
return max(map(str_to_len, first_students))
def error_handle():
print "Error: " + str(sys.exc_info()[1])
if DEBUG:
print "Trace: "
raise
else:
os._exit(1)
def str_to_date(s):
error_message = '"%s" must have format MMDD' % s
assert re.match(r'^\d{4}$',s), error_message
month, day = int(s[:2]),int(s[2:4])
year = dt.datetime.now().year
date = dt.datetime(year,month,day)
return date
def date_to_shift(date,student_count):
workday_count = date_to_workday_count(date)
shift = workday_count_to_shift(workday_count, student_count)
return shift
def argv_to_date(argv):
if arg_is_today(argv[1]):
return dt.datetime.now()
date_string = argv[1]
date = str_to_date(date_string)
return date
def path_to_dir(path):
assert 1 == 0
def argv_to_students(argv):
script_path = argv[0]
script_dir = os.path.dirname(script_path)
students_file_path = os.path.join(script_dir,STUDENTS_FILE_NAME)
students = []
with open(students_file_path,'rb') as file:
for line in file.readlines():
student = line.strip()
students.append(student)
return students
def arg_in_list(arg,values):
arg = arg.replace('-','').lower()
return arg in values
def arg_is_today(arg):
return arg_in_list(arg,['today','now'])
def arg_is_help(arg):
return arg_in_list(arg,['help','h','?'])
def argv_to_exception(argv):
if len(sys.argv) != 2 or arg_is_help(sys.argv[1]):
print USAGE
os._exit(1)
def main(argv):
try:
argv_to_exception(argv)
date = argv_to_date(argv)
students = argv_to_students(argv)
students = students_to_even_students(students)
student_count = students_to_count(students)
shift = date_to_shift(date,student_count)
print "Day %d" % (shift + 1)
index = count_to_index(student_count)
index = index_to_rotated_index(index,shift)
index_pairs = index_to_index_pairs(index)
student_pairs = index_pairs_to_student_pairs(index_pairs,students)
output_str = student_pairs_to_output_str(student_pairs)
print output_str,
except:
error_handle()
if __name__ == '__main__':
main(sys.argv)
| true |
2a86d1bfa5f5a0c7a5e1a210042d798279c9b816 | Python | JeffStodd/StockBot-v2 | /Junk/Experimental Implementation.py | UTF-8 | 5,287 | 2.578125 | 3 | [] | no_license | import pandas as pd
import tensorflow as tf
import numpy as np
import os
import random
'''
Same inputs as original stock bot
2 output nodes for bearish and bullish confidence levels
'''
def loadData(path):
data = pd.read_csv(path, names = ["Change"])
return data
def main():
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
data = loadData("Data.csv") #load data from csv
inputs = [] #array or input arrays (size 7)
outputs = [] #array of output arrays (size 1)
buildDataset(inputs, outputs, data)
#generate validation data input and output sets
validationData = loadData("validate.csv")
BTCData = loadData("BTC.csv")
inputValidate = []
outputValidate = []
inputBTC = []
outputBTC = []
buildDataset(inputValidate, outputValidate, validationData)
buildDataset(inputBTC, outputBTC, BTCData)
model = tf.keras.models.load_model('Model.h5') #load from presaved model
#model = genModel()
adam = tf.keras.optimizers.Adam(
learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-07,
amsgrad=False,
name='Adam'
)
model.compile(loss='mean_squared_error', optimizer=adam, metrics=['binary_accuracy', tf.keras.metrics.FalsePositives(), tf.keras.metrics.FalseNegatives()])
allInputs = inputBTC
allOutputs = outputBTC
for i in range(1688):
orig = random.randint(0, len(inputs)-1)
validate = random.randint(0, len(inputValidate)-1)
allInputs.append(inputs[orig])
allInputs.append(inputValidate[validate])
allOutputs.append(outputs[orig])
allOutputs.append(outputValidate[validate])
sets = list(zip(allInputs, allOutputs))
random.shuffle(sets)
allInputs, allOutputs = zip(*sets)
'''
allInputs = inputs + inputValidate
allInputs = inputs + inputBTC
allOutputs = outputs + outputValidate
allOutputs = outputs + outputBTC
'''
#train using batch size 64
model.fit(allInputs, allOutputs, batch_size = 64, epochs=0, verbose=2)
#testing on validation sets
model.evaluate(inputs, outputs, verbose=2)
model.evaluate(inputValidate, outputValidate, verbose=2)
model.evaluate(inputBTC, outputBTC, verbose=2)
model.save('Model.h5') #save trained model
#model.save_weights('path_to_my_tf_checkpoint')
#os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
#return
#print(model.predict(training_data).round())
#simulate(model, BTCData, inputBTC, outputBTC, 1, 0.75, 0, 0)
#test through user input
test(model, data, inputs, outputs)
#generate model
def genModel():
model = tf.keras.Sequential() #feed forward
#activation tahn to for -1 to 1 range
model.add(tf.keras.layers.Dense(25, input_dim=7, activation='tanh')) #7 inputs
model.add(tf.keras.layers.Dense(25, input_dim=25, activation='tanh')) #dense hidden layer with 25 nodes
model.add(tf.keras.layers.Dense(2, input_dim=25, activation='sigmoid')) #output layer with 1 node
return model
def buildDataset(inputs, outputs, data):
#build dataset
#ignore last 7 days because can't extract an input/output value out of range
for i in range(len(data["Change"]) - 7):
temp = []
m = -100 #local max
for j in range(i, i+7): #getting max among local inputs
m = max(m, abs(data["Change"][j]))
m = max(m, abs(data["Change"][i+7])) #check if output is a max
for j in range(i, i+7):
temp.append(data["Change"][j]/m) #insert into temp input array
inputs.append(temp) #insert input array into array of inputs
future = data["Change"][i+7] #value we want to predict
if future > 0: #if bullish, set expected output to 1
outputs.append([1,0])
elif future < 0: #else if bearish, set expected output to -1
outputs.append([0,1])
else: #else the percent change is 0, set expected output to 0
outputs.append([0,0])
#test using user input
def test(model, data, inputs, outputs):
user = 0
print("Enter test day, -1 to exit")
while True:
user = int(input())
if user < 0:
return
predict(model, data, inputs, outputs, user)
#predict model on a single input array
def predict(model, data, inputs, outputs, day):
print("\nTesting on:\n",data[day:day+7])
output = model.predict([inputs[day]])
print("Bullish/Bearish Confidence: ", output)
print("Expected Confidence: ", outputs[day])
print("Actual Percent Change: ", data["Change"][day+7])
def simulate(model, data, inputs, outputs, buyIn, threshold, entryDay, exitDay):
money = buyIn
asset = 0
for i in range(entryDay, exitDay):
prev = money + asset
a = model.predict([inputs[i]])
asset = asset + asset * float(data["Change"][i+6])
if a[0][0] > threshold:
asset = asset + money
money = 0
elif a[0][1] > threshold:
money = money + asset
asset = 0
curr = money + asset
if curr < prev:
print("Loss: ", curr)
else:
print("Gain: ", curr)
main()
| true |
516c4f08bedfe51db1e3e7bd44f2f7212cc48cb8 | Python | paulromano/armi | /armi/physics/fuelPerformance/utils.py | UTF-8 | 3,588 | 3.078125 | 3 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | """
Fuel performance utilities.
"""
from armi.reactor.flags import Flags
def enforceBondRemovalFraction(block, bondRemovedFrac):
r"""
Update the distribution of coolant in this block to agree with a fraction
This pulls coolant material out of the bond component and adds it to the other
coolant-containing components while conserving mass.
Useful after db load with sodium bond. See armi.bookkeeping.db.database.updateFromDB
:math:`N_{hom} = \sum_{i} a_i N_i`
We want :math:`f = \frac{a_{bond} N_{bond}}{N_{hom}}`
So we can solve this for :math:`N_{bond}` and reduce the other
number densities accordingly.
Should work for coolants with more than 1 nuclide (e.g. H2O, Pb-Bi, NaK,...)
Parameters
----------
bondRemovedFrac : float
Fraction of the bond that has been removed.
See Also
--------
armi.reactor.assemblies.Assembly.applyBondRemovalFractions : does this in the original case
"""
bond = block.getComponent(Flags.BOND, quiet=True)
if not bond or not bondRemovedFrac:
return
volFracs = block.getVolumeFractions()
vBond = block.getComponentAreaFrac(Flags.BOND)
nuclides = bond.getNuclides()
# reduce to components of the same material.
coolantFracs = []
totalCoolantFrac = 0.0
for comp, vFrac in volFracs:
if comp.getProperties().getName() == bond.getProperties().getName():
coolantFracs.append((comp, vFrac))
totalCoolantFrac += vFrac
ndensHomog = []
for nuc in nuclides:
nh = 0.0 # homogenized number density of bond material (e.g. sodium)
for comp, vFrac in coolantFracs:
nh += comp.getNumberDensity(nuc) * vFrac
ndensHomog.append(nh)
# adjust bond values Nb'=(1-f)*Nb_bol
newBondNdens = []
for nuc, nh in zip(nuclides, ndensHomog):
ni = block.p.bondBOL * (1.0 - bondRemovedFrac)
newBondNdens.append(ni)
bond.setNumberDensity(nuc, ni)
# adjust values of other components (e.g. coolant, interCoolant)
for nuc, nh, nbNew in zip(nuclides, ndensHomog, newBondNdens):
newOtherDens = (nh - nbNew * vBond) / (totalCoolantFrac - vBond)
for comp, vFrac in coolantFracs:
if comp is bond:
continue
comp.setNumberDensity(nuc, newOtherDens)
def applyFuelDisplacement(block, displacementInCm):
r"""
Expands the fuel radius in a pin by a number of cm.
Assumes there's thermal bond in it to displace.
This adjusts the dimension of the fuel while conserving its mass.
The bond mass is not conserved; it is assumed to be pushed up into the plenum
but the modeling of this is not done yet by this method.
.. warning:: A 0.5% buffer is included to avoid overlaps. This should be analyzed
in detail as a methodology before using in any particular analysis.
.. math::
n V = n\prime V\prime
n\prime = \frac{V}{V\prime} n
"""
clad = block.getComponent(Flags.CLAD)
fuel = block.getComponent(Flags.FUEL)
originalHotODInCm = fuel.getDimension("od")
cladID = clad.getDimension("id")
# do not swell past cladding ID! (actually leave 0.5% buffer for thermal expansion)
newHotODInCm = min(cladID * 0.995, originalHotODInCm + displacementInCm * 2)
fuel.setDimension("od", newHotODInCm, retainLink=True, cold=False)
# reduce number density of fuel to conserve number of atoms (and mass)
fuel.changeNDensByFactor(originalHotODInCm ** 2 / newHotODInCm ** 2)
block.buildNumberDensityParams()
| true |
38e7bc429abbf72542f31a0d0a006d48a93ab6ef | Python | kzinmr/tftenarai | /estimator_custom.py | UTF-8 | 2,690 | 3.203125 | 3 | [] | no_license | # Instead of sub-classing Estimator,
# we simply provide Estimator a function `model_fn`
# that tells `tf.estimator` how it can evaluate pred, loss and opt.
# https://www.tensorflow.org/api_docs/python/tf/estimator
import numpy as np
import tensorflow as tf
# Check that we have correct TensorFlow version installed
tf_version = tf.__version__
print("TensorFlow version: {}".format(tf_version))
assert "1.4" <= tf_version, "TensorFlow r1.4 or later is needed"
def huber_loss(labels, predictions, delta=1.0):
residual = tf.abs(predictions - labels)
condition = tf.less(residual, delta)
small_res = 0.5 * tf.square(residual)
large_res = delta * residual - 0.5 * tf.square(delta)
return tf.where(condition, small_res, large_res)
def linear_regressor_huber(features, labels, mode):
# Build a linear model and predict values
W = tf.get_variable("W", [1], dtype=tf.float32)
b = tf.get_variable("b", [1], dtype=tf.float32)
y = W*features['x'] + b
# Loss sub-graph using Huber loss instead of MSE
loss = tf.reduce_sum(huber_loss(labels, y)) # tf.square(y - labels)
# Training sub-graph
global_step = tf.train.get_global_step()
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))
# EstimatorSpec connects subgraphs we built to the appropriate functionality
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=y,
loss=loss,
train_op=train)
# Declare list of feature instead of feature_columns
estimator = tf.estimator.Estimator(model_fn=linear_regressor_huber)
# We have to tell the input function `num_epochs` and `batch_size`
x_train = np.array([1., 2., 3., 4.]).astype(np.float32)
y_train = np.array([0., -1., -2., -3.]).astype(np.float32)
x_eval = np.array([2., 5., 8., 1.]).astype(np.float32)
y_eval = np.array([-1.01, -4.1, -7., 0.]).astype(np.float32)
input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
{"x": x_eval}, y_eval, batch_size=4, num_epochs=1, shuffle=False)
# train (invoke 1000 training steps while `num_epochs=None` in input_fn)
estimator.train(input_fn=input_fn, steps=1000)
# evaluate (num_epochs is specified in train/eval_input_fn)
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics) | true |
de6e0f4b2b7d6b8f91be98bb56f571d08bdbc2cc | Python | Aasthaengg/IBMdataset | /Python_codes/p03828/s914422541.py | UTF-8 | 928 | 2.609375 | 3 | [] | no_license | import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1:
arr.append([temp, 1])
if arr==[]:
arr.append([n, 1])
return arr
n=int(input())
if n==1:
print(1)
exit()
d=defaultdict(int)
for i in range(2,n+1):
tmp=factorization(i)
for j in tmp:
yaku,ko=j
d[yaku]+=ko
# print(d)
ans=1
for i in d.values():
ans*=i+1
ans%=mod
print(ans) | true |
97185534162ddb2be2135b94ee2b9c916556f4d2 | Python | hducati/machine-learning-tests | /keras_credit_data.py | UTF-8 | 1,521 | 3.0625 | 3 | [] | no_license | import pandas as pd
import keras
from sklearn.impute import SimpleImputer
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
def main():
data = pd.read_csv('files/credit-data.csv')
previsores = data.iloc[:, 1:4].values
classe = data.iloc[:, 4].values
imputer = SimpleImputer()
imputer = imputer.fit(previsores[:, 1:4])
previsores[:, 1:4] = imputer.transform(previsores[:, 1:4])
scaler = StandardScaler()
previsores = scaler.fit_transform(scaler)
previsores_treinamento, previsores_teste, classe_treinamento, classe_teste = train_test_split(
previsores, classe, test_size=0.25, random_state=1)
classifier = Sequential()
# units= quantos neuronios vão existir na camada oculta
classifier.add(Dense(units=2, activation='relu', input_dim=3))
classifier.add(Dense(2, 'relu'))
classifier.add(Dense(1, 'sigmoid'))
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# batch_size = atualiza os pesos a cada X registros
classifier.fit(previsores_treinamento, classe_treinamento, batch_size=10, nb_epoch=100)
prevision = classifier.predict(previsores_teste)
accuracy = accuracy_score(classe_teste, prevision)
matrix = confusion_matrix(classe_teste, prevision)
print(accuracy)
print(matrix)
| true |
0ad944bea961d4860625323e68efc5b36f2f6fd3 | Python | doyu/hy-data-analysis-with-python-summer-2021 | /part06-e06_nonconvex_clusters/src/nonconvex_clusters.py | UTF-8 | 2,707 | 3.8125 | 4 | [] | no_license | #!/usr/bin/env python3
'''Exercise 6 (nonconvex clusters)
Read the tab separated file "data.tsv" from the src folder into a
DataFrame. The dataset has two features X1 and X2, and the label y.
Cluster the feature matrix using DBSCAN with different values for the
eps parameter. Use values in np.arange(0.05, 0.2, 0.05) for
clustering. For each clustering, collect the accuracy score, the
number of clusters, and the number of outliers. Return these values in
a DataFrame, where columns and column names are as in the below
example.
Note that DBSCAN uses label -1 to denote outliers , that is, those
data points that didn’t fit well in any cluster. You have to modify
the find_permutation function to handle this: ignore the outlier data
points from the accuracy score computation. In addition, if the number
of clusters is not the same as the number of labels in the original
data, set the accuracy score to NaN.
eps Score Clusters Outliers
0 0.05 ? ? ?
1 0.10 ? ? ?
2 0.15 ? ? ?
3 0.20 ? ? ?
Before submitting the solution, you can plot the data set (with
clusters colored) to see what kind of data we are dealing with.
Points are given for each correct column in the result DataFrame.
'''
import pandas as pd
import numpy as np
import scipy
from sklearn.cluster import DBSCAN
from sklearn.metrics import accuracy_score
def find_permutation(n_clusters, real_labels, labels):
permutation=[]
for i in range(n_clusters):
idx = labels == i
# Choose the most common label among data points in the cluster
new_label = scipy.stats.mode(real_labels[idx])[0][0]
permutation.append(new_label)
return permutation
def nonconvex_clusters():
df = pd.read_csv("src/data.tsv", sep='\t')
y = df.y
X = df.iloc[:,:2]
df2 = pd.DataFrame(columns=["eps", "Score", "Clusters", "Outliers"])
for eps in np.arange(0.05, 0.2, 0.05):
model = DBSCAN(eps=eps)
model.fit(X)
n_clusters = np.unique(model.labels_[model.labels_ != -1]).size
if np.unique(y).size != n_clusters:
acc = np.nan
else:
permutation = find_permutation(np.unique(y).size, y, model.labels_)
acc = accuracy_score(y[model.labels_ != -1],
[permutation[x] for x in model.labels_[model.labels_ != -1]])
df2 = df2.append({"eps":eps, "Score":acc, "Clusters":n_clusters,
"Outliers":(model.labels_==-1).sum()},
ignore_index=True)
return df2
def main():
print(nonconvex_clusters())
if __name__ == "__main__":
main()
| true |
71d987430b310029d23c33a8ac4965739100a541 | Python | takoe-sebe/2019-fall-polytech-cs | /sketch_191113a_list23.pyde | UTF-8 | 628 | 3.28125 | 3 | [
"MIT"
] | permissive | def setup():
size(500,500)
smooth()
noLoop()
noStroke()
ellipseMode(CENTER)
def draw():
background(255)
border=50
nw=width-2*border
nh=height-2*border
number=5
nWstep=nw/number
nHstep=nh/number
for i in range(0,number):
for j in range(0,number):
x = border + j* nWstep + nWstep /2;
y = border + i* nHstep + nHstep /2;
size = 85 - (j+i)*10;
mColor = size *4;
fill(mColor , 78, 800);
ellipse (x, y, size , size);
fill (250);
ellipse (x, y, 3, 3);
| true |
929564dbf5a79d055b1a0ae7d88e15a28dcf2ff7 | Python | LiHRaM/P5 | /test_code/streamer.py | UTF-8 | 480 | 2.75 | 3 | [] | no_license | import sys
from nxt.bluesock import BlueSock
bs = BlueSock("00:16:53:12:C0:CA:00")
bs.debug = True
bs.connect()
size_bytes = 256
while True:
payload = [] # Received data
print("Main loop")
while sys.getsizeof(payload) < size_bytes:
print("Awaiting...")
t = bs.sock.recv(size_bytes)
payload.extend(t)
print("Payload: ", sys.getsizeof(payload))
strbuf = "".join(payload)
for i in range(0, size_bytes):
print(strbuf[i])
| true |
4ddd4a257bcbd8215dd768d39720c95fb8905777 | Python | evancjx/Stock_Prediction | /src/helper.py | UTF-8 | 2,523 | 3.0625 | 3 | [] | no_license |
from datetime import date, datetime, timedelta
from dateutil import tz
from os.path import isdir
from os import mkdir
import pickle
def count_number_digits(num):
if isinstance(num, float):
num = str(num).split('.', 1)[0]
elif isinstance(num, int):
num = str(num)
else:
raise ValueError('Not int or float object')
return len(list(num))
def check_datetime_instance(date_time):
if not isinstance(date_time, datetime) or not isinstance(date_time, date):
raise ValueError('Not datetime or date object')
def datetime_to_datetime_string(date_time, form):
check_datetime_instance(date_time)
return date_time.strftime(form)
def datetime_to_isoformat(date_time):
check_datetime_instance(date_time)
return date_time.isoformat()
def datetime_to_timestamp(date_time):
check_datetime_instance(date_time)
return date_time.timestamp()
def datetime_string_to_timestamp(date_time, form):
if isinstance(date_time, str):
date_time = datetime_string_to_datetime(date_time, form)
return float(datetime_to_timestamp(date_time))
def datetime_string_to_datetime(string, form):
if not isinstance(string, str):
raise ValueError('Not string object')
return datetime.strptime(string, form)
def timestamp_to_datetime(timestamp):
count = count_number_digits(timestamp)
if count < 10:
raise ValueError('Timestamp consist of 10 digits')
if count > 10:
timestamp = timestamp/(10**(count-10))
return datetime.fromtimestamp(timestamp)
def timestamp_to_datetime_string(timestamp, form):
return datetime_to_datetime_string(timestamp_to_datetime(timestamp), form)
def datetime_change_format(source, input_format, output_format):
if isinstance(source, datetime):
return datetime_string_to_datetime(
datetime_to_datetime_string(source, output_format),
output_format
)
def datetime_convert_timezone(date_time, tz_str='Asia/Singapore'):
return date_time.astimezone(tz.gettz(tz_str))
def pickle_dump(file_path, obj):
dest_folder = file_path.rsplit('/',1)[0]
if not isdir(dest_folder):
mkdir(dest_folder) # Create folder if it does not exist
with open(file_path, 'wb') as f:
pickle.dump(obj, f)
def pickle_load(file_path):
dest_folder = file_path.rsplit('/',1)[0]
if not isdir(dest_folder):
print(f'{dest_folder} not found')
return
with open(file_path, 'rb') as f:
return pickle.load(f)
| true |
ac9dac1b7a4fb89bdbb21b80ecc1c9c861f01d06 | Python | srijan-singh/CodeChef | /Beginner/Chef Judges a Competition (CO92JUDG)/judge.py | UTF-8 | 322 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | t = int(input())
while t:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort()
B.sort()
A.pop()
B.pop()
if sum(A) > sum(B):
print('Bob')
elif sum(A) < sum(B):
print('Alice')
else:
print('Draw')
t = t-1 | true |
846cf4d99adb64bea6183ad03c33e03991464e8b | Python | teemlinkSix/spider | /meizi.py | UTF-8 | 2,677 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import urllib.request
import pymysql
import threading
#设置最大线程锁
thread_lock = threading.BoundedSemaphore(value=5)
def crawl(url):
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
resquest = urllib.request.Request(url,headers=headers)#创建一个resquest对象
page = urllib.request.urlopen(resquest,timeout=20)#发出请求
contents = page.read()#获取响应
soup = BeautifulSoup(contents,'lxml')#解析相应
posts = soup.find_all('img')
for post in posts:
link = post.get('src') #图片链接
movie = post.get('alt') #图片名
# 操作数据库
sql_insert(movie,link)
# 下载图片
down_pic(link, movie)
# 操作文件
write_text(movie)
def write_text(movie):
# 操作文件
f = open(r'C:\Users\six\Desktop\movie.txt', 'a', encoding='utf-8') # 打开文件
f.write(movie + '\n')
f.close()
def down_pic(link,movie):
# 下载图片
urllib.request.urlretrieve(link, r'C:\Users\six\Desktop\movie_post\%s.jpg' % movie)
def sql_insert(movie,link):
# 创建数据库链接
database = pymysql.connect(host='localhost', user='root', passwd='', db='yiibaidb', port=3307, charset='utf8')
# 创建一个游标
cur = database.cursor()
sql_insert = 'insert into `doubanmovie` (name,link) VALUES ("'"%s"'","'"%s"'")' % (movie, link)
print(sql_insert)
try:
cur.execute(sql_insert) # 执行sql
database.commit() # 提交事物
except:
database.rollback() # 回滚
cur.close() # 关闭游标
database.close() # 释放数据库资源
def sql_distict():
# 操作数据库
# 创建数据库链接
database = pymysql.connect(host='localhost', user='root', passwd='', db='yiibaidb', port=3307, charset='utf8')
# 创建一个游标
cur = database.cursor()
sql_distict = 'delete from doubanmovie where id not in (select minid from (select min(id) as minid from doubanmovie group by name) b);'
print(sql_distict)
try:
cur.execute(sql_distict) # 执行sql
database.commit() # 提交事物
except:
database.rollback() # 回滚
cur.close() # 关闭游标
database.close() # 释放数据库资源
if __name__ == '__main__':
n=0
try:
while n<500:
url = 'https://movie.douban.com/top250?start=%d&filter=' %n
n = n+25
crawl(url)
finally:
sql_distict()
| true |
f28280b63b07f5c67370eb164dc7922bef627ded | Python | Legend0300/Python-OOP | /OOP_tutorial.py | UTF-8 | 8,333 | 4.1875 | 4 | [] | no_license | # This is the oop code that I have leared step by step
class Game:
def Work(self):
return('This is not a game perhaps -_-')
name = "There is no name of the game"
game1 = Game()
print(game1.Work())
print(game1.name)
class Human:
name = "ahmed"
def person(self):
print("This is the fucation of the human you just called")
ahmed = Human()
ahmed.person()
print(ahmed.name)
# THIS EG WILL BE using __init__ statement whih will just take arguments
# that will run initially and we can use .slef to access it in other methods and variables
#we pass values that we use in init's parameters
class Anime:
def __init__(self , name , rating):
self.name = name
self.rating = rating
def stats(self):
return f"the name of the anime is {self.name} and the rating of the anime is {self.rating}"
Naruto = Anime("Naruto" , 8.5)
OnePiece = Anime("One Piece" , 9)
print(Naruto.stats())
print(OnePiece.stats())
class constructor:
def __init__(self):
self.name = "ahmed"
self.age = 17
def call_const(self):
p2.name = "not ahmed"
p1.age = "1000"
p1 = constructor()
p2 = constructor()
p1.call_const()
p2.call_const()
print(p1.name)
print((p2.name))
print((p1.age))
print((p2.age))
# this is the example of the constructor
# we will use self. method to refer to the current object on which the funcation is applied
# or on which we are change the value.
class Compare:
def __init__(self , name , age):
self.name = name
self.age = age
def compare_obj(self , obj2):
if self.name == obj2.name and self.age == obj2.age:
print("THey are the same 0w0")
else:
print("they are not the same -_-")
# name = input("Enter the Name: ")
# age = int(input("Enter the age: "))
# name2 = input("Enter the Name: ")
# age2 = int(input("Enter the age: "))
obj1 = Compare("name" , 77)
obj2 = Compare("name", 55)
obj1.compare_obj(obj2)
obj2.compare_obj(obj1)
# we have two kinds of variables instance and class variables.
# when we define a class variable we can use it anywhere in our class
# it will also affect all the things in the class related to that
# we have to define the class var before the init var
# also we have to do: classname.property = something
class var:
one_piece_ep = 976
def __init__(self):
self.duration = "1999-idk what"
self.rating = 8.5
anime1 = var()
anime2 = var()
anime1.duration = "I changed this 0w0"
var.one_piece_ep = 999
print(anime1.duration)
print(anime2.duration)
print(anime1.one_piece_ep)
print((anime2.one_piece_ep))
# in oop we are 3 methods for a function:
# instance , class and static methods
# This is the exmple of instace methods
# there are 2 things .. accessors (funcations which get data) and mutators(funcations which set data)
# if you need input from funcation / input you will use parameters in __init__ funcation
class Student():
uni = "fast"
def __init__(self , marks1 , marks2):
self.marks1 = marks1
self.marks2 = marks2
# now I define use accessor here
def get_marks(self):
return(self.marks1 , self.marks2)
# here is the mutator here
def set_marks2(self , marks , marks_2):
self.marks2 = marks
#calculating the avg
def avg(self):
return(self.marks1 + self.marks2)/2
s1 = Student(22 , 34)
s2 = Student(45 , 56)
s1.set_marks2(22 , 56)
print(s1.get_marks())
print(s2.avg())
# new we will use class methods for class variables.
# and instad of slef. that we use in __init__ we use cls. that will refer to a class
# we will use @classmethod to define a class method -_-. or else we will have to pass the name of object
class CLS:
school = "0w0"
def __init__(self , name , age):
self.name = name
self.age = age
def profile(self):
return f"the name is {self.name} and age is {self.age} and the school is {CLS.school}"
@classmethod
def school_info(cls):
return cls.school
s1 = CLS("ahmed" , 17)
s2 = CLS("not ahmed" , 23)
s2.school = ":("
print(s1.profile())
print(s2.profile())
print(CLS.school_info())
print(CLS.school_info())
print(s2.school)
# NOW WE will work with static methods... like if we dont want to use variables
# and we dont want to use methods... like we want to do somethng different..
# then we will use static methods...
class Static:
@staticmethod
def owo():
print(("This is a Static method -_-"))
owo1 = Static()
owo1.owo()
# this is how you create a class inside a class 0w0
class Nothing:
def __init__(self , nothing , something):
self.nothing = nothing
self.something = something
self.Nothingness = self.Nothingness()
def show(self):
print(self.nothing , self.something)
self.Nothingness.show()
class Nothingness:
def __init__(self):
self.nothingness = "+_+"
self.void = "-_-"
def show(self):
print(self.nothingness , self.void)
n = Nothingness()
n.show()
Nothingness.show(n)
obj = Nothingness()
obj2 = Nothingness()
new = Nothing("owo", 22)
new2 = Nothing("uwu", 12)
new.show()
new2.show()
idk = new.obj
ik = new2.obj2
new.obj.show()
new2.obj2.show()
idk.show()
ik.show()
# THis section is about inheritance and levels of inheritance
# this code is single level inheritance
class A:
def f1(self):
print("This is the feature 1")
def f2(self):
print("This is the feature 2")
class B(A):
def f3(self):
print("This is the feature 3")
def f4(self):
print("This is the feature 4")
a = A()
b = B()
a.f1()
a.f2()
b.f1()
b.f2()
b.f3()
b.f4()
# This is multi level inhertance :)
# here C inherits from A and also B +_+
class C(B):
def f5(self):
print("this is feature 5")
def f6(self):
print("this is feature 6")
multi = C()
multi.f1()
multi.f2()
multi.f3()
multi.f4()
multi.f5()
multi.f6()
# now this is will an example of multiple level ineritance:
class D:
def f1(self):
print("This is the feature 1")
def f2(self):
print("This is the feature 2")
class E:
def f3(self):
print("This is the feature 3")
def f4(self):
print("This is the feature 4")
class F(D , E):
def f5(self):
print("This is feature 5")
def f6(self):
print("This is feature 6")
multiple = F()
multiple.f1()
multiple.f2()
multiple.f3()
multiple.f4()
multiple.f5()
multiple.f6()
# This is the an example of using __init__ (constructor) with inheritance.
# if there is no constructor in B then it will take it from A else it will render B
# this vid also talks about ORM or whatever which goes from left to right.
# in this eg it goes left to right.
class A2:
def __init__(self):
print("this is the self thing -_- in A")
class C2:
def __init__(self):
print("this is the self thing -_- in c")
def C(self):
print("this is the self thing -_- in c")
class B2(A2 , C2):
def __init__(self):
super().__init__()
super().C()
print("This is from the B thing -_-")
b2 = B2()
# now here is an example of pylomorphism +_+
# idk what is it but lets find out what is it.
# pylo means MANY and morphism means FORMS.
# there are 4 ways to implement pylomorphism in python OOP.
# 1. duck typing -_-
# 2. Method overloading
# 3. Method Overloading
# 4. Method Overriding
#1 duck typing
class OnePiece:
def typeowo(self):
print("the type is shonen")
print("the type is adventure")
print("and its the best anime on the planet right now")
class Naruto:
def typeowo(self):
print("the type is shonen")
print("the type is adventure")
print("not the best in the world -_-")
class Anime:
def Shonen(self , anime):
anime.typeowo()
a5 = Anime()
anime = Naruto()
a5.Shonen(anime) | true |
4c17aec0ad38909d8a6d7f0aa38b4d6de74060ad | Python | FITM-KMUTNB/TMRS | /Code07.py | UTF-8 | 5,090 | 2.71875 | 3 | [] | no_license | import networkx as nx
import matplotlib.pyplot as plot
import operator
from collections import defaultdict
G = nx.Graph()
G.add_edges_from([('A', 'B'), ('A', 'M'), ('A', 'L'), ('B', 'C'), ('B', 'D'),
('B', 'N'), ('B', 'O'), ('C', 'D'), ('D', 'E'), ('D', 'O'), ('E', 'F'), ('F', 'G'), ('F', 'N'), ('G', 'H'), ('H', 'N'), ('H', 'I'), ('H', 'P'), ('P', 'O'), ('P', 'I'), ('P', 'M'), ('I', 'J'), ('J', 'K'), ('K', 'M'), ('K', 'L')])
#print('Shortest path from E to L is :',
#nx.shortest_path(G, source='E', target='L'))
final_avg = 999999999.99
final_key = ''
# find node shortest path to all nodes
node_allSP = dict(nx.shortest_path_length(G, weight='weight'))
#print(node_allSP)
for key in node_allSP:
avg_nodeSP = sum(node_allSP[key].values())/(len(node_allSP[key]))
#print('AverageSP to all nodes of :', key, ' is ', avg_nodeSP)
if final_avg > avg_nodeSP:
final_avg = avg_nodeSP
final_key = key
print('The centroid is : ', final_key, 'the length is ', final_avg)
# Draw Graph
#pos = nx.spring_layout(G)
#nx.draw(G, pos, with_labels=True, font_color='yellow', node_size=1500)
#plot.show()
def spreading_activation_centroid(G, keywords):
activate_list = []
candidate = []
current_hop = 0
node_count = dict()
node_distance = []
for key in keywords:
activate_list.append([key])
node_distance.append({key : 0})
while len(candidate) <= 0:
for circle in range(len(activate_list)):
activate_node = activate_list[circle][current_hop]
for neighbors in nx.neighbors(G, activate_node):
if neighbors in keywords:
continue
# distance from initial point.
if neighbors not in node_distance[circle]:
node_distance[circle][neighbors] = node_distance[circle][activate_node] + 1
# check intersect
if neighbors in node_count:
if neighbors not in activate_list[circle]:
activate_list[circle].append(neighbors)
node_count[neighbors] += 1
if node_count[neighbors] == len(keywords):
candidate.append(neighbors)
else:
activate_list[circle].append(neighbors)
node_count[neighbors] = 1
current_hop += 1
print(candidate)
def disease_hop_activate(keywords):
activate_list = []
candidate = dict()
disease = dict()
current_hop = 0
node_count = dict()
node_distance = []
sum_distance = dict()
path = []
for key in keywords:
activate_list.append([key])
node_distance.append({key : 0})
path.append({key:[key]})
while len(disease) <= 1:
for circle in range(len(activate_list)):
activate_node = activate_list[circle][current_hop]
for neighbor in nx.neighbors(G, activate_node):
if neighbor in keywords:
continue
# distance from initial point.
if neighbor not in node_distance[circle]:
node_distance[circle][neighbor] = node_distance[circle][activate_node] + 1
prev_path = path[circle][activate_node]
current_path = prev_path + [neighbor]
path[circle][neighbor] = current_path
print(path)
# sum distance to all keywords.
if neighbor in sum_distance:
sum_distance[neighbor] += node_distance[circle][neighbor]
else:
sum_distance[neighbor] = node_distance[circle][neighbor]
# check intersect
if neighbor in node_count:
if neighbor not in activate_list[circle]:
activate_list[circle].append(neighbor)
node_count[neighbor] += 1
# if found node intersect, calculate average distance.
if node_count[neighbor] == len(keywords):
candidate[neighbor] = sum_distance[neighbor] / len(keywords)
disease[neighbor] = float(format(sum_distance[neighbor] / len(keywords) , '.4f'))
else:
activate_list[circle].append(neighbor)
node_count[neighbor] = 1
current_hop += 1
print(candidate)
return dict(sorted(disease.items(), key=operator.itemgetter(1))), dict(sorted(candidate.items(), key=operator.itemgetter(1)))
# Example
keywords = ['I', 'A', 'E']
disease_hop_activate(keywords)
dict1 = [{'a':['b']}]
prev = dict1[0]['a']
current = prev + ['c']
#print(dict1) | true |
575e0041bbc3bb7198b8e3e61019be0ca388ab37 | Python | namanpujari/hackerrank-problems | /oneNumbertoAnother.py | UTF-8 | 1,140 | 3.515625 | 4 | [] | no_license | # Complete the function below.
def swapdigits(a, m, index):
a_new = ''
m_new = ''
for i in range(len(a)):
if(i != index):
a_new = a_new + a[i]
else:
a_new = a_new + m[i]
for i in range(len(m)):
if(i != index):
m_new = m_new + m[i]
else:
m_new = m_new + a[i]
return str(a_new), str(m_new)
def minimumMoves(a, m):
numOfMoves = 0;
for pair_index in range(len(a)): # could also be len(m), since they have the same amount of numbers
number_a = str(a[pair_index]);
number_m = str(m[pair_index]);
for digit_index in range(len(number_a)): # could also be len(number_b), since they have same digit #.
if(int(number_a[digit_index]) > int(number_m[digit_index])):
number_a, number_m = swapdigits(number_a, number_m, digit_index)
to_add = 0
res = str((int(number_m) - int(number_a)))
for i in range(len(res)):
to_add = to_add + int(res[i])
numOfMoves = numOfMoves + to_add
return numOfMoves
| true |
472eaeb699127765a9893e01b33b689c549a1845 | Python | NickShatalov/ml_algorithms | /svm/svm.py | UTF-8 | 8,641 | 3.359375 | 3 | [] | no_license | import numpy as np
from cvxopt import solvers, matrix
from scipy.spatial import distance_matrix
class SVMSolver:
"""
Класс с реализацией SVM через метод внутренней точки.
"""
def __init__(self, C=1.0, method='primal', kernel='linear', gamma=None, degree=None):
"""
C - float, коэффициент регуляризации
method - строка, задающая решаемую задачу, может принимать значения:
'primal' - соответствует прямой задаче
'dual' - соответствует двойственной задаче
kernel - строка, задающая ядро при решении двойственной задачи
'linear' - линейное
'polynomial' - полиномиальное
'rbf' - rbf-ядро
gamma - ширина rbf ядра, только если используется rbf-ядро
d - степень полиномиального ядра, только если используется полиномиальное ядро
Обратите внимание, что часть функций класса используется при одном методе решения,
а часть при другом
"""
self.C = C
self.method = method
self.kernel = kernel
self.gamma = gamma
self.degree = degree
self.w = None
self.w_0 = None
self.dual_variables = None
self.X_train = None
self.y_train = None
self.eps = 10 ** (-8)
def compute_kernel_(self, X_1, X_2):
if self.kernel == 'linear':
return X_1.dot(X_2.T)
elif self.kernel == 'polynomial':
return (X_1.dot(X_2.T) + 1) ** self.degree
elif self.kernel == 'rbf':
return np.exp(-self.gamma * distance_matrix(X_1, X_2) ** 2)
def get_objective(self, X, y):
if self.method == 'primal':
return self.compute_primal_objective(X, y)
elif self.method == 'dual':
return self.compute_dual_objective(X, y)
def compute_primal_objective(self, X, y):
"""
Метод для подсчета целевой функции SVM для прямой задачи
X - переменная типа numpy.array, признаковые описания объектов из обучающей выборки
y - переменная типа numpy.array, правильные ответы на обучающей выборке,
"""
hinge_loss = 1 - y[:, np.newaxis] * (X.dot(self.w) + self.w_0)
hinge_loss[hinge_loss <= 0] = 0.0
return 1 / 2 * self.w.T.dot(self.w)[0][0] + self.C * hinge_loss.mean()
def compute_dual_objective(self, X, y):
"""
Метод для подсчёта целевой функции SVM для двойственной задачи
X - переменная типа numpy.array, признаковые описания объектов из обучающей выборки
y - переменная типа numpy.array, правильные ответы на обучающей выборке,
"""
K = self.compute_kernel_(X, X)
yyK = y * y[:, np.newaxis] * K
return 1 / 2 * self.dual_variables.T.dot(yyK.dot(self.dual_variables)) - \
self.dual_variables.sum()
def fit(self, X, y, tolerance=10**(-6), max_iter=100):
"""
Метод для обучения svm согласно выбранной в method задаче
X - переменная типа numpy.array, признаковые описания объектов из обучающей выборки
y - переменная типа numpy.array, правильные ответы на обучающей выборке,
tolerance - требуемая точность для метода обучения
max_iter - максимальное число итераций в методе
"""
solvers.options['reltol'] = tolerance
solvers.options['maxiters'] = max_iter
solvers.options['show_progress'] = False
l = X.shape[0]
d = X.shape[1]
if self.method == 'primal':
n = 1 + d + l # for w_0, w, \xi
P = np.zeros((n, n))
P[np.diag_indices(1 + d)] = 1.0 # for w
P[0, 0] = 0.0 # for w_0
P = matrix(P)
q = np.zeros((n, 1))
q[1 + d:] = self.C / l # for \xi
q = matrix(q)
G = np.zeros((2 * l, n))
# soft-margin condition
G[:l, 0] = y # for w_0
G[:l, 1:d + 1] = (y * X.T).T # for w
G[:l, d + 1:] = np.eye(l) # for \xi
# positive \xi (errors) condition
G[l:, d + 1:] = np.eye(l)
G = -G
G = matrix(G)
h = np.zeros((2 * l, 1))
h[:l, 0] = -1.0 # soft-margin condition
h[l:, 0] = 0.0 # positive \xi (errors) condition
h = matrix(h)
solution = np.array(solvers.qp(P, q, G, h)['x'])
self.w = solution[1:d + 1]
self.w_0 = solution[0]
elif self.method == 'dual':
P = y * y[:, np.newaxis] * self.compute_kernel_(X, X)
P = matrix(P)
q = -np.ones(l)
q = matrix(q)
G = np.zeros((2 * l, l))
G[:l, :l] = np.eye(l)
G[l:, :l] = -np.eye(l)
G = matrix(G)
h = np.zeros(l * 2)
h[:l] = self.C / l
h[l:] = 0.0
h = matrix(h)
b = matrix(np.zeros(1))
A = np.empty((1, l))
A[:] = y
A = matrix(A)
solution = np.array(solvers.qp(P, q, G, h, A, b)['x'])
self.dual_variables = solution.ravel()
self.X_train = X
self.y_train = y
def predict(self, X):
"""
Метод для получения предсказаний на данных
X - переменная типа numpy.array, признаковые описания объектов из обучающей выборки
"""
if self.method == 'primal':
res = X.dot(self.w) + self.w_0
elif self.method == 'dual':
if self.kernel == 'linear':
if self.w is None:
self.w = self.get_w(self.X_train, self.y_train)
if self.w_0 is None:
self.w_0 = self.get_w0(self.X_train, self.y_train)
res = X.dot(self.w) + self.w_0
else:
res = self.compute_kernel_(X, self.X_train).dot(self.dual_variables * self.y_train)
res[res >= 0] = 1
res[res < 0] = -1
return res.ravel()
def get_w(self, X=None, y=None):
"""
Получить прямые переменные (без учёта w_0)
Если method = 'dual', а ядро линейное, переменные должны быть получены
с помощью выборки (X, y)
return: одномерный numpy array
"""
if self.method == 'primal':
return self.w
elif self.method == 'dual':
if self.kernel == 'linear':
return (X.T).dot(self.dual_variables * y)
def get_w0(self, X=None, y=None):
"""
Получить вектор сдвига
Если method = 'dual', а ядро линейное, переменные должны быть получены
с помощью выборки (X, y)
return: float
"""
if self.method == 'primal':
return self.w_0
elif self.method == 'dual':
if self.kernel == 'linear':
mask = (self.dual_variables > self.eps)
x_ = X[mask, :][0]
y_ = y[mask][0]
if self.w is None:
self.w = self.get_w(X, y)
return -x_.dot(self.w) + y_
def get_dual(self):
"""
Получить двойственные переменные
return: одномерный numpy array
"""
if self.dual_variables is not None:
return np.copy(self.dual_variables)
def get_params(self, deep=False):
return {
"C": self.C
}
| true |
320d27ddb023b61bc6f9837bcd54ddd73825f202 | Python | lockwo/quantum_computation | /Pennylane/quantum_gradients_200_template.py | UTF-8 | 3,251 | 3.03125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/python3
import sys
import pennylane as qml
import numpy as np
def gradient_200(weights, dev):
r"""This function must compute the gradient *and* the Hessian of the variational
circuit using the parameter-shift rule, using exactly 51 device executions.
The code you write for this challenge should be completely contained within
this function between the # QHACK # comment markers.
Args:
weights (array): An array of floating-point numbers with size (5,).
dev (Device): a PennyLane device for quantum circuit execution.
Returns:
tuple[array, array]: This function returns a tuple (gradient, hessian).
* gradient is a real NumPy array of size (5,).
* hessian is a real NumPy array of size (5, 5).
"""
@qml.qnode(dev, interface=None)
def circuit(w):
for i in range(3):
qml.RX(w[i], wires=i)
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
qml.CNOT(wires=[2, 0])
qml.RY(w[3], wires=1)
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
qml.CNOT(wires=[2, 0])
qml.RX(w[4], wires=2)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(2))
gradient = np.zeros([5], dtype=np.float64)
hessian = np.zeros([5, 5], dtype=np.float64)
# QHACK #
s = np.pi/2
default = circuit(weights)
weight_copy = np.copy(weights)
for i in range(len(weights)):
weight_copy[i] += s
plus = circuit(weight_copy)
weight_copy[i] -= (2 * s)
minus = circuit(weight_copy)
gradient[i] = (plus - minus)/(2 * np.sin(s))
hessian[i][i] = (plus - 2 * default + minus) / 2
weight_copy[i] = weights[i]
weight_copy = np.copy(weights)
for i in range(len(hessian)):
for j in range(i, len(hessian[i])):
if i == j:
continue
else:
weight_copy[i] += s
weight_copy[j] += s
plus = circuit(weight_copy)
weight_copy[i] -= 2 * s
minus_1 = circuit(weight_copy)
weight_copy[i] += 2 * s
weight_copy[j] -= 2 * s
minus_2 = circuit(weight_copy)
weight_copy[i] -= 2 * s
minus_3 = circuit(weight_copy)
hessian[i][j] = (plus - minus_1 - minus_2 + minus_3) / (2 * np.sin(s))**2
weight_copy[i] = weights[i]
weight_copy[j] = weights[j]
for i in range(len(hessian)):
for j in range(0, i):
hessian[i][j] = hessian[j][i]
# QHACK #
return gradient, hessian, circuit.diff_options["method"]
if __name__ == "__main__":
# DO NOT MODIFY anything in this code block
weights = sys.stdin.read()
weights = weights.split(",")
weights = np.array(weights, float)
dev = qml.device("default.qubit", wires=3)
gradient, hessian, diff_method = gradient_200(weights, dev)
print(
*np.round(gradient, 10),
*np.round(hessian.flatten(), 10),
dev.num_executions,
diff_method,
sep=","
)
| true |
a5d9c8b51b61c745b9a17696bb4beb33eb9367ab | Python | blackox626/python_learn | /leetcode/top100/zijie_no2.py | UTF-8 | 487 | 3.8125 | 4 | [
"MIT"
] | permissive | """
有序链表,找到只出现一次的数字
1->2->2->3->3->5
1,5
"""
class Node:
def __init__(self, val):
self.val = val
self.next = None
instr = input()
lst = instr.split(',')
root = p = Node(lst[0])
for i in lst[1:]:
p.next = Node(i)
p = p.next
stack = []
while root:
top = root.val
stack.append(root.val)
q = root.next
while q and q.val == top:
stack.pop()
q = q.next
root = q
for i in stack:
print(i)
| true |
585cdbbbf6f17aaad435711280259b5fcf46c250 | Python | Jeongeun-Choi/CodingTest | /python_algorithm/Dynamic/BJ14501.py | UTF-8 | 433 | 2.890625 | 3 | [] | no_license | N = int(input())
arr = []
for _ in range(N):
arr.append(list(map(int, input().split())))
t = []
p = []
dp = []
for i in range(N):
t.append(arr[i][0])
p.append(arr[i][1])
dp.append(p[i])
for i in range(1, N):
for j in range(i):
if i - j >= t[j]:
dp[i] = max(p[i] + dp[j], dp[i])
maxTime = 0
for i in range(N):
if i + t[i] <= N:
maxTime = max(maxTime, dp[i])
print(maxTime)
| true |
28738e0d97cccb8242543d51ea2a8c2da6e92034 | Python | sclamons/DNA_Instrument | /seq_reading.py | UTF-8 | 4,709 | 3.15625 | 3 | [] | no_license | from nucleotides import *
from Bio import SeqIO
# Mapping of file endings (i.e., 'fa' in 'a-sequence.fa') to filetypes
# (i.e., 'fasta') for SeqIO.
filetype_map = {'fa' : 'fasta',
'fasta' : 'fasta',
'gb' : 'genbank'}
def sequences_in_file(filename, mode = 'scaffolds'):
'''
Generator returning all of the sequences in a file, as strings. Can handle
fasta files and genbank files as long as they have a nice standard file
ending ('.fasta' or '.fa' for fasta, '.gb' for genbank)
Parameters:
filename - Name of the file bearing sequences.
mode - Either 'scaffolds' or ('ORFs' or 'coding' or 'proteins').
'scaffolds' -> returns each sequence in the file
'ORFs' -> returns each coding region it can find as its own
sequence.
Returns: Each of the individual sequences or coding regions in the sequence
file.
'''
filename_ending = filename[filename.rfind('.')+1:]
seq_filetype = filetype_map[filename_ending]
with open(filename, 'rU') as seq_handle:
for record in SeqIO.parse(seq_handle, seq_filetype):
if mode == 'scaffolds':
yield str_to_nucleotide(str(record.seq))
elif mode in ['ORFs', 'coding', 'proteins']:
counter = 0
for coding_region in coding_regions_in(str(record.seq)):
counter += 1
#print("Parsing coding sequence #" + str(counter))
yield coding_region#str_to_nucleotide(coding_region)
else:
raise Exception('Invalid sequence file read mode "' + mode +
'"')
def str_to_nucleotide(seq_str):
'''
Generator for converting a string representing a sequence into nucleotide
values.
'''
for n in seq_str:
if n.upper() == 'A':
yield A
elif n.upper() == 'T':
yield T
elif n.upper() == 'C':
yield C
elif n.upper() == 'G':
yield G
else:
yield N
def coding_regions_in(sequence):
'''
Find the coding regions in a sequence. Returns them in the order they first
appear in the genome, regardless of orientation
'''
forward_start, forward_end = find_next_forward_indexes(sequence, 0)
#print("First forward found from " + str(forward_start) + " to " + str(forward_end))
rev_start, rev_end = find_next_reverse_indexes(sequence, 0)
#print("First reverse found from " + str(rev_end) + " to " + str(rev_start))
while forward_start or rev_start:
if not rev_start or (forward_start and forward_start <= rev_end):
yield sequence[forward_start:forward_end]
forward_start, forward_end = \
find_next_forward_indexes(sequence, forward_end)
#print("Next forward found from " + str(forward_start) + " to " + str(forward_end))
else:
yield reverse_complement(sequence[rev_end:rev_start])
rev_start, rev_end = find_next_reverse_indexes(sequence, rev_start)
#print("Next reverse found from " + str(rev_end) + " to " + str(rev_start))
def find_next_forward_indexes(sequence, start_pos):
next_forward_start = sequence.find(START, start_pos)
next_forward_stop = None
for pos in range(next_forward_start, len(sequence), 3):
# print("Checking F: " + str(sequence[pos:pos+3]))
if sequence[pos:pos+3] in STOPS:
next_forward_stop = pos + 3
break
if not next_forward_stop:
next_forward_stop = len(sequence)
return next_forward_start, next_forward_stop
def find_next_reverse_indexes(sequence, start_pos):
next_rev_start = 3 + sequence.find(reverse_complement(START), start_pos)
x = 0
while True:
x += 1
#print("Try #" + str(x) + ", next_rev_start = " + str(next_rev_start))
#print(range(next_rev_start, start_pos-1, -3))
#print("start_pos = " + str(start_pos))
if next_rev_start == 2:
# print("Out of sequence")
return None, None
next_rev_end = None
for pos in range(next_rev_start, start_pos-1, -3):
# print("Checking R: " + str(pos-3) + ", " + str(pos))
if reverse_complement(sequence[pos-3:pos]) in STOPS:
next_rev_end = pos - 3
break
if next_rev_end:
return next_rev_start, next_rev_end
else:
# print("No end found")
next_rev_start = \
3 + sequence.find(reverse_complement(START), next_rev_start+1)
| true |
cd7dc6542ebee3d97d4457208a7c4ac6b97c6821 | Python | soumasish/leetcodely | /python/longest_arithmetic_sequence.py | UTF-8 | 194 | 2.703125 | 3 | [
"MIT"
] | permissive | class Solution:
def longestArithSeqLength(self, A:[int]) -> int:
pass
if __name__ == '__main__':
solution = Solution()
print(solution.longestArithSeqLength([3, 6, 9, 12]))
| true |
1f8e16bbf8ab11174e1e36852cadaab03cf1336c | Python | EllieChanSZ/testDemoPython35 | /SeleniumDemo/select_box.py | UTF-8 | 475 | 2.734375 | 3 | [] | no_license | from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com/")
print("1")
link = driver.find_element_by_link_text("设置").click()
print("2")
driver.find_element_by_link_text("高级搜索").click()
print("3")
driver.find_element_by_css_selector("select[name=\'gpc\']").click()
print("4")
driver.find_element_by_css_selector("#adv-setting-4 > select > option:nth-child(2)").click()
time.sleep(2)
driver.quit()
| true |
cd05c724e1ccb16d3809960309df78da067dfcec | Python | piupiuup/competition | /ijcai/tool.py | UTF-8 | 3,517 | 3.171875 | 3 | [] | no_license | # -*-coding:utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier #GBM algorithm
from xgboost.sklearn import XGBClassifier
import xgboost as xgb
from sklearn import cross_validation, metrics #Additional scklearn functions
from sklearn.grid_search import GridSearchCV #Perforing grid search
from sklearn.linear_model import LinearRegression
import matplotlib.pylab as plt
from sklearn.metrics import f1_score
from matplotlib.pylab import rcParams
import os
#------------------------测评函数-------------------------#
def score(y_true,y_pred):
y_true = pd.DataFrame(y_true).fillna(0)
y_pred = pd.DataFrame(y_pred).fillna(0)
y_pred.columns = y_true.columns
y_pred.index = y_true.index
y_true.sort_index(ascending=True,inplace=True)
y_pred.sort_index(ascending=True,inplace=True)
if y_pred[y_pred<0].sum().sum()<0:
print '预测结果出现负数!请重新检查你的结果!'
y_pred = y_pred - y_pred[y_pred < 0].fillna(0)
shape = y_true.shape
dif = y_true-y_pred
summation = (y_true+y_pred).replace(0,np.nan)
return dif.divide(summation).sum().sum()/(shape[0]*shape[1])
def get_xy(data,day,sep=7):
week = day%7
day_x = range(day-week-sep,day-week)
result_x = data[day_x]
result_y = data[day]
return result_x,result_y
#客流量异常店铺检测,输入的天数大于14天
def abnormal(data,valve=0.25):
data = pd.DataFrame(data)
result1 = []
result2 = []
for i,row in data.iterrows():
for j in range(len(row)-13):
sum1 = sum(row[j:j+8])
sum2 = sum(row[j+8:j+15])
if abs(sum1-sum2)/(sum1+sum2)>valve:
result1.append(i)
result_list = []
for k in [8,15,22]:
result_list.append(False if sum(row[k-8:k])/sum(row)<0.25 else True)
result2.append(result_list)
break
print '异常店铺个数:' + str(len(result1))
result = pd.DataFrame(result2,index=result1)
return result
#检测提交结果是否异常
def inspect(url):
import pandas as pd
import numpy as np
data = pd.read_csv(url,header=None)
result = data
flag = True
if data.shape != (2000,15):
print '数据缺失或多余!请重新检查。'
flag = False
if data.abs().sum().sum() != data.sum().sum():
print '结果中出现负数!已用0代替。'
result = data - data[data < 0].fillna(0)
flag = False
for tp in data.dtypes.values:
if tp.type is not np.int64:
print '数据不是整数!已替换为整数。'
flag = False
break
if True in (data.isnull().values):
print '数据中包含空值,已替换为零。'
result = result.fillna(0).astype(int)
if flag == True:
print 'Great!数据完整,不存在空值、负数和零。'
return result
#使用本周其他6天数据预测 本周的,data是DataFrame格式的,返回的是的是一个data的变异副本
def getFeatrue_1(data):
data = data.fillna(0)
result = pd.DataFrame()
for i in range(7):
clf = LinearRegression()
train_x = data[range(0,i)+range(i+1,6)]
train_y = data[i]
clf.fit(train_x, train_y)
result[i] = clf.predict(train_x)
result.index = data.index
return result
| true |
973b72726593aeb87936ef1d7275609631fb36fd | Python | perthi/deep-learning | /surface2d.py | UTF-8 | 746 | 2.734375 | 3 | [] | no_license |
import pandas as pd
import sys
print (sys.argv[1:] )
df = pd.read_csv('ML_Data_Insight_121016.csv', header=1)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
#def randrange(n, vmin, vmax):
# '''
# Helper function to make an array of random numbers having shape (n, )
# with each number distributed Uniform(vmin, vmax).
# '''
# return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax2 = fig.add_subplot(111, projection='3d')
#n = 100
xs = df.ix[1:, sys.argv[1]]
ys = df.ix[1:, sys.argv[2]]
zs = df.ix[1:, sys.argv[3]]
ax2.scatter(xs, ys, zs, c='b', marker='*')
ax2.set_xlabel(sys.argv[1])
ax2.set_ylabel(sys.argv[2])
ax2.set_zlabel(sys.argv[3])
plt.show()
| true |
86346145cc6c8cf3bf28fcedfc17cad7db9e647d | Python | SubhamKumarPandey/DSA | /algorithms/Python/dynamic_programming/fibonacci_series_sum.py | UTF-8 | 690 | 4.46875 | 4 | [
"MIT"
] | permissive | # Find the sum up to nth term of fibonacci series using dynamic approach
# Fibonacci series starts from 0th term
"""
Output:
Sum up to term 10 of fibonacci series is: 143
"""
key = 10
if key < 0:
print("Please enter a valid term.")
exit()
d = {0: 0, 1: 1}
if key == 0:
print(f"Sum up to term {key} of fibonacci series: ", 0)
exit()
if key == 1:
print(f"Sum up to term {key} of fibonacci series: ", 1)
exit()
sum = 1
def fibo(n):
if n in d.keys():
return d[n]
else:
d[n] = fibo(n - 1) + fibo(n - 2)
global sum
sum += d[n]
return d[n]
fibo(key)
print(f"Sum up to term {key} of fibonacci series is: ", sum) | true |
cc2ebb0b46e4c361388cbf4b4b8bca6160ab48ed | Python | raphael-deeplearning/nlp | /nmtlab/evaluation/base.py | UTF-8 | 2,871 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from shutil import copyfile
from abc import ABCMeta, abstractmethod
import numpy as np
class EvaluationKit(object):
"""Class of evaluating translation results
"""
__metaclass__ = ABCMeta
def __init__(self, ref_path=None, ref_field=None, ref_delim="\t"):
if ref_field is None:
ref_field = 0
self.ref_lines = []
self.ref_path = ref_path
if ref_path is not None:
for ref_line in map(str.strip, open(ref_path)):
if ref_field is not None:
fields = ref_line.split(ref_delim)
assert len(fields) > ref_field
ref_line = fields[ref_field]
self.ref_lines.append(ref_line)
self.prepare()
def prepare(self):
"""Preparation function, which will be called after initialization.
"""
def evaluate(self, result_path):
"""Evaluate the given result file.
"""
result_lines = list(map(str.strip, open(result_path)))
scores = []
for result, ref in zip(result_lines, self.ref_lines):
scores.append(self.evaluate_line(result, ref))
return np.mean(scores)
def post_process(self, path, out_path="/tmp/preprocessed_results.txt",
recover_subwords=True, detokenize=True):
if recover_subwords:
self.recover_subwords(path, out_path)
if detokenize:
script = "scripts/detokenizer.perl"
os.system("perl {} < {} > {}.detok".format(script, out_path, out_path))
copyfile("{}.detok".format(out_path), out_path)
return out_path
def recover_subwords(self, path, out_path):
with open(out_path, "w") as outf:
for line in open(path):
# Remove duplicated tokens
tokens = line.strip().split()
new_tokens = []
for tok in tokens:
if len(new_tokens) > 0 and tok != new_tokens[-1]:
new_tokens.append(tok)
elif len(new_tokens) == 0:
new_tokens.append(tok)
new_line = " ".join(new_tokens) + "\n"
line = new_line
# Remove sub-word indicator in sentencepiece and BPE
line = line.replace("@@ ", "")
if "▁" in line:
line = line.strip()
line = "".join(line.split())
line = line.replace("▁", " ").strip() + "\n"
outf.write(line)
@abstractmethod
def evaluate_line(self, result_line, ref_line):
"""Evaluate one line in the result."""
| true |
a8fe49282a76295807363b861493c56f70456a05 | Python | joshuap233/algorithms | /leetcode/jian-zhi-offer/55-I.py | UTF-8 | 827 | 3.53125 | 4 | [] | no_license | # https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
# 剑指 Offer 55 - I. 二叉树的深度
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
_max = 0
def recur(node, deep):
nonlocal _max
if not node:
_max = max(_max, deep)
return
deep += 1
recur(node.left, deep)
recur(node.right, deep)
recur(root, 0)
return _max
# 简单的写法:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
| true |
91b11f4aeec06b0fd9cbc949a6a70d0e00a907b5 | Python | Mumujane/PythonAdvance | /Gevent/Introduction/CanIterable.py | UTF-8 | 232 | 3.46875 | 3 | [] | no_license | """
# 可迭代的对象
"""
from collections import Iterable
a = "1234ksadk"
for temp in a:
print(temp)
print(isinstance(a, Iterable))
# isinstance : 判断类型是否一致, isinstance(a, Iterable) 判断是否可迭代
| true |
0b288537b629ac8153033f541cee8f81b64cd405 | Python | dropbox/dropbox-sdk-python | /example/oauth/commandline-oauth.py | UTF-8 | 851 | 2.765625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect
'''
This example walks through a basic oauth flow using the existing long-lived token type
Populate your app key and app secret in order to run this locally
'''
APP_KEY = ""
APP_SECRET = ""
auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
try:
oauth_result = auth_flow.finish(auth_code)
except Exception as e:
print('Error: %s' % (e,))
exit(1)
with dropbox.Dropbox(oauth2_access_token=oauth_result.access_token) as dbx:
dbx.users_get_current_account()
print("Successfully set up client!")
| true |
afe3eede18b4bec429f7675300f9cd39c0e7f7e0 | Python | ofisser86/jb-Tic-Tac-Toe-with-AI | /Problems/Recursive multiplication/main.py | UTF-8 | 307 | 3.609375 | 4 | [] | no_license | def multiply(a, b):
if b == 1: # base case
return a
elif b == 0:
return 0
elif b == -1:
return a * -1
# ex 2 * (-3) = -2 - 2 - 2
# - 6 = - 6
elif b < -1:
return (a - multiply(a, b + 1)) * -1
# recursive case
return a + multiply(a, b - 1)
| true |
5788f211f2bb81a1a5565a0965b5dbba14287d66 | Python | atomliang/xling-el | /utils/read_write_vectors.py | UTF-8 | 3,193 | 3.109375 | 3 | [] | no_license | """Utils to read word vectors.
Also normalizes and removes accents, diacritics etc. if required
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import math
import numpy as np
import sys
import unidecode
import logging
logging.basicConfig(format='%(asctime)s: %(filename)s:%(lineno)d: %(message)s', level=logging.INFO)
import re
def zero_digits(s):
"""
Replace every digit in a string by a zero.
"""
return re.sub('\d', '0', s)
def read_word_vectors(word_vecs=None,
filename=None,
delim=' ',
norm=True,
scale=1.0,
lower=True,
remove_accents=False):
"""Read all the word vectors and normalize them.
Also takes word_vecs in case you want to read multiple vector files into
same word2vec map. Just keep passing it a new filename and the old word_vecs
dictionary
Args:
word_vecs: if None a new dict is returned, otherwise new words are added to
old one.
filename: file to read vecs from. should have word2vec like format.
delim: delimiter in the file (default ' ')
norm: whether to normalize vectors after reading.
remove_accents: whether to remove accents/diacritics from words for
languages like Turkish.
Returns:
a dictionary of word to vectors.
"""
# if starting afresh
if word_vecs is None:
word_vecs = {}
logging.info('Reading word vectors from file:%s', filename)
err = 0
if filename.endswith('.gz'):
file_object = gzip.open(filename, 'r')
else:
file_object = open(filename, 'r')
for line_num, line in enumerate(file_object):
if line_num == 0:
parts = line.strip().split(delim)
if len(parts)==2:
dim = int(parts[1])
logging.info("reading vecs of dim %d",dim)
continue
else:
dim = len(parts) - 1
logging.info("reading vecs of dim %d",dim)
line = line.strip()
if lower:
line = line.lower()
parts = line.split(delim)[1:]
if len(parts) != dim:
# logging.info("#%d error in line %d", err, line_num)
# logging.info("line started %s", line[0:5])
err += 1
continue
word = line.split(delim)[0]
if remove_accents: word = unidecode.unidecode(word)
if word in word_vecs:
# logging.info("word %s already seen! skipping ...",word)
continue
word_vecs[word] = np.zeros(dim, dtype=float)
for index, vec_val in enumerate(parts):
word_vecs[word][index] = float(vec_val)
if norm:
word_vecs[word] /= math.sqrt((word_vecs[word] ** 2).sum() + 1e-6)
word_vecs[word] *= scale
logging.info("total %d lines read", line_num)
logging.warning('%d vectors read from %s with dim %d, norm=%s accents=%s', len(word_vecs),
filename, dim, norm, remove_accents)
return word_vecs
if __name__ == '__main__':
pass
| true |
a9988c4009c01a6c1e05a81ea1bbb652203d8574 | Python | 0r3k1/youtube_downloader | /sqlite_3.py | UTF-8 | 3,214 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sqlite3
import os
from utilidades import _opt
class sqlite_3(object):
def __init__(self):
self.path = os.path.join(os.getcwd(), "dat")
self.exist_dir()
self.exist = False
if self.crear_tabla():
self.con = sqlite3.connect(os.path.join(self.path, "opt.db"))
self.cursor = self.con.cursor()
def exist_dir(self):
if not os.path.isdir(self.path):
os.mkdir("dat")
def crear_tabla(self):
if not os.path.isfile(os.path.join(self.path, "opt.db")):
self.con = sqlite3.connect(os.path.join(self.path, "opt.db"))
self.cursor = self.con.cursor()
self.exist = True
query = """
create table opciones(
id integer prymary key not null,
video_formato txt not null,
video_directorio txt not null,
musica_formato txt not null,
musica_directorio txt not null,
lista_formato txt not null,
lista_directorio txt not null,
lista_carpeta integer not null,
lista_enumera integer not null
);
"""
self.cursor.execute(query)
return False
return True
def insert(self, values):
query = """insert into opciones (
id,
video_formato,
video_directorio,
musica_formato,
musica_directorio,
lista_formato,
lista_directorio,
lista_carpeta,
lista_enumera
) values({0})
""".format(values)
self.cursor.execute(query)
self.con.commit()
def get_values(self):
self.cursor.execute("select * from opciones")
opt = _opt
for registro in self.cursor:
opt.video_formato = registro[1]
opt.video_directorio = registro[2]
opt.musica_formato = registro[3]
opt.musica_directorio = registro[4]
opt.lista_formato = registro[5]
opt.lista_directorio = registro[6]
opt.lista_carpeta = registro[7]
opt.lista_enumera = registro[8]
return opt
def update(self, opt):
query = "update opciones set "
query += "video_formato = '{0}',".format(opt.video_formato)
query += "video_directorio = '{0}',".format(opt.video_directorio)
query += "musica_formato = '{0}',".format(opt.musica_formato)
query += "musica_directorio = '{0}',".format(opt.musica_directorio)
query += "lista_formato = '{0}',".format(opt.lista_formato)
query += "lista_directorio = '{0}',".format(opt.lista_directorio)
query += "lista_carpeta = {0},".format(opt.lista_carpeta)
query += "lista_enumera = {0}".format(opt.lista_enumera)
self.cursor.execute(query)
self.con.commit()
def close(self):
self.con.close()
def __del__(self):
if self.exist:
self.con.close()
def main():
sql = sqlite_3()
sql.get_values()
if __name__ == '__main__':
main()
| true |
f1c2bbbeb1809b1d4969af1a3a5ace4bcffbc4dc | Python | omeradeel26/sudoku-solver | /game.py | UTF-8 | 15,963 | 3.359375 | 3 | [] | no_license | import pygame as p #import pygame... allows us to create GUI
import copy #import copy... allows for hardcopying variables
from solver import solve, generate, validify, find_empty #import from solver file
import time #creates delay in code at the end
GameScreen = "HOME" #starting screen
SIZE = 700 #set height and width
MARGIN = 75 #margin around board
mins = 0 #global vars for time so that when Timer function is called var is not reset
seconds = 0
run = True #controls end screen delay
cont = True #controls whether or not timer is ran
SQUARES = 9 #num of squares per side
SECTION = SQUARES//3 #num of sections per side
SECTION_SIZE = (SIZE - MARGIN * 2)/ SECTION #WIDTH of one section
SQ_SIZE = (SIZE - MARGIN*2)/ SQUARES #WIDTH of one square
NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] #possible values
COLOUR = (0,0,0) #colour of all borders and lines
SELECT_COL = (255,138,138) #color of selected box
BUTTON_COL = (144,238, 144) #color of box on home screen (Green)
SBUTTON_COL = (51,165,50) #color of box when hovering on home screen (dark green)
BACKGROUND_COL = (255,255,255) #color of background
FPS = 30 #framerate
CLOCK = p.time.Clock() #set framerate function
p.init() #initilizes GUI
SCREEN = p.display.set_mode((SIZE, SIZE)) #initializes screen
ICON = p.image.load('imgs/logo.png') #loads logo for game
p.display.set_caption("Sudoku") #sets screen title
p.display.set_icon(ICON) #sets logo for game
FONTSIZE = int((SIZE - MARGIN*2) *0.06)
LOWERFONTSIZE = int(FONTSIZE*0.75)
FONT = p.font.SysFont("calibri", FONTSIZE) #imports font & fontsize used for game
LOWERFONT = p.font.SysFont("calibri", LOWERFONTSIZE) #imports font & fontsize used for game
class GameBoard: #Gameboard class for the board
def __init__(self): #initializes attributes of board
self.board = generate() #randomizes board
self.mouseactive = False #whether or not a square is selected (default = NONE)
self.keyactive = False #whether or not a square is selected and key is pressed (default = NONE)
self.info = '' #content within the square
self.mistakes = 0 #number of mistakes made while playing
# self.run = True #ran when the screen size is changed
def DrawBoard(self): #draws out board
#DRAWING OUTLINE OF SECTIONS
increment = MARGIN #increment by size of one square each time
for i in range(SECTION + 1): #times to add a solid border for sections
p.draw.line(SCREEN, COLOUR, (MARGIN, increment), (SIZE - MARGIN, increment), 3) #draw horizontal line
p.draw.line(SCREEN, COLOUR, (increment, MARGIN),(increment, SIZE - MARGIN), 3) #draw vertical line
increment += SECTION_SIZE #increase size of incrememnt each time
#DRAWING OUTLINE FOR SQUARES
increment = MARGIN #starts off halfway in first square
for i in range(SQUARES + 1):
p.draw.line(SCREEN, COLOUR, (MARGIN, increment), (SIZE - MARGIN, increment)) #draw horizontal line
p.draw.line(SCREEN, COLOUR, (increment, MARGIN),(increment, SIZE - MARGIN)) #draw vertical line
increment += SQ_SIZE #increase size of incrememnt each time
increment_y = increment_x = MARGIN + SQ_SIZE//2 #starts from middle of first row
#DRAWING OUT NUMBERS
for row in range(len(self.board)): #loops through all rows in board
for col in range(len(self.board[0])): #loops through all columns in board
if self.board[row][col] != 0: #if board does not contain
text = FONT.render(str(self.board[row][col]), True, COLOUR) #renders number from array
textRect = text.get_rect() #centers text
textRect.center = (increment_x, increment_y)
SCREEN.blit(text, textRect) #draws number in
increment_x += SQ_SIZE # move over one square each time
increment_x = MARGIN + SQ_SIZE//2 #set to default
increment_y += SQ_SIZE #move one square down each row
increment_y = MARGIN + SQ_SIZE//2 #set to defualt
text = FONT.render("Press spacebar to solve", True, COLOUR) #renders number from array
SCREEN.blit(text, (MARGIN, SIZE*0.05)) #draws number in
def FindLocation(self, mouseX, mouseY): #Find the location of the selected square
self.Scol = int((mouseX-MARGIN) // SQ_SIZE) #column of selected square
self.Srow = int((mouseY-MARGIN) // SQ_SIZE) #row of selected square
self.location = (MARGIN + (self.Scol*int(SQ_SIZE)), MARGIN + (self.Srow*int(SQ_SIZE))) #gets location of square to place back again when square is selected
if (mouseX > MARGIN) and (mouseX < SIZE - MARGIN) and (mouseY > MARGIN) and (mouseY < SIZE - MARGIN) and self.board[self.Srow][self.Scol] == 0: #makes sure that selected square is empty and within boundaries
self.info = ''
self.mouseactive = True #square is selected
else:
del(self.Scol) #removes attributes b/c they are false
del(self.Srow)
del(self.location)
self.keyactive = False #makes sure that a key can not be placed
self.mouseactive = False #makes sure square is not selected
def DrawSelectedBox(self): #draws selected square to board
p.draw.rect(SCREEN, SELECT_COL, (self.location[0], self.location[1], SQ_SIZE, SQ_SIZE), 4) #draws rectangle in position selected
def DetectKeys(self, info): #function that detects valid key presses
if info.unicode in NUMBERS: #Checks if user input is between 1 and 9
self.keyactive = True #then it will continously print the number in the main loop which is attached to function DrawNum
self.info = info.unicode #sets info in selected square as follows
elif info.key == 13 and self.info in NUMBERS: #if user presses enter and fixes bug where person can press enter before finalizing key
self.FinalizeKey(info) #check function to see if answer is correct
else:
self.keyactive = False #key is not active at the moment
self.info = '' #information within key is reset
def DrawNum(self): #function that draws in number if DetectKeys is true
text = FONT.render(self.info, True, COLOUR) #renders number from array
textRect = text.get_rect() #centers text
textRect.center = (self.location[0] + SQ_SIZE//2, self.location[1] + SQ_SIZE//2) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
def FinalizeKey(self, event): #function that checks whether or not ENTER is pressed and then validfies answer chooses to add to board or not
new = copy.deepcopy(self.board) #creates dummy array to test whether or not user input can be solved
new[self.Srow][self.Scol] = int(self.info) #adds user input to dummy array
if validify(self.board, int(self.info), (self.Srow, self.Scol)) and solve(new): #follows rules of sudoku
self.board[self.Srow][self.Scol] = int(self.info) #adds the value to the board to be drawn in
self.mouseactive = False #resets variables
self.keyactive = False
self.info = ''
else:
self.mistakes +=1 #adds number of mistakes
self.keyactive = False #resets variables
self.mouseactive = False
self.info = ''
def DrawMistakes(self):
compound = "Mistakes: " + str(self.mistakes) #makes word using # of mistakes attribute
text = LOWERFONT.render(compound, True, COLOUR) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//7.5, SIZE - (MARGIN//2)) #Coordinates for text
SCREEN.blit(text, (MARGIN, SIZE*0.925)) #draws number in
class EndScreen():
def __init__(self):
self.sizeX = SIZE*0.4 #dimensions of button
self.buttonX = SIZE//2 - self.sizeX//2
self.sizeY = SIZE*0.1
self.buttonY = SIZE*0.6 - self.sizeY//2
self.maintext = p.font.SysFont("Calibri", int(self.sizeX*0.4)) #size of text used
self.smalltext = p.font.SysFont("Calibri", int(self.sizeX*0.1)) #size of text used
self.buttontext = p.font.SysFont("Calibri", int(self.sizeX*0.075), 1.5) #size of text used
self.active = False #whether or not button is hovered
def DrawOver(self, mistakes):
#draw title in
text = self.maintext.render("GAME OVER!", True, COLOUR) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//2, SIZE*0.35) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
compound = "You finished with " + str(mistakes) + " mistakes and in the time " + str(mins).zfill(2) + ":" + str(seconds).zfill(2)
text = FONT.render(compound, True, COLOUR) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//2, SIZE//2) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
self.Button()
text = self.buttontext.render("Generate New Board!", True, (255,255,255)) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//2, SIZE*0.6) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
def Button(self):
self.mouseX = p.mouse.get_pos()[0]
self.mouseY = p.mouse.get_pos()[1]
if (self.buttonX + self.sizeX) > self.mouseX > self.buttonX and (self.buttonY + self.sizeY) > self.mouseY > self.buttonY:
p.draw.rect(SCREEN, SBUTTON_COL, (self.buttonX, self.buttonY, self.sizeX, self.sizeY))
self.active = True #button is hovered
else:
p.draw.rect(SCREEN, BUTTON_COL, (self.buttonX, self.buttonY, self.sizeX, self.sizeY))
self.active = False #button is hovered
class HomeScreen:
def __init__(self):
self.sizeX = SIZE*0.4 #dimensions of button
self.buttonX = SIZE//2 - self.sizeX//2
self.sizeY = SIZE*0.1
self.buttonY = SIZE*0.6 - self.sizeY//2
self.maintext = p.font.SysFont("Calibri", int(self.sizeX*0.5)) #size of text used
self.smalltext = p.font.SysFont("Calibri", int(self.sizeX*0.1)) #size of text used
self.buttontext = p.font.SysFont("Calibri", int(self.sizeX*0.12), 1.5) #size of text used
self.active = False #whether or not button is hovered
def DrawHome(self):
#draw title in
text = self.maintext.render("Sudoku", True, COLOUR) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//2, SIZE*0.45) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
#draw name in
text = self.smalltext.render("Created by Omer Adeel", True, COLOUR) #renders words from array
SCREEN.blit(text, (SIZE*0.025, SIZE*0.925)) #draws number in
#button function
self.Button()
#draw button text
text = self.buttontext.render("Generate Board!", True, (255,255,255)) #renders words from array
textRect = text.get_rect() #centers text
textRect.center = (SIZE//2, SIZE*0.6) #Coordinates for text
SCREEN.blit(text, textRect) #draws number in
def Button(self):
self.mouseX = p.mouse.get_pos()[0]
self.mouseY = p.mouse.get_pos()[1]
if (self.buttonX + self.sizeX) > self.mouseX > self.buttonX and (self.buttonY + self.sizeY) > self.mouseY > self.buttonY:
p.draw.rect(SCREEN, SBUTTON_COL, (self.buttonX, self.buttonY, self.sizeX, self.sizeY))
self.active = True #button is hovered
else:
p.draw.rect(SCREEN, BUTTON_COL, (self.buttonX, self.buttonY, self.sizeX, self.sizeY))
self.active = False #button is hovered
def Timer():
global mins, seconds
SECOND = int((p.time.get_ticks() - start_ticks)/1000) #running clock of application
if cont:
mins = SECOND//60 #minuites
seconds = SECOND - mins*60 #seconds
if seconds == 60: #resets seconds to zero
seconds = 0
compound = "Timer: " + str(mins).zfill(2) + ":" + str(seconds).zfill(2) #format word as a clock
text = LOWERFONT.render(compound, True, COLOUR) #renders word
SCREEN.blit(text, (SIZE - MARGIN - SIZE*0.17, SIZE*0.925)) #draws timer in
def main(screen): #main function ran directly only from within this executed file
global run, start_ticks
running = True #var to control and run Pygame
sudoku = GameBoard() #instaciates GameBoard Class to Sudoku... assigns all attributes and methods
home = HomeScreen() #instaciates home Class to Sudoku... assigns all attributes and methods
end = EndScreen() #instaciates done Class to Sudoku... assigns all attributes and methods
while running: #loop function
if screen == "END":
for event in p.event.get(): #gets all events in PyGame
if event.type == p.QUIT: #if PyGame Window is shut
running = False #finish loop
if event.type == p.MOUSEBUTTONDOWN:
if end.active:
start_ticks += p.time.get_ticks()
sudoku = GameBoard()
screen = "PLAY"
if run: #add start function delay to show finished board
time.sleep(3) #show for 3 seconds
SCREEN.fill(BACKGROUND_COL) #fill screen white
end.DrawOver(sudoku.mistakes) #text for screen
run = False #makes sure that function is not ran again
if screen == "PLAY":
for event in p.event.get(): #gets all events in PyGame
if event.type == p.QUIT: #if PyGame Window is shut
running = False #finish loop
if event.type == p.MOUSEBUTTONDOWN: #if mouse is pressed record selected box location to sudoku
mouseX, mouseY = p.mouse.get_pos() #get position of mouse
sudoku.FindLocation(mouseX, mouseY) #find location of selected box
if event.type == p.KEYDOWN:
if sudoku.mouseactive:
sudoku.DetectKeys(event)
if event.key == p.K_SPACE:
solve(sudoku.board) #solve the board
cont = False #stops the clock
SCREEN.fill(BACKGROUND_COL) #white background
Timer() #keeps track of time
sudoku.DrawBoard() #Draw new board
sudoku.DrawMistakes() #Draw # of mistakes
if not find_empty(sudoku.board):
screen = "END"
sudoku.mouseactive = False
if sudoku.mouseactive: #if the mouse is selected
sudoku.DrawSelectedBox() #draw red box function
if sudoku.keyactive: #if the keyboard is active draw the number on screen
sudoku.DrawNum()
if screen == "HOME":
for event in p.event.get(): #gets all events in PyGame
if event.type == p.QUIT: #if PyGame Window is shut
running = False # break loop
if event.type == p.MOUSEBUTTONDOWN:
if home.active:
cont = True
start_ticks = p.time.get_ticks() #gets starting ticks unntil next event
screen = "PLAY"
SCREEN.fill(BACKGROUND_COL)
home.DrawHome()
p.display.update() #updates screen
CLOCK.tick(FPS) #framerate of application
if __name__=="__main__": #executes main function if python file is ran directly
main(GameScreen) | true |
6ca5e8b4511b0a2674da4882d7b88785a0906dd4 | Python | zazolla14/basic-python | /range.py | UTF-8 | 593 | 4.0625 | 4 | [] | no_license | #RANGE digunakan untuk memberi jarak data
#Contoh penulisan tanpa menggunakan range pada list indeks
nomor = [1,2,3,4,5,6,7,8,9,10]
#cara ini tidak efektif jika banyak data yang akan ditulis
#Solusi penulisan angka dengan menggunakn RANGE untuk 1 sampa 10
nomor2 = range(1, 11) #KENAPA 1, 11 karena range didalam angka antara 1 - 11 yaitu 1-10
for no in nomor2:
print(f"Hasil menggunakan range {no}")
#cara yang lebih mudah yaitu dengan memasukan RANGE kedalam for loop
for num in range(1, 11):
print("-----------------------------")
print(f"Hasil menggunakan range {num}") | true |
6090c1ade662123f2326f3b5e4d5e32f1cc3550d | Python | TSGreen/bangladesh-air-quality | /test_scraping.py | UTF-8 | 1,101 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Development script:
Used for finding the parameters needed to successfully scrape an individual webpage correctly
before parseing the code to the scrapy spider (which will crawl the full archive).
Created on Thu Aug 6 17:10:09 2020
@author: tim
"""
import requests
from scrapy import Selector
import pandas as pd
url = "http://case.doe.gov.bd/index.php?option=com_xmap&sitemap=1&Itemid=14"
#url = "http://case.doe.gov.bd/index.php?option=com_content&view=category&id=8&Itemid=32"
req = requests.get(url)
url_content = req.content
sel = Selector(text=url_content)
course_blocks = sel.xpath('//a[contains(@href,"aqi-archives")]')
course_links = course_blocks.xpath('@href')
var = course_blocks.xpath('text()').extract()
url = ''.join(['http://case.doe.gov.bd/', course_links.extract_first()])
print(url)
req = requests.get(url)
url_content = req.content
sel2 = Selector(text=url_content)
date = sel2.xpath('//span[contains(., "Date")]')
data_table = sel2.xpath('//table[@class="mceItemTable"]')
df = pd.read_html(data_table.extract_first())[0]
| true |
0d840fde7fcf4160cd58f6b6b5aba5b1bcd93185 | Python | ChrisAllenMing/ConfGF | /confgf/utils/torch.py | UTF-8 | 2,500 | 2.578125 | 3 | [
"MIT"
] | permissive | import copy
import warnings
import numpy as np
import torch
import torch.nn as nn
from torch_geometric.data import Data, Batch
def clip_norm(vec, limit, p=2):
norm = torch.norm(vec, dim=-1, p=2, keepdim=True)
denom = torch.where(norm > limit, limit / norm, torch.ones_like(norm))
return vec * denom
def repeat_data(data: Data, num_repeat) -> Batch:
datas = [copy.deepcopy(data) for i in range(num_repeat)]
return Batch.from_data_list(datas)
def repeat_batch(batch: Batch, num_repeat) -> Batch:
datas = batch.to_data_list()
new_data = []
for i in range(num_repeat):
new_data += copy.deepcopy(datas)
return Batch.from_data_list(new_data)
#customize exp lr scheduler with min lr
class ExponentialLR_with_minLr(torch.optim.lr_scheduler.ExponentialLR):
def __init__(self, optimizer, gamma, min_lr=1e-4, last_epoch=-1, verbose=False):
self.gamma = gamma
self.min_lr = min_lr
super(ExponentialLR_with_minLr, self).__init__(optimizer, gamma, last_epoch, verbose)
def get_lr(self):
if not self._get_lr_called_within_step:
warnings.warn("To get the last learning rate computed by the scheduler, "
"please use `get_last_lr()`.", UserWarning)
if self.last_epoch == 0:
return self.base_lrs
return [max(group['lr'] * self.gamma, self.min_lr)
for group in self.optimizer.param_groups]
def _get_closed_form_lr(self):
return [max(base_lr * self.gamma ** self.last_epoch, self.min_lr)
for base_lr in self.base_lrs]
def get_optimizer(config, model):
if config.type == "Adam":
return torch.optim.Adam(
filter(lambda p: p.requires_grad, model.parameters()),
lr=config.lr,
weight_decay=config.weight_decay)
else:
raise NotImplementedError('Optimizer not supported: %s' % config.type)
def get_scheduler(config, optimizer):
if config.type == 'plateau':
return torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
factor=config.factor,
patience=config.patience,
)
elif config.train.scheduler == 'expmin':
return ExponentialLR_with_minLr(
optimizer,
gamma=config.factor,
min_lr=config.min_lr,
)
else:
raise NotImplementedError('Scheduler not supported: %s' % config.type)
| true |
e699e88a8beb9b5b98a111c99640b917863c88c2 | Python | vincent-vega/adventofcode | /2020/day_17/17.py | UTF-8 | 1,250 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Counter
from functools import lru_cache
from itertools import combinations
@lru_cache(maxsize=None)
def _deltas(size: int) -> set:
zero_delta = (0,) * size
return { c for c in combinations([-1, 0, 1] * size, size) if c != zero_delta }
@lru_cache(maxsize=None)
def _neighbors(coord: tuple) -> set:
return { tuple(map(lambda c, d: c - d, coord, delta)) for delta in _deltas(len(coord)) }
def _cycle(cubes: dict, rounds: int=6) -> dict:
for _ in range(rounds):
nxt = {}
cubes_freq = Counter([ cc for c in cubes.keys() for cc in _neighbors(c) ])
for coord, neigh in cubes_freq.items():
active = cubes.get(coord)
if active and (neigh == 2 or neigh == 3):
nxt[coord] = True
elif not active and neigh == 3:
nxt[coord] = True
cubes = nxt
return cubes
if __name__ == '__main__':
with open('input.txt') as f:
lines = f.read().splitlines()
cubes = { (0, y, x): True for y in range(len(lines)) for x, s in enumerate(lines[y]) if s == '#' }
print(len(_cycle(cubes))) # 295
print(len(_cycle({ (0, *c): True for c in cubes }))) # 1972
| true |
1cb76c7b57843abc67ac75b30cae91c8a9c29c35 | Python | cathcart/Cool-code-scraps | /euler/fifteen.py | UTF-8 | 1,891 | 3.46875 | 3 | [] | no_license | '''
#global
paths=[]
def start(n):
x,y=0,0
path=[]
for i in range(n+1):
x=i
path.append((x,y))
for i in range(1,n+1):
x=n
y=i
path.append((x,y))
return path
def flip(path,t):
\'''flip the t th point in the given path\'''
tmp=path[:]
tmp[t]=(tmp[t][0]-1,tmp[t][1]+1)
return tmp
def legal(path,t):
#apply flip and get new path
test=flip(path,t)
#check to see path is legal
#check forward and back
if test[t-1][0]==test[t][0] or test[t-1][1]==test[t][1]:
if test[t+1][0]==test[t][0] or test[t+1][1]==test[t][1]:
return 1
else:
return 0
else:
return 0
def flip_iteration(path,n):
for i in range(1,2*n):#loop over all points but the first and last
if legal(path,i):#check legality of flip
legal_path=flip(path,i)
if legal_path not in paths:
paths.append(legal_path)
def reverse(path):
tmp=[]
for i in path:
tmp.append((i[1],i[0]))
return tmp
'''
#def pascal(n):
# r=n+1
# list=[]
# for c in range(n+1):
# if c ==0:
# list.append(1)
# previous=1
# else:
# list.append(previous*(r-c)/c)
# previous*=(r-c)/c
# return list
def pascal2(n):
r=n+1
list=[1,]
for c in range(1,(n+1)/2+1):
t=list[-1]
list.append((r-c)*int(float(t/c)))
return list[-1]
if __name__=="__main__":
#3x3 cube is on the 6th line therefor the nxn cube will be on the 2*nth line
N=20
print pascal2(2*N)
#for n in range(0,2*N+1,2):
# ans=pascal2(n)
# print ans
#no_paths=[]
#for n in range(7):
# list=pascal(n)
# if len(list)%2==1:
# no_paths.append(list[(len(list)-1)/2])
#print no_paths
#n=3
#path=start(n)
#paths.append(path)
#while reverse(paths[-1])!=paths[0]:
# flip_iteration(paths[-1],n)
#print len(paths)
#for i in paths:
# print i:w
| true |
688174b0ca0be4a52d45f8d11f960c30233ed85e | Python | Jack0427/python_basic | /pypy_test.py | UTF-8 | 263 | 2.78125 | 3 | [] | no_license | import time
def test():
for i in range(1, 10):
n = pow(10, i)
start_time = time.time()
sum(x for x in range(1, n + 1))
end_time = time.time()
print(f'10^{i}:{end_time-start_time}')
test()
# 下載pypy python實現
| true |
a681bba6675f7c8e752bd1629434acab56a4346f | Python | LYblogs/python | /Python1808/第一阶段/day3-变量和运算符/03-运算符.py | UTF-8 | 1,205 | 4.59375 | 5 | [] | no_license | """
Python中的运算符:数学运算符、比较运算符、逻辑运算符、
赋值运算符、位运算符。
1.数学运算符:+,-,*,/,%,//,**
+:加法运算符
-:减法运算
*:乘积运算符
/:除法运算
%:取余
//:取整
**:幂运算符
"""
print(5**2) #5的2次方
"""
2.比较运算符:
>,<,==,!=,<=,>=。
所有的比较运算符的运算结果都是布尔值
3.逻辑运算符:and ,or ,not
逻辑运算符的运算对象是布尔值,运算符结果也是布尔值
a.and(逻辑与运算)相当于生活中的"并且",当多个条件要同时满足就需要and。
值1 and 值2:如果值1和值2都为True,结果就是True,只要有一个False结果就是False
值1 or 值2: 如果值1 和值2的值
b.or(逻辑或运算)相当于生活中的"或者"
值1 or 值2:如果值1和值2中有一个是True,结果就是True。两个为假,才为假。
c.not(逻辑非运算)
not 值:如果值是Ture,结果就是false,反之亦可。
"""
#示例:是否能够进入网吧:年龄不小于18
age = 21
print("是否能进入网吧:",not age < 18)
print("是否能进入网吧:",age > 18)
| true |
7741636d88afee44fca5a72d7388502c942eab45 | Python | malikahm3d/arabic-letter-frequency-analysis | /LetterFreqDemo.py | UTF-8 | 2,215 | 3.6875 | 4 | [] | no_license | validChars = "اإأبجدهوزحطيكلمنسعفصقرشتثخذضظغؤءئآة"
#using a valid characters varible to check what the file reads against it. And only use what is read if it is valid.
countOfLetters = 0
#using this varible to count all the characters/letters and get the relative frequency
frequencyDictionary = dict()
#intilizing a collection (in this case, dictionary) to hold the letters (keys) and their respective count (value).
with open(r"all_tech_files.txt", encoding="utf8") as file:
#requires absloute path of the .txt file
#opening the file (more on the content of the file in the report)
#python would only accpet the full file path. Encoding is utf8 to read arabic characters
for line in file:
#loop through the file, line by line.
Words = line.split(" ")
#defning Words by splitting them at the occurance of a space
for word in Words:
#looping through the Words
Chars = list(word)
#breaking down the Words into lists of charatcers
for c in Chars:
#looping throguh the list of charaters
if c not in validChars:
#if a character is not valid: ignore it
continue
else:
countOfLetters += 1
#if it is valid: count it (to be used for the relative frequncy as the denominator).
if c in frequencyDictionary:
frequencyDictionary[c] += 1
#if it is valid && already exists in the dictionary: add to its count.
else:
frequencyDictionary[c] = 1
#if it valid && is not in the dictrionary: add it as a new item.
print(countOfLetters) #4 561 998 letters, which is sufficent and why I did not use all the files in the dataset.
print(f'{":":<2} {"Letter":<2} {":":<2} {"Frequency":<5} {":":<2} {"Relative frequency in the dataset":<5} {":":<2}')
for k,v in frequencyDictionary.items():
print(f'{":":<2} {k:^6} {":":<4} {v:<6} {":":>6} {round(((v/countOfLetters)*100),1):<6} {":":>1}')
#print out the results in a table-like structure.
file.close() | true |
df8fa12fd3db610385a6b7401791d38f4ed20149 | Python | sympy/sympy | /sympy/polys/agca/modules.py | UTF-8 | 46,946 | 3.25 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | """
Computations with modules over polynomial rings.
This module implements various classes that encapsulate groebner basis
computations for modules. Most of them should not be instantiated by hand.
Instead, use the constructing routines on objects you already have.
For example, to construct a free module over ``QQ[x, y]``, call
``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor.
In fact ``FreeModule`` is an abstract base class that should not be
instantiated, the ``free_module`` method instead returns the implementing class
``FreeModulePolyRing``.
In general, the abstract base classes implement most functionality in terms of
a few non-implemented methods. The concrete base classes supply only these
non-implemented methods. They may also supply new implementations of the
convenience methods, for example if there are faster algorithms available.
"""
from copy import copy
from functools import reduce
from sympy.polys.agca.ideals import Ideal
from sympy.polys.domains.field import Field
from sympy.polys.orderings import ProductOrder, monomial_key
from sympy.polys.polyerrors import CoercionFailed
from sympy.core.basic import _aresame
from sympy.utilities.iterables import iterable
# TODO
# - module saturation
# - module quotient/intersection for quotient rings
# - free resoltutions / syzygies
# - finding small/minimal generating sets
# - ...
##########################################################################
## Abstract base classes #################################################
##########################################################################
class Module:
"""
Abstract base class for modules.
Do not instantiate - use ring explicit constructors instead:
>>> from sympy import QQ
>>> from sympy.abc import x
>>> QQ.old_poly_ring(x).free_module(2)
QQ[x]**2
Attributes:
- dtype - type of elements
- ring - containing ring
Non-implemented methods:
- submodule
- quotient_module
- is_zero
- is_submodule
- multiply_ideal
The method convert likely needs to be changed in subclasses.
"""
def __init__(self, ring):
self.ring = ring
def convert(self, elem, M=None):
"""
Convert ``elem`` into internal representation of this module.
If ``M`` is not None, it should be a module containing it.
"""
if not isinstance(elem, self.dtype):
raise CoercionFailed
return elem
def submodule(self, *gens):
"""Generate a submodule."""
raise NotImplementedError
def quotient_module(self, other):
"""Generate a quotient module."""
raise NotImplementedError
def __truediv__(self, e):
if not isinstance(e, Module):
e = self.submodule(*e)
return self.quotient_module(e)
def contains(self, elem):
"""Return True if ``elem`` is an element of this module."""
try:
self.convert(elem)
return True
except CoercionFailed:
return False
def __contains__(self, elem):
return self.contains(elem)
def subset(self, other):
"""
Returns True if ``other`` is is a subset of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.subset([(1, x), (x, 2)])
True
>>> F.subset([(1/x, x), (x, 2)])
False
"""
return all(self.contains(x) for x in other)
def __eq__(self, other):
return self.is_submodule(other) and other.is_submodule(self)
def __ne__(self, other):
return not (self == other)
def is_zero(self):
"""Returns True if ``self`` is a zero module."""
raise NotImplementedError
def is_submodule(self, other):
"""Returns True if ``other`` is a submodule of ``self``."""
raise NotImplementedError
def multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
"""
raise NotImplementedError
def __mul__(self, e):
if not isinstance(e, Ideal):
try:
e = self.ring.ideal(e)
except (CoercionFailed, NotImplementedError):
return NotImplemented
return self.multiply_ideal(e)
__rmul__ = __mul__
def identity_hom(self):
"""Return the identity homomorphism on ``self``."""
raise NotImplementedError
class ModuleElement:
"""
Base class for module element wrappers.
Use this class to wrap primitive data types as module elements. It stores
a reference to the containing module, and implements all the arithmetic
operators.
Attributes:
- module - containing module
- data - internal data
Methods that likely need change in subclasses:
- add
- mul
- div
- eq
"""
def __init__(self, module, data):
self.module = module
self.data = data
def add(self, d1, d2):
"""Add data ``d1`` and ``d2``."""
return d1 + d2
def mul(self, m, d):
"""Multiply module data ``m`` by coefficient d."""
return m * d
def div(self, m, d):
"""Divide module data ``m`` by coefficient d."""
return m / d
def eq(self, d1, d2):
"""Return true if d1 and d2 represent the same element."""
return d1 == d2
def __add__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.add(self.data, om.data))
__radd__ = __add__
def __neg__(self):
return self.__class__(self.module, self.mul(self.data,
self.module.ring.convert(-1)))
def __sub__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return NotImplemented
return self.__add__(-om)
def __rsub__(self, om):
return (-self).__add__(om)
def __mul__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.mul(self.data, o))
__rmul__ = __mul__
def __truediv__(self, o):
if not isinstance(o, self.module.ring.dtype):
try:
o = self.module.ring.convert(o)
except CoercionFailed:
return NotImplemented
return self.__class__(self.module, self.div(self.data, o))
def __eq__(self, om):
if not isinstance(om, self.__class__) or om.module != self.module:
try:
om = self.module.convert(om)
except CoercionFailed:
return False
return self.eq(self.data, om.data)
def __ne__(self, om):
return not self == om
##########################################################################
## Free Modules ##########################################################
##########################################################################
class FreeModuleElement(ModuleElement):
"""Element of a free module. Data stored as a tuple."""
def add(self, d1, d2):
return tuple(x + y for x, y in zip(d1, d2))
def mul(self, d, p):
return tuple(x * p for x in d)
def div(self, d, p):
return tuple(x / p for x in d)
def __repr__(self):
from sympy.printing.str import sstr
return '[' + ', '.join(sstr(x) for x in self.data) + ']'
def __iter__(self):
return self.data.__iter__()
def __getitem__(self, idx):
return self.data[idx]
class FreeModule(Module):
"""
Abstract base class for free modules.
Additional attributes:
- rank - rank of the free module
Non-implemented methods:
- submodule
"""
dtype = FreeModuleElement
def __init__(self, ring, rank):
Module.__init__(self, ring)
self.rank = rank
def __repr__(self):
return repr(self.ring) + "**" + repr(self.rank)
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> F.is_submodule(F)
True
>>> F.is_submodule(M)
True
>>> M.is_submodule(F)
False
"""
if isinstance(other, SubModule):
return other.container == self
if isinstance(other, FreeModule):
return other.ring == self.ring and other.rank == self.rank
return False
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.convert([1, 0])
[1, 0]
"""
if isinstance(elem, FreeModuleElement):
if elem.module is self:
return elem
if elem.module.rank != self.rank:
raise CoercionFailed
return FreeModuleElement(self,
tuple(self.ring.convert(x, elem.module.ring) for x in elem.data))
elif iterable(elem):
tpl = tuple(self.ring.convert(x) for x in elem)
if len(tpl) != self.rank:
raise CoercionFailed
return FreeModuleElement(self, tpl)
elif _aresame(elem, 0):
return FreeModuleElement(self, (self.ring.convert(0),)*self.rank)
else:
raise CoercionFailed
def is_zero(self):
"""
Returns True if ``self`` is a zero module.
(If, as this implementation assumes, the coefficient ring is not the
zero ring, then this is equivalent to the rank being zero.)
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(0).is_zero()
True
>>> QQ.old_poly_ring(x).free_module(1).is_zero()
False
"""
return self.rank == 0
def basis(self):
"""
Return a set of basis elements.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(3).basis()
([1, 0, 0], [0, 1, 0], [0, 0, 1])
"""
from sympy.matrices import eye
M = eye(self.rank)
return tuple(self.convert(M.row(i)) for i in range(self.rank))
def quotient_module(self, submodule):
"""
Return a quotient module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2)
>>> M.quotient_module(M.submodule([1, x], [x, 2]))
QQ[x]**2/<[1, x], [x, 2]>
Or more conicisely, using the overloaded division operator:
>>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]]
QQ[x]**2/<[1, x], [x, 2]>
"""
return QuotientModule(self.ring, self, submodule)
def multiply_ideal(self, other):
"""
Multiply ``self`` by the ideal ``other``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x)
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.multiply_ideal(I)
<[x, 0], [0, x]>
"""
return self.submodule(*self.basis()).multiply_ideal(other)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).identity_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2
[0, 1]])
"""
from sympy.polys.agca.homomorphisms import homomorphism
return homomorphism(self, self, self.basis())
class FreeModulePolyRing(FreeModule):
"""
Free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of the ring instead:
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(3)
>>> F
QQ[x]**3
>>> F.contains([x, 1, 0])
True
>>> F.contains([1/x, 0, 1])
False
"""
def __init__(self, ring, rank):
from sympy.polys.domains.old_polynomialring import PolynomialRingBase
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, PolynomialRingBase):
raise NotImplementedError('This implementation only works over '
+ 'polynomial rings, got %s' % ring)
if not isinstance(ring.dom, Field):
raise NotImplementedError('Ground domain must be a field, '
+ 'got %s' % ring.dom)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y])
>>> M
<[x, x + y]>
>>> M.contains([2*x, 2*x + 2*y])
True
>>> M.contains([x, y])
False
"""
return SubModulePolyRing(gens, self, **opts)
class FreeModuleQuotientRing(FreeModule):
"""
Free module over a quotient ring.
Do not instantiate this, use the constructor method of the ring instead:
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3)
>>> F
(QQ[x]/<x**2 + 1>)**3
Attributes
- quot - the quotient module `R^n / IR^n`, where `R/I` is our ring
"""
def __init__(self, ring, rank):
from sympy.polys.domains.quotientring import QuotientRing
FreeModule.__init__(self, ring, rank)
if not isinstance(ring, QuotientRing):
raise NotImplementedError('This implementation only works over '
+ 'quotient rings, got %s' % ring)
F = self.ring.ring.free_module(self.rank)
self.quot = F / (self.ring.base_ideal*F)
def __repr__(self):
return "(" + repr(self.ring) + ")" + "**" + repr(self.rank)
def submodule(self, *gens, **opts):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
"""
return SubModuleQuotientRing(gens, self, **opts)
def lift(self, elem):
"""
Lift the element ``elem`` of self to the module self.quot.
Note that self.quot is the same set as self, just as an R-module
and not as an R/I-module, so this makes sense.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> e
[1 + <x**2 + 1>, 0 + <x**2 + 1>]
>>> L = F.quot
>>> l = F.lift(e)
>>> l
[1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]>
>>> L.contains(l)
True
"""
return self.quot.convert([x.data for x in elem])
def unlift(self, elem):
"""
Push down an element of self.quot to self.
This undoes ``lift``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
>>> e = F.convert([1, 0])
>>> l = F.lift(e)
>>> e == l
False
>>> e == F.unlift(l)
True
"""
return self.convert(elem.data)
##########################################################################
## Submodules and subquotients ###########################################
##########################################################################
class SubModule(Module):
"""
Base class for submodules.
Attributes:
- container - containing module
- gens - generators (subset of containing module)
- rank - rank of containing module
Non-implemented methods:
- _contains
- _syzygies
- _in_terms_of_generators
- _intersect
- _module_quotient
Methods that likely need change in subclasses:
- reduce_element
"""
def __init__(self, gens, container):
Module.__init__(self, container.ring)
self.gens = tuple(container.convert(x) for x in gens)
self.container = container
self.rank = container.rank
self.ring = container.ring
self.dtype = container.dtype
def __repr__(self):
return "<" + ", ".join(repr(x) for x in self.gens) + ">"
def _contains(self, other):
"""Implementation of containment.
Other is guaranteed to be FreeModuleElement."""
raise NotImplementedError
def _syzygies(self):
"""Implementation of syzygy computation wrt self generators."""
raise NotImplementedError
def _in_terms_of_generators(self, e):
"""Implementation of expression in terms of generators."""
raise NotImplementedError
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal represantition.
Mostly called implicitly.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x])
>>> M.convert([2, 2*x])
[2, 2*x]
"""
if isinstance(elem, self.container.dtype) and elem.module is self:
return elem
r = copy(self.container.convert(elem, M))
r.module = self
if not self._contains(r):
raise CoercionFailed
return r
def _intersect(self, other):
"""Implementation of intersection.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def _module_quotient(self, other):
"""Implementation of quotient.
Other is guaranteed to be a submodule of same free module."""
raise NotImplementedError
def intersect(self, other, **options):
"""
Returns the intersection of ``self`` with submodule ``other``.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, x]).intersect(F.submodule([y, y]))
<[x*y, x*y]>
Some implementation allow further options to be passed. Currently, to
only one implemented is ``relations=True``, in which case the function
will return a triple ``(res, rela, relb)``, where ``res`` is the
intersection module, and ``rela`` and ``relb`` are lists of coefficient
vectors, expressing the generators of ``res`` in terms of the
generators of ``self`` (``rela``) and ``other`` (``relb``).
>>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True)
(<[x*y, x*y]>, [(y,)], [(x,)])
The above result says: the intersection module is generated by the
single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where
`(x, x)` and `(y, y)` respectively are the unique generators of
the two modules being intersected.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._intersect(other, **options)
def module_quotient(self, other, **options):
r"""
Returns the module quotient of ``self`` by submodule ``other``.
That is, if ``self`` is the module `M` and ``other`` is `N`, then
return the ideal `\{f \in R | fN \subset M\}`.
Examples
========
>>> from sympy import QQ
>>> from sympy.abc import x, y
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> S = F.submodule([x*y, x*y])
>>> T = F.submodule([x, x])
>>> S.module_quotient(T)
<y>
Some implementations allow further options to be passed. Currently, the
only one implemented is ``relations=True``, which may only be passed
if ``other`` is principal. In this case the function
will return a pair ``(res, rel)`` where ``res`` is the ideal, and
``rel`` is a list of coefficient vectors, expressing the generators of
the ideal, multiplied by the generator of ``other`` in terms of
generators of ``self``.
>>> S.module_quotient(T, relations=True)
(<y>, [[1]])
This means that the quotient ideal is generated by the single element
`y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being
the generators of `T` and `S`, respectively.
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self._module_quotient(other, **options)
def union(self, other):
"""
Returns the module generated by the union of ``self`` and ``other``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(1)
>>> M = F.submodule([x**2 + x]) # <x(x+1)>
>>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)>
>>> M.union(N) == F.submodule([x+1])
True
"""
if not isinstance(other, SubModule):
raise TypeError('%s is not a SubModule' % other)
if other.container != self.container:
raise ValueError(
'%s is contained in a different free module' % other)
return self.__class__(self.gens + other.gens, self.container)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_zero()
False
>>> F.submodule([0, 0]).is_zero()
True
"""
return all(x == 0 for x in self.gens)
def submodule(self, *gens):
"""
Generate a submodule.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1])
>>> M.submodule([x**2, x])
<[x**2, x]>
"""
if not self.subset(gens):
raise ValueError('%s not a subset of %s' % (gens, self))
return self.__class__(gens, self.container)
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return all(self.contains(x) for x in self.container.basis())
def is_submodule(self, other):
"""
Returns True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([2, x])
>>> N = M.submodule([2*x, x**2])
>>> M.is_submodule(M)
True
>>> M.is_submodule(N)
True
>>> N.is_submodule(M)
False
"""
if isinstance(other, SubModule):
return self.container == other.container and \
all(self.contains(x) for x in other.gens)
if isinstance(other, (FreeModule, QuotientModule)):
return self.container == other and self.is_full_module()
return False
def syzygy_module(self, **opts):
r"""
Compute the syzygy module of the generators of ``self``.
Suppose `M` is generated by `f_1, \ldots, f_n` over the ring
`R`. Consider the homomorphism `\phi: R^n \to M`, given by
sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`.
The syzygy module is defined to be the kernel of `\phi`.
Examples
========
The syzygy module is zero iff the generators generate freely a free
submodule:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero()
True
A slightly more interesting example:
>>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y])
>>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x])
>>> M.syzygy_module() == S
True
"""
F = self.ring.free_module(len(self.gens))
# NOTE we filter out zero syzygies. This is for convenience of the
# _syzygies function and not meant to replace any real "generating set
# reduction" algorithm
return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0],
**opts)
def in_terms_of_generators(self, e):
"""
Express element ``e`` of ``self`` in terms of the generators.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> M = F.submodule([1, 0], [1, 1])
>>> M.in_terms_of_generators([x, x**2])
[-x**2 + x, x**2]
"""
try:
e = self.convert(e)
except CoercionFailed:
raise ValueError('%s is not an element of %s' % (e, self))
return self._in_terms_of_generators(e)
def reduce_element(self, x):
"""
Reduce the element ``x`` of our ring modulo the ideal ``self``.
Here "reduce" has no specific meaning, it could return a unique normal
form, simplify the expression a bit, or just do nothing.
"""
return x
def quotient_module(self, other, **opts):
"""
Return a quotient module.
This is the same as taking a submodule of a quotient of the containing
module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S1 = F.submodule([x, 1])
>>> S2 = F.submodule([x**2, x])
>>> S1.quotient_module(S2)
<[x, 1] + <[x**2, x]>>
Or more coincisely, using the overloaded division operator:
>>> F.submodule([x, 1]) / [(x**2, x)]
<[x, 1] + <[x**2, x]>>
"""
if not self.is_submodule(other):
raise ValueError('%s not a submodule of %s' % (other, self))
return SubQuotientModule(self.gens,
self.container.quotient_module(other), **opts)
def __add__(self, oth):
return self.container.quotient_module(self).convert(oth)
__radd__ = __add__
def multiply_ideal(self, I):
"""
Multiply ``self`` by the ideal ``I``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**2)
>>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1])
>>> I*M
<[x**2, x**2]>
"""
return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens])
def inclusion_hom(self):
"""
Return a homomorphism representing the inclusion map of ``self``.
That is, the natural map from ``self`` to ``self.container``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom()
Matrix([
[1, 0], : <[x, x]> -> QQ[x]**2
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(self)
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom()
Matrix([
[1, 0], : <[x, x]> -> <[x, x]>
[0, 1]])
"""
return self.container.identity_hom().restrict_domain(
self).restrict_codomain(self)
class SubQuotientModule(SubModule):
"""
Submodule of a quotient module.
Equivalently, quotient module of a submodule.
Do not instantiate this, instead use the submodule or quotient_module
constructing methods:
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> S = F.submodule([1, 0], [1, x])
>>> Q = F/[(1, 0)]
>>> S/[(1, 0)] == Q.submodule([5, x])
True
Attributes:
- base - base module we are quotient of
- killed_module - submodule used to form the quotient
"""
def __init__(self, gens, container, **opts):
SubModule.__init__(self, gens, container)
self.killed_module = self.container.killed_module
# XXX it is important for some code below that the generators of base
# are in this particular order!
self.base = self.container.base.submodule(
*[x.data for x in self.gens], **opts).union(self.killed_module)
def _contains(self, elem):
return self.base.contains(elem.data)
def _syzygies(self):
# let N = self.killed_module be generated by e_1, ..., e_r
# let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r
# Then self = F/N.
# Let phi: R**s --> self be the evident surjection.
# Similarly psi: R**(s + r) --> F.
# We need to find generators for ker(phi). Let chi: R**s --> F be the
# evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is
# contained in N, iff there exists Y in R**r such that
# psi(X, Y) = 0.
# Hence if alpha: R**(s + r) --> R**s is the projection map, then
# ker(phi) = alpha ker(psi).
return [X[:len(self.gens)] for X in self.base._syzygies()]
def _in_terms_of_generators(self, e):
return self.base._in_terms_of_generators(e.data)[:len(self.gens)]
def is_full_module(self):
"""
Return True if ``self`` is the entire free module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.submodule([x, 1]).is_full_module()
False
>>> F.submodule([1, 1], [1, 2]).is_full_module()
True
"""
return self.base.is_full_module()
def quotient_hom(self):
"""
Return the quotient homomorphism to self.
That is, return the natural map from ``self.base`` to ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0])
>>> M.quotient_hom()
Matrix([
[1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(self.killed_module)
_subs0 = lambda x: x[0]
_subs1 = lambda x: x[1:]
class ModuleOrder(ProductOrder):
"""A product monomial order with a zeroth term as module index."""
def __init__(self, o1, o2, TOP):
if TOP:
ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0))
else:
ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1))
class SubModulePolyRing(SubModule):
"""
Submodule of a free module over a generalized polynomial ring.
Do not instantiate this, use the constructor method of FreeModule instead:
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x, y).free_module(2)
>>> F.submodule([x, y], [1, 0])
<[x, y], [1, 0]>
Attributes:
- order - monomial order used
"""
#self._gb - cached groebner basis
#self._gbe - cached groebner basis relations
def __init__(self, gens, container, order="lex", TOP=True):
SubModule.__init__(self, gens, container)
if not isinstance(container, FreeModulePolyRing):
raise NotImplementedError('This implementation is for submodules of '
+ 'FreeModulePolyRing, got %s' % container)
self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP)
self._gb = None
self._gbe = None
def __eq__(self, other):
if isinstance(other, SubModulePolyRing) and self.order != other.order:
return False
return SubModule.__eq__(self, other)
def _groebner(self, extended=False):
"""Returns a standard basis in sdm form."""
from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora
if self._gbe is None and extended:
gb, gbe = sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom, extended=True)
self._gb, self._gbe = tuple(gb), tuple(gbe)
if self._gb is None:
self._gb = tuple(sdm_groebner(
[self.ring._vector_to_sdm(x, self.order) for x in self.gens],
sdm_nf_mora, self.order, self.ring.dom))
if extended:
return self._gb, self._gbe
else:
return self._gb
def _groebner_vec(self, extended=False):
"""Returns a standard basis in element form."""
if not extended:
return [FreeModuleElement(self,
tuple(self.ring._sdm_to_vector(x, self.rank)))
for x in self._groebner()]
gb, gbe = self._groebner(extended=True)
return ([self.convert(self.ring._sdm_to_vector(x, self.rank))
for x in gb],
[self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe])
def _contains(self, x):
from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora
return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order),
self._groebner(), self.order, self.ring.dom) == \
sdm_zero()
def _syzygies(self):
"""Compute syzygies. See [SCA, algorithm 2.5.4]."""
# NOTE if self.gens is a standard basis, this can be done more
# efficiently using Schreyer's theorem
# First bullet point
k = len(self.gens)
r = self.rank
zero = self.ring.convert(0)
one = self.ring.convert(1)
Rkr = self.ring.free_module(r + k)
newgens = []
for j, f in enumerate(self.gens):
m = [0]*(r + k)
for i, v in enumerate(f):
m[i] = f[i]
for i in range(k):
m[r + i] = one if j == i else zero
m = FreeModuleElement(Rkr, tuple(m))
newgens.append(m)
# Note: we need *descending* order on module index, and TOP=False to
# get an elimination order
F = Rkr.submodule(*newgens, order='ilex', TOP=False)
# Second bullet point: standard basis of F
G = F._groebner_vec()
# Third bullet point: G0 = G intersect the new k components
G0 = [x[r:] for x in G if all(y == zero for y in x[:r])]
# Fourth and fifth bullet points: we are done
return G0
def _in_terms_of_generators(self, e):
"""Expression in terms of generators. See [SCA, 2.8.1]."""
# NOTE: if gens is a standard basis, this can be done more efficiently
M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens))
S = M.syzygy_module(
order="ilex", TOP=False) # We want decreasing order!
G = S._groebner_vec()
# This list cannot not be empty since e is an element
e = [x for x in G if self.ring.is_unit(x[0])][0]
return [-x/e[0] for x in e[1:]]
def reduce_element(self, x, NF=None):
"""
Reduce the element ``x`` of our container modulo ``self``.
This applies the normal form ``NF`` to ``x``. If ``NF`` is passed
as none, the default Mora normal form is used (which is not unique!).
"""
from sympy.polys.distributedmodules import sdm_nf_mora
if NF is None:
NF = sdm_nf_mora
return self.container.convert(self.ring._sdm_to_vector(NF(
self.ring._vector_to_sdm(x, self.order), self._groebner(),
self.order, self.ring.dom),
self.rank))
def _intersect(self, other, relations=False):
# See: [SCA, section 2.8.2]
fi = self.gens
hi = other.gens
r = self.rank
ci = [[0]*(2*r) for _ in range(r)]
for k in range(r):
ci[k][k] = 1
ci[k][r + k] = 1
di = [list(f) + [0]*r for f in fi]
ei = [[0]*r + list(h) for h in hi]
syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies()
nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])]
res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero))
reln1 = [x[r:r + len(fi)] for x in nonzero]
reln2 = [x[r + len(fi):] for x in nonzero]
if relations:
return res, reln1, reln2
return res
def _module_quotient(self, other, relations=False):
# See: [SCA, section 2.8.4]
if relations and len(other.gens) != 1:
raise NotImplementedError
if len(other.gens) == 0:
return self.ring.ideal(1)
elif len(other.gens) == 1:
# We do some trickery. Let f be the (vector!) generating ``other``
# and f1, .., fn be the (vectors) generating self.
# Consider the submodule of R^{r+1} generated by (f, 1) and
# {(fi, 0) | i}. Then the intersection with the last module
# component yields the quotient.
g1 = list(other.gens[0]) + [1]
gi = [list(x) + [0] for x in self.gens]
# NOTE: We *need* to use an elimination order
M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi),
order='ilex', TOP=False)
if not relations:
return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if
all(y == self.ring.zero for y in x[:-1])])
else:
G, R = M._groebner_vec(extended=True)
indices = [i for i, x in enumerate(G) if
all(y == self.ring.zero for y in x[:-1])]
return (self.ring.ideal(*[G[i][-1] for i in indices]),
[[-x for x in R[i][1:]] for i in indices])
# For more generators, we use I : <h1, .., hn> = intersection of
# {I : <hi> | i}
# TODO this can be done more efficiently
return reduce(lambda x, y: x.intersect(y),
(self._module_quotient(self.container.submodule(x)) for x in other.gens))
class SubModuleQuotientRing(SubModule):
"""
Class for submodules of free modules over quotient rings.
Do not instantiate this. Instead use the submodule methods.
>>> from sympy.abc import x, y
>>> from sympy import QQ
>>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y])
>>> M
<[x + <x**2 - y**2>, x + y + <x**2 - y**2>]>
>>> M.contains([y**2, x**2 + x*y])
True
>>> M.contains([x, y])
False
Attributes:
- quot - the subquotient of `R^n/IR^n` generated by lifts of our generators
"""
def __init__(self, gens, container):
SubModule.__init__(self, gens, container)
self.quot = self.container.quot.submodule(
*[self.container.lift(x) for x in self.gens])
def _contains(self, elem):
return self.quot._contains(self.container.lift(elem))
def _syzygies(self):
return [tuple(self.ring.convert(y, self.quot.ring) for y in x)
for x in self.quot._syzygies()]
def _in_terms_of_generators(self, elem):
return [self.ring.convert(x, self.quot.ring) for x in
self.quot._in_terms_of_generators(self.container.lift(elem))]
##########################################################################
## Quotient Modules ######################################################
##########################################################################
class QuotientModuleElement(ModuleElement):
"""Element of a quotient module."""
def eq(self, d1, d2):
"""Equality comparison."""
return self.module.killed_module.contains(d1 - d2)
def __repr__(self):
return repr(self.data) + " + " + repr(self.module.killed_module)
class QuotientModule(Module):
"""
Class for quotient modules.
Do not instantiate this directly. For subquotients, see the
SubQuotientModule class.
Attributes:
- base - the base module we are a quotient of
- killed_module - the submodule used to form the quotient
- rank of the base
"""
dtype = QuotientModuleElement
def __init__(self, ring, base, submodule):
Module.__init__(self, ring)
if not base.is_submodule(submodule):
raise ValueError('%s is not a submodule of %s' % (submodule, base))
self.base = base
self.killed_module = submodule
self.rank = base.rank
def __repr__(self):
return repr(self.base) + "/" + repr(self.killed_module)
def is_zero(self):
"""
Return True if ``self`` is a zero module.
This happens if and only if the base module is the same as the
submodule being killed.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> (F/[(1, 0)]).is_zero()
False
>>> (F/[(1, 0), (0, 1)]).is_zero()
True
"""
return self.base == self.killed_module
def is_submodule(self, other):
"""
Return True if ``other`` is a submodule of ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False
"""
if isinstance(other, QuotientModule):
return self.killed_module == other.killed_module and \
self.base.is_submodule(other.base)
if isinstance(other, SubQuotientModule):
return other.container == self
return False
def submodule(self, *gens, **opts):
"""
Generate a submodule.
This is the same as taking a quotient of a submodule of the base
module.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> Q.submodule([x, 0])
<[x, 0] + <[x, x]>>
"""
return SubQuotientModule(gens, self, **opts)
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> F.convert([1, 0])
[1, 0] + <[1, 2], [1, x]>
"""
if isinstance(elem, QuotientModuleElement):
if elem.module is self:
return elem
if self.killed_module.is_submodule(elem.module.killed_module):
return QuotientModuleElement(self, self.base.convert(elem.data))
raise CoercionFailed
return QuotientModuleElement(self, self.base.convert(elem))
def identity_hom(self):
"""
Return the identity homomorphism on ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.identity_hom()
Matrix([
[1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module).quotient_domain(self.killed_module)
def quotient_hom(self):
"""
Return the quotient homomorphism to ``self``.
That is, return a homomorphism representing the natural map from
``self.base`` to ``self``.
Examples
========
>>> from sympy.abc import x
>>> from sympy import QQ
>>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)]
>>> M.quotient_hom()
Matrix([
[1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]>
[0, 1]])
"""
return self.base.identity_hom().quotient_codomain(
self.killed_module)
| true |
9c756fc1adeed95b891700d3e0122462fabd712c | Python | Electrostatics/mmcif_pdbx | /tests/test_version.py | UTF-8 | 239 | 2.6875 | 3 | [
"CC0-1.0"
] | permissive | import re
import pdbx
from pdbx import __version__
def test_version_exists():
assert hasattr(pdbx, "__version__")
def test_version():
assert re.match(r"[0-9]+\.[0-9]+\.[0-9]+", __version__)
print(f"VERSION: {__version__}")
| true |
77930bd3ff6c8f7d72f79061a9369a33b463bc34 | Python | fernandoans/problemasPython | /problema26/lerImagem.py | UTF-8 | 732 | 2.546875 | 3 | [] | no_license | # -------------------------------------------------------------
# Optical Character Recognition ou Optical Character Reader
# -------------------------------------------------------------
# sudo apt-get install tesseract-ocr tesseract-ocr-por
# sudo pip install pytesseract
# tesseract LGPD01.png saida -l por
# -------------------------------------------------------------
from PIL import Image
import pytesseract
with open("/home/fernando/Pictures/Palestras/meuGDPR.txt", "w") as f:
for i in range(1, 42):
nomeImg = '/home/fernando/Pictures/Palestras/GDPR/GDPR' + \
('0' if i < 10 else '') + str(i) + '.png'
f.writelines(pytesseract.image_to_string(
Image.open(nomeImg), lang='por'))
| true |
8b7c6c72c19c64162b21f71d372227897314fd5b | Python | eloitanguy/wikidiver | /models/ner.py | UTF-8 | 5,702 | 2.671875 | 3 | [] | no_license | from __future__ import unicode_literals, print_function
import spacy
import neuralcoref
import urllib
import json
from models.utils import character_idx_to_word_idx
class CoreferenceResolver(object):
"""
Class for executing coreference resolution on a given text
code from https://github.com/huggingface/neuralcoref/issues/288
"""
def __init__(self):
# Load SpaCy
nlp = spacy.load('en') # if OSError, use CLI: "python -m spacy download en"
# Add neural coreference to SpaCy's pipe
neuralcoref.add_to_pipe(nlp)
self.nlp_pipeline = nlp
def __call__(self, text):
doc = self.nlp_pipeline(text)
# fetches tokens with whitespaces from spacy document
tok_list = list(token.text_with_ws for token in doc)
for cluster in doc._.coref_clusters:
# get tokens from representative cluster name
cluster_main_words = set(cluster.main.text.split(' '))
for coref in cluster:
if coref != cluster.main: # if coreference element is not the representative element of that cluster
if coref.text != cluster.main.text and bool(
set(coref.text.split(' ')).intersection(cluster_main_words)) == False:
# if coreference element text and representative element text are not equal and none of the
# coreference element words are in representative element. This was done to handle nested
# coreference scenarios
tok_list[coref.start] = cluster.main.text + \
doc[coref.end - 1].whitespace_
for i in range(coref.start + 1, coref.end):
tok_list[i] = ""
return "".join(tok_list)
def wikifier(text, threshold=0.9, grouped=True):
"""
Function that fetches entity linking results from wikifier.com API, includes code from:
https://towardsdatascience.com/from-text-to-knowledge-the-information-extraction-pipeline-b65e7e30273e\n
:return: a list of detection dicts:
'start_idx': inclusive start index,
'end_idx':inclusive end index,
'id': entity Wikidata ID,
'name': a name for the entity,
'mention': the sentence slice relating to it
"""
# Resolve text co-references
# Prepare the URL.
data = urllib.parse.urlencode([
("text", text), ("lang", 'en'),
("userKey", "tgbdmkpmkluegqfbawcwjywieevmza"),
("pageRankSqThreshold", "%g" %
threshold), ("applyPageRankSqThreshold", "true"),
("nTopDfValuesToIgnore", "100"), ("nWordsToIgnoreFromList", "100"),
("wikiDataClasses", "true"), ("wikiDataClassIds", "false"),
("support", "true"), ("ranges", "false"), ("minLinkFrequency", "2"),
("includeCosines", "false"), ("maxMentionEntropy", "3")
])
url = "http://www.wikifier.org/annotate-article"
# Call the Wikifier and read the response.
req = urllib.request.Request(url, data=data.encode("utf8"), method="POST")
with urllib.request.urlopen(req, timeout=60) as open_request:
response = open_request.read()
response = json.loads(response.decode("utf8"))
# Output the annotations.
results = []
annotated = [False] * len(text.split(' ')) # only annotate once every word index
char_map = character_idx_to_word_idx(text)
for annotation in response["annotations"]:
characters = [(el['chFrom'], el['chTo']) for el in annotation['support']]
for start_char, end_char in characters:
start_w, end_w = char_map[start_char], char_map[end_char]
mention = text[start_char:end_char+1]
for w_idx in range(start_w, end_w+1):
if not annotated[w_idx]: # remove duplicates
try:
results.append([w_idx, annotation['wikiDataItemId'], annotation['title'], mention])
annotated[w_idx] = True
except KeyError: # in rare cases the annotation will not have a wikiDataItemId key, skip it
continue
return get_grouped_ner_results(results) if grouped else results
def get_grouped_ner_results(result_list):
"""
Used for grouping the outputs of wikifier.
:param result_list: a list of [idx, wikidatavitals id, name, mention] detections (one per detected word)
:return: a list of detection dicts:
'start_idx': inclusive start index,
'end_idx':inclusive end index,
'id': entity Wikidata ID,
'name': a name for the entity,
'mention': the sentence slice relating to it
"""
if not result_list:
return []
current_start_idx = 0
previous_id = result_list[0][1] # assigning a fake -1-th word with the same label as the first one
res = []
for word_idx, word_output in enumerate(result_list):
new_id = word_output[1]
if new_id != previous_id: # changed entity
res.append({'start_idx': current_start_idx,
'end_idx': result_list[word_idx-1][0],
'id': result_list[word_idx-1][1],
'name': result_list[word_idx-1][2],
'mention': result_list[word_idx-1][3]})
current_start_idx = result_list[word_idx][0]
previous_id = new_id
# add the last one
res.append({'start_idx': current_start_idx,
'end_idx': result_list[-1][0],
'id': result_list[-1][1],
'name': result_list[-1][2],
'mention': result_list[-1][3]})
return res
| true |
1b2c0cbd4af374197bd90b0d83d507d4f04458fb | Python | haobo724/cvex4 | /dir_curve.py | UTF-8 | 1,427 | 3.078125 | 3 | [] | no_license | from evaluation import OpenSetEvaluation
from classifier import NearestNeighborClassifier
import matplotlib.pyplot as plt
import numpy as np
# The range of the false alarm rate in logarithmic space to draw DIR curves.
false_alarm_rate_range = np.logspace(-3.0, 0, 1000, endpoint=False)
# Pickle files containing embeddings and corresponding class labels for the training and the test dataset.
train_data_file = "evaluation_training_data.pkl"
test_data_file = "evaluation_test_data.pkl"
# We use a nearest neighbor classifier for this evaluation.
classifier = NearestNeighborClassifier()
# Prepare a new evaluation instance and feed training and test data into this evaluation.
evaluation = OpenSetEvaluation(classifier=classifier,
false_alarm_rate_range=false_alarm_rate_range)
evaluation.prepare_input_data(train_data_file, test_data_file)
# Run the evaluation and retrieve the performance measures (identification rates and false alarm rates) on the test
# dataset.
results = evaluation.run()
# Plot the DIR curve.
plt.semilogx(false_alarm_rate_range, results['identification_rates'],
markeredgewidth=1,
linewidth=3,
linestyle="--",
color="blue")
plt.grid(True)
plt.axis([false_alarm_rate_range[0], false_alarm_rate_range[len(false_alarm_rate_range)-1], 0, 1])
plt.xlabel('False alarm rate')
plt.ylabel('Identification rate')
plt.show() | true |
6eef48a621cc63ebb3dd486d0b374fcf206740db | Python | NikitaLinberg/write-number-bot | /app/numbers_written_form.py | UTF-8 | 5,648 | 3.1875 | 3 | [] | no_license | import json
import os
import random
NUMBERS_JSON_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "numbers.json")
assert os.path.isfile(NUMBERS_JSON_PATH), f"{NUMBERS_JSON_PATH!r} file must exist!"
NUMBER_COMPONENTS = {int(k): v for k, v in json.load(open(NUMBERS_JSON_PATH)).items()}
WORD_COMPONENTS = {v: k for k, v in NUMBER_COMPONENTS.items()}
MAX_RANK = max(NUMBER_COMPONENTS.items())
MEANING_OF_LIFE = "Answer to the Ultimate Question of Life, the Universe, and Everything"
def _parse_number_group(nums, source_string):
""" Combine a group of numbers into a single integer, from 1 up to 999.
source_string - The source string of the numbers, for detailed exceptions.
"""
hundreds = 0
if nums[0] == 100:
raise Exception(f"A number can't start on a \"hundred\", please use \"one hundred\"")
if len(nums) >= 2 and nums[1] == 100:
if 0 <= nums[0] <= 9:
hundreds = nums[0] * 100
nums = nums[2:]
source_string = " ".join(source_string.split()[-2:])
else:
raise Exception(f"Expected a number of hundreds from 1 up to 9, instead got: {source_string!r}")
if len(nums) == 0:
return hundreds
if len(nums) == 1:
ones = nums[0]
if 1 <= ones <= 90:
return hundreds + ones
raise Exception(f"Expected a one-word number from range [1;90], instead got {source_string!r}")
if len(nums) == 2:
tens, ones = nums
if 20 <= tens <= 90 and 1 <= ones <= 9:
return hundreds + tens + ones
raise Exception(f"Expected a valid two-digit number, instead got: {source_string!r}")
raise Exception(f"Expected a valid quantity from range [1;999], instead got: {source_string!r}")
def parse_number_written_form(s):
""" Inverse of the number_written_form function - parse the number string into an integer.
"""
assert isinstance(s, str)
s = s.lower().strip()
if not s:
raise Exception(f"Expected a string of words, instead got an empty string")
if s == "zero":
return 0
if s == MEANING_OF_LIFE.lower() or s == MEANING_OF_LIFE.lower().replace(",", ""):
return 42
num_group, word_group, previous_rank, res = [], [], None, 0
for w in s.split():
if w == "zero":
raise Exception(f"\"Zero\" can only be used if it's alone")
if w not in WORD_COMPONENTS:
if w.endswith("illion"):
raise Exception(f"Unknown rank: {w!r}, this program only knows ranks up to " +
f"{MAX_RANK[1]!r} ({MAX_RANK[0]:.0e})")
raise Exception(f"This program can only handle numbers. It expected number word, instead got: {w!r}")
x = WORD_COMPONENTS[w]
if x and x % 1000 == 0:
if previous_rank is not None and x >= previous_rank:
raise Exception(f"Expected each number rank to be less than the previous rank, instead got rank {w!r}" +
f" ({x:.0e}) after rank {NUMBER_COMPONENTS[previous_rank]!r} ({previous_rank:.0e})")
if not num_group:
raise Exception(f"Expected to get quantity before each rank, instead got rank {w!r} without a quantity")
quantity = _parse_number_group(num_group, source_string=" ".join(word_group))
assert 1 <= quantity < 1000
res += quantity * x
num_group, word_group = [], []
previous_rank = x
else:
num_group.append(x)
word_group.append(w)
if num_group:
res += _parse_number_group(num_group, source_string=" ".join(word_group))
return res
def triplet_written_form(x):
if x < 100 and x in NUMBER_COMPONENTS:
return NUMBER_COMPONENTS[x]
if 20 < x < 100:
from_twenty_to_hundred = NUMBER_COMPONENTS[x // 10 * 10], NUMBER_COMPONENTS[x % 10]
return " ".join(from_twenty_to_hundred)
if 100 < x < 1000 and x % 100 != 0:
hundred_and_ = NUMBER_COMPONENTS[x // 100], NUMBER_COMPONENTS[100], triplet_written_form(x % 100)
return " ".join(hundred_and_)
if 100 <= x < 1000 and x % 100 == 0:
hundred_and_ = NUMBER_COMPONENTS[x // 100], NUMBER_COMPONENTS[100]
return " ".join(hundred_and_)
def number_written_form(x):
if x == 0:
return "zero"
if x == 42:
return MEANING_OF_LIFE
if x >= MAX_RANK[0] * 1000:
raise Exception(f"Sorry, can't write number {x}. This program only knows ranks up to " +
f"{MAX_RANK[1]!r} ({MAX_RANK[0]:.0e})")
triplets = []
while x > 0:
x, y = divmod(x, 1000)
triplets.append(y)
components = []
p = (len(triplets) - 1) * 3
for y in triplets[::-1]:
if y:
components.append(triplet_written_form(y))
if p:
components.append(NUMBER_COMPONENTS[10 ** p])
p -= 3
return " ".join(components)
if __name__ == "__main__":
print("running some parse_number_written_form tests...")
for test_num in range(1001):
test_s = number_written_form(test_num)
res_num = parse_number_written_form(test_s)
assert res_num == test_num, f"Expected to parse {test_s!r} into {test_num} instead got {res_num}"
for rank in range(3, 37):
start = 10 ** rank
test_num = random.randrange(start, start * 10)
test_s = number_written_form(test_num)
res_num = parse_number_written_form(test_s)
assert res_num == test_num, f"Expected to parse {test_s!r} into {test_num} instead got {res_num}"
print("passed all tests!")
| true |
74c0f7895a5605b49891f63435ca2e89f227bb6b | Python | ryanGT/krauss_misc | /rwkpickle.py | UTF-8 | 382 | 2.90625 | 3 | [] | no_license | import cPickle
def SavePickle(mydict, filepath, protocol=2):
"""Dump dictionary mydict to a Pickle file filepath using cPickle,
protocol=2."""
mypkl = open(filepath,'wb')
cPickle.dump(mydict, mypkl, protocol=protocol)
mypkl.close()
def LoadPickle(filepath):
mypkl = open(filepath,'rb')
mydict = cPickle.load(mypkl)
mypkl.close()
return mydict
| true |
4f10a14ca0e22fd354839cf1a774487c5884a91e | Python | WillieMaddox/pysfm | /bundle_io.py | UTF-8 | 790 | 2.578125 | 3 | [] | no_license | import numpy as np
from bundle import Bundle, Camera, Track
# Eek, currently hardcoded
width = 1480
height = 1360
K = np.array([1500, 0, width / 2, 0, 1500, height / 2, 0, 0, 1], float).reshape((3, 3))
def load(tracks_path, cameras_path):
bundle = Bundle()
bundle.K = K
# Read cameras
camera_data = np.loadtxt(open(cameras_path))
for row in camera_data:
P = row.reshape((3, 4))
bundle.add_camera(Camera(P[:, :3], P[:, 3]))
# Read tracks
for i, line in enumerate(open(tracks_path)):
tokens = line.strip().split()
assert len(tokens) % 3 == 0, 'Error at line %d:\n %s' % (i, line)
vs = np.array(map(int, tokens)).reshape((-1, 3))
bundle.add_track(Track(list(vs[:, 0].astype(int)), vs[:, 1:]))
return bundle
| true |
0a9ef4affdb2524fe54af7f8b4f8a13cc999733b | Python | saurabhariyan/daily_code | /projectEuler/problem3.py | UTF-8 | 140 | 3.25 | 3 | [] | no_license | import math
def sumdiff(n):
return (math.pow(n,4)/4 + math.pow(n,3)/6 - math.pow(n,2)/4 - n/6)
print (sumdiff (10));
print (sumdiff(100)); | true |
cafce2ad5011456ba51c25bf0f72b38deeea2227 | Python | hongjy127/TIL | /07. raspberrypi/python/video-ex/facedetect/ex02.py | UTF-8 | 877 | 2.625 | 3 | [] | no_license | import cv2
import sys
cascade_file = "haarcascade_frontalface_alt.xml"
cascade = cv2.CascadeClassifier(cascade_file)
image_file = "data/face1.jpg"
out_file = "data/face1-mosaic.jpg"
image = cv2.imread(image_file)
image_gs = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_list = cascade.detectMultiScale(image_gs, scaleFactor=1.1,
minNeighbors=1, minSize=(100,100))
if len(face_list) == 0:
print("no face")
quit()
mosaic_rate = 30
print(face_list)
color = (0,0,255)
for face in face_list:
x,y,w,h = face
face_img = image[y:y+h, x:x+w]
face_img = cv2.resize(face_img, (w//mosaic_rate, h//mosaic_rate))
face_img = cv2.resize(face_img, (w, h), interpolation=cv2.INTER_AREA)
image[y:y+h, x:x+w] = face_img
cv2.imwrite(out_file, image)
cv2.imshow('face1-mosaic.jpg', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
70af50726ea19e5de7ecf562d937a02144d1b844 | Python | mpajunen/advent-of-code | /2017/src/common/matrix.py | UTF-8 | 515 | 3.3125 | 3 | [] | no_license | def flip_vertical(a):
return a[::-1]
def get_rotations(a):
rotations = [a]
for _ in range(3):
a = rotate_ccw(a)
rotations.append(a)
return rotations
def rotate_ccw(a):
return tuple(reversed(list(zip(*a))))
if __name__ == "__main__":
assert flip_vertical(((1, 0), (0, 0))) == ((0, 0), (1, 0))
assert rotate_ccw(((1, 0), (0, 0))) == ((0, 0), (1, 0))
assert rotate_ccw(((1, 0, 0), (2, 0, 0), (0, 0, 0))) == ((0, 0, 0), (0, 0, 0), (1, 2, 0))
print('All ok')
| true |
53811d45468028b4c28a75fed4ed2c949d3a4788 | Python | raspberry-pi-maker/NVIDIA-Jetson | /face_recognition/findfaces2.py | UTF-8 | 859 | 3.015625 | 3 | [] | no_license | import argparse
import time
from PIL import Image, ImageDraw
import face_recognition
s_time = time.time()
parser = argparse.ArgumentParser(description='face match run')
parser.add_argument('--image', type=str, default='./img/groups/team2.jpg')
args = parser.parse_args()
image = face_recognition.load_image_file(args.image)
face_locations = face_recognition.face_locations(image)
pil_image = Image.fromarray(image)
img = ImageDraw.Draw(pil_image)
# Array of coords of each face
# print(face_locations)
for face_location in face_locations:
top, right, bottom, left = face_location
img.rectangle([(left, top),(right, bottom)], fill=None, outline='green')
print(f'There are {len(face_locations)} people in this image')
pil_image.save('findface_result.jpg')
e_time = time.time()
elapsed = e_time - s_time
print('Elapsed Time:%f seconds'%(elapsed))
| true |
e11d7ca1d385cc15d2abb226ab13fbbddaf2ada6 | Python | maw501/bayopt-gps | /notebooks/src/data_prep.py | UTF-8 | 1,949 | 2.53125 | 3 | [] | no_license | import gzip
import pickle
from pathlib import Path
import requests
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, TensorDataset
MNIST_H, MNIST_W = 28, 28
dev = (
torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
)
# torchvision datasets are PILImage images of range [0, 1] => transform to
# Tensors of normalized range [-1, 1]
mnist_transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
)
def download_mnist(folder="data"):
DATA_PATH = Path(folder)
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)
URL = "http://deeplearning.net/data/mnist/"
FILENAME = "mnist.pkl.gz"
if not (PATH / FILENAME).exists():
content = requests.get(URL + FILENAME).content
(PATH / FILENAME).open("wb").write(content)
with gzip.open((PATH / FILENAME).as_posix(), "rb") as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(
f, encoding="latin-1"
)
x_train, y_train, x_valid, y_valid = map(
torch.tensor, (x_train, y_train, x_valid, y_valid)
)
train_ds = TensorDataset(x_train, y_train)
valid_ds = TensorDataset(x_valid, y_valid)
return train_ds, valid_ds
def get_data(train_ds, valid_ds, bs):
return (
DataLoader(train_ds, batch_size=bs, shuffle=True),
DataLoader(valid_ds, batch_size=bs * 2),
)
def preprocess(x, y):
return x.view(-1, 1, MNIST_H, MNIST_W).to(dev), y.to(dev)
def to_gpu(x, y):
return x.to(dev), y.to(dev)
class WrapDL:
"""Generator applying pre-processing function to a batch as it's yielded"""
def __init__(self, dl, func):
self.dl = dl
self.func = func
def __len__(self):
return len(self.dl)
def __iter__(self):
batches = iter(self.dl)
for b in batches:
yield (self.func(*b))
| true |
41dbae8f79f9a5894d51b1388faf48d0b67b67bd | Python | Fraznist/prefect | /src/prefect/tasks/prometheus/pushgateway.py | UTF-8 | 9,333 | 2.71875 | 3 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | import abc
from prometheus_client import (
CollectorRegistry,
Gauge,
pushadd_to_gateway,
push_to_gateway,
)
from collections import namedtuple
from typing import Dict, List, Optional
from prefect import Task
from prefect.utilities.tasks import defaults_from_attrs
class _GaugeToGatewayBase(Task):
@abc.abstractmethod
def _push(self, **push_args):
pass
def __init__(
self,
pushgateway_url: str = None,
counter_name: str = None,
counter_description: str = None,
grouping_key: List[str] = None,
job_name: str = None,
**kwargs,
):
self.pushgateway_url = pushgateway_url
self.counter_name = counter_name
self.counter_description = counter_description
self.job_name = job_name
self.grouping_key = grouping_key
super().__init__(**kwargs)
@defaults_from_attrs(
"pushgateway_url",
"counter_name",
"counter_description",
"job_name",
"grouping_key",
)
def run(
self,
values: List[float],
labels: List[Dict[str, str]],
pushgateway_url: str = None,
counter_name: str = None,
counter_description: str = None,
grouping_key: Optional[List[str]] = None,
job_name: str = None,
) -> None:
"""
Push a Gauge to prometheus [PushGateway](https://prometheus.io/docs/practices/pushing/).
This will unpack the values and labels to create all the a collector that will be pushed
to pushgateway.
The following example is checking the data quality of a dataframe and output the metrics
for the job to the pushgateway
example:
```
from typing import Any, Dict, List, Tuple
import pandas as pd
from prefect import task, Flow, Parameter
from prefect.tasks.prometheus import PushAddGaugeToGateway
@task
def read_csv(path: str) -> pd.DataFrame:
return pd.read_csv(path)
@task
def check_na(
df: pd.DataFrame, dataframe_name: str
) -> Tuple[List[Dict[str, Any]], List[float]]:
total_rows = df.shape[0]
lkeys = []
lvalues = []
for c in df.columns:
na_values = len(df[df[c].isna()][c])
key = {"df": dataframe_name, "column": c}
lkeys.append(key)
lvalues.append(na_values / total_rows)
return (lkeys, lvalues)
with Flow("Check_Data") as flow:
source_path = Parameter(name="sourcePath", required=True)
name = Parameter(name="name", required=True)
pushgateway_url = Parameter(
name="pushgatewayUrl", default="http://localhost:9091"
)
df = read_csv(source_path)
check_result = check_na(df, name)
push_gateway = PushAddGaugeToGateway()
push_gateway(
values=check_result[1],
labels=check_result[0],
pushgateway_url=pushgateway_url,
counter_name="null_values_percentage",
grouping_key=["df"],
job_name="check_data",
)
flow.run(parameters={"sourcePath": "sample_data.csv", "name": "mySample"})
```
Args:
- values (List[float]): List of the values to push
- labels (List[Dict[str, str]]): List of the labels to push attached to the values
- pushgateway_url (str, optional): Url of the prometheus pushgateway instance
- counter_name (str, optional): Name of the counter
- counter_description (str, optional): description of the counter
- grouping_key (str, optional): List of the key used to calculate the grouping key
- job_name (str, optional): Name of the job
Returns:
- None
Raises:
- ValueError: if pushgateway_url or counter_name are empty and values and labels list
doesn't have the same length
"""
if not pushgateway_url:
raise ValueError("You need to provide the pushgateway_url parameter.")
if not counter_name:
raise ValueError("You need to provide the counter_name parameter.")
if not counter_description:
counter_description = counter_name
if len(values) != len(labels):
raise ValueError(
f"Values and labels need to have the same length. Values length is {len(values)}, "
f"labels length is {len(labels)}."
)
if len(values) == 0 or len(labels) == 0:
return
GroupingValues = namedtuple(
"GroupingValues", ["grouping_key", "labels_names", "labels", "values"]
)
groups = {}
for l, v in zip(labels, values):
grouping_key_values = (
{key: l[key] for key in grouping_key} if grouping_key else {}
)
group_key_id = "-".join(grouping_key_values.values())
group_values = groups.setdefault(
group_key_id, GroupingValues(grouping_key_values, l.keys(), [], [])
)
group_values.labels.append(l)
group_values.values.append(v)
for group in groups.values():
registry = CollectorRegistry()
g = Gauge(
counter_name,
counter_description,
labelnames=group.labels_names,
registry=registry,
)
for k, v in zip(group.labels, group.values):
g.labels(**k).set(v)
self._push(
gateway=pushgateway_url,
job=job_name,
grouping_key=group.grouping_key,
registry=registry,
)
class PushGaugeToGateway(_GaugeToGatewayBase):
"""
Task that allow you to push a Gauge to prometheus [PushGateway]
(https://prometheus.io/docs/practices/pushing/).This method is using the
[prometheus_client](https://github.com/prometheus/client_python#exporting-to-a-pushgateway).
This is a push mode task that it will remove all previous items that match the grouping key.
Some of the main usage of that task is to allow to push inside of your workflow to prometheus like
number of rows, quality of the values or anything you want to monitor.
Args:
- pushgateway_url (str, optional): Url of the prometheus pushgateway instance
- counter_name (str, optional): Name of the counter
- counter_description (str, optional): description of the counter
- grouping_key (str, optional): List of the key used to calculate the grouping key
- job_name (str, optional): Name of the job
- **kwargs (dict, optional): additional keyword arguments to pass to the
Task constructor
"""
def __init__(
self,
pushgateway_url: str = None,
counter_name: str = None,
counter_description: str = None,
grouping_key: List[str] = None,
job_name: str = None,
**kwargs,
):
super().__init__(
pushgateway_url=pushgateway_url,
counter_name=counter_name,
counter_description=counter_description,
job_name=job_name,
grouping_key=grouping_key,
**kwargs,
)
def _push(self, **push_args):
push_to_gateway(**push_args)
class PushAddGaugeToGateway(_GaugeToGatewayBase):
"""
Task that allow you to push add a Gauge to prometheus [PushGateway]
(https://prometheus.io/docs/practices/pushing/). This method is using the
[prometheus_client](https://github.com/prometheus/client_python#exporting-to-a-pushgateway).
This is a push add mode task that will add value into the same grouping key.
Some of the main usage of that task is to allow to push inside of your workflow to prometheus like
number of rows, quality of the values or anything you want to monitor.
Args:
- pushgateway_url (str, optional): Url of the prometheus pushgateway instance
- counter_name (str, optional): Name of the counter
- counter_description (str, optional): description of the counter
- grouping_key (str, optional): List of the key used to calculate the grouping key
- job_name (str, optional): Name of the job
- **kwargs (dict, optional): additional keyword arguments to pass to the
Task constructor
"""
def __init__(
self,
pushgateway_url: str = None,
counter_name: str = None,
counter_description: str = None,
grouping_key: List[str] = None,
job_name: str = None,
**kwargs,
):
super().__init__(
pushgateway_url=pushgateway_url,
counter_name=counter_name,
counter_description=counter_description,
job_name=job_name,
grouping_key=grouping_key,
**kwargs,
)
def _push(self, **push_args):
pushadd_to_gateway(**push_args)
# class PushAddGaugeToGateway(_GaugeToGatewayBase):
# def _push(self, **push_args):
# pushadd_to_gateway(**push_args)
| true |
e5953421c845098a5d9a2091a57dcc5ca05a43e6 | Python | hjuju/TF_Study-HAN | /Machine_Learning/ml17_pca_mnist5_xgb_gridSearch2.py | UTF-8 | 2,514 | 2.546875 | 3 | [] | no_license | # 0.999 이상의 n_componet=?를 사용하여 xgb 만들것
import numpy as np
from tensorflow.keras.datasets import mnist
from icecream import ic
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.svm import LinearSVC, SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression # 로지스틱회귀는 분류모델(회귀모델 X)
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
import warnings
from xgboost.sklearn import XGBClassifier
warnings.filterwarnings('ignore') # 경고무시
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 1. 데이터
x = np.append(x_train, x_test, axis=0)
y = np.append(y_train, y_test, axis=0)
ic(x.shape, y.shape) # (150, 4), (150,)->(150, 3)
# ic| x.shape: (70000, 28, 28), y.shape: (70000,)
compoents = 486
x = x.reshape(x.shape[0], 28*28)
# x.shape[1]
pca = PCA(n_components=compoents)
x = pca.fit_transform(x)
# pca_EVR = pca.explained_variance_ratio_
# cumsum = np.cumsum(pca_EVR)
# ic(np.argmax(cumsum >= 0.95)+1) # ic| np.argmax(cumsum >= 0.999)+1: 486
from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=66)
# ic(x_train.shape, x_test.shape, y_train.shape, y_test.shape, np.unique(y_train))
parameter = [{"n_estimators":[100, 200, 300], "learning_rate":[0.1,0.3,0.001,0.01], "max_depth":[4,5,6]},
{"n_estimators":[90, 100, 110], "learning_rate":[0.1,0.001,0.01], "max_depth":[4,5,6], "colsample_bytree":[0.6,0.9,1]},
{"n_estimators":[90, 110], "learning_rate":[0.1,0.001,0.5], "max_depth":[4,5,6], "colsample_bytree":[0.6,0.9,1],"colsample_bylevel":[0.6,0.7,0.9]}]
# 2. 모델(머신러닝에서는 정의만 해주면 됨)
n_splits=5
kfold = KFold(n_splits=n_splits, shuffle=True, random_state=66)
model = GridSearchCV(XGBClassifier(), parameter, cv=kfold, verbose=1) # 사용할 모델, parameter(정의), cv 명시 / 텐서플로로 하면 모델에 텐서플로 모델이 들어가면 됨
# model = SVC(C=1, kernel='linear')
model.fit(x_train,y_train)
print('최적의 매개변수: ', model.best_estimator_) # cv를 통해 나온 값 / GridSearchCV를 통해서만 출력 가능
print("best_score: ", model.best_score_)
| true |
3d1f83ffa2d5d5d23e6c6aa09b8235aa7457be62 | Python | Scipius02/181020-Hackathon | /181020 Hackathon2.py | UTF-8 | 1,326 | 3.6875 | 4 | [] | no_license | """ Selection of code that opens a plain text file, parses it into the Google Translate API
(whose library must be downloaded via https://github.com/BoseCorp/py-googletrans.git)
translates, then formats translation into a single sentence.
"""
from googletrans import Translator
translator = Translator()
# file-input.py
def open_text(txt_name):
f = open(txt_name,'r')
message = f.read()
print(message)
f.close()
txt_name = 'TestText.txt'
#if clicked, clicked item becomes variable Query, string
#print slice_translation(str(translator.translate(message))) # test line
# Give slice of translated portion for only the translation
def find_third_equals(s): #give index of third = sign
letter_count = 0
for i in range(len(s)):
if s[i] == "=":
letter_count += 1
if letter_count == 3:
return i + 1
def find_pronunciation(s): #give index of pronunciation
return int(s.find(" pronunciation"))
def slice_translation(s): #give slice of string for substring of only translated word
return s[find_third_equals(s):find_pronunciation(s)-1]
# print slice_translation("<Translated src=ko dest=ja text=hello there pronunciation=Kon'nichiwa.>")
# Slice functions above
print slice_translation(str(translator.translate(message)))
| true |
880355d57e92da6fe03223615f10bb4b700c8726 | Python | kasapenkonata/programming-practice | /pictures/picture2_2.py | UTF-8 | 5,120 | 3.546875 | 4 | [] | no_license | import pygame
from math import pi, cos, sin
def sun_(screen_, color, dx, dy, num_points, radius):
point_list = []
for i in range(num_points * 2):
radius_ = radius
if i % 2 == 0:
radius_ = radius - 5
ang = i * pi / num_points
x = dx + int(cos(ang) * radius_)
y = dy + int(sin(ang) * radius_)
point_list.append((x, y))
pygame.draw.polygon(screen_, color, point_list)
def cloud(screen_, color, x1, x2, y, radius):
for i in range(x1, x2, 20):
pygame.draw.circle(screen_, color[0], [i, y], radius + 1)
pygame.draw.circle(screen_, color[1], [i, y], radius)
pygame.init()
# Цвета, которые мы будем использовать в формате RGB
Black = (0, 0, 0)
White = (255, 255, 255)
Blue = (161, 235, 245)
BlueWindow = (14, 147, 145)
Green = (14, 147, 37)
GreenTrees = (15, 83, 14)
Red = (255, 0, 0)
Pink = (249, 194, 194)
Yellow = (255, 255, 0)
Brown = (147, 107, 14)
# Желаемое количество кадров в секунду
FPS = 30
# Установить высоту и ширину экрана
size = [700, 400]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Картинка 2_2.png")
# Цикл, пока пользователь не нажмет кнопку закрытия.
done = False
clock = pygame.time.Clock()
while not done:
# Это ограничивает цикл while до 30 раз в секунду.
clock.tick(FPS)
for event in pygame.event.get(): # Пользователь что-то сделал
if event.type == pygame.QUIT: # Если пользователь нажал кнопку "Закрыть"
done = True # Отметить, что мы закончили, поэтому мы выходим из цикла
# Весь код отрисовки происходит после цикла for, но
# внутри основного цикла while done == False.
# Очистить экран и установить фон экрана
screen.fill(White)
# Фон картинки
pygame.draw.rect(screen, Blue, [0, 0, 700, 200])
pygame.draw.rect(screen, Green, [0, 200, 700, 200])
# Солнце
sun_(screen, 'Black', 60, 60, 24, 41)
sun_(screen, 'Pink', 60, 60, 24, 40)
# Тучки
cloud(screen, ['Black', 'White'], 150, 241, 60, 20)
cloud(screen, ['Black', 'White'], 180, 211, 40, 20)
# Тучки
cloud(screen, ['Black', 'White'], 350, 441, 80, 15)
cloud(screen, ['Black', 'White'], 380, 411, 60, 15)
# Тучки
cloud(screen, ['Black', 'White'], 550, 641, 80, 20)
cloud(screen, ['Black', 'White'], 580, 611, 60, 20)
# Дом
pygame.draw.rect(screen, Black, [69, 169, 152, 152], 1)
pygame.draw.rect(screen, Brown, [70, 170, 150, 150])
# Окно
pygame.draw.rect(screen, BlueWindow, [113, 205, 65, 65])
# Крыша
pygame.draw.polygon(screen, Black, [[145, 90], [70, 169], [220, 169]])
pygame.draw.polygon(screen, Red, [[145, 92], [72, 168], [218, 168]])
# Ствол дерева
pygame.draw.rect(screen, Black, [300, 230, 20, 100])
# Листья
pygame.draw.circle(screen, Black, [310, 170], 22)
pygame.draw.circle(screen, GreenTrees, [310, 170], 21)
pygame.draw.circle(screen, Black, [290, 190], 22)
pygame.draw.circle(screen, GreenTrees, [290, 190], 21)
pygame.draw.circle(screen, Black, [330, 190], 22)
pygame.draw.circle(screen, GreenTrees, [330, 190], 21)
pygame.draw.circle(screen, Black, [310, 210], 22)
pygame.draw.circle(screen, GreenTrees, [310, 210], 21)
pygame.draw.circle(screen, Black, [290, 230], 22)
pygame.draw.circle(screen, GreenTrees, [290, 230], 21)
pygame.draw.circle(screen, Black, [330, 230], 22)
pygame.draw.circle(screen, GreenTrees, [330, 230], 21)
# Дом2
pygame.draw.rect(screen, Black, [409, 169, 112, 112], 1)
pygame.draw.rect(screen, Brown, [410, 170, 110, 110])
# Окно2
pygame.draw.rect(screen, BlueWindow, [445, 205, 40, 40])
# Крыша
pygame.draw.polygon(screen, Black, [[465, 120], [409, 169], [521, 169]])
pygame.draw.polygon(screen, Red, [[465, 122], [411, 168], [519, 168]])
# Ствол дерева2
pygame.draw.rect(screen, Black, [580, 220, 15, 70])
# Листья2
pygame.draw.circle(screen, Black, [590, 170], 18)
pygame.draw.circle(screen, GreenTrees, [590, 170], 17)
pygame.draw.circle(screen, Black, [570, 190], 18)
pygame.draw.circle(screen, GreenTrees, [570, 190], 17)
pygame.draw.circle(screen, Black, [605, 190], 18)
pygame.draw.circle(screen, GreenTrees, [605, 190], 17)
pygame.draw.circle(screen, Black, [590, 205], 18)
pygame.draw.circle(screen, GreenTrees, [590, 205], 17)
pygame.draw.circle(screen, Black, [570, 220], 18)
pygame.draw.circle(screen, GreenTrees, [570, 220], 17)
pygame.draw.circle(screen, Black, [605, 220], 18)
pygame.draw.circle(screen, GreenTrees, [605, 220], 17)
pygame.display.flip()
pygame.quit()
| true |
649c3abad9efe1f9c3a0724352b6d14629dd3b70 | Python | christofrancois/BioSWdev4ASN | /SNN_TUT/scripts/generate/new_stim_gene.py | UTF-8 | 1,230 | 2.953125 | 3 | [] | no_license | # The script writes in the files .stimtimes automatically
from random import randint
import math
import struct
file1 = "stim1.stimtimes"
file2 = "stim2.stimtimes"
fs1 = open(file1, "a+")
fs2 = open(file2, "a+")
MNIST_path = "../../data/train-labels.idx1-ubyte"
flab = open(MNIST_path, "rb")
start = 0
length = 3600 * 5
ton = 0.75 #time of stimulation
toff = 2.25 #time of rest
eps = 0.0001 #short period
#print magic number and the size
buff = flab.read(8)
print("%d %d" % (struct.unpack(">II", buff)))
def writePattern(time, patt, lab):
fs1.write("%s %s %s\n" % (time, 1, patt))
fs1.write("%s %s %s\n" % (time + eps, 0, patt))
fs1.write("%s %s %s\n" % (time + ton, 0, patt))
fs1.write("%s %s %s\n" % (time + ton + eps, 1, patt))
fs2.write("%s %s %s\n" % (time, 1, lab))
fs2.write("%s %s %s\n" % (time + eps, 0, lab))
fs2.write("%s %s %s\n" % (time + ton, 0, lab))
fs2.write("%s %s %s\n" % (time + ton + eps, 1, lab))
return
nb_patt = 100
buff = flab.read(nb_patt)
it = 0
i = start
while i < length:
label = struct.unpack(">B", buff[it])[0]
writePattern(i, it, label)
i += ton + toff
it += 1
if (it >= nb_patt):
it = 0
fs1.close()
fs2.close()
flab.close()
| true |
999b95e729b292c2e1aa96350acf1e8f37e17cc6 | Python | michaeltorku/ML-Classifier | /References/Climate Predictor Model/Code/Demonstration Chuck.py | UTF-8 | 1,561 | 2.9375 | 3 | [] | no_license | import csv
import numpy as np
import pandas as pd
import sklearn
from numpy import genfromtxt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
from sklearn.externals import joblib
Features = list(csv.reader(open(r'\Users\amoah_k\Desktop\T Hacks\Dataset/Features Edited.csv')))
Outputs = list(csv.reader(open(r'\Users\amoah_k\Desktop\T Hacks\Dataset/Outputs Edited.csv')))
# SPLITTING DATASET INTO TRAINING:TESTING 75:25
X_train, X_test, y_train, y_test = train_test_split(Features, Outputs, random_state = 0)
#DIMENSION REDUCTION WITH PCA
pca = PCA()
X_train = pca.fit_transform(X_train)
X_test = pca.fit_transform(X_test)
#Classification
def KNN(x):
""" Classifier with K-Nearest Neighbors"""
KNN = KNeighborsClassifier(n_neighbors = x) #Pick the number of neighbours
KNN.fit(X_train, np.ravel(y_train,order='C'))
filename = 'ClimateChuck.sav'
joblib.dump(KNN, filename)
def Predict():
ChuckName = 'ClimateChuck.sav'
ClimateChuck = joblib.load(ChuckName)
Prediction = ClimateChuck.predict(Data)
Probability = ClimateChuck.predict_proba(Data)
print("I believe that the weather is " + str(Prediction))
print("There is a " + str(Probability) + " chance that this is true")
print("Loading Demo Data")
print(" ")
print("Data Loaded")
print("Getting Predictions")
print(" ")
Data = list(csv.reader(open(r'\Users\amoah_k\Desktop\T Hacks\Dataset/Random Data.csv')))
Predict()
| true |
f5689da757196d92afe71acffa17d9709ba60ec2 | Python | TedCha/open-kattis-problems | /python/a_different_problem_2.7.py | UTF-8 | 166 | 2.703125 | 3 | [] | no_license | # https://open.kattis.com/problems/different
from sys import stdin
for line in stdin:
line = line.strip().split(" ")
print(abs(int(line[0]) - int(line[1]))) | true |
e213e881a00b1053ee3e161c07e36b2fa5fbeef0 | Python | anikpujan/Python-Project | /Bar_Lounge_Reviews.py | UTF-8 | 812 | 2.953125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import csv
pages = [0,10,20,30,40,50,60,70,80,90,100]
filename = open('bar_lounge.csv', 'w')
f = csv.writer(filename)
header = ['Name', 'Location', 'Reviews']
f.writerow(header)
for page in pages:
req = requests.get('https://www.yelp.com/biz/bar-karaoke-lounge-toronto?start={}'.format(page))
soup = BeautifulSoup(req.content,'html.parser')
list_items = soup.find_all(class_="review__373c0__13kpL border-color--default__373c0__3-ifU")
for i in list_items:
name = i.find(class_='css-166la90').get_text()
location = i.find(class_='css-n6i4z7').get_text()
reviews = i.find(class_='raw__373c0__3rcx7').get_text()
f.writerow([name, location, reviews])
filename.close()
| true |
5c6b7926b14536e8d4f1f3ac5cee2d94bf8a3b29 | Python | bennettj1087/aoc | /2015/day22.py | UTF-8 | 1,846 | 3.046875 | 3 | [] | no_license | #
# cost, damage, heal, mr, armor, duration
all_spells = { 'mm': [53, 4, 0, 0, 0, 1],
'd': [73, 2, 2, 0, 0, 1],
's': [113, 0, 0, 0, 7, 6],
'p': [173, 3, 0, 0, 0, 6],
'r': [229, 0, 0, 101, 0, 5] }
active_spells = dict()
wins = list()
bd = 10
def run_turn(mine, spent, mana, hp, boss_hp):
global active_spells
# apply effects
damage = sum(i[1] for i in active_spells.values())
armor = sum(i[4] for i in active_spells.values())
mana += sum(i[3] for i in active_spells.values())
# check boss hp
boss_hp -= damage
if boss_hp <= 0:
wins.append(spent)
return
# decrement durations and remove old effects
for x in list(active_spells.keys()):
active_spells[x][5] -= 1
if active_spells[x][5] == 0:
active_spells.pop(x)
#my turn
if mine:
# what can I cast?
poss_spells = [x for x in all_spells if all_spells[x][0] <= mana and x not in [y[0] for y in active_spells]]
# try them all!
for x in poss_spells:
spent += all_spells[x][0]
mana -= all_spells[x][0]
active_spells.update({x: all_spells[x]})
#print('run_turn(False, ', spent, mana, hp, boss_hp)
run_turn(False, spent, mana, hp, boss_hp)
#boss' turn
else:
hp = hp - max(bd - armor, 1)
if hp <= 0:
return
#print('run_turn(True, ', spent, mana, hp, boss_hp)
run_turn(True, spent, mana, hp, boss_hp)
run_turn(True, 0, 500, 50, 71)
print(wins)
##active_spells = {'r':[0,0,0,0,0]}
##poss_spells = [x for x in all_spells if all_spells[x][0] <= 500 and x not in [y[0] for y in active_spells]]
##print(poss_spells)
| true |
730b050649c34db55d086b3fbd32665967dc2752 | Python | SlavBite/Game_3-AlleyWay- | /_AlleyWay(3)/shop_in.py | UTF-8 | 4,187 | 2.65625 | 3 | [] | no_license | from print_text import *
from enemy import *
from inf import *
def going_to_1():
global click_press
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 490 < mouse[0] < 800 and 245 < mouse[1] < 450:
win.blit(shop_in_active,(490, 240))
if click[0] == 1 and click_press:
click_press = False
rack()
if click[0] != 1:
click_press = True
def draw_rack():
x = 100
y = 120
i = 0
win.blit(rack_image,(0,0))
leave_from_rack()
for item in save_item_pls.list_shop_item:
item.draw(x,y)
if item.sold:
save_item_pls.list_home_item.append(item)
save_item_pls.list_shop_item.remove(item)
x += 230
i += 1
if i % 5 == 0:
y += 120
x = 100
pygame.display.update()
def rack():
global main_rack
main_rack = True
win.fill((255,255,255))
while main_rack:
clock.tick(60)
draw_rack()
for event in pygame.event.get():
if event.type == pygame.QUIT:
save.save_data()
pygame.quit()
quit()
def leave_from_rack():
global main_rack, click_press
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 0 < mouse[0] < 50 and 0 < mouse[1] < 50:
pygame.draw.rect(win,(60,90,60),(0, 0, 50, 50))
if click[0] == 1 and click_press:
click_press = False
main_rack = False
if click[0] != 1:
click_press = True
class Shop_item():
def __init__(self, widht, height): # image, active_image,
#self.image = image
#self.active_image = active_image
self.widht = widht
self.height = height
self.sold = False
def draw(self,x,y):
global click_press
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x <= mouse[0] <= x + self.widht and y <= mouse[1] <= y + self.height:
pygame.draw.rect(win,(255,0,0),(x, y, self.widht, self.height))
#win.blit(self.image_active,(x,y))
if click[0] == 1 and click_press:
click_press = False
self.sold = True
elif click[0] != 1:
click_press = True
else:
pygame.draw.rect(win,(155,0,0),(x, y, self.widht, self.height))
#win.blit(self.image,(self.x,self.y))
class Home_item():
def draw_button(self):
global click_press
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if self.x <= mouse[0] <= self.x + self.widht and self.y <= mouse[1] <= self.y + self.height:
win.blit(self.image_active,(self.x,self.y))
if mouse[0] == 1 and click_press:
click_press = False
elif mouse[0] != 1:
click_press = True
else:
win.blit(self.image,(self.x,self.y))
def add_item(self, image, active_image, widht, height):
self.image = image
self.active_image = active_image
self.widht = widht
self.height = height
self.x = 100
self.y = 120
save_item_pls = [Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),
Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50)]
class Save_item:
def __init__(self,item):
self.list_shop_item = item
self.list_home_item = []
save_item_pls = Save_item([Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),
Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50),Shop_item(50, 50)])
class Save:
def __init__(self):
self.file = shelve.open('data')
def save_data(self):
self.file['unlock_level'] = unlock_level.unlock_level
self.file['shop_item_1'] = save_item_pls.list_shop_item
self.file['home_item'] = save_item_pls.list_home_item
def add(self, name, value):
self.file[name] = value
def get_date(self, name):
return self.file[name]
def delete_all_saves(self):
self.file['unlock_level'] = 1
def __del__(self):
self.file.close()
save = Save()
unlock_level.unlock_level = save.get_date('unlock_level')
save_item_pls.list_shop_item = save.get_date('shop_item_1')
save_item_pls.list_home_item = save.get_date('home_item')
| true |
446ea03fbdc4eca72cac7ed2e12ac18640860f27 | Python | Parkyunhwan/BaekJoon | /21_05/ThridWeek/P_Lv2_큰 수 만들기*.py | UTF-8 | 1,043 | 4.09375 | 4 | [] | no_license | '''
스택을 이용하자.
현재 스택의 top보다 작은 값은 무조건 삽입하고
top보다 큰 값은 더 큰 값이 상단에 올때까지 pop()한다.
이 작업을 k == 0이 될 때까지 또는 전체 문자열을 검사할 때 까지 진행한다.
이 작업을 거치면 스택에는 "앞자리 숫자가 가장 큰 순서"를 가지게 된다.
-> 앞자리를 최고 큰 수로 만들기 전략!!
## 주의할 점 ##
k의 갯수보다 적게 삭제하는 경우가 있을 수 있다. ex) 17442, k = 3 -> 처리를 거치면 7442가 나옴
남은 k가 2 이므로 스택의 뒤에서 부터 2를 pop()해준다. answer -> 74
'''
def solution(number, k):
answer = ''
stack = []
for idx, num in enumerate(number):
while stack and k > 0:
if stack[-1] < num:
stack.pop()
k -= 1
else:
break
stack.append(num)
while k > 0:
stack.pop()
k -= 1
return "".join(stack) | true |
7194af83c2d5be323ed8efc55b50be39feaa77e7 | Python | TimWeaving/z-quantum-core | /tests/zquantum/core/interfaces/ansatz_utils_test.py | UTF-8 | 3,574 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | """Test cases for ansatz-related utilities."""
import unittest
from unittest import mock
import numpy as np
import numpy.testing
from zquantum.core.interfaces.ansatz_utils import (
DynamicProperty,
ansatz_property,
combine_ansatz_params,
invalidates_parametrized_circuit,
)
class PseudoAnsatz:
n_layers = ansatz_property(name="n_layers")
def __init__(self, n_layers):
self.n_layers = n_layers
self._parametrized_circuit = None
@property
def parametrized_circuit(self):
if self._parametrized_circuit is None:
self._parametrized_circuit = f"Circuit with {self.n_layers} layers"
return self._parametrized_circuit
@invalidates_parametrized_circuit
def rotate(self):
"""Mock method that "alters" some characteristics of ansatz.
Using this method should invalidate parametrized circuit.
"""
class DynamicPropertyTests(unittest.TestCase):
def test_uses_default_value_if_not_overwritten(self):
class MyCls:
x = DynamicProperty(name="x", default_value=-15)
obj = MyCls()
self.assertEqual(obj.x, -15)
def test_can_be_set_in_init(self):
class MyCls:
length = DynamicProperty(name="length")
def __init__(self, length):
self.length = length
obj = MyCls(0.5)
self.assertEqual(obj.length, 0.5)
def test_values_are_instance_dependent(self):
class MyCls:
height = DynamicProperty(name="height")
obj1 = MyCls()
obj2 = MyCls()
obj1.height = 15
obj2.height = 30
self.assertEqual(obj1.height, 15)
self.assertEqual(obj2.height, 30)
class TestAnsatzProperty(unittest.TestCase):
"""Note that we don't really need an ansatz intance, we only need to check that
_parametrized_circuit is set to None.
"""
def test_setter_resets_parametrized_circuit(self):
ansatz = PseudoAnsatz(n_layers=10)
# Trigger initial computation of parametrized circuit
self.assertEqual(ansatz.parametrized_circuit, "Circuit with 10 layers")
# Change n_layers -> check if it recalculated.
ansatz.n_layers = 20
self.assertIsNone(ansatz._parametrized_circuit)
self.assertEqual(ansatz.parametrized_circuit, "Circuit with 20 layers")
class InvalidatesParametrizedCircuitTest(unittest.TestCase):
def test_resets_parametrized_circuit(self):
ansatz = PseudoAnsatz(n_layers=10)
# Trigger initial computation of parametrized circuit
self.assertEqual(ansatz.parametrized_circuit, "Circuit with 10 layers")
# Trigger circuit invalidation
ansatz.rotate()
self.assertIsNone(ansatz._parametrized_circuit)
def test_forwards_arguments_to_underlying_methods(self):
method_mock = mock.Mock()
decorated_method = invalidates_parametrized_circuit(method_mock)
ansatz = PseudoAnsatz(n_layers=10)
# Mock calling a regular method. Notice that we need to pass self explicitly
decorated_method(ansatz, 2.0, 1.0, x=100, label="test")
# Check that arguments were passed to underlying method
method_mock.assert_called_once_with(ansatz, 2.0, 1.0, x=100, label="test")
def test_combine_ansatz_params():
params1 = np.array([1.0, 2.0])
params2 = np.array([3.0, 4.0])
target_params = np.array([1.0, 2.0, 3.0, 4.0])
combined_params = combine_ansatz_params(params1, params2)
np.testing.assert_array_equal(combined_params, target_params)
| true |
2926d26198262b6bfbf8dfa00c6ff726133c0940 | Python | cnangel/hyperdex | /test/python/testlib.py | UTF-8 | 984 | 3.578125 | 4 | [
"BSD-3-Clause"
] | permissive | def assertEqualsApprox(actual, expected, tolerance):
# Recurse over all subdocuments
if isinstance(actual, dict) and isinstance(expected, dict):
for k,v in actual.iteritems():
assert k in expected
assertEqualsApprox(v, expected[k], tolerance)
elif isinstance(actual, float) and isinstance(expected, float):
if not (abs(actual - expected) < tolerance):
print "AssertEqualsApprox failed"
print "Should be: " + str(expected) + ", but was " + str(actual) + "."
assert False
else:
raise ValueError('Invalid Type(s) in AssertEqualsApprox')
def assertEquals(actual, expected):
if not actual == expected:
print "AssertEquals failed"
print "Should be: " + str(expected) + ", but was " + str(actual) + "."
assert False
def assertTrue(val):
if not val:
print "AssertTrue failed"
assert False
def assertFalse(val):
if val:
print "AssertFalse failed"
assert False
| true |
f211e387afb4744426b783bedefe81b75e19d259 | Python | adamorhenner/Fundamentos-programacao | /exercicios/exercicio-7.py | UTF-8 | 234 | 3.75 | 4 | [] | no_license | print("====Calculo do resto da divisao====")
primeiro = (int)(input("informe o primeiro numero: "))
segundo = (int)(input("informe o segundo numero: "))
print("o resto da divisao de", primeiro, "por", segundo, "eh", primeiro%segundo ) | true |
280770daba19b8fcf4e43a9a2df481616d869967 | Python | maryszmary/xml4webcorpora | /bookxml2xml_for_corp.py | UTF-8 | 9,740 | 2.78125 | 3 | [] | no_license | # coding: utf-8
import os
import re
import lxml.etree
import time
import xml.sax.saxutils
rxWords = re.compile('^([^\\w0-9’ʼ]*)(.+?)([^\\w0-9’́̀ʼ]*)$')
def process_alignment(lines):
lines = re.sub(' *\t *— *([\t\n])', ' —\\1', lines)
lines = [l for l in lines.split('\n') if len(l) > 2]
if len(lines) % 2 != 0:
print('********\nOdd number of lines in the alignment:', lines)
return ''
result = ''
sourceLines = lines[::2]
glossLines = lines[1::2]
for i in range(len(sourceLines)):
wordsSource = [w.strip() for w in sourceLines[i].split('\t')
if len(w.strip()) > 0]
wordsGloss = [w.strip() for w in glossLines[i].split('\t')
if len(w.strip()) > 0]
if len(wordsGloss) != len(wordsSource):
print('********\nBroken alignment.\nSource: ' + sourceLines[i] +
'\nGloss: ' + glossLines[i])
continue
for j in range(len(wordsSource)):
m = rxWords.search(wordsSource[j])
if m is None:
print('********\nWrong word: ' + wordsSource[j])
continue
if len(m.group(1)) > 0:
result += '<word><item type="punct" lang="source-lang">' +\
m.group(1) + '</item></word>\n'
result += '<word><item type="txt" lang="source-lang">' +\
m.group(2) + '</item><item type="gls" lang="ru">' +\
wordsGloss[j] + '</item></word>\n'
if len(m.group(3)) > 0:
result += '<word><item type="punct" lang="source-lang">' +\
m.group(3) + '</item></word>\n'
return result
def convert2xml(text):
result = '<interlinear-text>\n'
meta, start_of_text = get_meta(text)
title = meta.split('\t')[0]
result += '<item type="title" lang="en">' + title + '</item>\n'
result += '<paragraphs>\n<paragraph>\n<phrases>\n'
body = get_text(text, start_of_text)
print('1:\n' +meta)
if body is not None:
for sentence in body:
sentNo, lines, trans, footnotes = sentence[0], sentence[1], sentence[2], sentence[3]
result += '<word><words>\n'
result += process_alignment(lines)
result += '</words>\n'
result += '<item type="segnum" lang="en">' + sentNo.strip() + '</item>\n'
result += '<item type="gls" lang="en">' + xml.sax.saxutils.escape(trans.strip()) + '</item>\n'
for fn in footnotes:
result += '<item type="note" lang="en">' + xml.sax.saxutils.escape(fn.strip()) + '</item>\n'
result += '</word>\n'
result += '</phrases>\n</paragraph>\n</paragraphs>\n</interlinear-text>'
return result, meta
print('body is none')
def get_text(text, start):
'''получает экземпляры узлов с отдельными текстами, возвращает список кортежей с глоссами и переводом'''
paragraphs = text.xpath('para')[start:]
gloss_lines, smthn_weird = get_sentences([el for el in paragraphs if el.text is not None and '\t' in el.text])
translations, comments = get_sentences([el for el in paragraphs if el.text is not None and '\t' not in el.text])
gl = convert_to_strings(footnote_dealer(gloss_lines))
tr = convert_to_strings(footnote_dealer(translations))
if len(gl) != len(tr):
pass
for a in set([el[0] for el in gl]).difference(set([el[0] for el in tr])):
print(a)
else:
return [[tr[i][0], gl[i][1], tr[i][1], tr[i][2] + gl[i][2]] for i in range(len(gl))]
def translations_spliter(paragraphs):
'''получает 3-х-мерный массив из convert_to_strings с текстами предложений,
возвращает такое же, но с правильно разделёнными предложениями, правильно сопоставленными им сносками
и отделёнными номерами'''
translations = []
for group in paragraphs:
# '(\\([0-9]+[аб]?\\)|[IXV]+\\.)(.+?)(?=\n[IXV]+\\.|\\([0-9]+[аб]?\\)|$)'
# есть ли у нас римскиие цифры и боимся ли мы I.sg
cur_translations = re.findall('([0-9]+[аб]?\\.)(.+?)(?=\n[0-9]+[аб]?\\.|$)',
group[0], flags = re.DOTALL)
translations += [[el[0], el[1], []] for el in cur_translations]
if group[1] != []:
for footnote in group[1]:
for sent in range(len(translations)):
if '[[[footnote-mark]]]' in translations[sent][1]:
translations[sent][2].append(footnote)
translations[sent][1] = translations[sent][1][:translations[sent][1].index('[[[')] +\
translations[sent][1][translations[sent][1].index('[[[') + 19:]
break
return translations
def convert_to_strings(sentences, split_sentences = False):
'''получает 3-х-мерный массив из footnote_dealer с объектами тегов, возвращает такой же массив,
но с текстами предложений, причём предложения разделены правильно'''
text_sentences = [['\n'.join([line.text for line in group[0]]),
[line.text for line in group[1]]] for group in sentences]
text_sentences = translations_spliter(text_sentences)
return text_sentences
def footnote_dealer(sentences):
'''получает список тегов с предложениями, возвращает массив массивов, в каждом из которых два элемента:
массив с тегами предложений и массив с тегами сносок'''
new_sentences = []
for i in range(len(sentences)):
new_sentences.append([sentences[i], []])
for line in sentences[i]:
for fn in line.xpath('footnote/para'):
fn.text = re.split('[\s\t]', line.text)[-1] + ': ' + fn.text # эта строка значит, что в каждой сноске пишется предыдущее слово
new_sentences[-1][1] += [fn]
fn.getparent().getparent().text += '[[[footnote-mark]]]'
if fn.getparent().tail:
fn.getparent().getparent().text += fn.getparent().tail
# for arr in new_sentences:
# for sent in arr[0]:
# print(sent.text)
# for sent in arr[1]:
# print('FOOTNOTES: \n' + sent.text)
return new_sentences
def get_sentences(paragraphs):
'''получает список со всеми тегами, не относящимися к заглавию текста, возвращает
массив массивов, каждый из которых прядставляет из себя предложение, где каждый элемент массива -- тег с одной строкой'''
sentences, comments = [], []
for el in paragraphs:
if el.text[0] in '(IXV0123456789':
sentences.append([el])
else:
try:
sentences[len(sentences) - 1] += [el]
except IndexError:
comments.append([el])
# for el in sentences:
# print('\nnumber of lines: ' + str(len(el)))
# for i in el:
# print(i.text)
# time.sleep(20)
return sentences, comments
def get_meta(text):
'''получает экземпляры узлов с отдельными текстами, возвращает метаданные и элемент, с которого начинается текст'''
meta = [text.xpath('title')[0].text]
info = text.xpath('para')[:6]
for el in range(len(info)):
if info[el].text is None:
start_of_text = el + 1
break
else:
meta.append(info[el].text)
meta = '\t'.join(meta)
return meta, start_of_text
def process_file(fname):
print('\n\n=================\nStarting ' + fname + '...')
fIn = open(fname, 'r', encoding='utf-8-sig')
file_text = fIn.read().replace('¬', '')
fIn.close()
texts = lxml.etree.fromstring(file_text).xpath('sect1')
print('number of texts: ' + str(len(texts)))
xmlTexts = [convert2xml(t) for t in texts if len(t) > 20]
xmlOutput = '\n'.join(t[0] for t in xmlTexts)
csvOutput = '\n'.join(str(i + 1) + '\t' + xmlTexts[i][1]
for i in range(len(xmlTexts)))
fnameXml = fname + '-out.xml'
fXml = open(fnameXml, 'w', encoding='utf-8-sig')
fXml.write('<?xml version="1.0" encoding="utf-8"?>\n'
'<document xsi:noNamespaceSchemaLocation="file:FlexInterlinear.xsd" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n')
fXml.write(xmlOutput)
fXml.write('\n</document>')
fXml.close()
fnameCsv = fname + '-meta.csv'
fCsv = open(fnameCsv, 'w', encoding='utf-8-sig')
fCsv.write(csvOutput)
fCsv.close()
def process_dir(dirname):
for fname in os.listdir(dirname):
if not fname.lower().endswith('.xml') or fname.lower().endswith('-out.xml'):
continue
process_file(fname)
if __name__ == '__main__':
process_dir('.')
| true |
bf6536c4d32523cec19f3b5398613608b4cbcde4 | Python | NyWeb/PICOPTER | /sensors/pwm.py | UTF-8 | 1,895 | 2.609375 | 3 | [] | no_license | import threading
import smbus
import random
import time
class pwm(threading.Thread):
bus = False
address = False
k = 2
m = 294
error = False
def __init__(self, address=0x40):
threading.Thread.__init__(self)
self.daemon = True
self.bus = smbus.SMBus(1)
self.address = address
try:
self.bus.write_byte_data(self.address, 0x01, 0x04)
mode1 = self.bus.read_byte_data(self.address, 0x00)
mode1 = mode1 & ~0x10
self.bus.write_byte_data(self.address, 0x00, mode1)
oldmode = self.bus.read_byte_data(self.address, 0x00)
newmode = (oldmode & 0x7F) | 0x10
self.bus.write_byte_data(self.address, 0x00, newmode)
self.bus.write_byte_data(self.address, 0xFE, 100)
self.bus.write_byte_data(self.address, 0x00, oldmode)
self.bus.write_byte_data(self.address, 0x00, oldmode | 0x80)
#Reset motors
self.set(0, 0)
self.set(1, 0)
self.set(2, 0)
self.set(3, 0)
self.set(4, 0)
except IOError:
self.error = "ioerror initialize"
return
def run(self):
return False
def read(self):
return False
def set(self, motor, input, calculate = True):
if calculate:
input = int(((input)*self.k)+self.m)
try:
self.bus.write_byte_data(self.address, 0x06+4*motor, 0 & 0xFF)
self.bus.write_byte_data(self.address, 0x07+4*motor, 0 >> 8)
self.bus.write_byte_data(self.address, 0x08+4*motor, input & 0xFF)
self.bus.write_byte_data(self.address, 0x09+4*motor, input >> 8)
except IOError:
self.error = "ioerror"
def cancel(self, motors):
for motor in motors:
self.set(motors[motor], 0, False) | true |
b38ad2bd5f52876832e0d13ec8a9b30ef1fb51cf | Python | matthewrmettler/project-euler | /Problems 1 through 50/problem37_truncatable_primes.py | UTF-8 | 1,165 | 4.09375 | 4 | [] | no_license | '''
Author: Matthew Mettler
Project Euler, Problem 37
https://projecteuler.net/problem=37
The number 3797 has an interesting property. Being prime itself, it is possible
to continuously remove digits from left to right, and remain prime at each
stage: 3797, 797, 97, and 7.
Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to
right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
Status: Correct
'''
from math import sqrt
def is_prime(num):
if num == 1: return False
if num == 2: return True
if num % 2 == 0: return False
for i in range(2, int(sqrt(num))+1):
if num % i == 0: return False
return True
def truncatable(num):
if not is_prime(num): return False
num = str(num)
for i in range(len(num)):
if not is_prime(int(num[i:])): return False
if not is_prime(int(num[:i+1])): return False
return True
def main():
nums = []
for i in range(11,1000000,2):
if truncatable(i):
nums.append(i)
print(sum(nums))
if __name__ == "__main__":
main() | true |
98b19e6001120f617616171d853254e19e9ada45 | Python | akash682/Natural-Language-Processing_UDEMY | /Lesson30/Lesson30.py | UTF-8 | 544 | 3 | 3 | [] | no_license | # Tokenize : Split by " ", "."
# Stemming : Stemming is process of reducing infected or derived words to their word stem, base or root form" - Wikipedia
# intelligence, intelligent, inteligently
# intelligen
# going, goes, gone
# go
# Produced intermediate representation of the word may not have any meaning.
# Takes less time
# Meaning not important: Spam detection
# Lemmatization
# intelligence, intelligent, intelligently
# intelligent
# Has meaning
# Takes more time
# Meaning inportant: question answering application | true |
5ae8abf3d661cd9b4bb94652e76206be380d59b1 | Python | a3r0d7n4m1k/YACS | /courses/templatetags/course_tags.py | UTF-8 | 3,398 | 2.703125 | 3 | [
"MIT"
] | permissive | from django import template
from courses.utils import DAYS, ObjectJSONEncoder
from courses.encoder import default_encoder
register = template.Library()
def remove_zero_prefix(timestr):
if timestr[0] == '0':
return timestr[1:]
return timestr
@register.filter
def bold_topics_include(string):
return string.replace('Topics include', '<strong>Topics include</strong>')
@register.filter
def requires_truncation(string, summary_size):
tstr = string.lower().strip()
return len(tstr[:summary_size].strip()) != len(tstr.strip())
@register.filter
def reverse_truncatechars(string, start):
"""Inverse of truncate chars. Instead of the first x characters,
excludes the first nth characters.
"""
return string[start:]
@register.filter
def toJSON(obj):
return ObjectJSONEncoder().encode(default_encoder.encode(obj))
@register.filter
def get(obj, key):
if obj:
try:
return getattr(obj, key)
except (AttributeError, TypeError):
pass
try:
return obj[key]
except (KeyError, IndexError):
pass
return None
@register.filter
def display_period(period):
fmt = "%s-%s"
start_format, end_format = "%I", "%I"
if period.start.minute != 0:
start_format += ':%M'
if period.end.minute != 0:
end_format += ':%M'
end_format += " %p"
return fmt % (
remove_zero_prefix(period.start.strftime(start_format)).lower(),
remove_zero_prefix(period.end.strftime(end_format)).lower(),
)
@register.filter
def sort(iterable):
return sorted(iterable)
@register.filter
def dow_short(dow):
if isinstance(dow, list) or isinstance(dow, tuple):
return tuple(map(dow_short, dow))
return {
'Monday': 'Mon',
'Tuesday': 'Tue',
'Wednesday': 'Wed',
'Thursday': 'Thu',
'Friday': 'Fri',
'Saturday': 'Sat',
'Sunday': 'Sun',
}.get(dow)
@register.filter
def period_dow_buckets(periods):
"""Prepares periods by day of the week.
"""
slots = {}
for period in periods:
for dow in period.days_of_week:
slots.setdefault(dow, []).append(period)
return slots
@register.filter
def period_type_buckets(periods):
"""Converts periods into buckets of days of the week.
The periods in each bucket is sorted by start time.
"""
slots = {}
for period in periods:
dows = tuple(period.days_of_week)
slots[dows[0]] = slots.get(dows[0], {})
slots[dows[0]][dows] = slots[dows[0]].get(dows, []) + [period]
for slot in slots.values():
for periods in slot.values():
periods.sort(key=lambda p: p.start)
return slots
@register.filter
def sections_for(sections, course):
return [s for s in sections if s.course_id == course.id]
@register.filter
def sum_credits(courses):
min_creds = max_creds = 0
for course in courses:
min_creds += course.min_credits
max_creds += course.max_credits
if min_creds == max_creds:
return "%d credit%s" % (min_creds, '' if min_creds == 1 else 's')
return "%d - %d credits" % (min_creds, max_creds)
@register.filter
def seats_left(sections):
return sum(s.seats_left for s in sections)
@register.filter
def join(collection, sep=', '):
return unicode(sep).join(map(unicode, collection))
| true |
9dd8bb183b9af5af9abdcc8b060854fbc3c08b53 | Python | JannaKim/PS | /ExhaustiveSearch/2422_한윤정.py | UTF-8 | 429 | 2.953125 | 3 | [] | no_license | n, m= map(int, input().split())
nots={}
for _ in range(m):
a,b= map(int,input().split())
if b<a:
a,b= b,a
nots[(a,b)]=True
ans=0
for i in range(1,n-1):
for j in range(i+1,n):
for k in range(j+1, n+1):
if (i,j) in nots:
continue
if (j,k) in nots:
continue
if (i,k) in nots:
continue
ans+=1
print(ans) | true |
1f67c72218127129fce6ca17b4ac993b2b35fc7c | Python | werthergit/MyPyMLRoad | /6-news.py | UTF-8 | 2,261 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 09:22:03 2018
@author: zhengyuv
"""
from keras.datasets import reuters
import numpy as np
from keras import models
from keras import layers
import matplotlib.pyplot as plt
from keras import metrics
#read dataset
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(path=r'D:\datasets\reuters.npz', num_words=10000)
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1
return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = vectorize_sequences(train_labels, dimension=46)
y_test = vectorize_sequences(test_labels, dimension=46)
#model definition
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10000, )))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(46, activation='softmax'))
#model compile
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
#split data
x_val = x_train[:1000]
x_train = x_train[1000:]
y_val = y_train[:1000]
y_train = y_train[1000:]
#fit model
history = model.fit(x_train,
y_train,
epochs=20,
batch_size=512,
validation_data=(x_val,y_val))
#plot
loss = history.history['loss']
val_loss = history.history['val_loss']
acc = history.history['acc']
val_acc = history.history['val_acc']
epochs = range(1, len(loss)+1)
plt.plot(epochs, loss, 'bo', label='training loss')
plt.plot(epochs, val_loss, 'r', label='validation loss')
plt.title('training and validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.show()
plt.clf()
plt.plot(epochs, acc, 'bo', label='training acc')
plt.plot(epochs, val_acc, 'r', label='validation acc')
plt.title('training and validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()
#test
score = model.evaluate(x_test, y_test)
print("测试集损失为:", score[0])
print("测试集准确率为:",score[1]) | true |
37859ad59ea89b4ed0c968ff0f4fbcd936fc6308 | Python | yichi-yang/QRantine-backend | /community/management/commands/updatecvdb.py | UTF-8 | 1,661 | 2.515625 | 3 | [] | no_license | from django.core.management.base import BaseCommand, CommandError
from community.models import Community
from bs4 import BeautifulSoup
import urllib.request
import re
url = "http://publichealth.lacounty.gov/media/Coronavirus/locations.htm"
class Command(BaseCommand):
help = 'Update LA Covid-19 database'
def handle(self, *args, **options):
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
city = (soup.select(
'html > body > div#content > div.content-padding > table.table.table-striped.table-bordered.table-sm > tbody >tr > th'))
number = (soup.select(
'html > body > div#content > div.content-padding > table.table.table-striped.table-bordered.table-sm > tbody >tr > td'))
num_lst = []
city_lst = []
res = {}
for city, number in zip(city, number):
city_name = city.get_text()
num_str = number.get_text()
# print("{}:\t{}".format(city_name, num_str))
if not ("City of" in city_name or "Los Angeles - " in city_name or "Unincorporated - " in city_name):
continue
num = None
try:
num = int(num_str)
except ValueError as e:
continue
parts = city_name.split(" - ")
if len(parts) > 1:
city_name = parts[1]
c, created = Community.objects.get_or_create(
name=city_name, defaults={"cases": num})
if not created:
c.cases = num
c.save()
print("{}:\t{}".format(city_name, num))
| true |
93f06f9ada346e390044c0f7622c2c4a4ab0ee3b | Python | brainysmurf/pydir | /pydir/Select.py | UTF-8 | 4,676 | 3.078125 | 3 | [] | no_license | """
Select Module
Subclasses main Dir class so that it presents user a list of choices,
selection.
"""
from dir.Dir import Dir
from dir.Filer import File_list, File_object
from dir.Menu import Menu, BadArguments
from dir.Console import Output
from dir.Command import Shell_Emulator as Shell
from colorama import Fore, Back, Style
import os
class SelectList(File_list):
def __init__(self, _list):
File_list.__init__(self, "", [item for item in _list if item], klass=SelectObject)
class SelectObject(File_object):
def __init__(self, path, name, i):
"""
Detect whether name has a path built-in or not,
if so it sets path accordingly
"""
_extra = None
if isinstance(name, list):
_extra = name[1:]
name = name[0]
p, n = os.path.split(name)
if p:
File_object.__init__(self, p, n, i)
else:
File_object.__init__(self, path, name, i)
self._extra = _extra
class SelectMenu(Menu):
def tutorial(self, *args):
pass
def name(self, *args):
if not args or not args[0]:
raise BadArguments("name what?")
else:
input(self.cntrl.get_item(args[0]).full_path)
if self.cntrl.pages:
return self.cntrl.pages['page']
else:
return None
class SelectDir(Dir):
def __init__(self, _list, header=None):
"""
Override completely is easier
"""
self.ask_pound()
self.header=header
self.reset_pages()
self.user_sorter = 'name'
self.menu = SelectMenu(self)
self.command = Shell(avoid_recursion="projects")
self.last_mod_time = None
self.output = Output()
self.initialize()
self._list = SelectList(_list)
def ask_pound(self):
self.ask = '-> '
def initialize(self):
self._selection = None
def list_current_directory(self):
return self._list
def pre_process(self, file_name):
return True
def print_header(self):
print(Fore.BLACK + Back.WHITE + " {} ".format(self.header) + Style.RESET_ALL)
def post_process(self, file_name, num, max_length):
return (num, file_name)
def parse_input(self, user_input):
# TODO: I shouldn't need to call this, find out what is throwing off the indexing
self.list_current_directory().do_indexing()
this = None
if user_input.isdigit() and not user_input.startswith('name '):
# "make it so" feature: user types in number and we figure out if it's a cd or an open statement
which = int(user_input)
if which < len(self.list_current_directory()):
this = self.list_current_directory().index(which)
try:
handled = self.menu._parse(user_input)
except BadArguments:
handled = False
input("Bad arguments")
if not handled:
if user_input == self.quit_request:
self.stop()
elif user_input.startswith('+'):
if self.pages:
return self.pages['page'] + user_input.count('+')
else:
input("No page to turn")
elif user_input.startswith('-'):
if self.pages:
return self.pages['page'] - user_input.count('-')
else:
input("No page to turn")
if this:
self.got_good_input(self.derive_selectable_from_this(this))
self.stop()
def derive_selectable_from_this(self, _this):
"""
You can override me
"""
raise NotImplemented
def got_good_input(self, _input):
"""
Sets _selection
"""
self._selection = _input
def execute(self):
"""
"""
self.clear_screen()
# Send control to list current directory, or the currage page, if available
if not self.pages:
self.list_items()
else:
self.list_current_page()
page = self.parse_input(input(self.ask))
# Clean up pages state as appropriate
if page is None:
# If parse_input returns None (page 0 is legitimate number)
self.reset_pages()
else:
self.turn_page(page)
def stop(self):
Dir.stop(self)
return self._selection
def select(self, using):
self.derive_selectable_from_this = using
return self.start().stop()
| true |
924f5b36aadc0cfccb1c4c3ae146bbaa7984731d | Python | Python3pkg/pyduino-mk | /python/pyduino_mk/arduino.py | UTF-8 | 7,972 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# Copyright (c) 2015 Nelson Tran
#
# 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 .constants import *
import serial.tools.list_ports
import threading
import tkinter
import serial
import struct
import glob
import time
import sys
class Arduino(object):
def __init__(self, port=None, baudrate=115200):
"""
Args:
port (str, optional): Device name or port number number or None.
baudrate (str, optional): Baud rate such as 9600 or 115200 etc.
Raises:
SerialException: In the case the device cannot be found.
Note:
You should not have to specify any arguments when instantiating
this class. The default parameters should work out of the box.
However, if the constructor is unable to automatically identify
the Arduino device, a port name should be explicitly specified.
If you specify a baud rate other than the default 115200 baud, you
must modify the arduino sketch to match the specified baud rate.
"""
if port is None:
port = self.__detect_port()
self.serial = serial.Serial(port, baudrate)
if not self.serial.isOpen():
raise serial.SerialException('Arduino device not found.')
# used to get mouse position and screen dimensions
self.__tk = tkinter.Tk()
# this flag denoting whether a command is has been completed
# all module calls are blocking until the Arduino command is complete
self.__command_complete = threading.Event()
# read and parse bytes from the serial buffer
serial_reader = threading.Thread(target=self.__read_buffer)
serial_reader.daemon = True
serial_reader.start()
def press(self, button=MOUSE_LEFT):
if button in MOUSE_BUTTONS:
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_PRESS)
self.__write_byte(button)
elif isinstance(button, int):
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_PRESS)
self.__write_byte(button)
elif isinstance(button, str) and len(button) == 1:
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_PRESS)
self.__write_byte(ord(button))
else:
raise ValueError('Not a valid mouse or keyboard button.')
self.__command_complete.wait()
def release(self, button=MOUSE_LEFT):
if button in MOUSE_BUTTONS:
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_RELEASE)
self.__write_byte(button)
elif isinstance(button, int):
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_RELEASE)
self.__write_byte(button)
elif isinstance(button, str) and len(button) == 1:
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_RELEASE)
self.__write_byte(ord(button))
else:
raise ValueError('Not a valid mouse or keyboard button.')
self.__command_complete.wait()
def release_all(self):
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_RELEASE_ALL)
self.__command_complete.wait()
def write(self, keys, endl=False):
if isinstance(keys, int):
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_WRITE)
self.__write_byte(keys)
elif isinstance(keys, str) and len(keys) == 1:
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_WRITE)
self.__write_byte(ord(keys))
elif isinstance(keys, str):
if not endl:
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_PRINT)
self.__write_str(keys)
else:
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_PRINTLN)
self.__write_str(keys)
else:
raise ValueError('Not a valid keyboard keystroke. ' +
'Must be type `int` or `char` or `str`.')
self.__command_complete.wait()
def type(self, message, wpm=80, mistakes=True, accuracy=96):
if not isinstance(message, str):
raise ValueError('Invalid keyboard message. ' +
'Must be type `str`.')
if not isinstance(wpm, int) and wpm < 1 or wpm > 255:
raise ValueError('Invalid value for `WPM`. ' +
'Must be type `int`: 1 <= WPM <= 255.')
if not isinstance(mistakes, bool):
raise ValueError('Invalid value for `mistakes`. ' +
'Must be type `bool`.')
if not isinstance(accuracy, int) and accuracy < 1 or accuracy > 100:
raise ValueError('Invalid value for `accuracy`. ' +
'Must be type `int`: 1 <= accuracy <= 100.')
self.__write_byte(KEYBOARD_CMD)
self.__write_byte(KEYBOARD_TYPE)
self.__write_str(message)
self.__write_byte(wpm)
self.__write_byte(mistakes)
self.__write_byte(accuracy)
self.__command_complete.wait()
def click(self, button=MOUSE_LEFT):
if button not in MOUSE_BUTTONS:
raise ValueError('Not a valid mouse button.')
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_CLICK)
self.__write_byte(button)
self.__command_complete.wait()
def fast_click(self, button):
if button not in MOUSE_BUTTONS:
raise ValueError('Not a valid mouse button.')
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_FAST_CLICK)
self.__write_byte(button)
self.__command_complete.wait()
def move(self, dest_x, dest_y):
if not isinstance(dest_x, (int, float)) and \
not isinstance(dest_y, (int, float)):
raise ValueError('Invalid mouse coordinates. ' +
'Must be type `int` or `float`.')
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_MOVE)
self.__write_short(dest_x)
self.__write_short(dest_y)
self.__command_complete.wait()
def bezier_move(self, dest_x, dest_y):
if not isinstance(dest_x, (int, float)) and \
not isinstance(dest_y, (int, float)):
raise ValueError('Invalid mouse coordinates. ' +
'Must be `int` or `float`.')
self.__write_byte(MOUSE_CMD)
self.__write_byte(MOUSE_BEZIER)
self.__write_short(dest_x)
self.__write_short(dest_y)
self.__command_complete.wait()
def close(self):
self.serial.close()
return True
def __detect_port(self):
ports = serial.tools.list_ports.comports()
arduino_port = None
for port in ports:
if 'Arduino' in port[1]:
arduino_port = port[0]
return arduino_port
def __read_buffer(self):
while True:
byte = ord(self.serial.read())
if byte == MOUSE_CALIBRATE:
self.__calibrate_mouse()
elif byte == SCREEN_CALIBRATE:
self.__calibrate_screen()
elif byte == COMMAND_COMPLETE:
self.__command_complete.set()
self.__command_complete.clear()
def __calibrate_screen(self):
width = self.__tk.winfo_screenwidth()
height = self.__tk.winfo_screenheight()
self.__write_short(width)
self.__write_short(height)
def __calibrate_mouse(self):
x, y = self.__tk.winfo_pointerxy()
self.__write_short(x)
self.__write_short(y)
def __write_str(self, string):
for char in string:
self.__write_byte(ord(char))
self.__write_byte(0x00)
def __write_byte(self, byte):
struct_pack = struct.pack('<B', byte)
self.serial.write(struct_pack)
def __write_short(self, short):
struct_pack = struct.pack('<H', int(short))
self.serial.write(struct_pack)
| true |
1ab2e16c6af4798a7a14b388d5d55b9de08c5969 | Python | ashray-00/Convolution-Model-Step-by-Step | /distribute_value.py | UTF-8 | 644 | 3.59375 | 4 | [] | no_license | import numpy as np
def distribute_value(dz, shape):
"""
Distributes the input value in the matrix of dimension shape
Arguments:
dz -- input scalar
shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz
Returns:
a -- Array of size (n_H, n_W) for which we distributed the value of dz
"""
# Retrieve dimensions from shape
(n_H, n_W) = shape
# Compute the value to distribute on the matrix
average = dz/(n_H * n_W)
# Create a matrix where every entry is the "average" value
a = np.full((n_H,n_W),average)
return a | true |
7fb4c089f02f5d7dc234cd4b063821824e09e0b8 | Python | qulu622/DTW | /dtw_thre.py | UTF-8 | 5,673 | 3.328125 | 3 | [] | no_license | # DTW_THRE
import numpy as np # matrix
import pandas as pd # dataframe
import math # inf
import time # time
import os # listdir
def dtw_thre(ts1, ts2, minimum_distance): # DTW with threshold
cell = 0
ts1_len = len(ts1) - 1
ts2_len = len(ts2) - 1
dtw_thre_matrix = np.zeros([ts1_len + 1, ts2_len + 1])
for i in range(1, ts1_len + 1):
dtw_thre_matrix[i][0] = math.inf
for j in range(1, ts2_len + 1):
dtw_thre_matrix[0][j] = math.inf
for i in range(1, ts1_len + 1):
row_minimum_cell = math.inf
for j in range(1, ts2_len + 1):
cell += 1
dist = abs(ts1[i] - ts2[j])
dtw_thre_matrix[i][j] = dist + min(dtw_thre_matrix[i - 1][j], dtw_thre_matrix[i][j - 1],
dtw_thre_matrix[i - 1][j - 1])
if dtw_thre_matrix[i][j] < row_minimum_cell:
row_minimum_cell = dtw_thre_matrix[i][j]
if row_minimum_cell > minimum_distance:
return math.inf, cell
return dtw_thre_matrix[ts1_len][ts2_len], cell
def main():
print('DTW_THRE')
cur_dir = 'other'
dtw_thre_data = pd.DataFrame(columns=['NAME', 'TIME', 'CELL', 'ACCURACY'])
dtw_thre_data.to_csv('dtw_thre_' + cur_dir + '.csv', index=0)
for file in os.listdir(cur_dir + '/1/'):
print('Dataset {} begins.'.format(file))
test_file = cur_dir + '/1/' + file + '/' + file + '_TEST.tsv'
train_file = cur_dir + '/1/' + file + '/' + file + '_TRAIN.tsv'
test_df = pd.read_csv(test_file, header=None, sep='\t')
train_df = pd.read_csv(train_file, header=None, sep='\t')
dtw_thre_total_time = 0
dtw_thre_total_cell = 0
dtw_thre_matched = 0
dtw_thre_unmatched = 0
for test_index, test_series in test_df.iterrows():
minimum_distance = math.inf
test_class = test_series.iat[0]
for train_index, train_series in train_df.iterrows():
dtw_thre_start = time.time()
dtw_thre_distance, dtw_thre_cell = dtw_thre(test_series.to_list(), train_series.to_list(),
minimum_distance)
dtw_thre_end = time.time()
dtw_thre_time = dtw_thre_end - dtw_thre_start
dtw_thre_total_time += dtw_thre_time
dtw_thre_total_cell += dtw_thre_cell
if dtw_thre_distance < minimum_distance:
minimum_distance = dtw_thre_distance
train_class = train_series.iat[0]
# print(minimum_distance)
if test_class == train_class:
dtw_thre_matched += 1
else:
dtw_thre_unmatched += 1
# print(dtw_thre_total_time)
# print(dtw_thre_total_cell)
dtw_thre_data = dtw_thre_data.append({'NAME': file, 'TIME': str(dtw_thre_total_time), 'CELL': str(dtw_thre_total_cell),
'ACCURACY': str(dtw_thre_matched / (dtw_thre_matched + dtw_thre_unmatched))}, ignore_index=True)
print(dtw_thre_data)
dtw_thre_data.to_csv('dtw_thre_' + cur_dir + '.csv', mode='a', header=0, index=0)
dtw_thre_data.drop(index=0, inplace=True)
for file in os.listdir(cur_dir + '/10/'):
print('Dataset {} begins.'.format(file))
for i in range(1, 11):
test_file = cur_dir + '/10/' + file + '/' + file + '_TEST' + str(i) + '.tsv'
train_file = cur_dir + '/10/' + file + '/' + file + '_TRAIN' + str(i) + '.tsv'
test_df = pd.read_csv(test_file, header=None, sep='\t')
train_df = pd.read_csv(train_file, header=None, sep='\t')
dtw_thre_total_time = 0
dtw_thre_total_cell = 0
dtw_thre_matched = 0
dtw_thre_unmatched = 0
for test_index, test_series in test_df.iterrows():
minimum_distance = math.inf
test_class = test_series.iat[0]
for train_index, train_series in train_df.iterrows():
dtw_thre_start = time.time()
dtw_thre_distance, dtw_thre_cell = dtw_thre(test_series.to_list(), train_series.to_list(),
minimum_distance)
dtw_thre_end = time.time()
dtw_thre_time = dtw_thre_end - dtw_thre_start
dtw_thre_total_time += dtw_thre_time
dtw_thre_total_cell += dtw_thre_cell
if dtw_thre_distance < minimum_distance:
minimum_distance = dtw_thre_distance
train_class = train_series.iat[0]
# print(minimum_distance)
if test_class == train_class:
dtw_thre_matched += 1
else:
dtw_thre_unmatched += 1
# print(dtw_thre_total_time)
# print(dtw_thre_total_cell)
dtw_thre_data = dtw_thre_data.append({'NAME': file, 'TIME': str(dtw_thre_total_time), 'CELL': str(dtw_thre_total_cell),
'ACCURACY': str(dtw_thre_matched / (dtw_thre_matched + dtw_thre_unmatched))},
ignore_index=True)
print(dtw_thre_data)
dtw_thre_data.to_csv('dtw_thre_' + cur_dir + '.csv', mode='a', header=0, index=0)
dtw_thre_data.drop(index=0, inplace=True)
if __name__ == "__main__":
main()
| true |