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
09cc7ceb217f14538db204560cbe039839aa967a
Python
enkiprobo/tugasAIAgkt2015
/Tugas 1/Pengumpulan/1301154553 RANESTARI SASTRIANI/SA/tubesSA.py
UTF-8
786
3.5625
4
[]
no_license
import random # definisi fungsi def fungsi(a, b): return ((4 - (2.1 * (a ** 2)) + ((a ** 4) / 3)) * (a ** 2)) + (a * b) + ((-4 + (4 * (b ** 2))) * (b ** 2)) def probabilitas(a, b, c): return 2.71828183 ** ((a-b)/c) # deklarasi variabel temp = 10000 alpha = 0.999 r = random.uniform(0,1) x1 = random.uniform(-10, 10) x2 = random.uniform(-10, 10) bestsofar = fungsi(x1, x2) #algoritma SA while (temp > 0.00001): for x in range(30): x1 = random.uniform(-10, 10) x2 = random.uniform(-10, 10) newstate = fungsi(x1, x2) if (newstate>bestsofar): if (probabilitas(bestsofar, newstate, temp) > r): bestsofar = newstate else: bestsofar = newstate temp=alpha*temp print(bestsofar)
true
e01e3a527e9e42b65cd0be5f1d8a3106a7f19f9b
Python
po3rin/python_playground
/practical-recommender-systems/util/metric_calculator.py
UTF-8
2,211
3.015625
3
[]
no_license
import numpy as np from sklearn.metrics import mean_squared_error from util.models import Metrics from typing import Dict, List class MetricCalculator: def calc( self, true_rating: List[float], pred_rating: List[float], true_user2items: Dict[int, List[int]], pred_user2items: Dict[int, List[int]], k: int, ) -> Metrics: rmse = self._calc_rmse(true_rating, pred_rating) precision_at_k = self._calc_precision_at_k(true_user2items, pred_user2items, k) recall_at_k = self._calc_recall_at_k(true_user2items, pred_user2items, k) return Metrics(rmse, precision_at_k, recall_at_k) def _precision_at_k(self, true_items: List[int], pred_items: List[int], k: int) -> float: if k == 0: return 0.0 p_at_k = (len(set(true_items) & set(pred_items[:k]))) / k return p_at_k def _recall_at_k(self, true_items: List[int], pred_items: List[int], k: int) -> float: if len(true_items) == 0 or k == 0: return 0.0 r_at_k = (len(set(true_items) & set(pred_items[:k]))) / len(true_items) return r_at_k def _calc_rmse(self, true_rating: List[float], pred_rating: List[float]) -> float: return np.sqrt(mean_squared_error(true_rating, pred_rating)) def _calc_recall_at_k( self, true_user2items: Dict[int, List[int]], pred_user2items: Dict[int, List[int]], k: int ) -> float: scores = [] # テストデータに存在する各ユーザーのrecall@kを計算 for user_id in true_user2items.keys(): r_at_k = self._recall_at_k(true_user2items[user_id], pred_user2items[user_id], k) scores.append(r_at_k) return np.mean(scores) def _calc_precision_at_k( self, true_user2items: Dict[int, List[int]], pred_user2items: Dict[int, List[int]], k: int ) -> float: scores = [] # テストデータに存在する各ユーザーのprecision@kを計算 for user_id in true_user2items.keys(): p_at_k = self._precision_at_k(true_user2items[user_id], pred_user2items[user_id], k) scores.append(p_at_k) return np.mean(scores)
true
9d9710be397361882655aa60786092b0d7602173
Python
sguttikon/sim-environment
/src/old_code_feb_12/pf_net/display.py
UTF-8
4,140
2.984375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python3 import cv2 import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.patches import Wedge class Render(object): def __init__(self, fig_shape=(7, 7)): self.fig = plt.figure(figsize=fig_shape) self.plt_ax = self.fig.add_subplot(111) plt.ion() plt.show() self.plots = { 'map': None, 'gt_robot': { 'pose': None, 'heading': None, }, 'est_robot': { 'pose': None, 'heading': None, 'particles': None, }, } def update_figures(self, data): gt_pose = data['gt_pose'] est_pose = data['est_pose'] particle_states = data['particle_states'] particle_weights = data['particle_weights'] self.plot_gt_robot(gt_pose, 'green') self.plot_est_robot(est_pose, 'blue') self.plot_particles(particle_states, particle_weights, 'coral') self.plt_ax.legend([self.plots['gt_robot']['pose'], self.plots['est_robot']['pose']], \ ["gt_robot", "est_robot"]) plt.draw() plt.pause(0.00000000001) def plot_map(self, floor_map, floor_map_res): rows, cols = floor_map.shape self.map_res = floor_map_res self.map_rows = rows extent = [-cols/2, cols/2, -rows/2, rows/2] map_plt = self.plots['map'] if map_plt is None: # floor_map = cv2.flip(floor_map, 0) map_plt = self.plt_ax.imshow(floor_map, origin='upper', extent=extent) self.plt_ax.grid() self.plt_ax.set_xlabel('x coords') self.plt_ax.set_ylabel('y coords') else: pass self.plots['map'] = map_plt def plot_gt_robot(self, gt_pose, clr): pose_plt = self.plots['gt_robot']['pose'] heading_plt = self.plots['gt_robot']['heading'] pose_plt, heading_plt = self.plot_robot(gt_pose, pose_plt, heading_plt, clr) self.plots['gt_robot']['pose'] = pose_plt self.plots['gt_robot']['heading'] = heading_plt def plot_est_robot(self, est_pose, clr): pose_plt = self.plots['est_robot']['pose'] heading_plt = self.plots['est_robot']['heading'] pose_plt, heading_plt = self.plot_robot(est_pose, pose_plt, heading_plt, clr) self.plots['est_robot']['pose'] = pose_plt self.plots['est_robot']['heading'] = heading_plt def plot_robot(self, robot_pose, pose_plt, heading_plt, clr): x, y, theta = robot_pose x = x * self.map_rows * self.map_res y = y * self.map_rows * self.map_res radius = 0.1 * self.map_rows * self.map_res length = 0.1 * self.map_rows * self.map_res xdata = [x, x + (radius + length) * np.cos(theta)] ydata = [y, y + (radius + length) * np.sin(theta)] if pose_plt is None: pose_plt = Wedge((x, y), radius, 0, 360, color=clr, alpha=.75) self.plt_ax.add_artist(pose_plt) heading_plt, = self.plt_ax.plot(xdata, ydata, color=clr, alpha=.75) else: pose_plt.update({ 'center': [x, y], }) heading_plt.update({ 'xdata': xdata, 'ydata': ydata, }) return pose_plt, heading_plt def plot_particles(self, particles, particle_weights, clr): if particle_weights is None: colors = clr else: colors = cm.rainbow(particle_weights) positions = particles[:, 0:2] * self.map_rows * self.map_res particles_plt = self.plots['est_robot']['particles'] if particles_plt is None: particles_plt = plt.scatter(positions[:, 0], positions[:, 1], s=10, c=colors, alpha=.5) else: particles_plt.set_offsets(positions[:, 0:2]) particles_plt.set_color(colors) self.plots['est_robot']['particles'] = particles_plt def __del__(self): # to prevent plot from automatic closing plt.ioff() plt.show()
true
7877ca63ef935218c5b23d0e40accdf9e47263b6
Python
Harshsa28/algs
/merge_sort.py
UTF-8
787
3.703125
4
[]
no_license
import math #for floor def merge_sort(lst): if len(lst) < 2: #if len is 1, return the list return lst mid = math.floor(len(lst)/2) lst1 = merge_sort(lst[0:mid]) #simple divide n conquer lst2 = merge_sort(lst[mid:len(lst)]) #simple divide n conquer return merge(lst1, lst2) #merge the 2 smaller sorted lists def merge(lst1 , lst2): len1 = len(lst1) len2 = len(lst2) lst3 = [] i = 0 j = 0 while (True): if lst1[i] <= lst2[j]: lst3.append(lst1[i]) i += 1 else: lst3.append(lst2[j]) j += 1 if i == len1 or j == len2: break if i == len1: while j != len2: lst3.append(lst2[j]) j += 1 if j == len2: while i != len1: lst3.append(lst1[i]) i += 1 return lst3 lst = [2,4,1,4,6,2,5,7,8] #lst = [2,5,7,8] print(merge_sort(lst))
true
64bcacb358f43ff39b5f2ec8d1633538e6e46146
Python
hmcka/1511
/shape-calculations/circle.py
UTF-8
611
4.5
4
[]
no_license
#This program provides functions that allow you to find the area and circumference of a circle. #programmed by Hethur Aluma | 2/19/20 import math def calc_circle_area(): """Calculates the area of a circle""" radius = float(input("What is the radius of your circle? ")) circle_area = math.pi * radius print("The area of the circle is:", circle_area) def calc_circle_circum(): """Calculates the circumference of a circle.""" radius = float(input("What is the radius of your circle? ")) circle_circum = 2 * math.pi * radius print("The circumference of the circle is:", circle_circum)
true
0787f62c2d4309448dc5b50cec0773417245a0fa
Python
michaelprummer/datascience
/clustering/data_preprocessing/remove_duplicates_cluster.py
UTF-8
1,441
2.703125
3
[]
no_license
import codecs, os if __name__ == '__main__': input_path = "data/" output_path = "out/" files_in_folder = os.listdir(input_path + "/") if not os.path.exists(input_path): os.makedirs(input_path) if not os.path.exists(output_path): os.makedirs(output_path) print("{0} Files found in {1}.".format(len(files_in_folder), input_path)) for file in files_in_folder: out = codecs.open(output_path + file, "w", "utf-8") file = codecs.open(input_path + file, encoding='utf-8') fileList = [] fileNDF = [] fileLDA = [] fileKM = [] # out outFile = [] for i, line in enumerate(file, 0): fileList.append(line) values = line.split("\t") if values[1] != "-1": fileNDF.append(values) elif values[2] != "-1": fileLDA.append(values) elif values[3] != "-1": fileKM.append(values) else: print("fail") fileList = sorted(fileList, key=lambda x: x[0]) fileNDF = sorted(fileNDF, key=lambda x: x[0]) fileLDA = sorted(fileLDA, key=lambda x: x[0]) fileKM = sorted(fileKM, key=lambda x: x[0]) for k, lineA in enumerate(fileNDF, 0): lineA[2] = fileLDA[k][2] lineA[3] = fileKM[k][3] out.write("\t".join(lineA)) exit("EZ")
true
2a6b70c3b1b05ea59843406bbb96ef4c3ae9c1cd
Python
adobrich/Pongy
/pongy/pongy.py
UTF-8
5,666
2.796875
3
[]
no_license
#!/usr/bin/env python import pyglet from enum import Enum import entity class Game(pyglet.window.Window): """Initialise and run the Pongy game.""" def __init__(self, *args, **kwargs): super(Game, self).__init__(*args, **kwargs) self.table = entity.Table(self.width, self.height) self.ball = entity.Ball(self.width / 2, self.height / 2, 8, 8) self.score_one = entity.Score(self.width * 0.25, self.height) self.score_two = entity.Score(self.width * 0.75, self.height) self.game_over() def game_over(self): """End game, and bounce the ball around the screen while waiting for players to start a new game.""" self.game_in_progress = False self.table.set_demo_mode() self.ball.reset(self.width / 2, self.height / 2) def new_game(self): """Reset score, player/ball positions and start a new game.""" self.game_in_progress = True self.table.set_game_mode() self.score_one.reset() self.score_two.reset() self.ball.reset(self.width / 2, self.height / 2) self.paddle_one = entity.Paddle(self.table.gutter_width, self.height / 2, 8, 50) self.paddle_two = entity.Paddle(self.width - self.table.gutter_width, self.height / 2, 8, 50) def update(self, dt): """Update game objects and check for collisions.""" self.ball.move(dt) # Check for ball / paddle collision if self.game_in_progress: # Check win condition if self.score_one.score == 11 or self.score_two.score == 11: self.game_over() # Check lose condition if self.has_collided(self.ball, self.table.right): self.score_one.increment() self.ball.reset(self.width / 2, self.height / 2) elif self.has_collided(self.ball, self.table.left): self.score_two.increment() self.ball.reset(self.width / 2, self.height / 2) # Update paddles self.paddle_one.update(dt) self.paddle_two.update(dt) if (self.has_collided(self.paddle_one, self.ball) or self.has_collided(self.paddle_two, self.ball)): self.ball.paddle_bounce() if self.has_collided(self.paddle_one, self.table.top): self.paddle_one.stop() self.paddle_one.max_y(self.height) elif self.has_collided(self.paddle_one, self.table.bottom): self.paddle_one.stop() self.paddle_one.min_y() if self.has_collided(self.paddle_two, self.table.top): self.paddle_two.stop() self.paddle_two.max_y(self.height) elif self.has_collided(self.paddle_two, self.table.bottom): self.paddle_two.stop() self.paddle_two.min_y() # Bounce of top and bottom of screen if (self.has_collided(self.ball, self.table.top) or self.has_collided(self.ball, self.table.bottom)): self.ball.wall_bounce('y') # Bounce ball of left and right walls if game is not in progress if not self.game_in_progress: if (self.has_collided(self.ball, self.table.left) or self.has_collided(self.ball, self.table.right)): self.ball.wall_bounce('x') def on_key_press(self, symbol, modifiers): """Keyboard event handler for key press.""" if symbol == pyglet.window.key.ESCAPE: exit(0) elif symbol == pyglet.window.key.SPACE: if not self.game_in_progress: self.new_game() if self.game_in_progress: if symbol == pyglet.window.key.A: self.paddle_one.move_up() elif symbol == pyglet.window.key.Z: self.paddle_one.move_down() elif symbol == pyglet.window.key.UP: self.paddle_two.move_up() elif symbol == pyglet.window.key.DOWN: self.paddle_two.move_down() def on_key_release(self, symbol, modifiers): """Keyboard event handler for key release.""" if self.game_in_progress: if symbol == pyglet.window.key.A: self.paddle_one.stop() elif symbol == pyglet.window.key.Z: self.paddle_one.stop() elif symbol == pyglet.window.key.UP: self.paddle_two.stop() elif symbol == pyglet.window.key.DOWN: self.paddle_two.stop() def on_draw(self): """Render game objects.""" self.clear() self.table.draw() self.score_one.draw() self.score_two.draw() self.ball.draw() # Only draw paddles if game is in progress if self.game_in_progress: self.paddle_one.draw() self.paddle_two.draw() def has_collided(self, one, two): """Check for collision between two objects using AABB method.""" self.x_collision = (one.x + one.half_width >= two.x - two.half_width and two.x + two.half_width >= one.x - one.half_width) self.y_collision = (one.y + one.half_height >= two.y - two.half_height and two.y + two.half_height >= one.y - one.half_height) return self.x_collision and self.y_collision if __name__ == '__main__': game = Game(caption='Pongy', width=800, height=500, fullscreen=False) pyglet.clock.schedule_interval(game.update, 1.0 / 60.0) pyglet.app.run()
true
1ce41e4a6c7dc41c38e652e0230b0f7cb86dfe61
Python
cherylchoon/DojoAssignments
/pycode/Python_Fundamentals/new.py
UTF-8
100
2.9375
3
[]
no_license
my_name = "Cheryl" print my_name my_name = "Choon" print my_name print 5+5 print my_name + str(5+5)
true
2856c182b426aae39b4f79765910183e48768d0f
Python
abhaysinh/Data-Camp
/Data Science for Everyone Track/19-Introduction to Shell/05- Creating new tools/03-How can I save commands to re-run later.py
UTF-8
1,132
3.71875
4
[]
no_license
''' How can I save commands to re-run later? You have been using the shell interactively so far. But since the commands you type in are just text, you can store them in files for the shell to run over and over again. To start exploring this powerful capability, put the following command in a file called headers.sh: head -n 1 seasonal/*.csv This command selects the first row from each of the CSV files in the seasonal directory. Once you have created this file, you can run it by typing: bash headers.sh This tells the shell (which is just a program called bash) to run the commands contained in the file headers.sh, which produces the same output as running the commands directly. Instructions 100 XP 1 Use nano dates.sh to create a file called dates.sh that contains this command: cut -d , -f 1 seasonal/*.csv to extract the first column from all of the CSV files in seasonal. Solution : # This solution uses `cp` instead of `nano` # because our automated tests can't edit files interactively. cp /solutions/dates.sh ~ 2 Use bash to run the file dates.sh. Solution: bash dates.sh '''
true
88175b290d15104f587489c27774cffb2894b278
Python
biswaspiyalCSERUET/ML_Pattern
/Perceptron/MultiClass-KERSEL/kesler.py
UTF-8
3,820
2.5625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 18 12:56:26 2018 @author: yeaseen """ import numpy as np def split(s, delim=[" ", '\n']): words = [] word = [] for c in s: if c not in delim: word.append(c) else: if word: words.append(''.join(word)) word = [] if word: words.append(''.join(word)) return words def loadfile(filename,checkTrain): file = open(filename, "r") first = checkTrain rows = list() for line in file: if(first) == True: dims = split(line) first = False else: vals = split(line, [' ' ,'\t', '\n']) #print(vals) rows.append(vals) if(checkTrain): return dims, rows else: return rows dims, rows = loadfile('Train.txt',True) test = loadfile('Test.txt',False) dims=np.array(dims) dims = dims.astype(np.float) rows=np.array(rows) mat = rows.astype(np.float) test=np.array(test) test= test.astype(np.float) #print(test) #print(dims) #print(mat) ''' matrix=[[11.0306 , 9.0152 , 8.0199 , 7.62 , 1], [11.4008 , 8.7768 , 6.7652 , 8.9 , 1], [14.6263 , 1.8092 , 10.7134 , 6.7 , 2], [15.4467 , 1.2589 , 12.6625 , 8.2 , 2], [1.3346 , 5.8191 , 2.0320 , 7.5 , 3], [0.7506 , 5.6132 , 0.9061 , 7.7 , 3] ] matrixOutput=[11.0306 , 9.0152 , 8.0199 , 7.62 ] ''' #matrixOutput=matrixOutput+ [1] att=int(dims[0]) #print(att) clss=int(dims[1]) #print(clss) finalMat=np.empty((0,(att+1)*clss)) w =np.random.random_sample(((att+1)*clss,)) #print(w) matrix=np.array(mat) Y=matrix[:,-1].copy() Y=np.array(Y) Y=Y.astype(np.int) Y=np.array(Y).tolist() #print([Y]) matrix[:,-1]=np.ones((matrix.shape[0])) targetOutput=test[:,-1].copy() targetOutput=np.array(targetOutput) targetOutput=targetOutput.astype(np.int) targetOutput=np.array(targetOutput).tolist() test[:,-1] = np.ones((test.shape[0])) #print(test) #print(matrix) count=0 for i in matrix: #print(i) a=np.zeros(((att+1)*clss)) #print(Y[count]) #print(count) classVal=int(Y[count]) #print(classVal) a[(classVal-1)*(att+1) : classVal*(att+1)]=i #print([a]) for j in range(clss): if( (j+1) != classVal): x=a.copy() x[j*(att+1) : (j+1)*(att+1)] = -i finalMat = np.vstack([finalMat, x]) #print(x) count+=1 #print(finalMat) counter=0 maxCounter=finalMat.shape[0] constantTerm= 0.5 discriminant= True while(discriminant): for i in finalMat: product=np.dot(i,w) counter+=1 if(product < 0): w=w+(i*constantTerm) #print(w) counter = 0 #print(product) if(counter == maxCounter): discriminant = False #print(w) predictedOutput=[] for eachrow in test: val=0 classed=0 for k in range(clss): a=np.zeros(((att+1)*clss)) a[k*(att+1) : (k+1)*(att+1)] = eachrow got=np.dot(a,w) if(val<got): val=got classed=k+1 predictedOutput.append(classed) #print(classed) #print(predictedOutput) from sklearn.metrics import classification_report target_names = [] for i in range(clss): target_names.append('class'+str(i)) print(classification_report(targetOutput, predictedOutput, target_names=target_names)) from sklearn.metrics import accuracy_score print("Accuracy is: "+str(accuracy_score(targetOutput, predictedOutput))) ''' print(matrixOutput) matrixOutput = np.array(matrixOutput) for k in range(clss): a=np.zeros(((att+1)*clss)) a[k*(att+1) : (k+1)*(att+1)] = matrixOutput #print(a) print(np.dot(a,w)) '''
true
855feacb21f328da839cd9cb16357de024774b35
Python
BadoinoMatteo/ES_PYTHON_quarta
/PHYTON/thread/es4.py
UTF-8
1,057
2.796875
3
[]
no_license
import threading import logging import random totalebiglietti=100 def cassa(tID): s1.acquire() print("cassa 1") numeroBiglietti=[0,1,2,3,4,5,6,7,8,9,10] biglietti=(int)(random.choice(numeroBiglietti)) global totalebiglietti print(totalebiglietti) if totalebiglietti==0: #biglietti esauriti print("biglietti esauriti") elif totalebiglietti>0 and biglietti<=totalebiglietti: print(f"biglietti acquistati {biglietti}" ) totalebiglietti=totalebiglietti-biglietti elif 0 < totalebiglietti < biglietti: print(f"biglietti acquistati {totalebiglietti}") totalebiglietti=0 s1.release() if __name__ == '__main__': format = "%(asctime)s: %(message)s" logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S") t = [] s1 = threading.Lock() for i in range(10): t.append(threading.Thread(target=cassa, args=(int(i+1), ))) t[i].start() for i,t in enumerate(t): t.join()
true
b0294ac9e94ca69d1c7fe79be9695f18bab82de4
Python
joshbenner/mudsling
/src/mudsling/utils/locks.py
UTF-8
4,637
3.265625
3
[]
no_license
""" Implements a generic pyparsing lock parser grammar. Syntax for a lock: [NOT] func1(args) [AND|OR] [NOT] func2() [...] Lock syntax involves functions, operators, and parentheses. * Functions take the form of: <funcName>([<arg1>[, ...]]) * Binary (two-side) operators: and, or * Unary (one-side) operators: not * Parentheses can be used to logically group operations. Examples: foo() foo() and bar(1) (foo() and bar(1)) or baz(a, b) Syntax based on Evennia's lock system. """ from pyparsing import Suppress, Literal, CaselessLiteral, Word, Group,\ ZeroOrMore, alphanums, alphas, delimitedList, operatorPrecedence, opAssoc # Can be imported from this module by other modules, do not remove. from pyparsing import ParseException from mudsling.storage import PersistentSlots # Alias symbols to their built-in functions. Used in LockParser(). opMap = { '!': 'not', '&': 'and', '|': 'or' } class LockFunc(PersistentSlots): """ Generic form of a lock function. A child class using the specified function map will be dynamically created when a new L{LockParser} is created. """ __slots__ = ('fname', 'args') def eval(self, *args): """ Evaluate the lock and return the result. The position args will be passed to the lock function (and on to any functions it contains) at the front of parameter list. @param args: Position arguments to prepend to argument lists. @type args: C{tuple} @return: The result of evaluating the LockFunc. @rtype: bool """ return False # Mimics class naming since it is essentially a dynamic class instantiation. def LockParser(funcMap): """ Generate a lock parsing expression tree. @param funcMap: Dictionary of in-script function names to their Python functions. @rtype funcMap: C{dict} @return: An expression tree which can be evaluated. @rtype: L{pyparsing.ParserElement} """ funcs = { 'not': lambda _, __, x: not x, 'or': lambda _, __, l, r: l or r, 'and': lambda _, __, l, r: l and r } funcs.update(funcMap) class _lockFunc(LockFunc): def __init__(self, tok): self.fname, self.args = tok if self.fname in opMap: self.fname = opMap[self.fname] def __repr__(self): return '%s(%s)' % (self.fname, str(self.args)[1:-1]) def eval(self, *args): if self.fname in funcs: myArgs = list(args) for a in self.args: if isinstance(a, _lockFunc): myArgs.append(a.eval(*args)) else: myArgs.append(a) return funcs[self.fname](*myArgs) else: raise NameError("Invalid lock function: %s" % self.fname) def unary_op(tok): op, rhs = tok[0] return _lockFunc((op, [rhs])) def binary_op(tok): lhs, op, rhs = tok[0] return _lockFunc((op, [lhs, rhs])) opAnd = CaselessLiteral('and') | Literal('&') opOr = CaselessLiteral('or') | Literal('|') opNot = CaselessLiteral('not') | Literal('!') arg = Word(alphanums + r' #$%&*+-./:<=>?@[\]^_`{|}~') args = Group(ZeroOrMore(delimitedList(arg))) fname = Word(alphas, alphanums + '_') func = fname + Suppress('(') + args + Suppress(')') func.setParseAction(_lockFunc) # noinspection PyUnresolvedReferences expr = operatorPrecedence( func, [ (opNot, 1, opAssoc.RIGHT, unary_op), (opOr, 2, opAssoc.LEFT, binary_op), (opAnd, 2, opAssoc.LEFT, binary_op), ] ) return expr if __name__ == '__main__': import time test = [ 'very_strong()', 'id(42)', 'not dead()', 'id(42) and not dead()', 'has_perm(use things) or is_superuser()', 'invalid_func()' ] funcMap = { 'very_strong': lambda: True, 'id': lambda id: int(id) == 42, 'dead': lambda: False, 'has_perm': lambda p: p in ['do stuff'], 'is_superuser': lambda: True, } _grammar = LockParser(funcMap) for t in test: print t start = time.clock() try: r = _grammar.parseString(t)[0] except ParseException as e: r = e duration = time.clock() - start print "parsed: ", r print "time: ", duration * 1000 try: v = r.eval() except Exception as e: v = repr(e) print ' val = ', v, '\n'
true
ae1f58e7fc6b4f507ae4b3fdd10c63f23f0968ec
Python
FanciestW/AdventOfCode2020
/Day_11/main.py
UTF-8
3,238
3.234375
3
[]
no_license
import os from typing import List, Tuple import itertools import copy import numpy as np def read_file(file_name: str) -> List[List[str]]: try: data = list() read_file = open(file_name, 'r') while True: line = read_file.readline().strip() if not line: break data.append(list(line)) return data except Exception as e: print(str(e)) return [] def pretty_print(data: list): for row in data: if type(row[0]) is str: print(''.join(row)) else: print(row) def part_1(data: List[List[str]]) -> int: seating = data did_change = True while did_change: seating, did_change = seat_move(seating) return [c for row in seating for c in row].count('#') def seat_move(data: List[List[str]]) -> Tuple[List[List[str]], bool]: new_seat_map = copy.deepcopy(data) did_not_change = True for i, row in enumerate(data): for j, c in enumerate(row): if c not in ['L', '#']: new_seat_map[i][j] = '.' continue row_i = [i + n for n in range (-1, 2) if i + n >= 0 and i + n < len(data)] col_i = [j + n for n in range (-1, 2) if j + n >= 0 and j + n < len(row)] coord = [(x, y) for x, y in list(itertools.product(row_i, col_i)) if not (x == i and y == j)] neighbors_count = [data[x][y] for x, y in coord].count('#') if neighbors_count >= 4: new_seat_map[i][j] = 'L' elif neighbors_count == 0 and c == 'L': new_seat_map[i][j] = '#' else: new_seat_map[i][j] = c if data[i][j] != new_seat_map[i][j]: did_not_change &= False return new_seat_map, not did_not_change def seat_move_v2(data: np.ndarray) -> Tuple[np.ndarray, bool]: new_seat_map = np.copy(data) did_not_change = True for x, row in enumerate(data): for y, c in enumerate(row): if c not in ['L', '#']: new_seat_map[x][y] = '.' continue top = data[:x, y] bottom = data[x+1:, y] left = data[x, :y] right = data[x, y+1:] top_left_diag = np.diagonal(data[:x,:y], offset=1 if y % 2 == 1 else 0) top_right_diag = np.diagonal(np.fliplr(data[:x,y+1:]), offset=1 if (len(row) - y - 1) % 2 == 1 else 0) bottom_left_diag = np.diagonal(np.flipud(data[x+1:,:y])) bottom_right_diag = np.diagonal(data[x+1:,y+1:]) if (x > 3 and y > 3): print(data[:x,y+1:]) print(top_left_diag) print(top_right_diag) print(bottom_left_diag) print(bottom_right_diag) continue def part_2(data: List[List[int]]): seating = np.array(data) did_change = True while did_change: seating, did_change = seat_move_v2(seating) return [c for row in seating for c in row].count('#') if __name__ == '__main__': data = read_file(os.path.join(os.path.dirname(__file__), 'test_input.txt')) # print(part_1(data)) # > 2270 part_2(data)
true
40773a05b155e7507118b5d0d55989d93227666b
Python
WEICHENGIT/Sentiment-Analysis-PRIM
/sentiment_discovery/model/serialize.py
UTF-8
1,047
2.828125
3
[]
no_license
import torch def save(model, savepath, save_dict=None, keep_vars=True): """save model weights and other metadata""" if save_dict is not None: #if save_dict is provided save that instead of model state_dict torch.save(state_dict_cpu_copy(save_dict), savepath) else: torch.save(state_dict_cpu_copy(model.state_dict(keep_vars=keep_vars)), savepath) def state_dict_cpu_copy(chkpt): """save cpu copy of model state, so it can be reloaded by any device""" #if chkpt has things other than state_dict get the state_dict if 'state_dict' in chkpt: state_dict = chkpt['state_dict'] else: state_dict = chkpt for n, p in state_dict.items(): state_dict[n] = p.cpu() return chkpt def restore(model, load_path): """restore saved model and handle dictionary format and application/removal of weight norm""" chkpt = torch.load(load_path) #check if checkpoints has only save_dict or more information if 'state_dict' in chkpt: state_dict = chkpt['state_dict'] else: state_dict = chkpt model.load_state_dict(state_dict) return chkpt
true
eb27fe649c41c39f52e7614d3ea31e8d738e330e
Python
wavefly1972/Python-learning
/SVM_SklearnExample.py
UTF-8
467
3.171875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 09:57:15 2017 @author: 100419 """ from sklearn import svm x=[[2,0],[1,1],[2,3]] y=[0,0,1] #Class label clf=svm.SVC(kernel='linear') #分类器 clf.fit(x,y) #带入预测值 print(clf) ##get support vectors print(clf.support_vectors_) #a=clf.support_vectors_ #print(a) #get indices of support vectors print(clf.support_) #get number of support vectors for each class print(clf.n_support_)
true
f7ef29e5032183a0b62d3b6d2695f970dceeab21
Python
jayelm/nldissect-fork
/script/save_cub_np.py
UTF-8
1,525
2.921875
3
[]
no_license
""" For each class, load images and save as numpy arrays. """ import numpy as np import os from PIL import Image from tqdm import tqdm import multiprocessing as mp def npify(args): img_dir, bird_class = args bird_imgs_np = {} class_dir = os.path.join(img_dir, bird_class) bird_imgs = sorted([x for x in os.listdir(class_dir) if x != "img.npz"]) for bird_img in bird_imgs: bird_img_fname = os.path.join(class_dir, bird_img) img = Image.open(bird_img_fname).convert("RGB") img_np = np.asarray(img) bird_imgs_np[os.path.join(bird_class, bird_img)] = img_np np_fname = os.path.join(class_dir, "img.npz") np.savez_compressed(np_fname, **bird_imgs_np) if __name__ == "__main__": from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser( description="Save numpy", formatter_class=ArgumentDefaultsHelpFormatter ) parser.add_argument( "--cub_dir", default="dataset/CUB_200_2011", help="Directory to load/cache" ) parser.add_argument( "--workers", default=4, type=int, help="Number of multiprocessing workers" ) args = parser.parse_args() img_dir = os.path.join(args.cub_dir, "images") bird_classes = os.listdir(img_dir) mp_args = [(img_dir, bc) for bc in bird_classes] with mp.Pool(args.workers) as pool: with tqdm(total=len(mp_args), desc="Classes") as pbar: for _ in pool.imap_unordered(npify, mp_args): pbar.update()
true
da2d5a7182194073c902be437f049efa5e61004f
Python
calvin-and-smit/ds-interview-qs
/python/max_profit.py
UTF-8
933
4.3125
4
[]
no_license
''' Sell, sell, sell! Suppose we are given an array of n integers which represent the value of some stock over time. Assuming you are allowed to buy the stock exactly once and sell the stock once, what is the maximum profit you can make? Can you write an algorithm that takes in an array of values and returns the maximum profit? For example, if you are given the following array: [2, 7, 1, 8, 2, 8, 14, 25, 14, 0, 4, 5] The maximum profit you can make is 24 because you would buy the stock when its price is 1 and sell when it's 25. Note that we cannot make 25, because the stock is priced at 0 after it is priced at 25 (e.g you can't sell before you buy). ''' stock_values = [2, 7, 1, 8, 2, 8, 14, 25, 14, 0, 4, 5] profit = 0 days = len(stock_values) for i in range(0, days): for j in range(i+1, days): if stock_values[j] - stock_values[i] > profit: profit = stock_values[j] - stock_values[i] profit
true
97b182504612c03ba9efdb5666cee96e4e39b13a
Python
Coolbust/SidGotBots-TwitterApiTest
/WebScrapeExample2SCSBOA.py
UTF-8
1,470
2.625
3
[]
no_license
import requests import tweepy from bs4 import BeautifulSoup r= requests.get("https://www.scsboa.org/field-recaps/)") c = r.content parse = BeautifulSoup(c, "html.parser") x = 10 i = 0 while i < x: object = "table_55_row_" + str(i) id = "id" + str(i) pdfs = parse.find("tr",{"id":object}) if i == 0: aDict = {id: pdfs} else: aDict.update({id : pdfs}) i=i + 1 #print(pdfs) #print(object) #nPfds = str(pdfs) #print('\n') #print(aDict) addressString = aDict.__getitem__("id0") nAddressString = str(addressString) index = nAddressString.find('href') endIndex = nAddressString.find('.pdf"') #print(nAddressString) #print(type(nAddressString)) startPoint = index endPoint = endIndex finAddressString = '' finAddressString = (nAddressString[startPoint+6 : endPoint+4]) #print(startPoint) #print(endPoint) print(finAddressString) # Code to Authenticate to Twiiter auth = tweepy.OAuthHandler("Your Handler Key", "Your secret Key") auth.set_access_token("Access Token", "Secret Access Token") # Create API object api = tweepy.API(auth) # Create a tweet try: api.verify_credentials() print("Auth OK") except: print("Error during auth") try: api.update_status("Test Results: " + finAddressString) print("Update succesful") #print("test") #Print my followers # print(api.followers(api.me())) except: print("Update fail")
true
8e478bad7a9f62e7a2374582a83d9af9f6532722
Python
rook88/poincare
/walkthroughLabels.py
UTF-8
7,057
2.8125
3
[]
no_license
import numpy as np import cv2 import poincare import random import copy import imageio theta = 1.5 - np.sqrt(5) * 0.5 class gonClass(): def __init__(self, p, q, r, path): self.path = path label = "-".join([str(d) for d in reversed(path)]) self.label = label if label == "": self.gon = poincare.polygon(poincare.origin, verticeCount = p, radius = r) else: if label in gons: self.gon = copy.copy(gons[label]).gon else: gonIter = gonClass(p, q, r, path[1:]) self.gon = gonIter.gon.getMirror(int(path[0])) self.color = colorFromZ(self.gon.center.z, self.path) if path: d = path[0] else: d = 1 self.direction = np.imag(np.log(self.gon.center.z ** p)) # self.direction = np.imag(np.log(self.gon.center.z - np.exp(1j ** d) * 0.001)) # self.direction = np.imag(np.log(self.gon.center.z ** p * np.exp(np.pi * theta * 1j))) def __str__(self): ret = "Gon, label = {}, polygon = {}, direction = {}".format(self.label, self.gon, self.direction) return ret def getGon(p, q, r, label): if label == []: return poincare.polygon(poincare.origin, verticeCount = p, radius = r) else: iter = getGon(p, q, r, label[1:]) return iter.getMirror(int(label[0])) def colorFromLabel(label): hue = int(len(label) * theta * 180) % 180 return (hue, 255, 255) def colorFromPath2(path): hue = 0.0 delta = 1.0 / (p + 1) for direction in path: hue += direction * delta * 180 delta *= theta hue = int(hue) % 180 return (hue, 255, 255) def colorFromPath3(z, path, weightRaw): weight = np.sqrt(weightRaw) (hue1, saturation1, value1) = colorFromZ(z, path) value2 = 128 saturation = int(weight * saturation1) value = int(weight * value1 + (1 - weight) * value2) hue = hue1 return (hue, saturation, value) def colorFromPath2(z, path, weightRaw): weight = np.sqrt(weightRaw) (hue1, saturation1, value1) = colorFromZ(z, path) value2 = 1 + ((len(path) + 1) % 2) * 254 saturation = int(weight * saturation1) value = int(weight * value1 + (1 - weight) * value2) hue = hue1 return (hue, saturation, value) def colorFromPath(path): hue = 0.0 delta = 1.0 / p for direction in list(reversed(path)): hue += (direction - 2) * delta * 180 delta /= p hue = int(hue) % 180 if path: value = int(255 * (3.0 / (2.0 + len(path)))) saturation = 255 else: value = 255 saturation = 0 return (hue, saturation, value) def colorFromZ(z, path): hue = int(np.imag(np.log(z)) / np.pi * 90) % 180 # print z, hue if path: # value = int(255 * (3.0 / (2.0 + len(path)))) value = 255 saturation = 255 else: value = 255 saturation = 0 return (hue, saturation, value) centers = [] def isNewGon(gNew): if abs(gNew.gon.center.z) > 0.9999: return False for label in gons: if label <> gNew.label: gOld = gons[label] if abs(gNew.gon.center.z - gOld.gon.center.z) < 0.001: return False return True def iterLabels(n): generation = [gons[l] for l in gons if len(gons[l].path) == n] generation.sort(key = lambda x: x.direction) for zerolabel in zerolabels: for gOld in generation: if gOld.path: nextLabelItem = (zerolabel + gOld.path[-1] - 1) % p + 1 # nextLabelItem = zerolabel else: nextLabelItem = zerolabel newPath = gOld.path + [nextLabelItem] temp = gonClass(p, q, gonRadius, newPath) if isNewGon(temp): gons[temp.label] = temp def showImg(pImg, f = 1.0): img = getImg(pImg, f = f) cv2.imshow('myImg', img) cv2.imwrite("lastPolygon.jpg", img) cv2.waitKey(0) def getImg(pImg, color = "rgb", f = 1.0): multiplier = pImg.multiplier img = pImg.getImg(multiplier = multiplier) if color == "rgb": img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB) if color == "bgr": img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR) img[np.where((img == [0,0,0]).all(axis = 2))] = [255,255,255] img = cv2.blur(img, (4, 4)) img = cv2.resize(img, dsize = (800, 800)) return img def iterImg(multiplier = 1.0, reverse = False, radiusFactor = 1.0): radius = int(900 * radiusFactor) pImg = poincare.poincareImg(radius = radius, pointRadius = 5, size = [2000, 2000], backgroundIsWhite = True) pImg.multiplier = multiplier if reverse: tempTable = reversed(gonsTable) else: tempTable = gonsTable for gon in tempTable: gonNew = getGon(p, q, gonRadius / multiplier, gon.path) if multiplier < 1: w = 1.0 else: w = 1.0 / multiplier / multiplier color = colorFromPath3(gon.gon.center.z, gon.path, w) # print gon, gonNew, gon.color, color pImg.drawPolygon(gonNew, color = color, offset = multiplier) return pImg p = poincare.p q = poincare.q zerolabels = [i + 1 for i in range(p)] t1 = 1 - np.tan(np.pi / p) * np.tan(np.pi / q) t2 = 1 + np.tan(np.pi / p) * np.tan(np.pi / q) gonRadius = np.sqrt(t1 / t2) gonFundamental = poincare.polygon(poincare.origin, verticeCount = 5, radius = gonRadius) gons = {} gons[""] = gonClass(p, q, gonRadius, []) depth = poincare.depth for i in range(depth): iterLabels(i) print [label for label in gons] gonsTable = [gons[l] for l in gons] gonsTable.sort(key = lambda x: x.direction) print [g.label for g in gonsTable] ims = [] ims2 = [] frameCount = poincare.frameCount zoomFactor = poincare.zoom mpInit = 10.0 ** (1.0 / frameCount) ts = np.linspace(0.0, 1.0, frameCount) tsRaw = [(1.0 + n) / frameCount for n in range(frameCount)] ts = [t - t * np.exp(-t * 8) for t in tsRaw] print zip(ts, tsRaw) #exit(0) if poincare.multiplier: mps = [poincare.multiplier] zooms = [poincare.zoom] else: mps = [(1.0 / t) ** 0.6 for t in ts] zooms = [zoomFactor + (1 - zoomFactor) * t for t in ts] print mps print zooms #exit(0) frameN = 0 for mp, zoom in zip(mps, zooms): frameN += 1 print "frame {}".format(frameN) pImg = iterImg(mp, reverse = False, radiusFactor = zoom) pImg2 = iterImg(mp, reverse = True, radiusFactor = zoom) if poincare.testMode: # showImg(pImg, f = zoomFactor) showImg(pImg) showImg(pImg2) if poincare.outputFile: # ims.append(getImg(pImg, color = "bgr"), f = zoomFactor) ims.append(getImg(pImg, color = "bgr")) ims2.append(getImg(pImg2, color = "bgr")) if poincare.outputFile: ims += list(reversed(ims2)) if 'mp4' in poincare.outputFile: imageio.mimwrite(uri = poincare.outputFile, ims = ims, macro_block_size = None, fps = 24) else: imageio.mimwrite(uri = poincare.outputFile, ims = ims, fps = 24)
true
e9d20098c201eda09bf8530a9d486075e22dbb9e
Python
gadhiar/SmartMirror
/bin/hand_recognition.py
UTF-8
7,068
3.40625
3
[]
no_license
from tkinter import * from math import sqrt import cv2 import time from threading import * from datetime import datetime # ML Classifier to define hands hand_cascade = cv2.CascadeClassifier('insert path of Gest.xml here') # set array if tuples that hold x and y values of the location of the hand and time posx = [] posy = [] time_array = [] # rate at which to check if gesture is done refresh = 0 # how long btwn gestures determines if we're done swiping (ms) sleep = 1500 # 1.5 seconds # create variables to track which screen is currently open and which we are going to open prev_locationX = None prev_locationY = None screenX = 0 screenY = 0 # instantiate the roots of all windows for access to open later main_root = None right_root = None left_root = None top_root = None bot_root = None class perpetualTimer(): def __init__(self, t, hFunction): self.t = t self.hFunction = hFunction self.thread = Timer(self.t, self.handle_function) def handle_function(self): self.hFunction() self.thread = Timer(self.t, self.handle_function) self.thread.start() def start(self): self.thread.start() def cancel(self): self.thread.cancel() # returns the elapsed milliseconds def millis(past_time): dt = datetime.now() - past_time ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0 return ms def increment_rate(): global refresh if refresh >= 3: refresh = 0 refresh += 1 print(refresh) def standard_deviation(lst): """Calculates the standard deviation for a list of numbers.""" num_items = len(lst) mean = sum(lst) / num_items differences = [x - mean for x in lst] sq_differences = [d ** 2 for d in differences] ssd = sum(sq_differences) variance = ssd / num_items return sqrt(variance) def check_gesture(x, y, array_time, sleep1, refresh_rate): """ runs periodically, at time refresh_rate, to check the position arrays to see if a gesture was performed. """ # refresh is the rate at which we want to check it # sleep - time between gestures to determine if we stopped global main_root global prev_locationX global prev_locationY global screenX global screenY rate = refresh_rate locx = x locy = y time_array1 = array_time length = len(time_array1) sd_x = standard_deviation(x) sd_y = standard_deviation(y) rangex = locx[length - 1] - locx[0] rangey = locy[length - 1] - locy[0] prev_locationX = screenX prev_locationY = screenY """ STORE THE OLD VALUES OF X/Y AND CHECK FOR CHANGE, IF CHANGE THEN CREATE APPROPRIATE SCREEN """ # every 2 seconds, check the arrays if rate == 2: last_time = time_array1[length - 1] elapsed_time = millis(last_time) # if the time between the last gesture movement is too great, analyze the gesture b/c gesture is done if elapsed_time >= sleep1: # check if the y standard deviation is large, if not, it's horizontal movement if sd_y <= 80 <= sd_x: if rangex > 0: print("you're swiping right") if screenX < 1: screenX += 1 else: print("you're swiping left") if screenY > -1: screenX -= 1 else: if rangey > 0: print("you're swiping up") if screenY < 1: screenY += 1 else: print("you're swiping down") if screenY > -1: screenY -= 1 # changing to main FROM right if screenX == 0 and screenY == 0 and prev_locationX == 1 and prev_locationY == 0: main_root.deiconify() right_root.withdraw() # changing to main FROM left if screenX == 0 and screenY == 0 and prev_locationX == -1 and prev_locationY == 0: main_root.deiconify() left_root.withdraw() # changing to main FROM top if screenX == 0 and screenY == 0 and prev_locationX == 0 and prev_locationY == 1: main_root.deiconify() top_root.withdraw() # changing to main FROM bottom if screenX == 0 and screenY == 0 and prev_locationX == 0 and prev_locationY == -1: main_root.deiconify() bot_root.withdraw() # switching to right if screenX == 1 and screenY == 0: main_root.withdraw() right_root.deiconify() # switching to left if screenX == -1 and screenY == 0: main_root.withdraw() left_root.deiconify() # switching to top if screenX == 0 and screenY == 1: main_root.withdraw() top_root.deiconify() # switching to bot if screenX == 0 and screenY == -1: main_root.withdraw() bot_root.deiconify() posx.clear() posy.clear() time_array.clear() def motion(): global main_root cap = cv2.VideoCapture(0) while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) hands = hand_cascade.detectMultiScale(gray, 1.3, 5) # track right hand by using original image for (x, y, w, h) in hands: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) centerx = x + int(w / 2) centery = y + int(h / 2) current_millis = datetime.now() cv2.circle(img, (centerx, centery), int(h / 2), (0, 255, 0), 2) cv2.circle(img, (centerx, centery), 5, (0, 255, 0), -1) posx.append(centerx) posy.append(centery) time_array.append(current_millis) # Check if arrays have values otherwise, things stop working if len(posx) != 0: check_gesture(posx, posy, time_array, sleep, refresh_rate=refresh) cv2.imshow('img', img) # press escape to stop tracking and end program k = cv2.waitKey(30) & 0xff if k == 27: cap.release() cv2.destroyAllWindows() break time.sleep(50 / 1000.0) def start(ms, rs, ls, ts, bs): global main_root global right_root global left_root global top_root global bot_root right_root = rs.top main_root = ms.root left_root = ls.top top_root = ts.top bot_root = bs.top thread1 = Thread(target=motion) thread1.start() t = perpetualTimer(1, increment_rate) t.start()
true
f9dd8b218ee6d2810c99a2f5051ce117e10b1ca7
Python
forgi86/gym-control
/examples/example_experiment_design.py
UTF-8
2,356
2.625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 14 10:06:01 2019 @author: marco """ import gym import gym_control # contains the first order system environment import matplotlib.pyplot as plt import numpy as np OBS = [] REW = [] ACT = [] I = [] if __name__ == '__main__': env_arx = gym.make("ExperimentDesign-v0", leaky='NO') env = env_arx total_reward = 0.0 total_steps = 0 obs_0 = env.reset() # s0 reward_0 = 0.0 OBS.append(obs_0) # s0 REW.append(reward_0) # I.append(env.I) while True: #action = env.action_space.sample() action = 2.0 * np.random.rand(1) - 1 #action = np.array([1.0]) # obs, reward, done, _ = env.step(action) ACT.append(action) # Ai OBS.append(obs) # Si+1 REW.append(reward) # Ri+1 I.append(env.I) total_reward += reward total_steps += 1 if done: break ACT.append(np.nan) G = np.cumsum(REW, axis=0) # In[1] OBS = np.vstack(OBS) REW = np.vstack(REW) ACT = np.vstack(ACT) I = np.stack(I) #I = np.vstack(I) t = np.arange(0, len(OBS)) fig, ax = plt.subplots(4, 1) ax[0].plot(t, OBS[:, 0]) ax[0].set_xlabel("Time index (-)") ax[0].set_ylabel("State (-)") ax[0].grid(True) ax[1].plot(t, ACT) ax[1].set_xlabel("Time index (-)") ax[1].set_ylabel("Action (-)") ax[1].grid(True) ax[2].plot(t, REW) ax[2].set_xlabel("Time index (-)") ax[2].set_ylabel("Reward (-)") ax[2].grid(True) ax[3].plot(t, G) ax[3].set_xlabel("Time index (-)") ax[3].set_ylabel("Return (-)") ax[3].grid(True) OBS = np.vstack(OBS) REW = np.vstack(REW) ACT = np.vstack(ACT) I = np.stack(I) #I = np.vstack(I) t = np.arange(0, len(OBS)) fig, ax = plt.subplots(4, 1) ax[0].plot(t, I[:, 0, 0]) ax[0].set_xlabel("Time index (-)") ax[0].set_ylabel("$I_{11}$") ax[0].grid(True) ax[1].plot(t, I[:, 0, 1]) ax[1].set_xlabel("Time index (-)") ax[1].set_ylabel("$I_{12}$") ax[1].grid(True) ax[2].plot(t, I[:, 1, 0]) ax[2].set_xlabel("Time index (-)") ax[2].set_ylabel("$I_{21}$") ax[2].grid(True) ax[3].plot(t, I[:, 1,1]) ax[3].set_xlabel("Time index (-)") ax[3].set_ylabel("$I_{22}$") ax[3].grid(True)
true
38966986f2cb04c1e287c0d38ddb635ed933d5e7
Python
AndrewSLowe/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/buddymove.py
UTF-8
793
3.03125
3
[ "MIT" ]
permissive
import pandas as pd import sqlite3 import os # remove the sqlite3 file if it already exists os.system("rm buddymove_holidayiq.sqlite3") # Create dataframe from csv. Open connection to sqlite3, save output sqlite3 infile = "buddymove_holidayiq.csv" df = pd.read_csv(infile) conn = sqlite3.connect("buddymove_holidayiq.sqlite3") df.to_sql("buddymove_holidayiq.sqlite3", con=conn, index=False) # perform and display SQL quereies curs = conn.cursor() print("\nNumber of rows:") query = "select count(*) from 'buddymove_holidayiq.sqlite3'"; print(curs.execute(query).fetchall()[0]) print("\nNumber of people who viewed > 100 Nature and Shopping:") query = 'SELECT COUNT(*) FROM "buddymove_holidayiq.sqlite3" WHERE Nature > 100 and Shopping >100;' print(curs.execute(query).fetchall()[0][0])
true
df65f0f1c7fb8a98be9326e5c876b444b7d143fb
Python
listenzcc/learning_tensorflow
/Regression_solution_example.py
UTF-8
2,591
3.453125
3
[]
no_license
# %% import tensorflow as tf import numpy as np # %% # Ground truth session # Parameters, ground-truth of W and b W_true = np.array([1, 2, 3, 4, 5, 6]).reshape(3, 2).astype(np.float32) b_true = np.array([7, 8, 9]).reshape(3, 1).astype(np.float32) # y = W * x + b def linear_forward(x, W=None, b=None, forward=False, W_true=W_true, b_true=b_true): # Fast forward for ground-truth if forward: return tf.matmul(tf.Variable(W_true), x) + tf.Variable(b_true) # Compute regression with input x and current W and b return tf.matmul(W, x) + b # Datas NUM_EXAMPLES = 2000 x_data = np.random.normal(size=(2, NUM_EXAMPLES)).astype(np.float32) # Random fetch method def random_fetch(x_data=x_data, batchsize=10): # Shuffle on column dimension np.random.shuffle(np.transpose(x_data)) # Cut data with batchsize x = x_data[:, :batchsize] # Generate noise noise = np.random.normal(size=(3, batchsize)).astype(np.float32) # Return x and y return x, linear_forward(x, forward=True) + noise # %% random_fetch() # %% # Module building session # LinearModule building class LinearModel(tf.keras.Model): # Cross init def __init__(self): super(LinearModel, self).__init__() # Variables that are trainable self.W = tf.Variable(tf.random.uniform((3, 2)), name='weight') self.b = tf.Variable(tf.random.uniform((3, 1)), name='bias') # 'call method' of LinearModel def call(self, inputs): return linear_forward(inputs, self.W, self.b) # Computation of loss function to be optimized def loss(model, inputs, targets): error = model(inputs) - targets return tf.reduce_mean(tf.square(error)) # Computation of gradient def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) # Return current loss_value and gradient return loss_value, tape.gradient(loss_value, [model.W, model.b]) # %% # Training session # Init LinearModuel as model model = LinearModel() # Init optimizer optimizer = tf.optimizers.Adam(0.1) # optimizer = tf.keras.optimizers.SGD(learning_rate=0.1) # Training 1000 times for i in range(1000): # Random fetch x and y x, y = random_fetch(batchsize=100) # Compute loss_value and grads loss_value, grads = grad(model, x, y) # Apply gradients optimizer.apply_gradients(zip(grads, [model.W, model.b])) # Print loss each 100 steps if i % 100 == 0: print("Loss at step {:03d}: {:.3f}".format(i, loss_value)) # Print trained W and b print(model.W, model.b) # %%
true
16eef158495c1e6f86016f5703c00f504010be3d
Python
jakeelwes/mjpeg-wishes
/mjpegviewer.py
UTF-8
4,165
2.578125
3
[]
no_license
import time import sys import os import httplib import base64 import StringIO import Image import pygame from pygame.locals import * import getopt class mjpegviewer: path = 'stream/' filename = 'snap' extension = 'jpg' number = 0 request = '/axis-cgi/mjpg/video.cgi' nowindow = False def __init__(self, ip, username='admin', password='admin', request = '/axis-cgi/mjpg/video.cgi', path=0, nowindow=False): self.ip = ip self.username = username self.password = password self.base64string = base64.encodestring('%s:%s' % (username, password))[:-1] self.number = 0 self.path = path self.request = request self.nowindow = nowindow if not os.path.exists(self.path): os.makedirs(self.path) def connect(self): h = httplib.HTTP(self.ip) h.putrequest('GET',self.request) h.putheader('Authorization', 'Basic %s' % self.base64string) h.endheaders() errcode, errmsg, headers = h.getreply() self.file = h.getfile() def update(self, window, size, offset): data = self.file.readline() if data[0:15] == 'Content-Length:': count = int(data[16:]) s = self.file.read(count) while s[0] != chr(0xff): s = s[1:] if self.path != 0: p = StringIO.StringIO(s) im = Image.open(p) try: im.load() except KeyboardInterrupt: self.close() except Exception, x: pass fullpath = self.path + self.filename + ("%04d" % self.number) + '.' + self.extension im.save(fullpath) self.number += 1 if not self.nowindow: try: p = StringIO.StringIO(s) campanel = pygame.image.load(p).convert() #pygame.image.save(campanel,fullpath) campanel = pygame.transform.scale(campanel, size) window.blit(campanel, offset) except KeyboardInterrupt: self.close() except Exception, x: print x p.close() def close(self): sys.exit() def main(argv): nowindow = False host = '216.123.238.207' path = 'stream/' request = '/axis-cgi/mjpg/video.cgi' screen = '' try: opts, args = getopt.getopt(argv,"hni:p:r:",["nowindow", "ip=", "path=", "request="]) except getopt.GetoptError: print 'mjpegviewer.py -h to get help' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'run "mjpegviewer.py --nowindow" for a x-less run' print 'run "mjpegviewer.py --ip 127.0.0.1" to specify your camera\'s IP' print 'run "mjpegviewer.py --path myfolder" to specify a path to save images to' print 'run "mjpegviewer.py --ip 127.0.0.1 --request /axis-cgi/mjpg/video.cgi" to specify a custom request' sys.exit() elif opt in ("-n", "--nowindow"): nowindow = True elif opt in ("-i", "--ip"): host = arg elif opt in ("-p", "--path"): path = arg + '/' elif opt in ("-r", "--request"): request = arg pygame.init() if not nowindow: screen = pygame.display.set_mode((660,500), 0, 32) pygame.display.set_caption('mjpegviewer.py') background = pygame.Surface((660,500)) background.fill(pygame.Color('#E8E8E8')) screen.blit(background, (0,0)) camera = mjpegviewer(host, '', '', request, path, nowindow) camera.connect() while True: try: camera.update(screen, (640,480), (10,10)) pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) time.sleep(.01) except KeyboardInterrupt: camera.close() if __name__ == '__main__': main(sys.argv[1:])
true
822c05509a4ca0f196f906527998e84c053b976e
Python
groove-x/pura
/tests/test_keyboard_key.py
UTF-8
352
2.609375
3
[ "MIT" ]
permissive
from pura import KeyboardKey def test_key(): a = KeyboardKey('a') a2 = KeyboardKey('a') a_alt = KeyboardKey('a', alt_modifier=True) b = KeyboardKey('b') assert a == a2 assert a == 'a' assert not a != 'a' # pylint: disable=unneeded-not assert str(a) == 'a' assert a != a_alt assert a < b assert a < 'b'
true
895b831cf08ecdca6eb3936b7cf975d3b5dc7641
Python
sangnv3007/tailieuhoctapTLU
/Năm 2/Lập trình khoa học dữ liệu/Python/TH/TH buoi 2/VD2.py
UTF-8
414
3.5
4
[]
no_license
a=int(input("Nhap a:")) b=int(input("Nhap b:")) temp1 = a; temp2 = b; while (temp1 != temp2): if (temp1 > temp2): temp1 -= temp2; else: temp2 -= temp1; uscln = temp1; bscnn =(a*b)/uscln; #tính USCLN của a và b print("Ước số chung lớn nhất của", a, "và", b, "là:", uscln); #tính BSCNN của a và b print("Bội số chung nhỏ nhất của", a, "và", b, "là:", bscnn);
true
89a0f8c57303ac2d965f68678b1638e622a17013
Python
oliveross/MachineLearning
/DeepLearning/SingleLayerNetwork.py
UTF-8
2,600
3.953125
4
[]
no_license
from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # seed the random number generator, so it generates the same numbers # every time the program is ran random.seed(1) # we model a single neuron, with 3 input connections and 1 output connection # we assign random weights to a 3x1 matrix, with values in the range -1 to 1 # and a mean of 0 self.synaptic_weights = 2 * random.random((3, 1)) - 1 # the signmoid function, which describes an s shaped curve # we pass the weighted sum of the inputs through this function # to normalize them between 0 and 1 def __sigmoid(self, x): return 1 / (1 + exp(-x)) # gradient of sigmoid curve def __sigmoid_derivative(self, x): return x * (1 - x) def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): # pass the training set through our neural net output = self.predict(training_set_inputs) # calculate the error error = training_set_outputs - output # multiply the error by the input and again by the gradient of the # sigmoid curve adjustment = dot(training_set_inputs.T, error * self.__sigmoid_derivative(output)) # adjust the weights self.synaptic_weights += adjustment def predict(self, inputs): # pass inputs through our neural network (our single neuron) print('i: ', inputs.shape, inputs) print('s: ', self.synaptic_weights.shape, self.synaptic_weights) dot_result = dot(inputs, self.synaptic_weights) return self.__sigmoid(dot_result) # if __name__ = '__main__': # initialize a single neuron neural network neural_network = NeuralNetwork() print('Random starting synaptic weights:') print(neural_network.synaptic_weights) # the training set. We have 4 examples, each consisting of 3 input values # and 1 output value training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_outputs = array([[0, 1, 1, 0]]).T # train the neural network using a training set. # Do it 10000 times and make small adjustments each time neural_network.train(training_set_inputs, training_set_outputs, 10000) print('New synaptic weights after training: ') print(neural_network.synaptic_weights) # test the neural network with a new situation print('Considering new sitatuion [1, 0, 0] -> ?: ') print(neural_network.predict(array([1, 0, 0])))
true
8de5fa60b343ff799a8ad9478c10a71ddc9b2e04
Python
bjkim777/project
/euler/problem20.py
UTF-8
122
3.765625
4
[]
no_license
sum=1 for a in range(1,100): sum*=a sum2=0 for index in range(len(str(sum))): sum2+=int(str(sum)[index]) print(sum2)
true
8065e5e7c46c866312927b047c6da08e012cd6ac
Python
Jedi18/ScanPartitionPython
/compareVaryingChunk.py
UTF-8
3,880
2.609375
3
[]
no_license
import csv import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from os import listdir import os def readCsv(): labelToCol = { 'seq' : 'red', 'par' : 'green', 'old' : 'blue' } chunkFolders = ['int_default_chunk_size', 'int_chunk_size_by_24', 'int_chunk_size_by_48', 'int_chunk_size_by_96'] chunkColorsPar = { 'int_default_chunk_size' : "#FFB300", 'int_chunk_size_by_24' : "#803E75", 'int_chunk_size_by_48' : "#FF6800", 'int_chunk_size_by_96' : "#A6BDD7" } chunkColorsOld = { 'int_default_chunk_size' : "#CEA262", 'int_chunk_size_by_24' : "#817066", 'int_chunk_size_by_48' : "#007D34", 'int_chunk_size_by_96' : "#F6768E" } scan_files = listdir('C:\\Users\\targe\\Pictures\\scan_benchmarks\\24cores\\int_default_chunk_size\\csv_files') output_folder = 'C:\\Users\\targe\\Pictures\\scan_benchmarks\\varying_chunk_size\\24cores' for scan_file in scan_files: fig, ax = plt.subplots() for folder_name in chunkFolders: inputSizes = [] seqTime = [] parTime = [] oldTime = [] parRelative = [] oldRelative = [] with open('C:\\Users\\targe\\Pictures\\scan_benchmarks\\24cores\\' + folder_name + '\\csv_files\\' + scan_file) as csvfile: valueReader = csv.reader(csvfile) first = True c = 5 for row in valueReader: N = float(row[0]) seq = float(row[1]) par = float(row[2]) old = float(row[3]) inputSizes.append(c) c += 1 seqTime.append(seq) parTime.append(par) oldTime.append(old) parRelative.append(seq/par) oldRelative.append(seq/old) ax.set_xticks(range(5, 32, 1)) ax.plot(inputSizes, parRelative, color=chunkColorsPar[folder_name]) ax.plot(inputSizes, oldRelative, color=chunkColorsOld[folder_name]) ax.plot([5, 30], [1, 1], color=labelToCol['seq']) ax.set_xlabel('i where the input size is 2^i') ax.set_ylabel('Relative speedup to sequential') handles = [] handles.append(mpatches.Patch(color=labelToCol['seq'], label="seq")) handles.append(mpatches.Patch(color=chunkColorsPar['int_default_chunk_size'], label="par - default")) handles.append(mpatches.Patch(color=chunkColorsPar['int_chunk_size_by_24'], label="par - chunk size by 24")) handles.append(mpatches.Patch(color=chunkColorsPar['int_chunk_size_by_48'], label="par - chunk size by 48")) handles.append(mpatches.Patch(color=chunkColorsPar['int_chunk_size_by_96'], label="par - chunk size by 96")) handles.append(mpatches.Patch(color=chunkColorsOld['int_default_chunk_size'], label="old - default")) handles.append(mpatches.Patch(color=chunkColorsOld['int_chunk_size_by_24'], label="old - chunk size by 24")) handles.append(mpatches.Patch(color=chunkColorsOld['int_chunk_size_by_48'], label="old - chunk size by 48")) handles.append(mpatches.Patch(color=chunkColorsOld['int_chunk_size_by_96'], label="old - chunk size by 96")) handles.append(mpatches.Patch(color='white', label="")) handles.append(mpatches.Patch(color='white', label="L1 Cache - 32 KiB")) handles.append(mpatches.Patch(color='white', label="L2 Cache - 512 KiB")) handles.append(mpatches.Patch(color='white', label="L3 Cache - 16 MiB")) plt.legend(loc="upper left", handles=handles) plt.savefig(output_folder + '\\' + os.path.splitext(scan_file)[0] + '.png') if __name__ == "__main__": readCsv()
true
716ef3d9d4f7b00d31c25bf1b2ca39fb9c6e1bf8
Python
kezhengzhu/buildcg
/functions.py
UTF-8
14,039
2.84375
3
[]
no_license
#!/usr/bin/env python import re import os import copy import math import numpy as np def checkerr(cond, message): if not (cond): raise Exception(message) return def atype_calc(sig, epsi, lr, la): ''' Takes in sigma (nm), epsilon (kJ/mol), lr, la returns C, A or V(c6), W(c12) ''' c_mie = lr/(lr-la) * pow(lr/la, la/(lr-la)) A = c_mie * epsi * pow(sig,lr) # repulsion coefficient C = c_mie * epsi * pow(sig,la) return (C,A) def get_atomtype(name, atnum, mass, charge, ptype, C, A): ''' Write a single line of atom type in ffnonbonded by default: ptype should be 'A' ''' strcheck = [isinstance(s, str) for s in [name, atnum, ptype]] floatcheck = [isinstance(f, float) for f in [mass, charge, C, A]] checkerr(all(strcheck), "Name, at. num or ptype not of type str") checkerr(all(floatcheck), "Mass, charge, C or A not of type float") return " {:<6}{:<11}{:<11.3f}{:<9.3f}{:<11}{:<13.5e}{:<11.5e}\n".format(name, atnum, mass, charge, ptype, C, A) def get_atomnbp(name1, name2, C, A): ''' Write the cross interaction between two different atom type in ffnonbonded ''' strcheck = [isinstance(s, str) for s in [name1, name2]] floatcheck = [isinstance(f, float) for f in [C, A]] checkerr(all(strcheck), "Names not of type str") checkerr(all(floatcheck), "C or A not of type float") return " {:<5}{:<6}{:<6}{:<15.5e}{:<15.5e}\n".format(name1,name2,"1",C,A) def write_atomtype(template, atypes, nbp=None): ''' Takes in template, search for $ATOM_TYPES and write in given str ''' checkerr(isinstance(atypes, str), "Input atom_types info not of type str") f = open(template, 'r') content = f.read() f.close() ffnb = re.sub("[$]ATOM_TYPES", atypes, content) if nbp is None: ffnb = re.sub("[$]NBP_START[\s\S]+[$]NBP_STOP", "", ffnb) else: checkerr(isinstance(nbp, str), "Non-bonded params should be given in type str for input") ffnb = re.sub("[$]NBP_START", "", ffnb) ffnb = re.sub("[$]NBP_STOP", "", ffnb) ffnb = re.sub("[$]NONBOND_PARAMS", nbp, ffnb) return ffnb def write_molecule(template, molecule_name, molecule_type, atoms, bonds=None): ''' Takes in template, search for $MOLECULE_NAME, $MOLECULE_TYPE, $ATOMS and $BONDS And writes in the relevant info ''' strcheck = [isinstance(s, str) for s in [molecule_name, molecule_type, atoms]] checkerr(all(strcheck), "Input information not all of type str") f = open(template, "r") content = f.read() f.close() molfile = re.sub("[$]MOLECULE_NAME", molecule_name, content) molfile = re.sub("[$]MOLECULE_TYPE", molecule_type, molfile) molfile = re.sub("[$]ATOMS", atoms, molfile) if bonds is None: molfile = re.sub("[$]BONDS_START[\s\S]+[$]BONDS_STOP", "", molfile) else: checkerr(isinstance(bonds, str), "Bonds should be of type str for input") molfile = re.sub("[$]BONDS_START", "", molfile) molfile = re.sub("[$]BONDS_STOP", "", molfile) molfile = re.sub("[$]BONDS", bonds, molfile) return molfile def get_rings(edges, curr=None, found=None): ''' Identifying the rings in the molecule. Make sure that the rings are created in order and triple connected rings doesn't work as of now. ''' # initializing for zeroth layer if found is None: found = [] if curr is None: curr = [0] # print("{:40s}\n{:10s} -- {:20s}".format(repr(edges),repr(curr),repr(found))) # Get current node current = curr[-1] # Check if ring is formed by tracking if this node has been visited if current in curr[:-1]: # remove traversed nodes and the ring, flip the ring, and return id = curr.index(current) f = curr[id:] addback = [] for n in f[:-1]: if len(edges[n]) > 0: addback.append(n) curr[id:] = addback found.append(tuple(f)) return found while len(edges[current])>0: # next in line is smallest in the current set that is left L = edges[current] next = min(L) # remove traversed L.remove(next) edges[next].remove(current) # successful ring would have removed current if len(curr) == 0 or curr[-1] != current: curr.append(current) curr.append(next) old = len(found) found = get_rings(edges, curr, found) if len(found) == old: curr.pop(-1) return found def protate(x, n, a): # vector, normal of plane, angle to rotate by checkerr(isinstance(x, np.ndarray) and isinstance(n, np.ndarray), "Use numpy array for vectors") result = math.cos(a) * x + math.sin(a) * np.cross(n,x) return result def norm_scale(x, m=1): # m is magnitude, reduce vector into unit vector then scale by magnitude checkerr(isinstance(x, np.ndarray), "Use numpy array for vectors") result = x / np.linalg.norm(x) if isinstance(m, (int,float)): result = result * m elif isinstance(m, np.ndarray): result = result * np.linalg.norm(m) else: raise Exception("Use numpy array or int/float for magnitude") return result def make_zeroes(x): result = x * 1. # make duplicate result[np.abs(result) < 1e-5] = 0. return result def get_bond_position(total_bonds, connected_pos): checkerr(isinstance(total_bonds, int), "No. of bonds specified not int") checkerr(total_bonds > 1 and total_bonds <= 4, "Total bonds should be between 2 to 4 to use this function") checkerr(isinstance(connected_pos, (list,tuple,np.ndarray)), "Connected positions should be an iterable") n_connected = len(connected_pos) checkerr(n_connected < total_bonds and n_connected > 0, "No. of connected bonds should be less than total bonds and more than 1") result = [] if n_connected == 3: u1 = norm_scale(np.cross(connected_pos[0], connected_pos[1])) result = [u1] elif n_connected == 2: uimean_vec = norm_scale(-np.mean(connected_pos, axis=0)) if total_bonds - n_connected == 1: result = [uimean_vec] else: # case total-connected == 2 angle = math.acos(-1/3) # 109.47 pn1 = norm_scale(np.cross(*connected_pos)) # normal vector to connected plane, which is on rotating plane pn2 = np.cross(uimean_vec, pn1) # rotating plane c1 = protate(uimean_vec, pn2, angle/2) c2 = protate(uimean_vec, pn2, -angle/2) result = [c1, c2] elif n_connected == 1: adding = total_bonds - n_connected if adding == 1: uimean_vec = norm_scale(-connected_pos[0]) result = [uimean_vec] else: a = connected_pos[0] seed = np.array([1.,0,0]) if np.linalg.norm(np.cross(a,seed)) < 1e-4: seed += np.array([0.,0.,1.]) pn1 = norm_scale(np.cross(a, seed)) if adding == 2: t = 2*math.pi/3 uc1 = norm_scale(protate(a, pn1, t)) uc2 = protate(uc1, pn1, t) result = [uc1, uc2] elif adding == 3: t = math.acos(-1/3) # rotate once by 109.47 on random plane to generate one bond ua = norm_scale(a) uc1 = protate(ua, pn1, t) # mean vec + norm vec = orthogonal plane against a,c1 plane uimean_vec = -np.mean([ua,uc1], axis=0) pn2 = norm_scale(np.cross(pn1, uimean_vec)) # rotate mean vec up and down uc2 = protate(uimean_vec, pn2, t/2) uc3 = protate(uimean_vec, pn2, -t/2) result = [uc1, uc2, uc3] return result def parse_mdp(mdpfile): f = open(mdpfile, "r") content = f.read() f.close() content = re.sub('[;][^\n]+', '', content) content = re.sub('[ ]{2,}', ' ', content) content = re.sub('[\n]{2,}', '\n', content) content = content.strip() listing = content.split("\n") mapping = dict() for item in listing: s = item.split("=") val = s[1].strip() if re.match('^[-+]?\d+$', val) != None: val = int(val) elif re.match('^[-+]?((\d+\.\d*)|(\.\d+)|(\d+))([eE][-+]?((\d+\.\d*)|(\.\d+)|(\d+)))?$', val) != None: val = float(val) mapping[s[0].strip()] = val return mapping def write_mdp(output_file, mapping, title=None): if title is None: title = "Auto generated .mdp file for Gromacs MD simulation with BuildCG" s = "; {:s}\n".format(title) for key, val in mapping.items(): if val is None: continue if isinstance(val, float): val = "{:0.4f}".format(val) if val > 1e-3 else "{:0.4e}".format(val) elif not isinstance(val, str): val = str(val) if "_" in key: key = key.replace("_", "-") s += "{:<30s} = {:s}\n".format(key, val) fout = open(output_file, "w") fout.write(s) fout.close return output_file def print_dict(dictionary): # Just prints dictionaries in the way that u can copy into python # Assuming that both sides are strings text = "{\n" for key, val in dictionary.items(): if isinstance(val, str): val = '"' + val + '"' text += ' {:<30s}: {},\n'.format('"'+key+'"', val) text += "}" print(text) return text def write_topol(template, ff, sysname, molinfo): ''' Takes in template, search for $FORCEFIELD, $SYSNAME and $N_MOLECULES And writes in the relevant info ''' strcheck = [isinstance(s, str) for s in [ff, sysname, molinfo]] checkerr(all(strcheck), "Input information not all of type str") f = open(template, "r") content = f.read() f.close() topol = re.sub("[$]FORCEFIELD", ff, content) topol = re.sub("[$]SYSNAME", sysname, topol) topol = re.sub("[$]N_MOLECULES", molinfo, topol) return topol def write_ff(template, ffnb, molecules): f = open(template, "r") content = f.read() f.close() ff = re.sub("[$]FF_NONBONDED", f'#include "{ffnb:s}"', content) if isinstance(molecules, (list, tuple)): mols = [f'#include "{molecules[i]:s}"' for i in range(len(molecules))] molinfo = "\n".join(mols) else: molinfo = f'#include "{molecules:s}"' ff = re.sub("[$]MOLECULES", molinfo, ff) return ff def main(): # print(parse_mdp("em.mdp")) d1 = parse_mdp("eql.mdp") d2 = parse_mdp("npt.mdp") missing = {"eql": [x for x in d1 if x not in d2], "npt": [x for x in d2 if x not in d1]} shared_diff = {k: [d1[k], d2[k]] for k in d1 if k in d2 and d1[k] != d2[k]} shared_same = {k: d1[k] for k in d1 if k in d2 and d1[k] == d2[k]} print_dict(missing) print_dict(shared_diff) print(shared_same.keys()) d1 = parse_mdp("nvt.mdp") d2 = parse_mdp("nvt_eq.mdp") missing = {"nvt": [x for x in d1 if x not in d2], "nvt_eq": [x for x in d2 if x not in d1]} shared_diff = {k: [d1[k], d2[k]] for k in d1 if k in d2 and d1[k] != d2[k]} shared_same = {k: d1[k] for k in d1 if k in d2 and d1[k] == d2[k]} print_dict(missing) print_dict(shared_diff) print(shared_same.keys()) print(write_ff("template/forcefield_template.itp", "ffnonbonded.itp", ["cgmolecule-eth.itp","cgmolecule-tmh.itp","cgmolecule-tm6.itp",])) # # print_dict(parse_mdp("npt.mdp")) # print_dict(parse_mdp("nvt.mdp")) # '^[-+]?((\d+\.\d*)|(\.\d+)|(\d+))([eE][-+]?((\d+\.\d*)|(\.\d+)|(\d+)))?$' # print(parse_mdp("nvt_eq.mdp")) # print(parse_mdp("nvt.mdp")) # print(write_mdp("nvttest1.mdp", parse_mdp("nvt.mdp"), title="Testing a NVT mdp file")) # angle = math.acos(-1/3) # a = np.array([4,1,2]) # seed = np.array([1,1,1]) # n1 = norm_scale(np.cross(a, seed)) # c1 = protate(a, n1, angle) # m_inv = norm_scale(-np.mean([a,c1], axis=0), a) # p2 = norm_scale(np.cross(a, c1)) # n2 = norm_scale(np.cross(m_inv, p2)) # c2 = protate(m_inv, n2, angle/2) # c3 = protate(m_inv, n2, -angle/2) # a1 = protate(a, n1, 2*math.pi/3) # a2 = protate(a1, n1, 2*math.pi/3) # c34 = get_bond_position(3,[a]) # c1 = c34[0] * np.linalg.norm(a) # c2 = c34[1] * np.linalg.norm(a) # c3 = c34[2] * np.linalg.norm(a) # print(c1, c2) # # print(n1) # print(a,c1,c2) # rot = [a,c1,c2] # for i in rot: # print(i, end=" ---- ") # print(np.linalg.norm(i)) # # for i in range(3): # for j in range(i+1,3): # print(i, j, math.acos(np.dot(rot[i],rot[j])/np.linalg.norm(rot[i])/np.linalg.norm(rot[j]))*180/math.pi) # f = open("ffnonbonded_template.itp", "r") # t = f.read() # f.close() # vars = re.sub("[$][A-Z0-9_]{1}[A-Z0-9_]+", write_atomtype("OCT", "10", 10.0, 0.0, "A", 12.3e-3, 2.13e-4), t) # print(write_atomtype("ffnonbonded_template.itp", get_atomtype("OCT", "10", 10.0, 0.0, "A", 12.3e-3, 2.13e-4))) # edges = [{1},{0,2,3},{1,3},{1,2,4,7},{3,5},{4,6},{5,7}, {3,6}] # print(get_rings(edges)) # # edges = [{1},{0,2,3,5},{1,3},{1,2,4},{3,5},{1,4}] # print(get_rings(edges)) # # edges = [{1,3},{0,2},{1,3},{0,2,4},{3,5},{4,6,7},{5,7},{5,6}] # print(get_rings(edges)) # # edges = [{1,5},{0,2},{1,3},{2,4},{3,5},{0,4}] # print(get_rings(edges)) # # edges = [{1,5},{0,2,8},{1,3},{2,4},{3,5},{0,4,6},{5,7},{6,8},{1,7}] # print(get_rings(edges)) # # edges = [{1,10},{0,2,5},{1,3},{2,4},{3,5,6},{1,4,8},{4,7},{6,8},{5,7,9},{8,10},{0,9}] # print(get_rings(edges)) # # edges = [{3},{3,9},{3,5},{0,1,2},{5,7,8},{2,4,9},{7},{4,6},{4},{1,5}] # print(get_rings(edges)) # # edges = [{1},{0,2,5},{1,3},{2,4},{3,5,6},{1,4},{4}] # print(get_rings(edges)) # # edges = [{1},{0,2,6},{1,3},{2,4},{3,5,6},{4},{1,4}] # print(get_rings(edges)) return if __name__ == '__main__': main()
true
f792da43c8a84c478b256d83723d50200e9b9373
Python
jtemplon/cbb_data_parsing
/SeasonSim/multiseasonsim.py
UTF-8
1,410
3.328125
3
[]
no_license
from seasonsim import seasonsim, standingscounter, seasonreset class SeasonStats(): tied_seasons = 0 two_team_tie = 0 three_team_tie = 0 multi_team_tie = 0 most_wins = {} def multiseasonsim(team_dict, bool): season_counter = 1 balanced = bool seasonstats = SeasonStats() #while season_counter < 10001: while season_counter < 10001: seasonreset(team_dict) seasonsim(team_dict, balanced) standingscounter(team_dict, seasonstats) season_counter = season_counter + 1 print "Name - Season Wins - Season Ties - Undefeated Seasons - Winless Seasons - Best Season - Worst Season - Total Win Margin" for k in team_dict.keys(): print "%s - %s - %s - %s - %s - %s - %s - %s - %s" %(team_dict[k].name, team_dict[k].season_wins, team_dict[k].season_ties, team_dict[k].undefeated_seasons, team_dict[k].winless_seasons, team_dict[k].best_season, team_dict[k].worst_season, team_dict[k].win_margin, team_dict[k].total_wins) print "Tie Stats: %s ties, %s two-team, %s three-team, %s more than three" %(seasonstats.tied_seasons, seasonstats.two_team_tie, seasonstats.three_team_tie, seasonstats.multi_team_tie) print seasonstats.most_wins for k in team_dict.keys(): print team_dict[k].name print team_dict[k].places print team_dict[k].place_ties print team_dict[k].win_distribution
true
53f1ba359d907d79b7923a2f054f0483c8521fce
Python
Mercurius-0227/Baekjoon
/find_rest.py
UTF-8
425
3.109375
3
[]
no_license
#1978 #소수 찾기 #2020.07.17 완성! import sys input=sys.stdin.readline N=int(input()) list_A=input().split() list_A=list(map(int,list_A)) count=0 i=0 j=0 mark=1 for i in range(N): for j in range(2,list_A[i]): rest=list_A[i]%j if list_A[i]==1: mark=1 if rest==0: mark=1 else: mark=0 if mark==0: count+=1 print(count)
true
7dab3b954b7359b0cd4491c1c5b24f8ed2758617
Python
MatthewTsan/Leetcode
/python/q287/q287.py
UTF-8
274
2.640625
3
[ "Apache-2.0" ]
permissive
from typing import List class Solution: def findDuplicate(self, nums: List[int]) -> int: busket = [False for item in nums] for item in nums: if busket[item]: return item else: busket[item] = True
true
61ac7d6832302d5b178b70772648ed8b36f49d15
Python
Fapfood/nlp
/lab9/task2.py
UTF-8
1,322
3.046875
3
[]
no_license
import numpy as np from matplotlib import pyplot as plt def histogram(data): word, frequency = zip(*data) indices = np.arange(len(data)) plt.bar(indices, frequency, color='r') plt.xticks(indices, word, rotation='vertical') plt.tight_layout() plt.show() with open('tmp_dict', encoding='utf8') as f: content = f.read() dct = eval(content) dct1 = {} for d in dct: v = sum(dct[d].values()) dct1[d] = v res1 = sorted(dct1.items(), key=lambda x: x[1], reverse=True) for d in res1: print(d) histogram(res1) print() dct2 = {} for d in dct: k = d[0:7] dct2[k] = dct2.get(k, 0) + dct1[d] res2 = sorted(dct2.items(), key=lambda x: x[1], reverse=True) for d in res2: print(d) histogram(res2) print() dct3 = {} for d in dct: for c in dct[d]: k = (c, d) dct3[k] = dct[d][c] res3 = sorted(dct3.items(), key=lambda x: x[1], reverse=True)[:50] for d in res3: print(d) print() dct4 = {} for d in dct: k = d[0:7] dct4[k] = dct4.get(k, {}) dct4[k][d] = dct[d] for z in dct4: dct5 = {} for d in dct4[z]: for c in dct4[z][d]: k = (c, d) dct5[k] = dct4[z][d][c] res5 = sorted(dct5.items(), key=lambda x: x[1], reverse=True)[:10] print(z) for d in res5: print(d) print()
true
188a710860c4fca33ef38562ea8a31b3203918c0
Python
basfl/advance_python
/mongodb/db_util/db_crud.py
UTF-8
2,158
2.90625
3
[]
no_license
from pymongo import MongoClient class CRUD: """ find only one record from the collection """ @staticmethod def find_one(collection_name): print(f'{collection_name.find_one()}') """ post only one record to the collection """ @staticmethod def post_one(collection_name, post): collection_name.insert_one(post) """ insert many records to the collection """ @staticmethod def insert_many_records(collection_name, *posts): posts_list = [] print(posts) for post in posts: posts_list.append(dict(post)) # collection_name.insert_one(post) expanded_list = [dict(i) for i in posts_list] # print(f"***********{l}") collection_name.insert_many(expanded_list) """ find specific value inside the collection docuemnt by passing key and value """ @staticmethod def find_value(collection_name, key, value): try: result = collection_name.find_one({key: value}) print(f"result is {result['name']}") except: print("Database Error Occoured") """ delete only one specific record from collection """ @staticmethod def delete_one(collection_name, key, value): collection_name.delete_one({key: value}) """ perform specific query and delete record base on the result of query """ @staticmethod def delete_all_except(collection_name, key, value): query = {key: {"$ne": value}} # print(query) try: collection_name.delete_many(query) except: print("Database Error Occoured") """ update value in collection and add new value to the collection """ @staticmethod def update_record(collection_name, key, value, update_key, update_value): myquery = {key: value} newvalues = {"$set": {update_key: update_value}} collection_name.update_many(myquery, newvalues) collection_name.update_many({update_key: update_value}, { "$set": {"updated": True}})
true
a2a0d06a35f9b9d0b8b08b3418efeeeddc521cce
Python
peacock0803sz/pyconjpbot
/pyconjpbot/plugins/plusplus.py
UTF-8
5,783
2.953125
3
[ "MIT" ]
permissive
import random from slackbot.bot import respond_to, listen_to from slackbot import settings import slacker from .plusplus_model import Plusplus from ..botmessage import botsend, botwebapi PLUS_MESSAGE = ( 'leveled up!', 'レベルが上がりました!', 'やったね', '(☝՞ਊ ՞)☝ウェーイ', ) MINUS_MESSAGE = ( 'leveled down.', 'レベルが下がりました', 'ドンマイ!', '(´・ω・`)', ) def _get_user_name(user_id): """ 指定された Slack の user_id に対応する username を返す Slacker で users.list API を呼び出す - https://github.com/os/slacker - https://api.slack.com/methods/users.info """ webapi = slacker.Slacker(settings.API_TOKEN) response = webapi.users.info(user_id) if response.body['ok']: return response.body['user']['name'] else: return '' def _update_count(message, target, plusplus): """ 指定ユーザーのカウンターを更新する """ target = target.lower() plus, created = Plusplus.get_or_create(name=target, defaults={'counter': 0}) if plusplus == '++': plus.counter += 1 msg = random.choice(PLUS_MESSAGE) else: plus.counter -= 1 msg = random.choice(MINUS_MESSAGE) plus.save() botsend(message, '{} {} (通算: {})'.format(target, msg, plus.counter)) @listen_to(r'^<@(.+)>:?\s*(\++|-+)') def mention_plusplus(message, user_id, plusplus): """ mentionされたユーザーに対して ++ または -- する """ if len(plusplus) != 2: return target = _get_user_name(user_id) _update_count(message, target, plusplus) @listen_to(r'^(\w\S*[^\s:+-]):?\s*(\++|-+)') def plusplus(message, target, plusplus): """ 指定された名前に対して ++ または -- する takanory++ takanory:++ takanory: ++ 日本語++ takanory++ コメント takanory ++ """ if len(plusplus) != 2: return _update_count(message, target, plusplus) @respond_to(r'^plusplus\s+(del|delete)\s+(\S+)') def plusplus_delete(message, subcommand, name): """ 指定された名前を削除する カウントが10未満のもののみ削除する """ try: plus = Plusplus.get(name=name) except Plusplus.DoesNotExist: message.send('`{}` という名前は登録されていません'.format(name)) return if abs(plus.counter) > 10: botsend(message, '`{}` のカウントが多いので削除を取り消しました(count: {})'.format(name, plus.counter)) return plus.delete_instance() message.send('`{}` を削除しました'.format(name)) @respond_to(r'^plusplus\s+rename\s+(\S+)\s+(\S+)') def plusplus_rename(message, old, new): """ 指定された old から new に名前を変更する """ try: oldplus = Plusplus.get(name=old) except Plusplus.DoesNotExist: botsend(message, '`{}` という名前は登録されていません'.format(old)) return newplus, created = Plusplus.create_or_get(name=new, counter=oldplus.counter) if not created: # すでに存在している message.send('`{}` という名前はすでに登録されています'.format(new)) return # 入れ替える oldplus.delete_instance() botsend(message, '`{}` から `{}` に名前を変更しました(count: {})'.format(old, new, oldplus.counter)) @respond_to(r'^plusplus\s+merge\s+(\S+)\s+(\S+)') def plusplus_merge(message, old, new): """ 指定された old と new を一つにまとめる """ try: oldplus = Plusplus.get(name=old) except Plusplus.DoesNotExist: botsend(message, '`{}` という名前は登録されていません'.format(old)) return try: newplus = Plusplus.get(name=new) except Plusplus.DoesNotExist: botsend(message, '`{}` という名前は登録されていません'.format(new)) return oldcount = oldplus.counter newcount = newplus.counter # 値を統合する newplus.counter += oldplus.counter newplus.save() oldplus.delete_instance() botsend(message, '`{}` を `{}` に統合しました(count: {} + {} = {})'.format(old, new, oldcount, newcount, newplus.counter)) @respond_to(r'^plusplus\s+search\s+(\S+)') def plusplus_search(message, keyword): """ 指定されたキーワードを含む名前とカウントの一覧を返す """ pattern = '%{}%'.format(keyword) pluses = Plusplus.select().where(Plusplus.name ** pattern) if len(pluses) == 0: botsend(message, '`{}` を含む名前はありません'.format(keyword)) else: pretext = '`{}` を含む名前とカウントの一覧です\n'.format(keyword) text = '' for plus in pluses: text += '- {}(count: {})\n'.format(plus.name, plus.counter) attachments = [{ 'pretext': pretext, 'text': text, 'mrkdwn_in': ['pretext', 'text'], }] botwebapi(message, attachments) @respond_to(r'^plusplus\s+help+') def plusplus_help(message): """ ヘルプメッセージを返す """ botsend(message, '''- `名前++`: 指定された名前に +1 カウントする - `名前--`: 指定された名前に -1 カウントする - `$plusplus search (キーワード)`: 名前にキーワードを含む一覧を返す - `$plusplus delete (名前)`: カウントを削除する(カウント10未満のみ) - `$plusplus rename (変更前) (変更後)`: カウントする名前を変更する - `$plusplus merge (統合元) (統合先)`: 2つの名前のカウントを統合先の名前にまとめる ''')
true
300a2fcbc48aae6404bae6f3cde9b84fd370b744
Python
wfjo852/wh2-webhook-public
/wh2_script/wh_rocket_chat/api/channel.py
UTF-8
2,036
2.578125
3
[]
no_license
#-*- coding:utf-8 -*- from wh2_script.wh_rocket_chat.api import wh_rocket_chat_request, wh_rocket_chat_api def list(): return wh_rocket_chat_request.get(wh_rocket_chat_api.channel_list) def create(channel_name): #data 추가 payload = {'name': channel_name} return wh_rocket_chat_request.post_payload(wh_rocket_chat_api.channel_create, payload) def rename(roomid,newname): #data 추가 payload = {"roomId":roomid,"name":newname} return wh_rocket_chat_request.post_payload(wh_rocket_chat_api.channel_rename, payload) def member_list(roomid): # date 추가 params = {'roomId':roomid} return wh_rocket_chat_request.get_params(wh_rocket_chat_api.channel_members, params) def invite(roomid,user_uid): # date 추가 payload = {'roomId':roomid,'userId':user_uid} return wh_rocket_chat_request.post_payload(wh_rocket_chat_api.channel_invite, payload) def kick(roomid,user_uid): # date 추가 payload = {'roomId':roomid,'userId':user_uid} return wh_rocket_chat_request.post_payload(wh_rocket_chat_api.channel_kick, payload) # 채널의 ID 검색 def get_roomid(roomname): lists = list() channels = lists['channels'] for channel in channels: if channel['name'] == roomname: roomid = channel['_id'] print(roomname,'의 room id : ',roomid) return roomid else: print(roomname+"의 이름이 정확하지 않습니다.") #유저Id리스트를 기준으로 채널의 인원을 변경 def members_change(roomid,userid_list): # userid_list = ["a","b"] members = member_list(roomid) before = [] for x in members['members']: before.append(x['username']) #채널에 인원 초대 invite_list = list(set(userid_list)-set(before)) #채널에 인원 내보내기 kick_list = list(set(before)-set(userid_list)) #채널에 맴버 추가 / 삭제 invite(roomid,invite_list) kick(roomid,kick_list) print("in :",invite_list,"\n","out :",kick_list)
true
0300ef414fd961910bc9c1628798ada3b879f5a6
Python
joneslabND/ICB_Fall2017
/Tutorials/Tutorial08/Exercise08_1_Pseudo.py
UTF-8
794
3.21875
3
[]
no_license
#Exercise 8, Python question 1 #10/13/17, MMD #Open files to read and write vcffile = open("Cflorida.vcf","r") outfile = open("CfloridaCounts.txt","w") #assign regex to variable name, or compile to variable name #loop over file for :#look at old code to see how you looped over a file #strip end of line if : #how can you tell if this is the header line? #write unchanged header line to file elif : #how can you tell if this is the line with the column headings? #standardize (replace) sample names with TX and FL regexes #write new version of line to file else: #now you're in the data #replace full SNP info with allele counts only #replace missing data with NA #write new version of line to new file #Close files
true
6223fc10e771616f0bf54cf9507b7b0783598156
Python
tstl87/PythonInterviewQuestions
/sort/KthLargestElement/Solution.py
UTF-8
402
3.53125
4
[]
no_license
import heapq class Solution(): def findKthLargest1(self, nums, k): nums = sorted(nums) return nums[-k] def findKthLargest2(self, nums, k): return heapq.nlargest(k,nums)[-1] print('[3,2,3,1,2,4,5,5,6] and k = 4') print( Solution().findKthLargest2([3,2,3,1,2,4,5,5,6],4) ) print('') print('[3,2,1,5,6,4] and k=2') print( Solution().findKthLargest2( [3,2,1,5,6,4], 2 ) )
true
3019b93210677b6b8c7887c94e9a3f4515ccc4db
Python
BingoZ/python_scripts
/word_similarity/similarity.py
UTF-8
1,936
3.421875
3
[]
no_license
#!/usr/bin/env python def longest_substring(one,two): lone = len(one) ltwo = len(two) max_len = min(lone,ltwo) longest = '' for i in reversed(xrange(max_len)): for j in reversed(xrange(i,lone+1-i)): chunk = one[i:i+j] if len(chunk) < len(longest): continue if chunk in two: if len(chunk) > len(longest): longest = chunk return longest def similar(word1,word2, fast=False): if word1 == word2: return 1.0 if fast: guess = float(len(word1))/float(len(word2)) guess = min(float(len(word2))/float(len(word1)),guess) if guess < 0.8: return 0.0 max_len = max(len(word1),len(word2)) piece1 = longest_substring(word1,word2) total_len = len(piece1) if piece1 != word1 and piece1 != word2: if piece1: word2 = word2.replace(piece1,'') leftover = word1.split(piece1) for piece2 in leftover: piece3 = longest_substring(piece2,word2) total_len += len(piece3) word2 = word2.replace(piece3,'') else: piece2 = '' s2 = 0.0 s1 = float(total_len)/float(max_len) return s1 piece2 = longest_substring(word2,word1) s2 = float(len(piece2)/float(max_len)) return max(s1,s2) def test(a,b): print '%s vs %s'%(a,b), similar(a,b) def dict_test(word): f = open('/usr1/hcsjad/words/new_words','rb') for word in f: word = word.replace('\n','') yield (similar(word1.lower(),word.lower(),True),word) f.close() if __name__ == '__main__': test('dog','cot') test('me','you') test('you','me') test('cat','cat') test('sudden','suddenly') test('suddenly','sudden') test('male','female') test('female','male') test('graduation','gratuation') test('a1b2c3','123abc') test('test','west') word1 = raw_input('word: ') print 'Similar words are:' results = dict_test(word1) for x in reversed(sorted(results)[-25:]): print x[1], '(%.2f%%)' % (x[0]*100)
true
1651768e425c14ec40d012e824e49700ac154db1
Python
GetTuh/KODI-plugin-Torrentz2-qbittorrent-remote
/resources/lib/site_parsing.py
UTF-8
1,168
2.828125
3
[ "MIT" ]
permissive
import re from bs4 import BeautifulSoup import conn import time def link_to_magnet(site): raw_html = conn.simple_get(site) soup = BeautifulSoup(raw_html, 'html.parser') all_links = soup.findAll("div", {"class": "downlinks"}) all_links = all_links[0].findAll("a") adblock=0 for siteLink in all_links: if(adblock==0): #pierwszy wynik to reklama wiec go omijam adblock+=1 else: siteLink=siteLink.get('href') print("trying " + siteLink) magnet = siteLink_to_magnet(siteLink) if(magnet!=None): return(magnet) print("No magnet found") def siteLink_to_magnet(siteLink): raw_html = conn.simple_get(siteLink) try: soup = BeautifulSoup(raw_html, 'html.parser') mag_re=re.compile("href=\"magnet:\?") magnet = soup.findAll('a') for a in magnet: if re.findall("href=\"magnet:\?",str(a.encode('utf-8'))): return(a.get('href')) except: return None # print(siteLink_to_magnet("https://1337x.to/torrent/3223403/Solo-A-Star-Wars-Story-2018-BluRay-1080p-YTS-YIFY/")) print(link_to_magnet("https://torrentz2.eu/e2e457b2e77128cd20fafd0837bbdb9a4d543578"))
true
e7d72e98839a15d41a75c3e0250a5fb91054a40b
Python
maxyonghuawei/Unet_seg
/mask_binary.py
UTF-8
2,374
3.03125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Feb 10 22:14:02 2019 Turn the grey level Images to binary Images and save in the files @author: Kumawife """ from __future__ import print_function #import numpy as np from PIL import Image import os #mask = np.ones([256,256,3]) # #mask = mask[:,:,0] #print(mask.shape) # #new_mask = np.zeros(mask.shape + (3,)) # #print(new_mask.shape) # #for i in range(3): # new_mask[mask==i, i] = 3 # #print(new_mask) #im = Image.open("frame049.png") # format shows the image format, mode shows the image is "L grey scale" or "RGB" #print(im.format, im.size, im.mode) #im.show() #im_binary = im.convert("1") #im_binary.show() #print(im_binary.size, im_binary.mode) def grey_to_binary(img, thresh): """ Converting the grey scale image to binary image through the PIL API defining the "thresh" for binarize the pixel in the input image """ thresh = thresh fn = lambda x: 255 if x>thresh else 0 r = img.point(fn, mode="1") # r.save('foo.png') print("convert mode from grey to binary") return r def saveImage(in_path, out_path, thresh): """ Enter the grey images input path "in_path" Enter the save path "out_path" The threshold for the frey scale images transfered to binary images """ if os.path.exists(in_path): for img in os.listdir(in_path): temp = in_path + '/' + img img_pic = Image.open(temp) img_bir = grey_to_binary(img_pic, thresh) f, e = os.path.splitext(img) outname = f + ".jpg" final_out_path = out_path + outname # print(final_out_path) try: img_bir.save(final_out_path) except IOError: print("Fail to save the file") print("Binary pictures are successfully saved") else: print("Input path is not exist.") #im_bir_test = grey_to_binary(im, 25) #im_bir_test.show() if __name__ == "__main__": out_path = 'D:/Msc.project/data_2017/training/instrument_dataset_1/instrument_dataset_1/ground_truth/other/' in_path = 'D:/Msc.project/data_2017/training/instrument_dataset_1/instrument_dataset_1/ground_truth/Other_labels' thresh = 7 saveImage(in_path, out_path, thresh)
true
62c9967126c2cd809bce9b026d99b766ee20b2a7
Python
seequest/Learning
/ExtraHop/find_longest_word.py
UTF-8
19,611
3.890625
4
[]
no_license
#!/usr/bin/env python36 """ ExtraHop Programming Problem-- Written by David Noble <david@thenobles.us>. This module was developed and tested under Python 3.6 on macOS Sierra. Please ask for Python 2.7 code or code that will run under Python 2.7 or Python 3.6, if you would prefer it. I mention this because I see that your deprecated Python SDK is written for Python 2.7.3 or higher, but not Python 3.x. mypy 0.511 clean """ import io import random import re from collections import deque from string import ascii_lowercase from typing import Deque, Dict, Iterator, List, Mapping, Optional, MutableSet, Sequence, Tuple def find_longest_word(grid: 'Grid', words: List[str]) -> Optional[Tuple[str, Tuple[Tuple[int, int], ...]]]: """ Find the longest word from a list of words that can be produced from an 8 x 8 grid using grid movement rules Words on the grid are located using this set of rules: 1. Start at any position in the grid, and use the letter at that position as the first letter in the candidate word. 2. Move to a position in the grid that would be a valid move for a knight in a game of chess, and add the letter at that position to the candidate word. 3. Repeat step 2 any number of times. This function preserves the contents of the `words` list. Length ties are broken by alphabetic sort order. Hence, for example, if `foo` and `bar` are * in the list of words and * the longest words to be found on a graph :func:`find_longest_word` will return `'bar'` and a tuple of the coordinates of its letters in the grid as its result. Parameters ---------- :param grid: A grid presumably filled with letters from some alphabet. :type grid: Grid :param words: A list of words that might be produced from letters on the 'grid' using grid moves. :type words: List[str] :return: Longest word that can be produces from letters on the 'grid' using grid moves; or :const:`None`, if no word can be produced from letters on the 'grid'. :rtype: Optional[Tuple[str, Tuple[Tuple[int, int]]]] Implementation notes ==================== A grid should be thought of as a directed graph. The cells of a grid are its vertices. The movements that are permitted from a cell on the graph are edges. The vertices are labeled by row, column coordinates and contain a single piece of data: a letter drawn from some alphabet. Producing a word from the letters contained by the cells on a grid amount to a graph traversal in the search for a path that traces out the word. In this solution we represent a grid with `Grid` class which encapsulates the small number of movement and lookup operations that are required to trace out such a path. The `Grid` class also comes with a set of methods useful for testing: `Grid.generate`, `Grid.load`, and `Grid.save`. See the `Grid` class for specifics. Algorithm --------- `find_longest_word` non-destructively sorts words by length and alphabetic order. It then iterates over the set of positions from which a word might start as determined by `Grid.occurrences`. The search for a word from a starting position is conducted by a local recursive function: `find_path`. All potential paths may be considered, but the search is done depth-first and so the first complete path found will be taken. The order in which paths are considered is fixed. This is based on the order of `Grid._moves`. One might have considered more advanced/exotic data structures and algorithms. We chose to keep the code and data structures simple with an assumption that grid (graph) traversal operations are not performance critical. We are content, for example, to consider all moves from a grid position sequentially without providing auxiliary lookup capabilities or more advanced data structures. These might or might not be required based on space or time requirements. An alternative -------------- For each cell create a map of the coordinates of all reachable cells: a map of `Map[str, Tuple[int, int]]` keyed by letter. When moving from one letter of a word to another, consider only those cells with the required letter. As in this code, rule out known fruitless paths; those visited previously and found to be dead ends. To speed searches over time one might also store (memoize) words/word stems; pre-populating some and building up others over time. One might for example, create such a map of words/word stems from the output of `Grid.generate`. Other words or word paths unknown to the author might likely be discovered over time. Here's a Wikipedia article that **might** be useful, should it be determined that this naive implementation is insufficient from a time perspective. * [String searching algorithm](https://en.wikipedia.org/wiki/String_searching_algorithm) Command line ============ This function may be executed from the command line using this syntax:: python find_longest_word.py --grid <filename> <word>... Alternatively you may create a command argument file and reference it like this:: python @<command-file-name> A command file should contain one argument per line as illustrated in `Programming-language-names.args`, included with this code:: --grid grid-1 ALGOL FORTRAN Simula Output includes the word found and the sequence of coordinates of the letters of the word found on the input grid. You will see that this command:: python @Programming-language-names.args produces this output:: ('FORTRAN', ((3, 4), (5, 3), (3, 2), (2, 0), (3, 2), (1, 3), (0, 5))) The coordinates written are zero-based row, column values, not unit-based column, row values as presented in `PythonCodingProblem.docx`. """ def find_path(index: int, origin: Tuple[int, int]) -> Optional[Deque[Tuple[int, int]]]: """ Perform a recursive search for the tail end of a case-folded word from a position on the current grid This local function economizes on stack space by relying on variables in its closure and short-circuiting recursion along previously traversed paths. It is worth noting that words, even very long words in languages like German aren't that long. Stack space should not be an issue and the code is straight forward with this recursive implementation. Sidebar ------- According to the [BBC](http://www.bbc.com/news/world-europe-22762040) the longest German word was just lost after an EU law change. It is 65 characters long, one more than the number of cells in a grid:: Rindfleischetikettierungsueberwachungsaufgabenuebertragungsgesetz In our experiments the `Grid.generate` function has not yet found a placement for this word in a grid; though there is a non-zero probability that the current implementation could. Alternatively one could update `Grid.generate` to consider all possible starting places and all possible paths from each of them. We leave this as an exercise. Parameters ---------- :param index: Index into the current case-folded word. :type index: int :param origin: Grid coordinates from which to start the search. :type origin: Tuple[int, int] :return: Sequence of coordinates of the letters of the tail end of the cased-folded word starting at index or :const:`None`, if the current case-folded word cannot be found. :rtype: Optional[Tuple[Tuple[int, int]]] """ letter: str = case_folded_word[index] for position in grid.moves_from(origin): eliminated = eliminations[index - 1] if eliminated and position in eliminated: continue if letter == grid[position]: if index == end: return deque((position,)) path: Deque[Tuple[int, int]] = find_path(index + 1, position) if path is not None: path.appendleft(position) return path if eliminated: eliminated.add(position) else: eliminations[index - 1] = {position} return None words = sorted((word for word in words if word), key=lambda x: (-len(x), x)) for word in words: case_folded_word: str = word.casefold() # type: ignore end: int = len(case_folded_word) - 1 first_letter: str = case_folded_word[0] eliminations: List[Optional[MutableSet[Tuple[int, int]]]] = [None] * (len(case_folded_word) - 1) for position in grid.occurrences(first_letter): path: Optional[Deque[Tuple[int, int]]] = find_path(1, position) if end > 0 else deque() if path is not None: path.appendleft(position) return word, tuple(path) return None class Grid(object): """ Represents an 8 x 8 grid--presumably--containing letters drawn from one or more alphabets Grid entries are case folded when the grid is instantiated to ensure that case-insensitive comparisons can be made with any (?) alphabet. Implementation notes -------------------- A grid is internally represented as a List[List[str]]. A cell on the grid is accessed by its zero-based row, column coordinate: a `Tuple[int, int]`. All grids are 8 x 8 as indicated by the value of `Grid.size`: `8`. """ __slots__ = ('_grid',) # saves space; good practice for objects with no dynamic membership requirements def __init__(self, grid: Sequence[str]) -> None: assert len(grid) == Grid.size self._grid: List[List[str]] = [] for record in grid: record = Grid._replace_whitespace('', record).casefold() # type: ignore assert len(record) == Grid.size self._grid.append([c for c in record]) def __getitem__(self, position: Tuple[int, int]) -> str: """ Get the letter in a cell on the current grid This method only partially implements `self[key]` semantics. Most notably slicing is not supported. :param position: row, column coordinates of a cell on the current grid :type position: Tuple[int, int] :return: The letter at 'position' on the current grid. :rtype: str :raises IndexError: If 'position' does not specify a location on the current grid. """ return self._grid[position[0]][position[1]] def __str__(self) -> str: """ Get a human readable string representation of the current grid :return: A human readable string representation of the current grid :rtype: str """ return '\n'.join(' '.join(column for column in row) for row in self._grid) @classmethod def generate(cls, words: Iterator[str]) -> Tuple['Grid', Mapping[str, Tuple[str, Tuple[Tuple[int, int],...]]]]: """ Generate a grid containing a set of words that can be found using grid movement rules Use this method to create test grids. An error message is produced for each word that cannot be put on the grid. Randomly generated ASCII characters are used to fill cells not filled by the words or--as explained in the code--partial words we put on the grid. The implementation of this method is rudimentary, but useful for producing test grids and verifying correctness. Parameters ---------- :param words: An iterator over the set of words to be put on to the grid. :type words: Iterator[str] :return: A grid object containing the words or partial words we put on the grid mixed with random ASCII fill characters. :rtype: Grid Example ------- To see this method in action run these statements from a Python 3.6 REPL. A variable number of letters from the German word "Rindfleischetikettierungsueberwachungsaufgabenuebertragungsgesetz" will be placed on the grid:: from find_longest_word import Grid, find_longest_word grid, paths = Grid.generate([ 'foo', 'bar', 'Rindfleischetikettierungsueberwachungsaufgabenuebertragungsgesetz' ]) find_longest_word(grid, ['foo', 'bar', 'rindfleischetikettierun']) grid.save('grid-4') We're OK with this given our intent: generate some useful test grids. As indicated in the above REPL session output you will find the results of example this REPL session in `grid-4'. We did not save the paths created for the words. """ paths: Dict[str, Tuple[str, Tuple[Tuple[int, int], ...]]] = {} missing_data = chr(0) data = [[missing_data] * Grid.size for i in range(0, Grid.size)] for word in words: # Put this word on the grid starting at a random location origins = [(x, y) for x in range(0, Grid.size) for y in range(0, Grid.size)] path: List[Tuple[int, int]] = None row, column = None, None random.shuffle(origins) case_folded_word = word.casefold() # type: ignore def put(letter: str, x: int, y: int) -> bool: if data[x][y] in (missing_data, letter): data[x][y] = letter return True return False index = 0 for row, column in origins: if put(case_folded_word[0], row, column): path = [None] * len(case_folded_word) path[0] = row, column index = 1 break if index == 0: print('could not find a place for any of the letters from', case_folded_word) paths[word] = None else: while index < len(case_folded_word): # Try to put the letter at word[index] on the grid using a sequence of random grid moves # One might try alternative paths the way function find_longest_word does, but we'll # scope that out of this exercise and accept two things: # # * By selecting the first random letter placement that works and not trying alternatives path ways # out chance of failure is high. # * In the failure case this algorithm will leave partial words on the grid. # # We're OK with this given our intent for this method: generate some random grids for testing. moves = [move for move in cls._moves] random.shuffle(moves) put_letter = False for x, y in moves: x, y = row + x, column + y if 0 <= x < Grid.size and 0 <= y < Grid.size: if put(case_folded_word[index], x, y): path[index] = row, column = x, y put_letter = True index += 1 break if not put_letter: break if index < len(case_folded_word): print( 'only placed', index, 'out of', len(case_folded_word), 'letters from', case_folded_word, ':', case_folded_word[:index] ) paths[word] = case_folded_word[:index], tuple(path[:index]) for record in data: for column in range(0, Grid.size): if record[column] == missing_data: record[column] = random.choice(ascii_lowercase) # we do not use a larger alphabet like latin-1 :( return Grid([' '.join(row) for row in data]), paths @classmethod def load(cls, filename: str) -> 'Grid': """ Load a grid from a file :param filename: Name of a file containing a grid. :type filename: str :return: A Grid object :rtype: Grid """ with io.open(filename) as istream: lines: List[str] = istream.readlines() return cls(lines) @classmethod def moves_from(cls, origin: Tuple[int, int]) -> Iterator[Tuple[int, int]]: """ Enumerate the coordinates of cells that can be reached from a cell on the current grid Use this method to obtain the position of each element that can be legally reached from origin. Off-grid moves are--as one should expect--excluded from the enumeration. :param origin: A position on the current grid specified as a row, column coordinate :type origin: Tuple[int, int] :return: An iterator over the coordinates of cells that can be reached from 'origin'. :rtype: Iterator[Tuple[int, int]] """ row, column = origin for move in cls._moves: x, y = row + move[0], column + move[1] if 0 <= x < cls.size and 0 <= y < cls.size: yield x, y def occurrences(self, letter: str) -> Iterator[Tuple[int, int]]: """ Enumerate the coordinates of each occurrence of a letter on the current grid :param letter: A letter which might or might not be on the grid. :type letter: str :return: An iterator over the coordinates of those cells containing 'letter' :rtype: Iterator[Tuple[int, int]] """ for row, record in enumerate(self._grid, 0): column = -1 while True: try: column = record.index(letter, column + 1) except ValueError: break yield row, column def save(self, filename: str) -> None: """ Save the current grid to a file :param filename: Name of the file to which the current grid should be saved. :type filename: str :return: :const:`None` """ with io.open(filename, 'w') as ostream: ostream.write(str(self)) size = 8 # region Protected _moves = [ (-1, +2), # lt 1 up 2 (-1, -2), # lt 1 dn 2 (-2, +1), # lt 2 up 1 (-2, -1), # lt 2 dn 1 (+1, +2), # rt 1 up 2 (+1, -2), # rt 1 dn 2 (+2, +1), # rt 2 up 1 (+2, -1), # rt 2 dn 1 ] _replace_whitespace = re.compile('\s+').sub # endregion if __name__ == '__main__': from argparse import ArgumentParser import sys parser = ArgumentParser( description='Find the longest word from a list of words that can be produced from an 8 x 8 grid of letters', fromfile_prefix_chars='@' ) parser.add_argument('--grid', required=True) parser.add_argument('words', nargs='+') arguments = parser.parse_args(sys.argv[1:]) print(find_longest_word(Grid.load(arguments.grid), arguments.words))
true
c1f7e0d258322ac5b1c97e61b3586cf5805714f6
Python
LHB6540/Python_programming_from_entry_to_practice_code_demo
/part1_4th_list_control/practice4_8_4_9.py
UTF-8
389
4.5625
5
[]
no_license
# 将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3表示。 # 请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for循环将这些立方数都打印出来 # 使用列表解析生成一个列表,其中包含前10个整数的立方 numbers = [value ** 3 for value in range(1, 11)] for i in numbers: print(i)
true
41461624fec1d2c51042ee1e81126ef6b18d2d9a
Python
robbymeals/topicmod
/lib/python_lib/topicmod/corpora/altlaw.py
UTF-8
4,537
2.5625
3
[]
no_license
#!/usr/bin/python __author__ = "Sean Gerrish (sgerrish@cs.princeton.edu)" __copyright__ = "GNU Public License" import datetime import lexicon import os import re import sys import time from nlp import tokenizer from util.pdf_wrapper import PdfOpen, Clean from xml.parsers import expat YEAR_RE = re.compile("(1[89]\d\d|2[01]\d\d)") class AltLawParser(lexicon.Document): def __init__(self, lex): self.parser_ = expat.ParserCreate() self.parser_.StartElementHandler = self.StartElementHandler self.parser_.EndElementHandler = self.EndElementHandler self.parser_.CharacterDataHandler = self.CharacterDataHandler self.elements_ = {} self.body = "" self.date = datetime.datetime(1, 1, 1) self.id = "" self.title = "" self.case_number = "" self.court = "" self.docket = "" lexicon.Document.__init__(self, lex) def Parse(self, pdf_filename, meta_pdf_filename=None): try: pdf_file = PdfOpen(pdf_filename) except RuntimeError: print >>sys.stderr, "Error parsing pdf file. Skipping." raise AssertionError self.body = pdf_file.read() pdf_file.close() if meta_pdf_filename is None: meta_pdf_filename = pdf_filename + ".xml" self.meta_pdf_filename_ = meta_pdf_filename if not os.path.exists(meta_pdf_filename): print >>sys.stserr, ( "No document metadata found (looked in %s)." % meta_pdf_filename) return meta_pdf_file = open(meta_pdf_filename) self.meta_text_ = "".join(meta_pdf_file.readlines()) self.parser_.Parse(self.meta_text_) meta_pdf_file.close() def ParseDate(self, data): data = data.encode("ascii", "ignore") try: self.date = datetime.datetime( *(time.strptime(data, "%Y/%m/%d")[0:6])) return except ValueError: pass try: self.date = datetime.datetime( *(time.strptime(data, "%m/%d/%Y")[0:6])) return except: pass try: date_parts = data.split("/") if len(date_parts[2]) == 2: if len(date_parts[2]) < 10: date_parts[2] = "20" + date_parts[2] elif date_parts[2] > 10: date_parts[2] = "19" + date_parts[2] old_data = data data = "/".join(date_parts) self.date = datetime.datetime(*(time.strptime(data, "%m/%d/%Y")[0:6])) print >>sys.stderr, ( "Warning: inferring possibly ambiguous date string from %s" % old_data) return except: pass try: match_obj = YEAR_RE.search(data) if match_obj: # Don't bother with trying to infer # anything more than the year. self.date = datetime.datetime(int(match_obj.groups()[0]), 1, 1) print >>sys.stderr, ( "Warning: ignoring month and day for document %s" % self.meta_pdf_filename_) return except IOError: pass print >>sys.stderr, ( "Failed to parse date string '%s'" % data) def CharacterDataHandler(self, data): if "case" not in self.elements_: return if "Title" in self.elements_: self.title = data if "Court" in self.elements_: self.court = data if "CaseNum" in self.elements_: self.case_number = data if "Docket" in self.elements_: self.docket = data # Handle the date. if "Released" in self.elements_: self.ParseDate(data) elif "Date" in self.elements_: self.ParseDate(data) elif "DateTimeSize" in self.elements_: self.ParseDate(data) def StartElementHandler(self, name, attrs): if name not in self.elements_: self.elements_[name] = [] self.elements_[name].append(attrs) def EndElementHandler(self, name): assert name in self.elements_ assert len(self.elements_[name]) self.elements_[name].pop() if not len(self.elements_[name]): del self.elements_[name] def TokenizeBody(self): self.Concatenate(tokenizer.Tokenize(self.body_)) def Write(self, fh): lexicon.Document.Write(self, fh)
true
e655ffa94b4ce98610d7935ea1ce92d841de8562
Python
dyjwb001/autoimplant_vnet
/AutoImplant_downsampling/datasets/dataAugmentation.py
UTF-8
3,490
2.703125
3
[]
no_license
import numpy as np import scipy from scipy.ndimage import interpolation def translateit(image, offset, isseg=False): order = 0 if isseg == True else 5 return scipy.ndimage.interpolation.shift(image, (int(offset[0]), int(offset[1]), 0), order=order, mode='nearest') def scaleit(image, factor, isseg=False): order = 0 if isseg == True else 3 height, width, depth= image.shape zheight = int(np.round(factor * height)) zwidth = int(np.round(factor * width)) zdepth = depth if factor < 1.0: newimg = np.zeros_like(image) row = (height - zheight) // 2 col = (width - zwidth) // 2 layer = (depth - zdepth) // 2 newimg[row:row+zheight, col:col+zwidth, layer:layer+zdepth] = interpolation.zoom(image, (float(factor), float(factor), 1.0), order=order, mode='nearest')[0:zheight, 0:zwidth, 0:zdepth] return newimg elif factor > 1.0: row = (zheight - height) // 2 col = (zwidth - width) // 2 layer = (zdepth - depth) // 2 newimg = interpolation.zoom(image[row:row+zheight, col:col+zwidth, layer:layer+zdepth], (float(factor), float(factor), 1.0), order=order, mode='nearest') extrah = (newimg.shape[0] - height) // 2 extraw = (newimg.shape[1] - width) // 2 extrad = (newimg.shape[2] - depth) // 2 newimg = newimg[extrah:extrah+height, extraw:extraw+width, extrad:extrad+depth] return newimg else: return image def resampleit(image, dims, isseg=False): order = 0 if isseg == True else 5 image = interpolation.zoom(image, np.array(dims)/np.array(image.shape, dtype=np.float32), order=order, mode='nearest') if image.shape[-1] == 3: # rgb图像 return image else: return image if isseg else (image-image.min())/(image.max()-image.min()) def rotateit(image, theta, isseg=False): order = 0 if isseg == True else 5 return rotate(image, float(theta), reshape=False, order=order, mode='nearest') def intensifyit(image, factor): return image*float(factor) def flipit(image, axes): if axes[0]: image = np.fliplr(image) if axes[1]: image = np.flipud(image) return image def cropit(image, seg=None, margin=5): fixedaxes = np.argmin(image.shape[:2]) trimaxes = 0 if fixedaxes == 1 else 1 trim = image.shape[fixedaxes] center = image.shape[trimaxes] // 2 if seg is not None: hits = np.where(seg!=0) mins = np.argmin(hits, axis=1) maxs = np.argmax(hits, axis=1) if center - (trim // 2) > mins[0]: while center - (trim // 2) > mins[0]: center = center - 1 center = center + margin if center + (trim // 2) < maxs[0]: while center + (trim // 2) < maxs[0]: center = center + 1 center = center + margin top = max(0, center - (trim //2)) bottom = trim if top == 0 else center + (trim//2) if bottom > image.shape[trimaxes]: bottom = image.shape[trimaxes] top = image.shape[trimaxes] - trim if trimaxes == 0: image = image[top: bottom, :, :] else: image = image[:, top: bottom, :] if seg is not None: if trimaxes == 0: seg = seg[top: bottom, :, :] else: seg = seg[:, top: bottom, :] return image, seg else: return image
true
abd7e138a8496b91491528913c414f27b50ade32
Python
jaymekirchner/mybookmgr
/SqliteHelper.py
UTF-8
6,105
3.6875
4
[]
no_license
import sqlite3 class SqliteHelper: """Creates connection to database and facilitates sqlite queries to create and modify the user's data. METHODS: __init__(self, name = None) Accepts a database name to initialize the database connection and cursor, and call the open() method open(self, name) Attempts to connect to the database with the passed-in name and if it does not exist, the database will be created create_table(self) Creates the books table if it does not already exist create_calendar_table(self) Creates the calendar table if it does not already exist create_filter_table(self) Creates the filter table if it does not already exist insert(self, query, inserts) Executes the insert query with parameterized statements select(self, query): Executes the select query without parameterized statements sort_items(self, query, comparisons): Executes the select query with parameterized statements update(self, query, updates): Executes the update query with parameterized statements delete(self, query) Executes the delete query without parameterized statements filter_items(self, category, data) SQLite query to insert data into results table based on user's filter """ def __init__(self, name = None): """Accepts a database name to initialize the database connection and cursor, and call the open() method. Parameters: name (string) - default is None or user can pass in a database name """ self.conn = None self.cursor = None if name: self.open(name) def open(self, name): """Attempts to connect to the database with the passed-in name and if it does not exist, the database will be created. Raises sqlite3.Error Failed to connect to database """ try: self.conn = sqlite3.connect(name) self.cursor = self.conn.cursor() print(sqlite3.version) except sqlite3.Error as e: print("Failed to connect to database") def create_table(self): """Creates the books table if it does not already exist.""" c = self.cursor c.execute("""CREATE TABLE IF NOT EXISTS books ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, author TEXT NOT NULL, rating INTEGER NOT NULL, genre TEXT NOT NULL, series TEXT NOT NULL, notes TEXT NOT NULL )""") def create_calendar_table(self): """Creates the calendar table if it does not already exist.""" c = self.cursor c.execute("""CREATE TABLE IF NOT EXISTS calendar ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, title TEXT NOT NULL, author TEXT NOT NULL )""") def create_filter_table(self): """Creates the filter table if it does not already exist.""" c = self.cursor c.execute("""CREATE TABLE IF NOT EXISTS results ( id INTEGER NOT NULL, title TEXT NOT NULL, author TEXT NOT NULL, rating INTEGER NOT NULL, genre TEXT NOT NULL, series TEXT NOT NULL, notes TEXT NOT NULL )""") def insert(self, query, inserts): """Executes the insert query. Parameters: query (string) - sqlite query passed in by user with parameterized statements inserts (tuple) - items to be inserted into parameterized sqlite statement """ c = self.cursor c.execute(query, inserts) self.conn.commit() def select(self, query): """Executes the select query without parameterized statements. Parameters: query (string) - sqlite query without parameterized statements """ c = self.cursor c.execute(query) return c.fetchall() #returns a list ([] if no matches) def sort_items(self, query, comparisons): """Executes the select query with parameterized statements. Parameters: query (string) - sqlite query with parameterized statements comparisons (tuple) - items to be inserted into parameterized sqlite statement """ c = self.cursor c.execute(query, comparisons) return c.fetchall() #returns a list ([] if no matches) def update(self, query, updates): """Executes the update query with parameterized statements. Parameters: query (string) - sqlite query with parameterized statements updates (tuple) - items to be inserted into parameterized sqlite statement """ c = self.cursor c.execute(query, updates) self.conn.commit() def delete(self, query): """Executes the delete query without parameterized statements. Parameters: query (string) - sqlite query without parameterized statements """ c = self.cursor c.execute(query) self.conn.commit() def filter_items(self, category, data): """SQLite query to insert data into results table based on user's filter. Parameters: category (string) - category chosen from radio button in filter wizard (author, genre, rating, or notes) data (string) - value selected from drop-down menu in filter wizard """ c = self.cursor query = "INSERT INTO results SELECT * FROM books WHERE "+ category + "= \"" + data +"\"" c.execute(query)
true
c890846fcf46863f4bd4bf521b42a613626677bd
Python
RemcoHalman/PythonTodoAction
/src/utils/writer.py
UTF-8
994
2.984375
3
[]
no_license
import json from .colors import BackgroundColors class Writer(): def put(data, filename): try: jsondata = json.dumps(data, indent=4, skipkeys=False, sort_keys=True) fd = open(filename, 'w') fd.write(jsondata) fd.close() except Exception as e: BackgroundColors.printColor( value=f"ERROR writing: {e.filename}", color=BackgroundColors.WARNING ) pass def get(filename): returndata = {} try: fd = open(filename, 'r') text = fd.read() fd.close() returndata = json.loads(text) print(returndata) except IOError as e: BackgroundColors.printColor( value=f"COULD NOT LOAD: {e.filename}", color=BackgroundColors.FAIL )
true
44200ee2ace0afcc53a3c27af8c2b8c31b178515
Python
johannbrehmer/manifold-flow
/manifold_flow/transforms/standard.py
UTF-8
2,179
2.9375
3
[ "MIT" ]
permissive
"""Implementations of some standard transforms.""" import torch from manifold_flow import transforms class IdentityTransform(transforms.Transform): """Transform that leaves input unchanged.""" def forward(self, inputs, context=None, full_jacobian=False): batch_size = inputs.shape[0] if full_jacobian: jacobian = torch.eye(inputs.shape[1:]).unsqueeze(0) return inputs, jacobian else: logabsdet = torch.zeros(batch_size) return inputs, logabsdet def inverse(self, inputs, context=None, full_jacobian=False): return self(inputs, context, full_jacobian) class AffineScalarTransform(transforms.Transform): """Computes X = X * scale + shift, where scale and shift are scalars, and scale is non-zero.""" def __init__(self, shift=None, scale=None): super().__init__() if shift is None and scale is None: raise ValueError("At least one of scale and shift must be provided.") if scale == 0.0: raise ValueError("Scale cannot be zero.") self.register_buffer("_shift", torch.tensor(shift if (shift is not None) else 0.0)) self.register_buffer("_scale", torch.tensor(scale if (scale is not None) else 1.0)) @property def _log_scale(self): return torch.log(torch.abs(self._scale)) def forward(self, inputs, context=None, full_jacobian=False): batch_size = inputs.shape[0] num_dims = torch.prod(torch.tensor(inputs.shape[1:]), dtype=torch.float) outputs = inputs * self._scale + self._shift if full_jacobian: raise NotImplementedError logabsdet = torch.full([batch_size], self._log_scale * num_dims) return outputs, logabsdet def inverse(self, inputs, context=None, full_jacobian=False): batch_size = inputs.shape[0] num_dims = torch.prod(torch.tensor(inputs.shape[1:]), dtype=torch.float) outputs = (inputs - self._shift) / self._scale if full_jacobian: raise NotImplementedError logabsdet = torch.full([batch_size], -self._log_scale * num_dims) return outputs, logabsdet
true
517faa0b3de1c68c0db59628ef27339d57079b0a
Python
zhuli19901106/hackerrank
/Practice/Algorithms/Sorting/insertionsort1(AC).py
UTF-8
355
2.859375
3
[]
no_license
import re def main(): n = int(raw_input()) a = [int(val) for val in re.split(' ', raw_input())] key = a[n - 1] i = n - 1 while True: if i == 0 or a[i - 1] <= key: a[i] = key print(' '.join([str(val) for val in a])) break else: a[i] = a[i - 1] i -= 1 print(' '.join([str(val) for val in a])) if __name__ == '__main__': main()
true
631cbba81289f8ea79e44776cc21f6318decc581
Python
atashi/LLL
/algorithm/328.odd-even-linked-list.py
UTF-8
1,740
3.484375
3
[]
no_license
# # @lc app=leetcode id=328 lang=python # # [328] Odd Even Linked List # # https://leetcode.com/problems/odd-even-linked-list/description/ # # algorithms # Medium (48.41%) # Total Accepted: 137.7K # Total Submissions: 284.3K # Testcase Example: '[1,2,3,4,5]' # # Given a singly linked list, group all odd nodes together followed by the even # nodes. Please note here we are talking about the node number and not the # value in the nodes. # # You should try to do it in place. The program should run in O(1) space # complexity and O(nodes) time complexity. # # Example 1: # # # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # # # Example 2: # # # Input: 2->1->3->5->6->4->7->NULL # Output: 2->3->6->7->1->5->4->NULL # # # Note: # # # The relative order inside both the even and odd groups should remain as it # was in the input. # The first node is considered odd, the second node even and so on ... # # # # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head total = 1 last = head while last.next: last = last.next total += 1 h = head i = 1 while i <= total // 2 and h.next.next: # 取出下一个节点,不破坏链表结构 next = h.next h.next = h.next.next # 取出节点放到最后 last.next = next last = last.next last.next = None h = h.next i += 1 return head
true
5359bccdf0a7b9c943e7c48aa8aefa3a274afcbc
Python
kmollee/2014_fall_cp
/4/practice_scripts/flashcards.py
UTF-8
702
3.78125
4
[]
no_license
# sys is a module. It lets us access command line arguments, which are # stored in sys.argv. import sys if len(sys.argv) < 2: print "Please supply a flash card file." exit(1) flashcard_filename = sys.argv[1] with open(flashcard_filename, 'r') as f: for line in f.readlines(): # line format is: # question,answer # strip() removes any trailing whitespace (like newlines). # split(",") turns a string into a list of elements, split on ','. question, answer = line.strip().split(",") print "Question: " + question raw_input("> Press return to show answer ") print "Answer: " + answer print "" # Print an empty line.
true
fa1376606b86dfec2185c70f1a29b32a9abebdb3
Python
RoshaniPatel10994/ITCS1140---Python-
/final exam/exam example.py
UTF-8
1,609
4.15625
4
[]
no_license
# For loop def LoadLists(): sales = [0]*12 one_sale = float() for index in range (0, len(sales)): one_sale = float(input("Enter monthly sales: ")) sales[index]=one_sale return sales #Determine Total def DetermineTotal(sales): one_sale = float() total = float() for index in range (0, len(sales)): one_sale = sales[index] total = total + one_sale return total #Determine Average def DetermineAverage(total): average = float() average = total/12 return average #FindHighest def FindHighest(sales): high = float() one_sale = float() for index in range (0, len(sales)): one_sale = sales[index] if one_sale >high: high = one_sale return high def FindLowest(sales): low = float() one_sale = float() low = sales[0] for index in range (0, len(sales)): one_sale = sales[index] if one_sale < low: low = one_sale return low # Call main def main(): monthly_sales = [0]*12 total_sales = float() average_sales = float() high_sales = float() low_sales = float() monthly_sales = LoadLists() total_sales = DetermineTotal(monthly_sales) average_sales = DetermineAverage(total_sales) high_sales = FindHighest(monthly_sales) low_sales = FindLowest(monthly_sales) #Print print("Total sales: ", total_sales) print("Average sales: ", average_sales) print("Highest sales: ", high_sales) print("Lowest sales: ", low_sales) main()
true
973cbd13835591797898446c503195069525be86
Python
OlgaUlrich/prework
/PY-Training/13.py
UTF-8
344
3.6875
4
[]
no_license
def prime_number(n): if n<=0: return "Input positive number, please" elif n == 1: return [] elif n == 2: return [2] else: primeNum = [2, 3] for i in range(3, n+1): if i % 2 != 0 and i % 3 != 0: primeNum.append(i) return primeNum print(prime_number(6))
true
80169d5cf53103156489d0220924149e2a14dd4d
Python
elllot/Algorithms
/Strings/longestCommonSubsequence.py
UTF-8
491
3.375
3
[]
no_license
def lcs(word1, word2): row = [0 for _ in range(len(word1) + 1)] for r in range(1, len(word2)+1): prev = 0 for c in range(1, len(row)): val = prev + 1 if word2[r-1] != word1[c-1]: val = max(row[c-1], row[c]) row[c], prev = val, row[c] return row[-1] if __name__ == '__main__': one = 'aggtab' two = 'gxtxayb' print(lcs(one, two)) three = 'abcdgh' four = 'aedfhr' print(lcs(three, four))
true
b28023b698c2cdb87ebcf25329d503e1c3672958
Python
nishant5254/Loop-Structure
/Alphabet2.py
UTF-8
237
3.796875
4
[]
no_license
Number_rows=int(input("Enter the no of rows you want to print: ")) Number=65 for i in range(0,Number_rows): for j in range(0,i+1): ch=chr(Number) print(ch,end=" ") Number=Number+1 Number=65 print("\n")
true
afe2539f9603a6843c7292e59e4e13106e70890a
Python
buihoang95/dialogue-act-project
/src/convertToCRFData.py
UTF-8
1,057
2.625
3
[]
no_license
import codecs import os import csv import re dialogueList = [] file = open('data/normallizedCRF/' + "CRFdata" + '.csv','wb') def convertDataToNormalizeData(fileName): overallData=[] with open('data/normallized/' + fileName + '.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in spamreader: break data=[] count = 0 for row in spamreader: item=row[0].split(':::'); item[1]=item[1].split(':')[0] data.append('<'+item[1]+'>'+item[0]+'</'+item[1]+'>') count+=1 if(count == 15): overallData.append(' '.join(data)) data=[] count=0 file.write('Data') file.write('\n') file.write('\n'.join(overallData)) def main(): for file in os.listdir('./data/normallized'): if file.endswith('.csv'): file_name = file[:-4] convertDataToNormalizeData(file_name) if __name__ == '__main__': main()
true
ac39f7558d25cda02c7e82646a853610b6e0d2fb
Python
npinto/craigslistParser
/gmail.py
UTF-8
2,336
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
#!/usr/bin/python # -*- coding: utf-8 -*- import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders import os # modified from # http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html class Gmail(): def __init__(self, gmail_username, gmail_password): self.gmail_user = gmail_username self.gmail_pwd = gmail_password def mail(self, to, subject, text, cc = None, attach = None): msg = MIMEMultipart() msg['From'] = self.gmail_user msg['To'] = to msg['Subject'] = subject if cc is not None: msg['CC'] = cc msg.attach(MIMEText(text)) if attach: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() print mailServer.login(self.gmail_user, self.gmail_pwd) mailServer.sendmail(self.gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() if __name__ == "__main__": # quick hardcoded cmd line import sys from pprint import pprint fin = open(sys.argv[1]) fnames = [fname.split()[0] for fname in fin.readlines()] txts = [open(fname).read() for fname in fnames] emails = [fname.split('__grading.txt')[0].split('/')[-1] for fname in fnames] pprint(emails) # init GMail object with user/pass from getpass import getpass print "*"*80 username = raw_input("Gmail account name: ") password = getpass("Password: ") gm = Gmail(username, password) print "*"*80 cc = "pinto@mit.edu" for email, txt in zip(emails, txts): to = email # DEBUG: "pinto@mit.edu" subject = "CS264 HW4 Grade (%s)" % email msg = txt attach = None # could be attach = "/path/to/file" print email, gm.mail(to, subject, msg, cc=cc, attach=attach)
true
6e842c09073784a1a2fb13e02ee2ce6e4c5d5e48
Python
KushalkumarUmesh/Internal-Initiative
/GoalSheet/empDash_Goalsheet_OnlineExam/realapp/modules/bcsdata/bcscheckclaims.py
UTF-8
9,909
2.640625
3
[ "Apache-2.0" ]
permissive
""" Overall Approach is as follows: Re-write the entire BCS-CHeck program. DO it in this order: 0) Creat main loop and view-file a) Create Holiday Table - Done b) Write methods for: -IsHoliday? -Hours booked by Emp on a day, on a project : Total billable hours -Is the emp on leave today? Is the leave approved? c) Write methods for Error recording: Need to define a table d) Methods for error-detection e) Aggregate metrics = For employee = For DC-Leads = For Org = YTD, MTD Values TODO: a) Bug: Total claimed hours does not include hours booked on Sunday - Pragnya.Senapati@msg-global.com """ import logging from flask_sqlalchemy import SQLAlchemy from sqlalchemy import and_ import datetime import os from bcsorgstruct import * from bcsdomain import * from projdomain import * from bcsmodel import * import calendar from emailstrings import * from hrmsempdata import getEmpDictbyEmail from notification import notify from hrmsdomain import getAllEmployees #### THIS NOT A VIEW FILE, views are being created only for testing to be moved to another file #Method for genering error-log for each employee #Overall structure is as follows: # For Each employee, For each day: # Get bookings, get leave info # Calculate agreegates # Calcuate Utiization def validEmpBcsData(empEmail,month, year, mrange ) : messageBuffer = [] bookedHours = 0 # Total billable and non-billable hours booked billableHours = 0 # Initialize total billable hours available totalLeaveHours = 0 # Total Leave approved totalLeaveAppliedHours = 0 # Total Leave Applied For (not yet approved) errorcount = 0 projBillableHash = dict() # Is the project billable? Not used projNameHash = dict() # Project Name projList = dict() # Hash of emp-hash hours e = empEmail # For convenience for d in range(1,mrange) : #Extremely inefficent, brute force, but also safest course of action day = datetime.date(year,month,d) dayOfWeek = day.weekday() wd = (dayOfWeek <= 4) and not isHoliday(day) # WorkingDay if true if wd : billableHours += 8 # Add 8 billable hours #Get Leave data ONLY if it is a working-date (leaveHours,leaveHoursApplied) = getLeaveInfo(e,day) totalLeaveHours += leaveHours totalLeaveAppliedHours += leaveHoursApplied #Emp. can work on weekends/holidays, so the processing need to be completed bookings = EmpBCSClaimData.query.filter_by(bookingDate = day).\ filter_by(empEmail = e).all() daysBooking = 0 # this day, this employe, store separately for b in bookings: # All bookings for this day project_ID = b.project_ID.strip() projectName = b.projectName.strip() billability = b.billability.strip() duration = b.duration empEmail = b.empEmail # Should be same as "e", no need to check...its part of the filter_by projBillableHash[project_ID] = billability projNameHash[project_ID] = projectName fduration = float(duration) #Convert String to float if (round(fduration*60) == 8 or round(fduration*60) == 4 ) : # Person has claimed min instead of hours msg = "WARNING:%s:Looks like MINUTES instead of HOURS on Project:%s" % (day.strftime('%Y-%m-%d'),projectName) logEmpBCSMessage(messageBuffer, msg ) # logEmpError(e, msg) daysBooking += fduration # Hours booked only today, all projects: Used for checking if project_ID in projList.keys() : # Project is already encountered if empEmail in projList[project_ID] : #Emp in this project encountered projList[project_ID][empEmail] += fduration #Add the hours else : projList[project_ID][empEmail] = fduration else : projList[project_ID] = dict() projList[project_ID][empEmail] = fduration #Start checking for various errors #No claim found if wd and not daysBooking and leaveHours != 8 : logEmpBCSMessage(messageBuffer, "REMINDER:%s:No booking or approved leave found, please book your hours." % (day.strftime('%Y-%m-%d')) ) errorcount += 1 #Total 8 hours claimed if leave was applied for if wd and daysBooking and (leaveHours or leaveHoursApplied) and \ ( (daysBooking + leaveHours) != 8 and (daysBooking + leaveHoursApplied) != 8) : logEmpBCSMessage(messageBuffer, "WARNING:%s:Hours Booked AND Leave(applied for) do not add-up to 8 hours" % (day.strftime('%Y-%m-%d') ) ) errorcount += 1 if wd and daysBooking > 8 : logEmpBCSMessage(messageBuffer, "INFORMATION:%s:More than 8 Hours(%d) Booked on a single day" % ( day.strftime('%Y-%m-%d'), daysBooking ) ) errorcount += 1 if errorcount : logEmpBCSMessage(messageBuffer, "Total %d discrepencies identified in BCS booking for month of %s" % \ (errorcount, calendar.month_name[month])) else : logEmpBCSMessage(messageBuffer, "Thanks for claiming BCS correctly. No errors detected") #Aggregate errors and messages billedHours = 0 # logEmpBCSMessage(messageBuffer, "") # logEmpBCSMessage(messageBuffer, "Utilization Summary:") bcsUtilSummary = dict() bcsProjSummary = dict() for pid in projList.keys() : for e in projList[pid].keys() : # logEmpBCSMessage(messageBuffer, "Project[%s]:Hours[%s]" % (projNameHash[pid], str(projList[pid][e]))) bcsProjSummary[pid] = "Project[%s]:Hours[%s]" % (projNameHash[pid], str(projList[pid][e])) if projBillableHash[pid] != 'N/B' : billedHours += projList[pid][e] bookedHours += projList[pid][e] bcsUtilSummary["AvailableHours"] = billableHours bcsUtilSummary["BookedHours"] = bookedHours bcsUtilSummary["BilledHours"] = billedHours bcsUtilSummary["LeaveHours"] = totalLeaveHours # logEmpBCSMessage(messageBuffer, "Available Hours[%d], Booked Hours[%d], Billed Hours[%d]" % \ # (billableHours, bookedHours,bookedHours)) return (messageBuffer, bcsProjSummary, bcsUtilSummary) def getLeaveInfo(e,day) : #Get Leave Data leaves = EmpBCSLeaveData.query.filter_by(empEmail = e).filter(and_(EmpBCSLeaveData.dateStart <= day, EmpBCSLeaveData.dateEnd >= day)).all() leaveHours = 0 leaveHoursApplied = 0 for l in leaves: #Leave record # print("Leave:[%s]:%s:Start=%s:End=%s:Hours:%s" %(str(day), e, str(l.dateStart), str(l.dateEnd), str(l.duration)) ) dur = float(l.duration[:-1]) #status ='Applied For' and 'Approved'. Others (planned, rejected, etc.) are ignored if l.status == 'Approved': if dur >=1 : leaveHours += 8 else : leaveHours += 4 if l.status == 'Applied For': if dur >=1 : leaveHoursApplied += 8 else : leaveHoursApplied += 4 # print("Half Day Leave:[%s]:%s:%s:%s:Hours:%s" %(str(day), e, str(l.dateStart), str(l.dateEnd), str(l.duration)) ) return(leaveHours,leaveHoursApplied) def isHoliday(day) : fetch = Holidays.query.filter_by(date = day).first() return fetch def logEmpBCSMessage(messageBuffer, message) : messageBuffer += [message] return def formatMessageBuffer(messList) : str = htmlhead + "<table>" for m in messList : str += "<tr><td>" + m + "</td></tr>" str += "</table>" + hrmsfooter + htmlfooter return str def emailBCSInfoToEmp(empEmail,date, fullmsgbuf, bcsProjSummary, bcsUtilSummary) : #Get emp Details empDict = getEmpDictbyEmail(empEmail) #Form Message subject ="BCS Booking and Error Summary:" + date.strftime('%d-%m-%y') message = htmlhead + "<h4>Summary for : " + empDict["FIRST_NAME"] + " " + empDict["LAST_NAME"] +"</h4>" message = "<h4>This is in BETA Test. Kindly help by pointing out any errors to K.Srinivas.</h4>" tstr = "<table>" for m in fullmsgbuf : tstr += "<tr><td>" + m + "</td></tr>" tstr += "</table>" message += tstr message += "<h3>Available Hours[%d], Booked Hours[%d], Billed Hours[%d] and Leave Hours[%d]</h3>" % \ (bcsUtilSummary["AvailableHours"], bcsUtilSummary["BookedHours"], \ bcsUtilSummary["BilledHours"],bcsUtilSummary["LeaveHours"] ) message += hrmsfooter + htmlfooter #Send e-mail notify(empEmail, "BETA:" + subject , message , templateId="-1") def emailBCSInfoToPMO (date, allErrors ) : #Form Message subject = "BCS Booking Errors-All:" + date.strftime('%d-%m-%y') message = "<h4>Error Summary for all employees</h4>" message = "<h4>This is in BETA Test. Kindly help by pointing out any errors to K.Srinivas.</h4>" tstr = "<table>" for m in allErrors : tstr += "<tr><td>" + m + "</td></tr>" tstr += "</table>" message += tstr message += hrmsfooter notifyGroup("PMO", "BETA:" + subject , htmlhead+ message+ htmlfooter, fromemail = "bcs-checkbookings@msg-global.com") return message def checkBCSEmailsWithHRMS(nameHash) : retStr = "" emps = getAllEmployees() empDict = {e.OFFICE_EMAIL_ID.lower():e.OFFICE_EMAIL_ID for e in emps } for n in nameHash.values() : if n.lower() not in empDict.keys() : retStr += ":" + n if retStr: return ("Following BCS-Emails not in HRMS:" + retStr) return("") ############################################################################################################## ### Stuff below is the old one that will not work with DB ######################################################### ##############################################################################################################
true
ecb19ef29d81b9d52502d24eff26bf36e82243df
Python
Ray980625/python200818
/turtle5.py
UTF-8
120
3.9375
4
[]
no_license
import turtle a = turtle.Turtle() b = int(input('邊數:')) for i in range(b): a.forward(100) a.left(360/b)
true
c11bd21069ace24167a3d9e341c9e0c818166b6f
Python
Elliotcomputerguy/LearningPython
/ListMethods.py
UTF-8
4,862
4.46875
4
[]
no_license
#!/usr/bin/env python # Methods are just like functions, except they are attached to a non-module value with a period. # A function is not a method just because it is in a module. It can some times get confusing. # Appending list elements via the method append() is the easiest solution rather than concatenating. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] sneakers.append('Zanotti') sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] newListName = ['Zanotti'] for element in range(len(sneakers)): newListName.append(sneakers[element]) print(newListName) # =============================================================== # If you want to insert a new item at any position you can use the insert() method. If you specify a position that is already allocated # it will not remove the element but change the position of the element. You specify the index and then the element you want to add. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] sneakers.insert(0, 'Zanotti') print(sneakers) # = ['Zanotti', 'Jordan', 'Nike', 'Yeezy', 'Adidas'] print(sneakers[0]) # = Zanotti print(sneakers[1]) # = Jordan # =============================================================== # Sometimes you will want to use a list element after removing it from the list. The pop() method allows you do just this. # If you do not pass an argument into the pop() method it will remove the last element in the list. To choose which element # you want to remove add the index position. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] popVariable = sneakers.pop() print(sneakers) print(popVariable) popVariable = sneakers.pop(0) print(sneakers) print(popVariable) # =============================================================== # How to pop in a nested list. # =============================================================== # Example: sneakers = [['Nike', 'Yeezy', 'Jordan', 'Adidas', 'Zanotti'],[8, 7, 9, 6, 5]] popped = sneakers[0].pop(0) popped1 = sneakers[1].pop(0) print(popped) print(popped1) # =============================================================== # if you only know the value of the list element you can use the remove() method. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] removeItem = 'Adidas' def func(): print(f'List item located. Removing item {removeItem}') if removeItem.upper() in sneakers: func() sneakers.remove(removeItem.upper()) elif removeItem.lower() in sneakers: func() sneakers.remove(removeItem.lower()) elif removeItem.capitalize() in sneakers: func() sneakers.remove(removeItem.capitalize()) else: print('Cannot locate List item') print(sneakers) # =============================================================== # Most likely when items are assigned to a list they are in a unpredicable order. To sort a list alphabetically or in reverse order # you can use the sort() method. You can either sort the list permanently or just display sorted list in the print() function. # When all values are not in lowercase sorting a list alphabetically is a little more complicated. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] print(sorted(sneakers)) #<-- Only print out the list in alphabetical order. If used with numbers will put them in numerical order. print(sneakers) sneakers.sort() #<-- Permanently sort the list alphabetically. print(sneakers) sneakers.sort(reverse=True) #<-- sort list in Reverse alphabetical order. Will reverse numerical order. Good for scores by keeping highest at top. sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] for sneaker in sorted(sneakers): print(sneaker) # =============================================================== # To reverse the list you can use the reverse() method. Again there is no way to just print this and # will be a permanent change. To reverse it back you simply rerun the reverse() method # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] sneakers.reverse() print(sneakers) sneakers.reverse() print(sneakers) # =============================================================== # Index method will return the integer index position of the list element. # If there are duplicates of the element then it will produce the first found. # =============================================================== # Example: sneakers = ['Jordan', 'Nike', 'Yeezy', 'Adidas'] sneakers.index('Jordan') # ===============================================================
true
6186d1b4608c02daf821f260c746d331d11be57e
Python
wattaihei/ProgrammingContest
/Codeforces/ECR84/probA.py
UTF-8
204
2.75
3
[]
no_license
import sys input = sys.stdin.readline Q = int(input()) Query = [list(map(int, input().split())) for _ in range(Q)] for n, k in Query: ok = k**2 <= n and (n-k)%2 == 0 print("YES" if ok else "NO")
true
18e4d911d7500fc1807d7f39796530bf88a2f257
Python
AnimState/AnimX_2018
/repivot.py
UTF-8
2,484
2.890625
3
[]
no_license
""" Copyright (c) 2018 Mike Malinowski 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. """ """ This is a simple re-pivoting tool which allows you to select an object you want to animate, and an object you want to animate it from. It will map all the motion of the object onto the new pivot object and allow you to manipulate the object from that pivot. You can then keep running this to change the pivot as and hwen you need. By Mike Malinowski www.twisted.space """ import pymel.core as pm # -- Assume a selection order. The first object is the object # -- we want to drive, the second object is the object we want # -- to use as a new pivot point driven = pm.selected()[0] driver = pm.selected()[1] # -- We need to map the motion of the soon-to-be driven # -- object onto our driver cns = pm.parentConstraint( driven, driver, maintainOffset=True, ) pm.bakeResults( driver, time=[ pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True), ], simulation=True, ) # -- Now remove the constraint, and ensure there are no # -- constraints on the soon-to-be driven object pm.delete(cns) constraints = list() for child in driven.getChildren(): if isinstance(child, pm.nt.Constraint): constraints.append(child) pm.delete(constraints) # -- Now we can constrain the driven to our new driver and # -- we should get the same result, but we can manipulate # -- it from our new space pm.parentConstraint( driver, driven, maintainOffset=True, )
true
7f27b0263fab50ba716c24013ce1ce5d95f4b73a
Python
openjason/refer
/listmysqldatabases.py
UTF-8
5,432
2.953125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 import json import pymysql class Mysql(object): # mysql 端口号,注意:必须是int类型 def __init__(self, host, user, passwd, port, db_name): self.host = host self.user = user self.passwd = passwd self.port = port self.db_name = db_name def select(self, sql): """ 执行sql命令 :param sql: sql语句 :return: 元祖 """ try: conn = pymysql.connect( host=self.host, user=self.user, passwd=self.passwd, port=self.port, database=self.db_name, charset='utf8', cursorclass=pymysql.cursors.DictCursor ) cur = conn.cursor() # 创建游标 # conn.cursor() cur.execute(sql) # 执行sql命令 res = cur.fetchall() # 获取执行的返回结果 cur.close() conn.close() return res except Exception as e: print(e) return False def get_all_db(self): """ 获取所有数据库名 :return: list """ # 排除自带的数据库 exclude_list = ["sys", "information_schema", "mysql", "performance_schema"] sql = "show databases" # 显示所有数据库 res = self.select(sql) # print(res) if not res: # 判断结果非空 return False db_list = [] # 数据库列表 for i in res: db_name = i['Database'] # 判断不在排除列表时 if db_name not in exclude_list: db_list.append(db_name) # print(db_name) if not db_list: return False #保存结果数据库列表 with open('dblist.txt','w') as fp: for oneitem in db_list: fp.write(oneitem+'\n') return db_list def get_user_list(self): """ 获取用户列表 :return: list """ # 排除自带的用户 exclude_list = ["root", "mysql.sys", "mysql.session"] sql = "select User from mysql.user" res = self.select(sql) # print(res) if not res: # 判断结果非空 return False user_list = [] for i in res: db_name = i['User'] # 判断不在排除列表时 if db_name not in exclude_list: user_list.append(db_name) if not user_list: return False return user_list def get_user_power(self): """ 获取用户权限 :return: {} { "test":{ # 用户名 "read":["db1","db2"], # 只拥有读取权限的数据库 "all":["db1","db2"], # 拥有读写权限的数据库 }, ... } """ info_dict = {} # 最终结果字典 # 获取用户列表 user_list = self.get_user_list() if not user_list: return False # 查询每一个用户的权限 for user in user_list: # print("user",user) sql = "show grants for {}".format(user) res = self.select(sql) if not res: return False for i in res: key = 'Grants for {}@%'.format(user) # print("key",key) # 判断key值存在时 if i.get(key): # print(i[key]) # 包含ALL或者SELECT时 if "ALL" in i[key] or "SELECT" in i[key]: # print(i[key]) if not info_dict.get(user): info_dict[user] = {"read": [], "all": []} cut_str = i[key].split() # 空格切割 # print(cut_str,len(cut_str)) power = cut_str[1] # 权限,比如ALL,SELECT if len(cut_str) == 6: # 判断切割长度 # 去除左边的` tmp_str = cut_str[3].lstrip("`") else: tmp_str = cut_str[4].lstrip("`") # 替换字符串 tmp_str = tmp_str.replace('`.*', '') value = tmp_str.replace('\_', '-') # 判断权限为select 时 if power.lower() == "select": if value not in info_dict[user].get("read"): # 只读列表 info_dict[user]["read"].append(value) else: if value not in info_dict[user].get("all"): # 所有权限列表 info_dict[user]["all"].append(value) # print(info_dict) return info_dict if __name__ == '__main__': host = "10.88.23.199" user = "it" passwd = "007" port = 3306 db_name = "mysql" obj = Mysql(host, user, passwd, port, db_name) all_db_list = obj.get_all_db() user_power = obj.get_user_power() print("all_db_list",all_db_list) print("user_power",user_power)
true
12446d8dbf64982ed30939ac150028c1ebc1ee8e
Python
soko48653a/MSE_Python
/ex010.py
UTF-8
188
3.484375
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: #예제 10번 : 5/3의 결과를 화면에 출력하세요. print(5/3) # print(A) -> A를 출력 ( 숫자 또는 연산으로 구성)
true
f2b59c0312f88057f785a4efb009f5f04c28abe4
Python
Safankov/NureQ_bot
/controller.py
UTF-8
17,202
2.59375
3
[]
no_license
import math import json import random from router import command_handler, response_handler, callback_handler, \ default_callback_handler, default_command_handler, default_response_handler NEW_QUEUE_COMMAND_RESPONSE_TEXT \ = "Введите имя новой очереди в ответ на это сообщение" DEFAULT_QUEUES_PAGE_SIZE = 3 class ButtonCallbackType: NOOP = 1 SHOW_NEXT_QUEUE_PAGE = 2 SHOW_PREVIOUS_QUEUE_PAGE = 3 SHOW_QUEUE = 4 ADD_ME = 5 CROSS_OUT = 6 UNCROSS_OUT = 7 REMOVE_ME = 8 class Controller: def __init__(self, telegram_message_manager, repository): self.telegram_message_manager = telegram_message_manager self.repository = repository @command_handler("/start") @command_handler("/start@NureQ_bot") def handle_start_command(self, message): self.telegram_message_manager.send_message( message["chat"]["id"], "Йоу" ) @command_handler("/newqueue") @command_handler("/newqueue@NureQ_bot") def handle_new_queue_command(self, message): self.telegram_message_manager.send_message( message["chat"]["id"], NEW_QUEUE_COMMAND_RESPONSE_TEXT, reply_markup={"force_reply": True} ) @command_handler("/showqueue") @command_handler("/showqueue@NureQ_bot") def handle_show_queue_command(self, message): self.handle_generic_queue_command( message, ButtonCallbackType.SHOW_QUEUE, "Выберите очередь, которую хотите посмотреть." ) @command_handler("/crossout") @command_handler("/crossout@NureQ_bot") def handle_cross_out_command(self, message): self.handle_generic_queue_command( message, ButtonCallbackType.CROSS_OUT, "Выберите очередь, из которой необходимо вычеркнуть участника" ) @command_handler("/uncrossout") @command_handler("/uncrossout@NureQ_bot") def handle_uncross_out_command(self, message): self.handle_generic_queue_command( message, ButtonCallbackType.UNCROSS_OUT, "Выберите очередь, в которую необходимо вернуть участника" ) @command_handler("/addme") @command_handler("/addme@NureQ_bot") def handle_add_me_command(self, message): self.handle_generic_queue_command( message, ButtonCallbackType.ADD_ME, "Выберите очередь, в которую хотите добавиться." ) @command_handler("/removeme") @command_handler("/removeme@NureQ_bot") def handle_remove_me_command(self, message): self.handle_generic_queue_command( message, ButtonCallbackType.REMOVE_ME, "Выберите очередь, которую хотите покинуть." ) @response_handler(NEW_QUEUE_COMMAND_RESPONSE_TEXT) def handle_new_queue_response(self, message): queue_name = message["text"] error = self.repository.create_queue(queue_name) if error == "INTEGRITY_ERROR": self.telegram_message_manager.send_message( message["chat"]["id"], "Очередь с именем " + queue_name + " уже существует" ) return self.repository.commit() self.telegram_message_manager.send_message( message["chat"]["id"], "Создана новая очередь: " + queue_name ) @callback_handler(ButtonCallbackType.ADD_ME) def handle_add_me_callback( self, callback_query, callback_query_data ): try: username = callback_query["from"]["username"] queue_id = callback_query_data["queue_id"] error = self.repository.add_me_to_queue(username, queue_id) self.repository.commit() queue_name = self.repository.get_queue_name_by_queue_id(queue_id) if error == "DUPLICATE_MEMBERS": self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"@{username} уже состоит в данной очереди: {queue_name}" ) return if error == "NO_QUEUE": self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "Данной очереди не существует: " + queue_name ) return self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"@{username} добавлен(а) в очередь: {queue_name}" ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.CROSS_OUT) def handle_cross_out_callback( self, callback_query, callback_query_data ): try: queue_id = callback_query_data["queue_id"] username = self.repository.find_uncrossed_queue_member(queue_id) queue_name = self.repository.get_queue_name_by_queue_id(queue_id) if username is None: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "В данной очереди не осталось участников: " + queue_name ) return self.repository.cross_out_the_queue_member(username, queue_id) self.repository.commit() self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"Участник @{username} вычеркнут из очереди: {queue_name}" ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.UNCROSS_OUT) def handle_uncross_out_callback( self, callback_query, callback_query_data ): try: queue_id = callback_query_data["queue_id"] username = self.repository.find_last_crossed_queue_member(queue_id) queue_name = self.repository.get_queue_name_by_queue_id(queue_id) if username is None: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "В данной очереди не осталось подходящих участников: " + queue_name ) return self.repository.uncross_out_the_queue_member(username, queue_id) self.repository.commit() self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"Участник @{username} снова в очереди: {queue_name}" ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.REMOVE_ME) def handle_remove_me_callback( self, callback_query, callback_query_data ): try: username = callback_query["from"]["username"] queue_id = callback_query_data["queue_id"] queue_name = self.repository.get_queue_name_by_queue_id(queue_id) success \ = self.repository.remove_user_from_queue(username, queue_id) if not success: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"@{username} не состоит в данной очереди: {queue_name}" ) return self.repository.commit() self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], f"Участник @{username} удален из очереди: {queue_name}" ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.NOOP) def handle_noop_callback(self, callback_query, callback_query_data): self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.SHOW_NEXT_QUEUE_PAGE) def handle_show_next_queue_page_callback( self, callback_query, callback_query_data ): try: main_button_type = callback_query_data["main_button_type"] queue_pagination_reply_markup \ = build_queue_pagination_reply_markup( self.repository, page_index=callback_query_data["page_index"] + 1, page_size=DEFAULT_QUEUES_PAGE_SIZE, main_button_type=main_button_type ) if queue_pagination_reply_markup is None: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "Пока что нету ни одной доступной очереди." ) return self.telegram_message_manager.edit_message_reply_markup( callback_query["message"]["chat"]["id"], callback_query["message"]["message_id"], queue_pagination_reply_markup ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.SHOW_PREVIOUS_QUEUE_PAGE) def handle_show_previous_queue_page_callback( self, callback_query, callback_query_data ): try: main_button_type = callback_query_data["main_button_type"] queue_pagination_reply_markup \ = build_queue_pagination_reply_markup( self.repository, page_index=callback_query_data["page_index"] - 1, page_size=DEFAULT_QUEUES_PAGE_SIZE, main_button_type=main_button_type ) if queue_pagination_reply_markup is None: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "Пока что нету ни одной доступной очереди." ) return self.telegram_message_manager.edit_message_reply_markup( callback_query["message"]["chat"]["id"], callback_query["message"]["message_id"], queue_pagination_reply_markup ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @callback_handler(ButtonCallbackType.SHOW_QUEUE) def handle_show_queue_callback(self, callback_query, callback_query_data): try: queue_id = callback_query_data["queue_id"] queue_name = self.repository.get_queue_name_by_queue_id(queue_id) if queue_name is None: self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "Очереди с ID: " + queue_id + " не существует" ) return queue_members \ = self.repository.get_queue_members_by_queue_id(queue_id) if len(queue_members) != 0: queue_description = f"{queue_name}:\n" + "".join(map( lambda member_index: member_index[1].format_queue_string( member_index[0] + 1 ), enumerate(queue_members) )) else: queue_description = f"{queue_name}:\nОчередь пуста" self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], queue_description, parse_mode="HTML" ) finally: self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @default_callback_handler def handle_unknown_callback(self, callback_query, callback_query_data): callback_type = callback_query_data["type"] print(f"Received an unknown callback query type: {callback_type}") self.telegram_message_manager.send_message( callback_query["message"]["chat"]["id"], "???" ) self.telegram_message_manager.answer_callback_query( callback_query["id"] ) @default_command_handler @default_response_handler def handle_unknown_response(self, message): self.telegram_message_manager.send_message( message["chat"]["id"], "???" ) def handle_error_while_processing_update(self, update): if "message" in update: chat_id = update["message"]["chat"]["id"] elif "callback_query" in update: chat_id = update["callback_query"]["message"]["chat"]["id"] else: return self.telegram_message_manager.send_message(chat_id, "Ошибка") def handle_generic_queue_command( self, message, main_button_type, success_message ): queue_pagination_reply_markup = build_queue_pagination_reply_markup( self.repository, page_index=1, page_size=DEFAULT_QUEUES_PAGE_SIZE, main_button_type=main_button_type ) if queue_pagination_reply_markup is None: self.telegram_message_manager.send_message( message["chat"]["id"], "Пока что нету ни одной доступной очереди." ) return self.telegram_message_manager.send_message( message["chat"]["id"], success_message, queue_pagination_reply_markup ) def build_queue_pagination_reply_markup( repository, page_index, page_size, main_button_type ): total_queue_count = repository.get_total_queue_count() if total_queue_count == 0: return None queues_page = repository.get_queues_page( page_index, page_size ) queue_choice_buttons = make_queue_choice_buttons( queues_page, page_index, page_size, total_queue_count, main_button_type ) return {"inline_keyboard": queue_choice_buttons} def make_queue_choice_buttons( queues_page, page_index, page_size, total_queue_count, main_button_type ): total_page_count = math.ceil(total_queue_count / page_size) is_first_page = page_index == 1 is_last_page = page_index == total_page_count return list(map( lambda queue: [ { "text": queue.name, "callback_data": json.dumps({ "type": main_button_type, "queue_id": queue.id, }), } ], queues_page )) + [[ { "text": "<" if not is_first_page else "x", "callback_data": json.dumps({ "type": ButtonCallbackType.NOOP, "distinction_factor": random.random(), }) if is_first_page else json.dumps({ "type": ButtonCallbackType.SHOW_PREVIOUS_QUEUE_PAGE, "page_index": page_index, "main_button_type": main_button_type, }), }, { "text": f"{page_index}/{total_page_count}", "callback_data": json.dumps({ "type": ButtonCallbackType.NOOP, "distinction_factor": random.random(), }), }, { "text": ">" if not is_last_page else "x", "callback_data": json.dumps({ "type": ButtonCallbackType.NOOP, "distinction_factor": random.random(), }) if is_last_page else json.dumps({ "type": ButtonCallbackType.SHOW_NEXT_QUEUE_PAGE, "page_index": page_index, "main_button_type": main_button_type, }), }, ]]
true
5c800ea4b15493913e6d8830957b90bbdaf588fd
Python
avirtualcoder/learning_code
/homework/100_1.py
UTF-8
423
4.28125
4
[]
no_license
#猜数字游戏 import random guess=1 number=random.randint(0,100) while True: numberGuess = eval(input('输入一个0和100间的整数: ')) print(numberGuess,end=' ') if numberGuess!=number: print('第{}次猜测,猜错了,结果偏{}'.format(guess,'大' if numberGuess>number else "小")) guess+=1 else: print('弟%d次,猜测猜对了!!!'%(guess)) break
true
b9d6c34c8be9db7d9e4ff49b07ebe245abca2319
Python
huangpd/nongAnServer
/naxy_api/apps/base/utils.py
UTF-8
6,733
2.71875
3
[]
no_license
# coding=utf-8 import calendar import json import urllib import urllib2 import re from datetime import datetime, date from decimal import * from django.db import connection class utils: """ 工具类 """ def __init__(self): pass @staticmethod def md5(str): """ md5加密 :param str: :return: """ import hashlib m = hashlib.md5() m.update(str) return m.hexdigest().upper() @staticmethod def send_request(type, url, params={}): """ 发送请求 :param type: 请求类型-str POST或GET :param url: 请求地址-str :param params: 发送请求参数 dict :return: """ try: if type in ['POST', 'GET']: request = urllib2.Request(url) if type == 'GET': res_data = urllib2.urlopen(request) elif type == 'POST': encode_param = urllib.urlencode(params) res_data = urllib2.urlopen(url=request, data=encode_param) data = res_data.read() return data else: return '' except Exception as e: return '' @staticmethod def param_list_index_value(parameter_list, str): ''' 接口参数值查询 :param parameter_list: 参数列表 :param str: 要查询得参数名称 :return: ''' if str == "service_charge": ret = "0" else: ret = "" for parameter in parameter_list: parameter_info = parameter.split(':') if parameter_info[0] == str: if len(parameter_info) > 1: ret = parameter_info[1] else: ret = '' break return ret @staticmethod def hiding_info(info, type): """ 隐藏用户信息 :param user_info: 用户信息手机或者email :param type: 屏蔽类型 1 手机, 2 email, 3 身份证号码, 4 银行卡号 :return: """ try: if info: if type == 1: info = info[0:3] + "****" + info[-4] elif type == 2: index = info.index("@") info = info[0:index - 4] + "****" + info[index:] elif type == 3: info = info[0:6] + "********" + info[len(info) - 2:len(info)] elif type == 4: info = info[0:6] + " **** **** ****" + info[len(info) - 3:len(info)] return info except Exception, e: return "" @staticmethod def checkPhoneNo(phone_no): """ 校验手机号 :param phone_no: :return: """ reMobile = re.match(r'1\d{10}$', phone_no) if not reMobile: return False else: return True pass @staticmethod def checkBankCardNo(card_no): """ 校验银行卡号 :param phone_no: :return: """ # 现在暂时只校验卡号长度,现在一般银行卡号都是16位和19位 if len(card_no) == 16 or len(card_no) == 19: return True return False pass @staticmethod def checkIDCardNo(card_no): """ 校验身份证号码 :param card_no: 身份证号 :return: """ def get_checkCode(card_no): CountValue = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] get_checkcode_key = reduce( lambda x, y: x + y, map( lambda x, y: x * y, [int(x) for x in card_no[:-1]], CountValue)) checkcode_key = get_checkcode_key % 11 CountRule = { '0': '1', '1': '0', '2': 'X', '3': '9', '4': '8', '5': '7', '6': '6', '7': '5', '8': '4', '9': '3', '10': '2'} get_checkcode_value = CountRule.get(str(checkcode_key), None) return get_checkcode_value if card_no[-1] == get_checkCode(card_no): return True return False @staticmethod def toJSON(self): """ 将models转换成json :return: """ return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]), cls=JsonDateEncoder) @staticmethod def calculate_age(born): today = date.today() try: birthday = born.replace(year=today.year) except ValueError: # raised when birth date is February 29 # and the current year is not a leap year birthday = born.replace(year=today.year, day=born.day-1) if birthday > today: return today.year - born.year - 1 else: return today.year - born.year @staticmethod def sql_helper(sql): """ sql语句操作,只执行sql语句查询 :param sql: sql语句 :return:返回查询结果 """ cursor = connection.cursor() # 创建游标 try: cursor.execute(sql) # 执行sql info = cursor.fetchall() # 获取查询结果集(元组类型) cursor.close() # 关闭连接 return info except Exception, e: cursor.close() return None @staticmethod def add_months(dt, months): month = dt.month - 1 + months year = dt.year + month / 12 month = month % 12 + 1 day = min(dt.day, calendar.monthrange(year, month)[1]) return dt.replace(year=year, month=month, day=day) class JsonDateEncoder(json.JSONEncoder): def default(self, obj): """ 对时间格式进行json转换 :param obj: :return: """ if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') elif isinstance(obj, Decimal): return "%.2f" % obj else: return json.JSONEncoder.default(self, obj)
true
fe127caf9f0aefd238d8cc65676b28dc8f0eaa50
Python
aws-samples/connected-drink-dispenser-workshop
/deploy/lambda_functions/cog_pre_signup/lambda.py
UTF-8
1,391
2.578125
3
[ "MIT-0" ]
permissive
""" Cognito UserPool Pre-SignUp Trigger Executed after sign up step and before completion of sign up """ import os import json import logging import boto3 __copyright__ = ( "Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved." ) __license__ = "MIT-0" logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): """Main entry into function""" logger.info("Received event: %s", json.dumps(event)) cog_client = boto3.client("cognito-idp") ddb_client = boto3.client("dynamodb") # If phone number already on confirmed user, reject try: phone_number = event["request"]["userAttributes"]["phone_number"] except KeyError: raise Exception(f"User attribute 'phone_number' not found in Cognito User Pool") # Check all other entries response = cog_client.list_users( UserPoolId=event["userPoolId"], Filter=f'phone_number = "{phone_number}"' ) if len(response["Users"]) > 0: raise Exception( f"Phone number {phone_number} already associated with an account" ) response = ddb_client.scan(TableName=os.environ["USER_TABLE"], Select="COUNT") if response["Count"] > int(os.environ["PARTICIPANT_LIMIT"]): raise Exception( "Maximum participants reached, please see workshop leader for assistance" ) return event
true
694764d9a0c126ab3bf47299d4d3afb7dc7bc3ed
Python
IanC13/NBA-Win-Loss-Predictor
/genetic_algorithm.py
UTF-8
5,288
3.28125
3
[]
no_license
import random from determine_record import * west = teams('west') east = teams('east') def individual(N,min,max): x = [] for i in range(N): x.append( random.randint(min,max) / 100 ) return x '''randomly generates a number between min, max and appends them into a list. does it N times ''' # Creates an individual in a population def population(count,N,min,max): x = [] for i in range(count): x.append(individual(N,min,max)) return x # Creates the population using the individual function def fitnessFunction(conference, numbers, target, cNum, tNum, year): # numbers is the list of coefficients print(numbers) if conference == 'east': observed = simulateEast(east[cNum][tNum], cNum, tNum, year, numbers) elif conference == 'west': observed = simulateWest(west[cNum][tNum], cNum , tNum, year, numbers) score = abs(target - observed) print(score, 'fitness score') return score # Takes in a LIST and a target # Generates a score based on the difference between the sum of the list and the target def evolution(prevPop, target, conf, cNum, tNum, year): newPop = [] targetLength = len(prevPop) noHP = (1/3) noLP = (1/3) while len(newPop) != int(targetLength * noHP): min = 100 for i in range(len(prevPop)): x = fitnessFunction(conf, prevPop[i], target, cNum, tNum, year) if x <= 0: return prevPop[i] ''' If we find the solution within the predefined population we return it straight away there is no need for evolution ''' else: if x <= min: k = i min = x newPop.append(prevPop[k]) prevPop.pop(k) ''' loop through everything if the individual is in our desired range of the target, we return it straight away otherwise , take the SMALLEST fitnessfunction score individuals (which would be 1D list) (smaller fitnessFunction scores are BETTER performers) (one of the arrays in the 2D array) put in new pop pop it off prevPop ''' # Randomly select lesser performers for i in range(int(targetLength * noLP)): ran = random.randint(0, len(prevPop)-1) newPop.append(prevPop[ran]) prevPop.pop(ran) # newPop are parents of next generation # 2/3 is selected to be parents # 1/3 is breeded # Breeding parentsLength = len(newPop) children = [] child1 = [] child2 =[] childrenTargetLength = targetLength - parentsLength while len(children) != childrenTargetLength: fatherNo = random.randint(0, parentsLength - 1) motherNo = random.randint(0, parentsLength - 1) ''' Randomly chooses mother and father from the group of parents With some high performers and some lower performers ''' if fatherNo != motherNo: # Ensures father and mother are not the same father = newPop[fatherNo] mother = newPop[motherNo] firstPoint = random.randint(0, len(father)-1) secondPoint = random.randint(0, len(father) - 1) # Multipoint crossover: Chooses two points in an individual as crossover points if firstPoint != secondPoint and secondPoint > firstPoint: # First point != second point (otherwise no crossover) # Second point > first point (prevents weird stuff from happening because of how child1 and child2 are defined) child1 = father[:firstPoint] + mother[firstPoint: secondPoint] + father[secondPoint:] child2 = mother[:firstPoint] + father[firstPoint: secondPoint] + mother[secondPoint:] children.append(child1) children.append(child2) # Mutations chanceToMutate = random.randint(1,20) # 5% chance if chanceToMutate == 1: individualToMutate = random.randint(0,len(children)-1) geneToMutate = random.randint(0, len(children[individualToMutate])-1) # Randomly chooses which individual and which gene in that individual to mutate children[individualToMutate][geneToMutate] = random.randint(75, 125) / 100 # randint is any number for generating individual print(individualToMutate, geneToMutate, 'mutated') newPop.extend(children) print(newPop) return newPop def runGA(target, conference, cNum, tNum, year ): size = 12 # not 4 test = population(size ,4,75,125) repeat = True count = 0 while repeat == True: count = count + 1 test = evolution(test, target, conference, cNum, tNum, year) solution = test print(count, 'evolution(s)') if len(solution) != size: return solution repeat = False break ''' If the returning value is a solution, the len of the 1 d list will be Four this is not 'size' so we know that what was returned was the solution if returning value is the new population for next evolution, the length will be 6 and the same as size so we know this is the pop for next evolution so these functions are not executed '''
true
cfecafbc4debfa95055f61502c2165b2bc902798
Python
z-x-z/rl
/src/rl_algorithms/A3C/test_a3c.py
UTF-8
1,138
2.640625
3
[]
no_license
''' Description : Author : CagedBird Date : 2021-08-13 15:19:51 FilePath : /rl/src/rl_algorithms/A3C/test_a3c.py ''' import gym from src.rl_algorithms.A3C.simple_a3c import SimpleA3C import torch.multiprocessing as mp import matplotlib.pyplot as plt def test_a3c(a3c: SimpleA3C): a3c.run() res = [] while not a3c.global_net.episode_reward_queue.empty(): r = a3c.global_net.episode_reward_queue.get() res.append(r) plt.xlabel("情节数") plt.ylabel("奖励") plt.title("A3C算法解决Pendulum-v0问题") plt.plot(res) plt.show() def show_chinese(): from matplotlib import rcParams config = { "font.family": 'serif', "font.size": 14, "mathtext.fontset": 'stix', "font.serif": ['SimSun'], "axes.unicode_minus": False } rcParams.update(config) if __name__ == "__main__": show_chinese() game_name = "Pendulum-v0" n_work = mp.cpu_count() envs = [gym.make(game_name) for _ in range(n_work)] lr = 1e-4 discount = 0.9 simple_a3c = SimpleA3C(lr, discount, envs) test_a3c(simple_a3c)
true
76c314c0b28c84d2bd6bcd796eff6fc67fb703bf
Python
abingham/project_euler
/python/src/euler/exercises/ex0028.py
UTF-8
821
4.125
4
[]
no_license
"""Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ def level_sum(n): """Sum of corners for a given level where the inner-most cell of a spiral is level 1. """ corner_average = (4 * n ** 2 - 7 * n + 4) return 4 * corner_average def diagonal_sum(side_length): # TODO: Can we analyze the sequence to find a non-iterative solution? depth = (side_length + 1) // 2 return 1 + sum(level_sum(level) for level in range(2, depth + 1)) def main(): return diagonal_sum(1001)
true
03a7ae07840ad4076055c33f3a07cc616fd07dee
Python
ivoryspren/basic_data_structures
/single_linked_list_recursive.py
UTF-8
1,760
3.6875
4
[]
no_license
class Node(object): def __init__(self, d, n = None): self.data = d self.next_node = n def get_next (self): return self.next_node def set_next (self, n): self.next_node = n def get_data (self): return self.data def set_data (self, d): self.data = d class SingleLinkedList (object): def __init__(self, r=None): self.root = r self.size = 0 def get_size (self): return self.size def add (self, d): new_node = Node (d, self.root) self.root = new_node self.size += 1 def remove (self, this_node, d): #this_node = self.root prev_node = None if this_node.get_data() == d: print("d is equal to: " + d) if prev_node: prev_node.set_next(this_node.get_next()) else: self.root = this_node.get_next() self.size -= 1 print("d removed") return True else: if this_node.get_next() == None: return None else: return self.remove(this_node.get_next(),d) def find (self, this_node, d): if this_node.get_data() == d: print("d is equal to: " + d) return d else: if this_node.get_next() == None: print("not found") return None else: return self.find(this_node.get_next(),d) myList = SingleLinkedList() myList.add("Breakfast") myList.add("Lunch") myList.add("Dinner") #x = myList.find(myList.root,"Breakfast") y = myList.remove(myList.root,"Breakfast") print(y) x = myList.find(myList.root,"Breakfast") #print(myList.root.get_next().get_data())
true
634a840fc0f135742444a7666d582195ab8aad6b
Python
sathiyapriya1997/github
/Base.py
UTF-8
513
2.609375
3
[]
no_license
from selenium import webdriver class Base: def Launch_Browser(self): self.driver = webdriver.Chrome(executable_path=r"C:\Users\Sathiyapriya\Documents\webdrivers\chromedriver.exe") self.driver.maximize_window() self.driver.implicitly_wait(10) return self.driver def load_url(self,url): self.driver.get(url) def send_text(self,e,data): e.send_keys(data) def btn_click(self,h): h.click() def quit_browser(self): self.driver.quit()
true
eea844323e5b2adde86e958fa76d422f155296b8
Python
viaacode/event-handler-deletes
/tests/services/pika_mock.py
UTF-8
743
2.78125
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Channel: """Mocks a pika Channel""" def __init__(self): self.queues = {} def basic_publish(self, *args, **kwargs): """Puts a message on the in-memory list""" self.queues[kwargs["routing_key"]].append(kwargs["body"]) def queue_declare(self, *args, **kwargs): """Creates an in-memory list to act as queue""" queue = kwargs["queue"] if not self.queues.get(queue): self.queues[queue] = [] class Connection: """Mocks a pika Connection""" def __init__(self): pass def channel(self): self.channel_mock = Channel() return self.channel_mock def close(self): pass
true
8e01af4e0e9f4e137c6738b35799c89bf65d3a49
Python
snehalmore/Video_Frame_Interpolation
/utils.py
UTF-8
7,650
2.890625
3
[]
no_license
import skvideo.io import numpy as np import tensorflow as tf from PIL import Image, ImageOps import matplotlib.pyplot as plt import os def generate_dataset_from_video(video_path): """ Convert the video frame into the desired format for training and testing :param video_path: String, path of the video :return: train_data -> [N, H, W, 6] train_target -> [H, W, 3] test_data -> [N, H, W, 6] test_target -> [H, W, 3] """ train_data = [] train_target = [] test_data = [] test_target = [] frames = skvideo.io.vread(video_path) frames = np.array(frames / 255, dtype=np.float32) mean_img = np.mean(frames[::2], 0) frames = frames - mean_img for frame_index in range(len(frames)): if frame_index % 2 == 1: test_target.append(frames[frame_index]) else: try: train_data.append(np.append(frames[frame_index], frames[frame_index + 4], axis=2)) train_target.append(frames[frame_index + 2]) test_data.append(np.append(frames[frame_index], frames[frame_index + 2], axis=2)) except IndexError: print("Dataset generation done!") break train_data = np.array(train_data).reshape([-1, 288, 352, 6]) train_target = np.array(train_target).reshape([-1, 288, 352, 3]) test_data = np.array(test_data).reshape([-1, 288, 352, 6]) test_target = np.array(test_target).reshape([-1, 288, 352, 3]) return train_data, train_target, test_data, test_target, mean_img def split_video_frames(video_path): video_frames = [] frames = skvideo.io.vread(video_path) frames = np.array(frames / 255, dtype=np.float32).reshape([-1, 288, 352, 3]) mean_img = np.mean(frames[::2], 0) frames = frames - mean_img for frame_index in range(len(frames)): try: video_frames.append(np.append(frames[frame_index], frames[frame_index + 1], axis=2)) except IndexError: print("Dataset prepared!") break video_frames = np.array(video_frames).reshape([-1, 288, 352, 6]) return video_frames # TODO: Remove this function later def split_video_frames_v2(images_path): frames = [] train_data = [] train_target = [] test_data = [] test_target = [] img_paths = sorted(os.listdir(images_path))[1:] for i, img_path in enumerate(img_paths): img = Image.open(images_path + '/' + img_path) img = ImageOps.crop(img, 130) img = np.array(img.resize([352, 288]))[:, :, :3] img = img/255 frames.append(img) frames = np.array(frames).reshape([-1, 288, 352, 3]) mean_img = np.mean(frames[::2], 0) frames = frames - mean_img for frame_index in range(len(frames)): if frame_index % 2 == 1: test_target.append(frames[frame_index]) else: try: train_data.append(np.append(frames[frame_index], frames[frame_index + 4], axis=2)) train_target.append(frames[frame_index + 2]) test_data.append(np.append(frames[frame_index], frames[frame_index + 2], axis=2)) except IndexError: print("Dataset generation done!") break train_data = np.array(train_data).reshape([-1, 288, 352, 6]) train_target = np.array(train_target).reshape([-1, 288, 352, 3]) test_data = np.array(test_data).reshape([-1, 288, 352, 6]) test_target = np.array(test_target).reshape([-1, 288, 352, 3]) return train_data, train_target, test_data, test_target, mean_img # TODO: Remove this later def split_video_frames_v3(images_path): video_frames = [] frames = [] img_paths = sorted(os.listdir(images_path))[1:] for i, img_path in enumerate(img_paths): img = Image.open(images_path + '/' + img_path) img = ImageOps.crop(img, 130) img = np.array(img.resize([352, 288]))[:, :, :3] img = img/255 frames.append(img) frames = np.array(frames).reshape([-1, 288, 352, 3]) for i, frame in enumerate(frames): plt.imsave('./Dataset/i_{:05d}.png'.format(i), frame) mean_img = np.mean(frames[::2], 0) frames = frames - mean_img for frame_index in range(len(frames)): try: video_frames.append(np.append(frames[frame_index], frames[frame_index + 1], axis=2)) except IndexError: print("Dataset prepared!") break video_frames = np.array(video_frames).reshape([-1, 288, 352, 6]) return video_frames # TODO: Understand this def tf_ms_ssim(img1, img2, mean_metric=True, level=5): with tf.variable_scope("ms_ssim_loss"): img1 = tf.image.rgb_to_grayscale(img1) img2 = tf.image.rgb_to_grayscale(img2) weight = tf.constant([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32) mssim = [] mcs = [] for l in range(level): ssim_map, cs_map = tf_ssim(img1, img2, cs_map=True, mean_metric=False) mssim.append(tf.reduce_mean(ssim_map)) mcs.append(tf.reduce_mean(cs_map)) filtered_im1 = tf.nn.avg_pool(img1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') filtered_im2 = tf.nn.avg_pool(img2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') img1 = filtered_im1 img2 = filtered_im2 # list to tensor of dim D+1 mssim = tf.stack(mssim, axis=0) mcs = tf.stack(mcs, axis=0) value = (tf.reduce_prod(mcs[0:level - 1] ** weight[0:level - 1]) * (mssim[level - 1] ** weight[level - 1])) if mean_metric: value = tf.reduce_mean(value) return value def tf_ssim(img1, img2, cs_map=False, mean_metric=True, size=11, sigma=1.5): window = _tf_fspecial_gauss(size, sigma) # window shape [size, size] K1 = 0.01 K2 = 0.03 L = 1 # depth of image (255 in case the image has a differnt scale) C1 = (K1 * L) ** 2 C2 = (K2 * L) ** 2 mu1 = tf.nn.conv2d(img1, window, strides=[1, 1, 1, 1], padding='VALID') mu2 = tf.nn.conv2d(img2, window, strides=[1, 1, 1, 1], padding='VALID') mu1_sq = mu1 * mu1 mu2_sq = mu2 * mu2 mu1_mu2 = mu1 * mu2 sigma1_sq = tf.nn.conv2d(img1 * img1, window, strides=[1, 1, 1, 1], padding='VALID') - mu1_sq sigma2_sq = tf.nn.conv2d(img2 * img2, window, strides=[1, 1, 1, 1], padding='VALID') - mu2_sq sigma12 = tf.nn.conv2d(img1 * img2, window, strides=[1, 1, 1, 1], padding='VALID') - mu1_mu2 if cs_map: value = (((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)), (2.0 * sigma12 + C2) / (sigma1_sq + sigma2_sq + C2)) else: value = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) if mean_metric: value = tf.reduce_mean(value) return value def _tf_fspecial_gauss(size, sigma): """Function to mimic the 'fspecial' gaussian MATLAB function """ x_data, y_data = np.mgrid[-size // 2 + 1:size // 2 + 1, -size // 2 + 1:size // 2 + 1] x_data = np.expand_dims(x_data, axis=-1) x_data = np.expand_dims(x_data, axis=-1) y_data = np.expand_dims(y_data, axis=-1) y_data = np.expand_dims(y_data, axis=-1) x = tf.constant(x_data, dtype=tf.float32) y = tf.constant(y_data, dtype=tf.float32) g = tf.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) return g / tf.reduce_sum(g)
true
2009c3ca969d8f5a51993d823ec0d26751e2e0f4
Python
hsson428/demo
/firstproject/aedlocation/aedlocation_repository.py
UTF-8
1,427
2.796875
3
[]
no_license
class AedlocationRepository: def __init__(self): self.connection_info = { 'host': 'localhost', 'db': 'demodb', 'user': 'root', 'password': 'PASSWORD', 'charset': 'utf8' } def select_aedlocation_by_name(self, name_key): import pymysql conn = pymysql.connect(**self.connection_info) cursor = conn.cursor() sql = "select num, Address from aedlocation where Address like %s" # where DetailedAddress like %s 추가 cursor.execute(sql, ("%" + name_key + "%",)) rows = cursor.fetchall() # 반환 값은 tuple의 list [ (...), (...), ..., (...) ] keys = ["num", "Address"] result = [] for row in rows: row_dict = { key:value for key, value in zip(keys, row) } result.append(row_dict) conn.close() return result def select_aedlocation_by_num(self, num): import pymysql conn = pymysql.connect(**self.connection_info) cursor = conn.cursor() sql = "select num, DetailedAddress from aedlocation where num = %s" cursor.execute(sql, (num,)) rows = cursor.fetchall() # 반환 값은 tuple (...) keys = ["num", "DetailedAddress"] result = [] for row in rows: row_dict = {key:value for key, value in zip(keys, row)} result.append(row_dict) conn.close() return result
true
00cd8eeebb67b566354a5251995a0f7eaeed59b6
Python
neszwil/Scraping_with_Django
/ilosc/author_finder.py
UTF-8
670
2.75
3
[]
no_license
from ilosc.adress_maker import adress_maker import requests from bs4 import BeautifulSoup import requests list_of_author = [] def author_finder(adress_urls): """ Function that finds authors for each article on the blog :param adress_urls: :return list_of_author: """ for adress in adress_urls: r = requests.get(adress) soup = BeautifulSoup(r.content, "lxml") author = soup.find('span', {'class': "author-content"}) author = (author.find('h4')).text.strip() author = author.replace(' ', '_') if author not in list_of_author: list_of_author.append(author) return(list_of_author)
true
6775ae05b1ce2ad9dd10dd88412cb8ed80efe95f
Python
aman9875/cs771
/assignment1/convex.py
UTF-8
1,720
3.15625
3
[]
no_license
import numpy as np num_seen_classes = 40 num_unseen_classes = 10 num_features = 4096 num_test_examples = 6180 # function to calculate the unseen class whose mean is at minimum distance from the mean of a given test sample. def calc_min_mean(mean_unseen,x_i): distance = np.sum((mean_unseen - x_i)**2 , axis = 1) min_index = np.argmin(distance) return min_index #loading data X_seen = np.load('X_seen.npy') Xtest = np.load('Xtest.npy') Ytest = np.load('Ytest.npy') class_attributes_seen=np.load('class_attributes_seen.npy') class_attributes_unseen=np.load('class_attributes_unseen.npy') mean_seen = np.zeros((num_seen_classes,num_features)) mean_unseen = np.zeros((num_unseen_classes,num_features)) #calculating mean of seen classes for i in range(num_seen_classes): mean_seen[i] = np.mean(X_seen[i] , axis = 0) #initializing and calculating similarity similarity = np.zeros((num_unseen_classes,num_seen_classes)) similarity = np.dot(class_attributes_unseen , class_attributes_seen.T) sum_similarity = np.sum(similarity , axis = 1) #normalizing similarity for i in range(num_unseen_classes): similarity[i] /= sum_similarity[i] #calculating mean for unseen classes using similarity for i in range(num_unseen_classes): for j in range(num_seen_classes): mean_unseen[i] += similarity[i][j] * mean_seen[j] Y_predict = np.zeros((num_test_examples)) #calculating prediction for each test example for i in range(num_test_examples): min_index = calc_min_mean(mean_unseen,Xtest[i]) Y_predict[i] = min_index + 1 #calculating accuracy count = 0 for i in range(num_test_examples): if(Ytest[i] == Y_predict[i]): count += 1 accuracy = count/(num_test_examples*1.0) print("Accuracy = %f" %(accuracy))
true
3a5880b61a0c70a3a5caca880d5c53b41215b294
Python
D3tenney/zip_it
/db/db_setup.py
UTF-8
1,179
2.5625
3
[ "MIT" ]
permissive
import sqlite3 sql_con = sqlite3.connect('./zipcode_db.sqlite') ZIP_FILENAME = './zip_data/uszips.csv' TABLE_NAME = 'zipcode' CREATE_TABLE = f""" CREATE TABLE {TABLE_NAME} ( zip TEXT PRIMARY KEY, lat TEXT, lng TEXT, city TEXT, state_id TEXT, state_name TEXT, zcta TEXT, parent_zcta TEXT, population TEXT, density TEXT, county_fips TEXT, county_name TEXT, county_weights TEXT, county_names_all TEXT, county_fips_all TEXT, imprecise TEXT, military TEXT, timezone TEXT ); """ sql_con.execute(CREATE_TABLE) id_count = 0 with open(ZIP_FILENAME, 'r') as f: for line in f: # skip headers in first row if id_count == 0: id_count += 1 continue insert_stmt = f"INSERT INTO {TABLE_NAME} VALUES ({line});" sql_con.execute(insert_stmt) id_count += 1 sql_con.commit()
true
5f147afd56bd872742934a7aef54113860e4b5ac
Python
Ezi4Zy/leetcode
/652.寻找重复的子树.py
UTF-8
889
3.046875
3
[]
no_license
# # @lc app=leetcode.cn id=652 lang=python # # [652] 寻找重复的子树 # # @lc code=start # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def findDuplicateSubtrees(self, root): """ :type root: TreeNode :rtype: List[TreeNode] """ dic = {} ret = [] def dfs(node): if not node: return '#' dfs_ = '%s,%s,%s' % (node.val, dfs(node.left), dfs(node.right)) if dfs_ in dic: dic[dfs_] += 1 else: dic[dfs_] = 1 if dic[dfs_] == 2: ret.append(node) return dfs_ dfs(root) return ret # @lc code=end
true
a571ca3a59192de780aafa906928acf74e288359
Python
nbvc1003/AI
/ch06/softMax1.py
UTF-8
263
3.109375
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt def softmax(x): e_x = np.exp(x-np.max(x)) return e_x / e_x.sum() x = np.array([1.0,1.0,2.0]) y = softmax(x) ration = y labels = y plt.pie(ration, labels= labels, shadow=True, startangle=90) plt.show()
true
f55dc596a671b7e0de6e99d22584ed490c2d2b65
Python
amrithrajvb/EmployeeDjango
/company/forms.py
UTF-8
3,155
2.640625
3
[]
no_license
from django import forms from django.forms import ModelForm from company.models import Employee import re class EmployeeAddForm(ModelForm): class Meta: model=Employee fields="__all__" widgets={ "emp_name":forms.TextInput(attrs={"class":"form-control"}), "department":forms.TextInput(attrs={"class":"form-control"}), "salary":forms.TextInput(attrs={"class":"form-control"}), "experience":forms.TextInput(attrs={"class":"form-control"}) } labels={ "emp_name":"Employee Name" } # emp_name=forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) # department=forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) # salary=forms.CharField(widget=forms.NumberInput(attrs={"class":"form-control"})) # experience=forms.CharField(widget=forms.NumberInput(attrs={"class":"form-control"})) def clean(self): cleaned_data=super().clean() emp_name=cleaned_data["emp_name"] salary=cleaned_data["salary"] department=cleaned_data["department"] experience=cleaned_data["experience"] x="[a-zA-Z]*" if int(salary)<0: msg="invalid salary" self.add_error("salary",msg) if int(experience)<0: msg="invalid experience" self.add_error("experience",msg) matcher=re.fullmatch(x,emp_name) if matcher is not None: pass else: msg="please enter valid employee name" self.add_error("emp_name",msg) depmatcher = re.fullmatch(x, department) if depmatcher is not None: pass else: msg = "please enter valid department name" self.add_error("department", msg) class EmployeeChange(ModelForm): class Meta: model=Employee fields="__all__" widgets={ "emp_name":forms.TextInput(attrs={"class":"form-control"}), "department":forms.TextInput(attrs={"class":"form-control"}), "salary":forms.TextInput(attrs={"class":"form-control"}), "experience":forms.TextInput(attrs={"class":"form-control"}) } labels={ "emp_name":"Employee Name" } # emp_name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"})) # department = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"})) # salary = forms.CharField(widget=forms.NumberInput(attrs={"class": "form-control"})) # experience = forms.CharField(widget=forms.NumberInput(attrs={"class": "form-control"})) def clean(self): cleaned_data=super().clean() salary = cleaned_data["salary"] experience = cleaned_data["experience"] if int(salary) < 0: msg="invalid price" self.add_error("salary",msg) if int(experience) < 0: msg="invalid experience" self.add_error("experience",msg) class SearchEmpForm(forms.Form): emp_name=forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
true
a39c10762443348880b8d23e0e0104acaba25d03
Python
beauthi/contests
/BattleDev/112020_0/test.py
UTF-8
1,275
3.265625
3
[]
no_license
mem = dict() def get_all_children_string(s): """ gets all 2-partitions of the string s """ children = set() for bitmask in range(2**len(s)-1): taken, left = [], [] b = 1 for i in range(len(s)): if (b & bitmask) == 0: left += [s[i]] else: taken += [s[i]] b *= 2 children.add(("".join(taken), "".join(left))) return children def get_all_children_pair(f, d): """ gets all pairs of strings that we can get from the pair (f,d) """ children_f, children_d = get_all_children_string(f), get_all_children_string(d) res = set() for taken_f, left_f in children_f: for taken_d, left_d in children_d: if left_f == left_d: res.add((taken_f, taken_d)) return res def get_mex(f, d): """ computes the Minimum EXcluded for a given state """ if (f, d) not in mem: excluded = set() children = get_all_children_pair(f, d) for new_f, new_d in children: excluded.add(get_mex(new_f, new_d)) res = 0 while res in excluded: res += 1 mem[(f, d)] = res return mem[(f, d)] print(get_mex("cabb", "abbd"))
true
913ebf555914b4b1fbc5c41f33a8b2588afc00d4
Python
StevenAWillis/login_registration
/apps/login_regist_app/models.py
UTF-8
2,706
2.6875
3
[]
no_license
from __future__ import unicode_literals from django.db import models class UserManager(models.Manager): def registration_validator(self, postData): errors = {} email_match = User.objects.filter(email = postData['email']) if len(postData['email']) == 0: errors["email_blank"] = "Please enter your email." elif len(email_match) > 0: errors["email_invalid"] = "That email exist in the database already." if len(postData['first_name']) == 0: errors["first_name"] = "First Name field cannot be blank." elif postData['first_name'].isalpha() == False: errors["first_name_alpha"] = "First Name field must only contain letters" elif len(postData['first_name']) < 2: errors["first_name_short"] = "First Name should be at least 2 characters" if len(postData['last_name']) == 0: errors["last_name"] = "Last Name field cannot be blank." elif postData['last_name'].isalpha() == False: errors["last_name_alpha"] = "Last Name field must only contain letters" elif len(postData['last_name']) < 2: errors["last_name_short"] = "Last Name should be at least 2 characters" if len(postData['password']) == 0: errors["pword_blank"] = "Password field cannot be blank." elif len(postData['password']) < 8: errors["pword_short"] = "Password must be at least 8 characters" if (postData['password'] != postData['confirm_pass']): errors["pword_match_fail"] = "Passwords do not match." return errors def login_validator(self, postData): errors = {} user = User.objects.filter(email = postData['email_login']) if len(user) == 0: errors["invalid"] = "Invalid login credentials." else: user = User.objects.get(email = postData['email_login']) if postData['password_login'] == user.password: print("Password accepted, logging in...") else: errors["invalid"] = "Invalid login credentials." return errors # Create your models here. class User(models.Model): first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) email = models.TextField() password = models.TextField() confirm_pass = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager()
true
641a8520843624adbf0ec2d3eb5b005efaad6a6c
Python
DANIL00FIONOV/work1
/test_sportsman.py
UTF-8
533
3.140625
3
[]
no_license
import pytest from Sportsman import Sportsman @pytest.mark.parametrize('answer',[7,6,12,23]) def test_run(answer): assert Sportsman.run(60) == answer @pytest.mark.parametrize('answer',[5,3,10,6]) def test_jump(answer): assert Sportsman.jump("from the spot") == answer @pytest.mark.parametrize('answer',[8,9,10,11]) def test_sleep(answer): assert Sportsman.sleep(answer) == "I recovered" @pytest.mark.parametrize('answer',["steroids",7,"eat",10]) def test_eat(answer): assert Sportsman.eat(answer) == "zaebumba"
true
941b00cf28387e0d15723f51c3e160dec5ba90c0
Python
rtoal/uva-problems
/195.py
UTF-8
935
3.390625
3
[]
no_license
import sys # String to array of ints that can be arranged and sorted according to the # weird rules of the problem. Interleaves upper and lower ASCII letters. def encoded(s): return [c*2 if c<92 else c*2-63 for c in bytes(s, 'utf-8')] # Encoded array back to string def decoded(a): return ''.join(chr(b//2 if b%2==0 else (b+63)//2) for b in a) # Credit to SO user jfs https://stackoverflow.com/a/34325140/831878 def next_permutation(a): for i in reversed(range(len(a) - 1)): if a[i] < a[i + 1]: break else: return False j = next(j for j in reversed(range(i + 1, len(a))) if a[i] < a[j]) a[i], a[j] = a[j], a[i] a[i + 1:] = reversed(a[i + 1:]) return True cases = int(sys.stdin.readline()) for _ in range(cases): word = sorted(encoded(sys.stdin.readline().strip())) while True: print(decoded(word)) if not next_permutation(word): break
true
a34bc3c7603dff5706166e8d54d0458638730def
Python
byrgazov/foolscap
/src/foolscap/slicers/decimal_slicer.py
UTF-8
1,345
2.609375
3
[ "MIT" ]
permissive
# -*- test-case-name: foolscap.test.test_banana -*- import decimal from twisted.internet.defer import Deferred from foolscap.tokens import BananaError, STRING, SVOCAB from foolscap.slicer import BaseSlicer, LeafUnslicer from foolscap.constraint import Any class DecimalSlicer(BaseSlicer): opentype = (b'decimal',) slices = decimal.Decimal def sliceBody(self, streamable, banana): yield str(self.obj) class DecimalUnslicer(LeafUnslicer): opentype = (b'decimal',) value = None constraint = None def setConstraint(self, constraint): if not isinstance(constraint, Any): raise BananaError('DecimalUnslicer does not currently accept a constraint') def checkToken(self, typebyte, size): if typebyte not in (STRING, SVOCAB): raise BananaError('DecimalUnslicer only accepts strings') #if self.constraint: # self.constraint.checkToken(typebyte, size) def receiveChild(self, obj, ready_deferred=None): assert not isinstance(obj, Deferred) assert ready_deferred is None if self.value is not None: raise BananaError('already received a string') self.value = decimal.Decimal(obj) def receiveClose(self): return self.value, None def describe(self): return '<unicode>'
true
27df9a371bc3caa459aa40ab7169047357a92b04
Python
MaxGabrielima/Python-Codes
/Desafios/desafio015.py
UTF-8
189
3.703125
4
[ "MIT" ]
permissive
km = float(input('Quantos km foram rodados? ')) dias = float(input('Por quantos dias o carro esteve alugado? ')) print('O valor total a pagar é de {} R$'.format((dias * 60) + (km * 0.15)))
true
0c0fc2beb016a549f428b98b6c3eec73910709bf
Python
bfishbaum/euler
/.prob60F2.py
UTF-8
1,012
3.203125
3
[]
no_license
import prime as pi import permutations as pr import math import time def confirmList(x): x = x[:] if(x == []): return False if(len(x) == 1): return pi.isPrime(x[0]) b = x[-1] for a in x[:-1]: p1 = (a * 10 ** (int(math.log(b,10))+1) + b) p2 = (b * 10 ** (int(math.log(a,10))+1) + a) if(not pi.isPrime(p1) or not pi.isPrime(p2)): return False return True def findPrimeCatSet(high,length): final = [] for j in range(1,3): sieve = pi.sieve(high) mod1 = [3] + [i for i in sieve if i % 3 == j] result = [[i] for i in mod1] leng = length while(leng > 1): temp = [] a = len(result) b = 1 for y in result: print(b,a) b += 1 for x in mod1: if(x > y[-1]): z = y + [x] if(confirmList(z)): temp += [z] result = temp leng -= 1 print(len(result)) final += result print(result) return final print([sum(x) for x in [[7, 1237, 2341, 12409, 18433], [13, 5197, 5701, 6733, 8389]]]) x = 1/0 r = findPrimeCatSet(20000,5) print(r)
true
2a3e198467beaa7e28281814c188425e4714831f
Python
danilorribeiro/training
/python/guppe/loop_for.py
UTF-8
920
4.34375
4
[]
no_license
""" iteráveis: - String nome = 'Geek University' - Lista lista = [1, 3, 5, 7, 9] - Range numeros = range [1,10] """ nome = 'Geek University' lista = [1, 3, 5, 7, 9] """ range = range(1, 10) for letra in nome: print(letra) for numero in lista: print (numero) for numero in range: print (numero) Enumerate: retorna indice,letra for indice, letra in enumerate(nome): print(nome[indice]) for _, letra in enumerate(nome): print (letra) for valor in enumerate(nome): print (valor[0],valor[1]) print (valor) qtd = int(input('Quantas vezess esse loop deve rodar? ')) soma = 0 for n in range(1,qtd+1): num = int(input(f'Informe o {n}/{qtd} valor: ')) soma = soma + num print(f'A soma é {soma}') for letra in nome: print(letra, end='') """ for _ in range(3): for num in range(1,11): print('\U0001F60D' * num)
true
2f01325ec7e327cab80d9596301a188f735fad78
Python
Yang-YiFan/shiftresnet-cifar
/models/depthwiseresnet.py
UTF-8
3,113
2.671875
3
[ "Apache-2.0" ]
permissive
"""PyTorch implementation of DepthwiseResNet ShiftResNet modifications written by Bichen Wu and Alvin Wan. Reference: [1] Bichen Wu, Alvin Wan, Xiangyu Yue, Peter Jin, Sicheng Zhao, Noah Golmant, Amir Gholaminejad, Joseph Gonzalez, Kurt Keutzer Shift: A Zero FLOP, Zero Parameter Alternative to Spatial Convolutions. arXiv:1711.08141 """ import torch.nn as nn import torch.nn.functional as F from .resnet import ResNet class DepthWiseWithSkipBlock(nn.Module): def __init__(self, in_planes, out_planes, stride=1, reduction=1): super(DepthWiseWithSkipBlock, self).__init__() self.expansion = 1 / float(reduction) self.in_planes = in_planes self.mid_planes = mid_planes = int(self.expansion * out_planes) self.out_planes = out_planes self.conv1 = nn.Conv2d( in_planes, mid_planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(mid_planes) self.depth = nn.Conv2d(mid_planes, mid_planes, kernel_size=3, padding=1, stride=1, bias=False, groups=mid_planes) self.bn2 = nn.BatchNorm2d(mid_planes) self.conv3 = nn.Conv2d( mid_planes, out_planes, kernel_size=1, bias=False, stride=stride) self.bn3 = nn.BatchNorm2d(out_planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != out_planes: self.shortcut = nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(out_planes) ) def flops(self): if not hasattr(self, 'int_nchw'): raise UserWarning('Must run forward at least once') (_, _, int_h, int_w), ( _, _, out_h, out_w) = self.int_nchw, self.out_nchw flops = int_h * int_w * self.mid_planes * self.in_planes + out_h * out_w * self.mid_planes * self.out_planes flops += out_h * out_w * self.mid_planes * 9 # depth-wise convolution if len(self.shortcut) > 0: flops += self.in_planes * self.out_planes * out_h * out_w return flops def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) self.int_nchw = out.size() out = self.bn2(self.depth(out)) out = self.bn3(self.conv3(out)) self.out_nchw = out.size() out += self.shortcut(x) out = F.relu(out) return out def DepthwiseResNet20(reduction=1, num_classes=10): block = lambda in_planes, planes, stride: \ DepthWiseWithSkipBlock(in_planes, planes, stride, reduction=reduction) return ResNet(block, [3, 3, 3], num_classes=num_classes) def DepthwiseResNet56(reduction=1, num_classes=10): block = lambda in_planes, planes, stride: \ DepthWiseWithSkipBlock(in_planes, planes, stride, reduction=reduction) return ResNet(block, [9, 9, 9], num_classes=num_classes) def DepthwiseResNet110(reduction=1, num_classes=10): block = lambda in_planes, planes, stride: \ DepthWiseWithSkipBlock(in_planes, planes, stride, reduction=reduction) return ResNet(block, [18, 18, 18], num_classes=num_classes)
true
5fad779f7be3fafc4f72639932121c165098a314
Python
davidgaribaldi/GuitarNeck
/Guitar Neck.py
UTF-8
692
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 13:07:28 2019 @author: DavidGaribaldi """ fretboard = {} fretboard['E'] = ['E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E'] fretboard['A'] = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A'] fretboard['D'] = ['D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D'] fretboard['G'] = ['G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G'] fretboard['B'] = ['B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] fretboard['e'] = ['E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E'] print(fretboard['B'][6])
true
1f2a9e73d6e4864bf087c1346fe6fcd1e0aa1791
Python
ballaneypranav/rosalind
/archive/perm.py
UTF-8
625
3.578125
4
[]
no_license
from copy import copy # n = int(input()) n = 7 def factorial(n): if n == 1: return 1 return n * factorial(n-1) print(factorial(n)) numbers = [x+1 for x in range(n)] def generate_permutations(numbers): if len(numbers) == 1: return [numbers] permutations = [] for number in numbers: numbers_copy = copy(numbers) numbers_copy.remove(number) for permutation in generate_permutations(numbers_copy): permutations.append([number] + permutation) return permutations for permutation in generate_permutations(numbers): print(*permutation)
true
4fa3823207d11fe6f53d306452ec4f7722724cd7
Python
Zhenye-Na/leetcode
/interview/amazon/shopping-patterns.py
UTF-8
1,800
3.53125
4
[ "MIT" ]
permissive
# Shopping Patterns # https://aonecode.com/amazon-online-assessment-shopping-patterns from collections import defaultdict class ShoppingPatterns: def __init__(self): self.neighbors = defaultdict(list) def getMinScore(self, products_nodes, products_edges, products_from, products_to): if products_edges <= products_nodes - 1: # graph without cycle, no trios return -1 if len(products_from) != len(products_to): return -1 self._build_graph(products_from, products_to) min_score = 3 * products_nodes for node in range(1, products_nodes): # extract node 1 neighbors = self.neighbors[node] for i in range(len(neighbors)): second_node = neighbors[i] second_node_neighbors = self.neighbors[second_node] for j in range(i + 1, len(neighbors)): if neighbors[j] in second_node_neighbors: # we find a trios, compute score min_score = min( min_score, len(self.neighbors[node]) + len(self.neighbors[second_node]) + len(self.neighbors[neighbors[j]]) - 6 ) print(min_score) return min_score def _build_graph(self, products_from, products_to): length = len(products_from) for i in range(length): self.neighbors[products_from[i]].append(products_to[i]) self.neighbors[products_to[i]].append(products_from[i]) # test solver = ShoppingPatterns() solver.getMinScore( 6, 6, [1,2,2,3,4,5], [2,4,5,5,5,6] ) solver2 = ShoppingPatterns() solver2.getMinScore( 5, 6, [1,1,2,2,3,4], [2,3,3,4,4,5] )
true
2b8fceddbcbeea7e7394c1740fc42740324e4a52
Python
RahulanT/Python_Stock_Analysis
/maincode/scipy_test.py
UTF-8
685
3.375
3
[]
no_license
from scipy.signal import argrelextrema import matplotlib.pyplot as plt import numpy as np # Generate random data. data_x = np.arange(start = 0, stop = 25, step = 1, dtype='int') data_y = np.random.random(25)*6 # Find peaks(max). peak_indexes = argrelextrema(data_y, np.greater) peak_indexes = peak_indexes[0] # Find valleys(min). valley_indexes = argrelextrema(data_y, np.less) valley_indexes = valley_indexes[0] # Plot main graph. (fig, ax) = plt.subplots() ax.plot(data_x, data_y) # Plot peaks. peak_x = peak_indexes peak_y = data_y[peak_indexes] ax.plot(peak_x, peak_y, marker='o', linestyle='dashed', color='green', label="Peaks") plt.show()
true
1a16644af849fe54031479496d6101b79bfd87e3
Python
log2timeline/dftimewolf
/dftimewolf/lib/exporters/gce_disk_export_base.py
UTF-8
5,877
2.65625
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- """Base class to Export Compute disk images to Google Cloud Storage.""" from typing import List, Optional from googleapiclient.errors import HttpError from libcloudforensics.providers.gcp.internal import project as gcp_project from libcloudforensics.providers.gcp.internal.compute import GoogleComputeDisk # pylint: disable=line-too-long from dftimewolf.lib import module from dftimewolf.lib.state import DFTimewolfState #pylint: disable=abstract-method class GoogleCloudDiskExportBase(module.BaseModule): """Google Cloud Platform (GCP) disk export base class. Attributes: source_project (gcp_project.GoogleCloudProject): Source project containing the disk/s to export. remote_instance_name (str): Instance that needs forensicating. source_disk_names (list[str]): Comma-separated list of disk names to copy. all_disks (bool): True if all disks attached to the source instance should be copied. """ def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical: bool=False) -> None: """Initializes GCP disk export base class. Args: state (DFTimewolfState): recipe state. name (Optional[str]): The module's runtime name. critical (Optional[bool]): True if the module is critical, which causes the entire recipe to fail if the module encounters an error. """ super(GoogleCloudDiskExportBase, self).__init__( state, name=name, critical=critical) self.source_project = None # type: gcp_project.GoogleCloudProject self.remote_instance_name = None # type: Optional[str] self.source_disk_names = [] # type: List[str] self.all_disks = False def _GetDisksFromNames( self, source_disk_names: List[str]) -> List[GoogleComputeDisk]: """Gets disks from a project by disk name. Args: source_disk_names: List of disk names to get from the project. Returns: List of GoogleComputeDisk objects to copy. """ disks = [] for name in source_disk_names: try: disks.append(self.source_project.compute.GetDisk(name)) except RuntimeError: self.ModuleError( 'Disk "{0:s}" was not found in project {1:s}'.format( name, self.source_project.project_id), critical=True) return disks def _GetDisksFromInstance( self, instance_name: str, all_disks: bool) -> List[GoogleComputeDisk]: """Gets disks to copy based on an instance name. Args: instance_name : Name of the instance to get the disks from. all_disks : If set, get all disks attached to the instance. If False, get only the instance's boot disk. Returns: list: List of GoogleComputeDisk objects to copy. """ try: remote_instance = self.source_project.compute.GetInstance(instance_name) except RuntimeError as exception: self.ModuleError(str(exception), critical=True) if all_disks: return list(remote_instance.ListDisks().values()) return [remote_instance.GetBootDisk()] def _FindDisksToCopy(self) -> List[GoogleComputeDisk]: """Determines which disks to copy depending on object attributes. Returns: The disks to copy to the analysis project. """ if not (self.remote_instance_name or self.source_disk_names): self.ModuleError( 'You need to specify at least an instance name or disks to copy', critical=True) if self.remote_instance_name and self.source_disk_names: self.ModuleError( ('Both --source_disk_names and --remote_instance_name are provided, ' 'remote_instance_name will be ignored in favour of ' 'source_disk_names.'), critical=False) disks_to_copy = [] try: if self.source_disk_names: disks_to_copy = self._GetDisksFromNames(self.source_disk_names) elif self.remote_instance_name: disks_to_copy = self._GetDisksFromInstance(self.remote_instance_name, self.all_disks) except HttpError as exception: if exception.resp.status == 403: self.ModuleError( '403 response. Do you have appropriate permissions on the project?', critical=True) if exception.resp.status == 404: self.ModuleError( 'GCP resource not found. Maybe a typo in the project / instance / ' 'disk name?', critical=True) self.ModuleError(str(exception), critical=True) if not disks_to_copy: self.ModuleError( 'Could not find any disks to copy', critical=True) return disks_to_copy def _DetachDisks(self, disks: List[GoogleComputeDisk]) -> None: """Detaches disks from VMs in case they are attached. Args: disks: disks to detach. """ try: for disk in disks: users = disk.GetValue('users') if users: instance_name = users[0].split('/')[-1] instance = self.source_project.compute.GetInstance(instance_name) self.logger.warning( 'Disk "{0:s}" will be detached from instance "{1:s}"'.format( disk.name, instance_name)) instance.DetachDisk(disk) except HttpError as exception: if exception.resp.status == 400: self.ModuleError( ('400 response. To detach the boot disk, the instance must be in ' 'TERMINATED state: {0!s}'.format(exception)), critical=True) self.ModuleError(str(exception), critical=True) def _VerifyDisksInSameZone(self, disks: List[GoogleComputeDisk]) -> bool: """Verifies that all dicts are in the same Zone. Args: disks: compute disks. Returns: Whether all disks are in the same zone. """ return all(disk.zone == disks[0].zone for disk in disks)
true
6b44138caab94ca20c827a7d9add8dd88a6d5456
Python
umbonoce/SignatureVerificationNN
/main_hmm.py
UTF-8
23,341
2.578125
3
[]
no_license
import os import numpy as np import math import csv import pandas as pd import matplotlib.pyplot as plt import sklearn from hmmlearn import hmm import warnings import random from scipy.interpolate import interp1d from scipy.optimize import brentq from sklearn.metrics import roc_curve from sklearn.neighbors import KNeighborsClassifier from collections import Counter warnings.filterwarnings("ignore") np.random.seed(42) # pseudorandomic N_USERS = 29 # tanh normalization; values between 0 and 1 def normalization(data): mean = data.mean() std = data.std() data = 0.5 * (np.tanh(0.01 * ((data - mean) / std)) + 1) return data def z_normalization(df): column_maxes = df.max() df_max = column_maxes.max() return df / df_max # time derivative approsimation def second_order_regression(data_list): pad_list = data_list.copy() pad_list.append(data_list[len(data_list) - 1]) pad_list.append(data_list[len(data_list) - 1]) pad_list.insert(0, data_list[0]) pad_list.insert(0, data_list[0]) derivata = [None] * (len(data_list)) for n in range(2, len(data_list) + 2): derivata[n - 2] = ((pad_list[n + 1] - pad_list[n - 1] + 2 * (pad_list[n + 2] - pad_list[n - 2])) / 10) return derivata def load_dataset(user): training_list = list() # dictionary of all training dataframes [1..40] testing_dict = {'skilled': [], 'genuine': [], 'random': []} # dictionary of all testing dataframes [41..56] training_fs_list = list() # list of training dataframes (feature selection) [alltrain - validation] validation_fs_dict = {'true': [], 'false': []} # dictionary of validation dataframes (feature selection) [one true for each session, 18 false random] random.seed(42) # pseudorandomic path = './xLongSignDB/' path_user = path + str(user) + '/' files = os.listdir(path_user) i = 0 for file in files: df = pd.read_csv(path_user + file, header=0, sep=' ', names=['X', 'Y', 'TIMESTAMP', 'PENSUP', 'AZIMUTH', 'ALTITUDE', 'Z']) df = initialize_dataset(df) if 'ss' in file: testing_dict['skilled'].append(df) elif 'sg' in file: i += 1 if i > 41: testing_dict['genuine'].append(df) else: training_list.append(df) if i % 4 == 0: validation_fs_dict['true'].append(df) else: training_fs_list.append(df) else: print(file) for i in range(0, 20): numbers = [x for x in range(1, 30)] numbers.remove(user) y = random.choice(numbers) path_user = path + str(y) + '/' files = os.listdir(path_user) z = random.randint(10, 40) df = pd.read_csv(path_user + files[z], header=0, sep=' ', names=['X', 'Y', 'TIMESTAMP', 'PENSUP', 'AZIMUTH', 'ALTITUDE', 'Z']) df = initialize_dataset(df) validation_fs_dict['false'].append(df) for u in range(1,30): if u != user: path_user = path + str(u) + '/' files = os.listdir(path_user) z = random.randint(10, 40) df = pd.read_csv(path_user + files[z], header=0, sep=' ', names=['X', 'Y', 'TIMESTAMP', 'PENSUP', 'AZIMUTH', 'ALTITUDE', 'Z']) df = initialize_dataset(df) testing_dict['random'].append(df) return training_list, testing_dict, training_fs_list, validation_fs_dict def initialize_dataset(df): del df['TIMESTAMP'] del df['AZIMUTH'] del df['ALTITUDE'] df = compute_features(df) new_df = pd.DataFrame(data=None) for column in df.columns.values: new_df[column] = normalization(df[column].values) return new_df def compute_features(df): e = np.finfo(np.float32).eps leng = len(df) x_list = df['X'].tolist() y_list = df['Y'].tolist() z_list = df['Z'].tolist() # pression up_list = df['PENSUP'].tolist() dx_list = second_order_regression(x_list) dy_list = second_order_regression(y_list) theta_list = [None] * leng v_list = [None] * leng # velocity for i in range(0, leng): theta_list[i] = np.arctan(dy_list[i] / (dx_list[i] + e)) v_list[i] = np.sqrt(dy_list[i] ** 2 + dx_list[i] ** 2) dtheta_list = second_order_regression(theta_list) p_list = [None] * leng # ro dv_list = second_order_regression(v_list) a_list = [None] * leng # acceleration for i in range(0, leng): dtheta = np.abs(dtheta_list[i] + e) v = np.abs(v_list[i] + e) p_list[i] = math.log(v / dtheta) a_list[i] = np.sqrt((dtheta_list[i] * v_list[i]) ** 2 + dv_list[i] ** 2) dz_list = second_order_regression(z_list) da_list = second_order_regression(a_list) dp_list = second_order_regression(p_list) ddx_list = second_order_regression(dx_list) ddy_list = second_order_regression(dy_list) ratios_list = [None] * leng # np.array([]) Ratio of the minimum over the maximum speed over a 5-samples window for n in range(0, leng - 4): vmin = np.amin(v_list[n:n + 4]) vmax = np.amax(v_list[n:n + 4]) + e ratios_list[n] = vmin / vmax alphas_list = [None] * leng # Angle of consecutive samples for n in range(0, leng - 1): alphas_list[n] = np.arctan((y_list[n + 1] - y_list[n]) / (x_list[n + 1] - x_list[n] + e)) alphas_list[leng - 1] = alphas_list[leng - 2] dalpha_list = second_order_regression(alphas_list) sinalpha_list = np.array(np.sin(alphas_list)) cosalpha_list = np.array(np.cos(alphas_list)) strokeratio5_list = [None] * leng # Stroke length to width ratio over a 5-samples window for n in range(0, leng - 4): stroke_len = np.sum(up_list[n:n + 4]) width = np.max(x_list[n:n + 4]) - np.min(x_list[n:n + 4]) + e strokeratio5_list[n] = stroke_len / width strokeratio7_list = [None] * leng # Stroke length to width ratio over a 7-samples window for n in range(0, leng - 6): stroke_len = np.sum(up_list[n:n + 6]) width = np.max(x_list[n:n + 6]) - np.min(x_list[n:n + 6]) + e strokeratio7_list[n] = stroke_len / width df['theta'] = theta_list df['v'] = v_list df['ro'] = p_list df['ac'] = a_list df['dX'] = dx_list df['dY'] = dy_list df['dZ'] = dz_list df['dTheta'] = dtheta_list df['dv'] = dv_list df['dRo'] = dp_list df['dAc'] = da_list df['ddX'] = ddx_list df['ddY'] = ddy_list df['vRatio'] = ratios_list df['alpha'] = alphas_list df['dAlpha'] = dalpha_list df['SIN'] = sinalpha_list df['COS'] = cosalpha_list df['5_WIN'] = strokeratio5_list df['7_WIN'] = strokeratio7_list df['vRatio'].fillna(value=df['vRatio'].mean(), inplace=True) df['alpha'].fillna(value=df['alpha'].mean(), inplace=True) df['dAlpha'].fillna(value=df['dAlpha'].mean(), inplace=True) df['SIN'].fillna(value=df['SIN'].mean(), inplace=True) df['COS'].fillna(value=df['COS'].mean(), inplace=True) df['5_WIN'].fillna(value=df['5_WIN'].mean(), inplace=True) df['7_WIN'].fillna(value=df['7_WIN'].mean(), inplace=True) del(df['PENSUP']) return df def feature_selection(training_set, validation_set): k = 0 # counter number of feature to select subset = set() # empty set ("null set") so that the k = 0 (where k is the size of the subset) header = list(training_set[0].columns.values) total_features = set(header) last_score = [1] * 10 while k != 9: best_score = 1 best_trust = 0 best_feature = "" feature_set = subset.copy() for f in (total_features - subset): feature_set.add(f) score, trust = evaluate_score(training_set, validation_set, list(feature_set)) feature_set.remove(f) if (score < best_score) or (score == best_score and trust > best_trust): best_trust = trust best_score = score best_feature = f subset.add(best_feature) k += 1 last_score[k] = best_score print("best " + str(best_feature)) still_remove = True first_time = True while still_remove: if len(subset) > 1: feature_set = subset.copy() worst_feature = "" removed_score = 1 for f in subset: feature_set.remove(f) score, trust = evaluate_score(training_set, validation_set, list(feature_set)) feature_set.add(f) if score < removed_score: removed_score = score worst_feature = f if (worst_feature == best_feature) and first_time: still_remove = False else: if removed_score >= last_score[k-1]: # if removed score is worse than before, go adding features still_remove = False else: # otherwise keep removing features # last_score[k-1] = removed_score subset.remove(worst_feature) k -= 1 first_time = False print("removed" + str(worst_feature)) else: still_remove = False return subset, best_score, best_trust def evaluate_score(train_set, valid_set, features): print(features) training_set = train_set.copy() validation_set = valid_set.copy() x_list = [signature[features] for signature in training_set] x_train = pd.concat(x_list) try: model = hmm.GMMHMM(n_components=32, n_mix=2, random_state=42).fit(x_train) score_train = [None] * (len(train_set)) score_test_gen = [None] * (len(validation_set["true"])) score_test_skilled = [None] * (len(validation_set["false"])) count_training = 0 count_validation = 0 for signature in x_list: score_train[count_training] = model.score(signature)/len(signature) count_training += 1 average_score = np.average(score_train) count_training = 0 for signature in x_list: distance = np.abs(score_train[count_training] - average_score) score_train[count_training] = np.exp((distance * -1) / len(features)) count_training += 1 for signature in validation_set["true"]: a = signature[features] distance = np.abs(model.score(a)/len(signature) - average_score) score_test_gen[count_validation] = np.exp((distance * -1) / len(features)) count_validation += 1 count_validation = 0 for signature in validation_set["false"]: a = signature[features] distance = np.abs(model.score(a)/len(signature) - average_score) score_test_skilled[count_validation] = np.exp((distance * -1) / len(features)) count_validation += 1 i = 0 for score in score_test_gen: i += 1 # print(f" prob signature testing genuine {i}: {score}") i = 0 for score in score_test_skilled: i += 1 # print(f" prob signature testing skilled {i}: {score}") labels = [1] * len(validation_set["true"]) + [0] * len(validation_set["false"]) probs = np.concatenate([score_test_gen, score_test_skilled]) fpr, tpr, thresh = roc_curve(labels, probs) equal_error_rate = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) threshold = interp1d(fpr, thresh)(equal_error_rate) print(f"threshold: {threshold} eer: {equal_error_rate}") except: equal_error_rate = 1 threshold = 0 print("Fit Training Error") print(f"equal error rate: {equal_error_rate}") return equal_error_rate, threshold def test_evaluation(train_set, features, valid_set, n_comp, n_mix): i = 0 training_set = train_set.copy() validation_set = valid_set.copy() x_list = [signature[features] for signature in training_set] x_train = pd.concat(x_list) try: model = hmm.GMMHMM(n_components=n_comp, n_mix=n_mix, random_state=42).fit(x_train) score_train = [None] * (len(training_set)) score_test_gen = [None] * (len(validation_set["genuine"])) score_test_skilled = [None] * (len(validation_set["skilled"])) count_training = 0 for signature in x_list: score_train[count_training] = model.score(signature)/len(signature) count_training += 1 average_score = np.average(score_train) count_training = 0 for signature in x_list: distance = np.abs(score_train[count_training] - average_score) score_train[count_training] = np.exp((distance * -1) / len(features)) count_training += 1 count_validation = 0 for signature in validation_set["genuine"]: a = signature[features] distance = np.abs(model.score(a)/len(signature) - average_score) score_test_gen[count_validation] = np.exp((distance * -1) / len(features)) count_validation += 1 count_validation = 0 for signature in validation_set["skilled"]: a = signature[features] distance = np.abs(model.score(a)/len(signature) - average_score) score_test_skilled[count_validation] = np.exp((distance * -1) / len(features)) count_validation += 1 i = 0 for score in score_test_gen: i += 1 print(f" prob signature testing genuine {i}: {score}") i = 0 for score in score_test_skilled: i += 1 print(f" prob signature testing random {i}: {score}") labels = [1] * len(score_test_gen) + [0] * len(score_test_skilled) probs = np.concatenate([score_test_gen, score_test_skilled]) fpr, tpr, thresh = roc_curve(labels, probs) equal_error_rate = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) threshold = interp1d(fpr, thresh)(equal_error_rate) print(f"threshold: {threshold} eer: {equal_error_rate}") except: equal_error_rate = 1.0 print("Raised exception") return equal_error_rate def knn_experiment(k, fs, type): train_list, testing_dict, training_fs_list, validation_fs_dict = load_dataset(k) training_list = [None] * len(train_list) count_training = 0 for signature in train_list: training_list[count_training] = signature[fs] count_training += 1 knn = KNeighborsClassifier(n_neighbors=5) labels = list() models = list() splits = list() splits.append(training_list[0:4]) splits.append(training_list[4:8]) splits.append(training_list[8:12]) splits.append(training_list[12:16]) splits.append(training_list[21:25]) splits.append(training_list[36:40]) first = np.sum(len(x) for x in training_list[0:4]) second = np.sum(len(x) for x in training_list[4:8]) third = np.sum(len(x) for x in training_list[8:12]) fourth = np.sum(len(x) for x in training_list[12:16]) fifth = np.sum(len(x) for x in training_list[21:25]) sixth = np.sum(len(x) for x in training_list[36:40]) for split in splits: x_train = pd.concat(split) models.append(hmm.GMMHMM(n_components=2, n_mix=16, random_state=42).fit(x_train)) df_training = pd.DataFrame() #training_list = training_list[0:16] + training_list[21:25] training_list = training_list[0:16] + training_list[21:25] + training_list[36:40] for element in training_list: df_training = df_training.append(element) labels.extend('1' for counter in range(0, first)) labels.extend('2' for counter in range(0, second)) labels.extend('3' for counter in range(0, third)) labels.extend('4' for counter in range(0, fourth)) labels.extend('5' for counter in range(0, fifth)) labels.extend('6' for counter in range(0, sixth)) df_labels = pd.DataFrame(data=labels, columns=['Y']) knn.fit(df_training, df_labels) average_training = [None] * len(models) score_test_gen = [None] * len(testing_dict["genuine"]) score_test_skilled = [None] * len(testing_dict[type]) for m in range(0, len(splits)): count_training = 0 score_training = [None] * 4 for signature in splits[m]: try: score_training[count_training] = models[m].score(signature)/len(signature) except: score_training[count_training] = 0 count_training += 1 average_training[m] = np.average(score_training) i = 0 for signature in testing_dict["genuine"]: a = signature[fs] score = knn.predict(a) occurrences = Counter(score) print(occurrences) index = int(max(occurrences, key=occurrences.get)) - 1 score = models[index].score(a)/len(signature) distance = np.abs(score - average_training[index]) score_test_gen[i] = np.exp(distance * (-1)/len(fs)) i += 1 i = 0 for signature in testing_dict[type]: a = signature[fs] score = knn.predict(a) occurrences = Counter(score) print(occurrences) index = int(max(occurrences, key=occurrences.get)) - 1 score = models[index].score(a)/len(signature) distance = np.abs(score - average_training[index]) score_test_skilled[i] = np.exp(distance * (-1)/len(fs)) i += 1 i = 0 for score in score_test_gen: i += 1 print(f" prob signature testing genuine {i}: {score}") i = 0 for score in score_test_skilled: i += 1 print(f" prob signature testing {type} {i}: {score}") labels = [1] * len(score_test_gen) + [0] * len(score_test_skilled) probs = np.concatenate([score_test_gen, score_test_skilled]) fpr, tpr, thresh = roc_curve(labels, probs) equal_error_rate = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) threshold = interp1d(fpr, thresh)(equal_error_rate) print(f"threshold: {threshold} eer: {equal_error_rate}") return equal_error_rate def testing(): exp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] results = dict() for i in exp: results[i] = [None] * N_USERS with open('features_HMM.csv', mode='r') as feature_file: feature_reader = csv.reader(feature_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) i = 0 for (fs) in feature_reader: if i > 0: print(f"user n#{i}") print(fs) fs.pop() training_list, testing_dict, training_fs_list, validation_fs_dict = load_dataset(i) n_mix = 16 n_comp = 2 training = training_list[0:4] results['a'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[4:8] results['b'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[8:12] results['c'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[12:16] results['d'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[21:25] results['e'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[36:40] results['f'][i - 1] = test_evaluation(training, fs, testing_dict, 1, 16) results['g'][i - 1] = results['a'][i - 1] n_mix = 2 n_comp = 32 training = training_list[0:16] results['h'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[0:31] results['i'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[0:16] + training_list[21:25] results['j'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[4:16] + training_list[21:25] results['k'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) n_mix = 16 n_comp = 2 training = training_list[8:16] + training_list[21:25] results['l'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) training = training_list[12:16] + training_list[21:25] results['m'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) results['n'][i - 1] = results['e'][i - 1] training = training_list[16:31] results['o'][i - 1] = test_evaluation(training, fs, testing_dict, n_comp, n_mix) results['p'][i - 1] = knn_experiment(i, fs) i += 1 eer = [None] * len(exp) i = 0 for e in exp: eer[i] = np.average(results[e])*100 i += 1 print("average equal error rate for experiment:") print(eer) plt.plot(exp[0:6], eer[0:6], color='r', linestyle='dashed', marker='o', label='Ageing Experiments (a-f)') plt.ylabel('EER (%)') plt.xlabel('Experiments') plt.show() plt.plot(exp[6:15], eer[6:15], color='r', linestyle='dashed', marker='o', label='Ageing Experiments (f-o)') plt.ylabel('EER (%)') plt.xlabel('Experiments') plt.show() def knn_testing(): exp = ['p', 'q'] results = dict() for i in exp: results[i] = [None] * N_USERS with open('features_HMM_tolosana.csv', mode='r') as feature_file: feature_reader = csv.reader(feature_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) i = 0 for (fs) in feature_reader: if i > 0: print(f"user n#{i}") print(fs) fs.pop() results['p'][i - 1] = knn_experiment(i, fs, "skilled") results['q'][i - 1] = knn_experiment(i, fs, "random") i += 1 eer = [None] * len(exp) i = 0 for e in exp: eer[i] = np.average(results[e])*100 i += 1 print("average equal error rate for experiment:") print(eer) def start_fs(): for i in range(1, 30): training_list, testing_dict, training_fs, validation_fs = load_dataset(i) subset, eer, thresh = feature_selection(training_fs, validation_fs) with open('features_HMM_tolosana.csv', mode='a') as feature_file: feature_writer = csv.writer(feature_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) subset = list(subset) subset.append(eer) feature_writer.writerow(subset) knn_testing()
true
5f672686e75121ff9b1e3062a464d495e63e34da
Python
Gundas3073/PDF-Downloaders
/FIS.py
UTF-8
1,307
2.703125
3
[]
no_license
import urllib2 def main(): global count count = 0 global n for n in range(0000,6000): global test test = n getName("http://www.freeinfosociety.com/media.php?id=" + str(n),"</h1>","</a>/", 30) download_file("http://www.freeinfosociety.com/media/pdf/" + str(n) + ".pdf") print str(count) def download_file(download_url): try: # Used to make sure no errors w/ HTTP request (AKA 404 Error trolls) response = urllib2.urlopen(download_url) file = open(name + ".pdf", 'wb') file.write(response.read()) file.close() print("Completed") count = count + 1 except urllib2.HTTPError, e: print "file " + str(n) + " " +name + " is not present or is not a pdf" except urllib2.URLError, e: print "file " + str(n) + " " + name + " is not present or is not a pdf" except: print " " def getName(url, beg, beg2, testlength): try: reponse2 = urllib2.urlopen(url) file2 = reponse2.read() # file2 = "".join(file2.split()) a = file2.find(beg2, 0, len(file2)) a = file2.find(beg2, a+6, len(file2)) a = file2.find(beg2, a+6, len(file2)) b = file2.find(beg, a, len(file2)) global name name = file2[a+5:b] print name except: print " " if __name__ == "__main__": main()
true
ef1d6939dd10926cccc9dd4dbfa4a999108d8599
Python
jonrh/lambda-lovelace
/sandbox/Python Xinqi/18jul2016/RecommenderTextual.py
UTF-8
5,089
2.78125
3
[ "ISC" ]
permissive
# -*- coding: utf-8 -*- from sklearn.feature_extraction.text import CountVectorizer from collections import Counter import tweepy import time import string class RecommenderTextual: #TO-DO: #-set language to users own twitter language #-currently misses end hashtags #-Does not search for hashtags, just "word-searches" #-does not add hashtags to term-frequency document #-does not distinguish Java from JavaScript (Could use a bigram list for this) def __init__(self, users_own_tweets, users_followed_tweets):#, ckey, csecret, atoken, atokensecret): self.vectorizer = CountVectorizer() self.own_tweets = users_own_tweets self.followed_tweets = users_followed_tweets self.get_term_frequency_weightings(None, None) #This method currently gets the top thirty terms that a users tweets with def get_term_frequency_weightings(self, number_of_terms_in_document, number_of_user_timeline_tweets): weightings = {}#Dictionary of terms (keys) and their weighting (value) top_amount_of_terms = 30# or just the "number_of_terms_in_document" parameter amount_of_tweets_to_gather = 101#Or just the "number_of_user_timeline_tweets" parameter, + 1 #The extra "1" is because python is not inclusive of the last digit in the range that #this variable is used for later on. #On a scale up to 10.0 numeric_scale = 10 #We want the top 5 most occurring terms top_x_terms = 5 #http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python exclude = set(string.punctuation) #generate a list of stop words stop_words = [word for word in CountVectorizer(stop_words='english').get_stop_words()] stop_words.append('rt') stop_words.append('https') #Filtering section my_first_x_tweets = self.own_tweets[0:amount_of_tweets_to_gather] overall_list = [] for sublist in my_first_x_tweets: for item in sublist['text'].split(): if item not in stop_words: transformed_item = item.lower().translate(string.punctuation) overall_list.append(transformed_item)# item.lower()) total_count = len(overall_list) frequency_doc = Counter(overall_list) term_frequncy_list = {} for term in frequency_doc.keys(): term_weight = (float(frequency_doc.get(term))/total_count) * numeric_scale term_frequncy_list[term] = term_weight self.termfreq_doc = term_frequncy_list top_terms = [] most_common_raw = frequency_doc.most_common(top_x_terms) for x in range(0, top_x_terms): top_terms.append(most_common_raw[x][0]) remove_these_terms = [] for term in self.termfreq_doc: if term not in top_terms: remove_these_terms.append(term) for removal in remove_these_terms: self.termfreq_doc.pop(removal, None) return weightings def get_tweet_term_weighting(self, tweet_text, term): weighting = 0 term_match_weighting = 0 already_weighted_terms = [] tweet_text_stripped = tweet_text.replace("#","").encode('utf-8') individual_tweet_words = tweet_text_stripped.split(" ") for word in individual_tweet_words: if self.termfreq_doc.get(word.lower()) is not None: term_match_weighting += self.termfreq_doc.get(word.lower()) weighting = term_match_weighting return weighting def generate(self, number_of_recommendations, how_many_days_ago): list_of_owners_tweets = [] unfollowed_tweets = [] for tweet in self.own_tweets: list_of_owners_tweets.append(tweet['text'].encode('utf-8')) self.vectorizer.fit_transform(list_of_owners_tweets) words = self.own_tweets #The users own tweets tweet_list = self.followed_tweets #tweets from accounts that the user is following data_returned = sorted(tweet_list, key=self.count_bag, reverse=True) results = data_returned[0:number_of_recommendations] counts = [self.count_bag(tweet) for tweet in results] return {"recommended_tweets":results, "counts":sorted(counts, reverse=True)} def count_bag(self, tweet): count = 0 sanitised_tweet_text = tweet['text'] #bug #Somehow, the following tweet is being counted as six (should be three) #Tweet! #Guavate: tiny library bridging Guava and Java8 - Core Java Google Guava, Guavate, Java 8 https://t.co/kQnWkUy9V7 #count! #6 for word in sanitised_tweet_text.split(): if word.lower() in self.termfreq_doc.keys(): count += 1 count += self.get_tweet_term_weighting(sanitised_tweet_text, self.termfreq_doc.get(word)) return count
true