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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
000f3e4956c35a1271281b4980f18f4271a3dabc
|
Python
|
dcrozz/GRADUATION-PRACTICE
|
/CRF/FeatureSelect.py
|
UTF-8
| 6,172
| 2.578125
| 3
|
[] |
no_license
|
"""
Feature Selection by Chi measure that can control numbers of labels
example:
py filename feature_number label1 label2
To be done (any amount of label)
"""
#coding:utf-8
def getFile(filename,label1,label2):
lst = []
with open(filename) as f:
#for test modify the line to 10
for line in f.readlines():
cur_line = line.strip().split('\t')
try:
cur_line[2]
if cur_line[-1] != label1 and cur_line[-1] != label2:
cur_line.pop()
cur_line.append('0')
lst.append(cur_line)
else:
lst.append(cur_line)
except IndexError:
pass
return lst
def featureSelect(lst):
dnalst = []
rnalst = []
linelst = []
typelst = []
prolst = []
for line in lst:
tmp = line[1:]
if tmp[-1] == 'DNA':
dnalst.append(map(int,tmp[:-1]))
elif tmp[-1] == 'RNA':
rnalst.append(map(int,tmp[:-1]))
elif tmp[-1] == 'cell_line':
linelst.append(map(int,tmp[:-1]))
elif tmp[-1] == 'cell_type':
typelst.append(map(int,tmp[:-1]))
elif tmp[-1] == 'protein':
prolst.append(map(int,tmp[:-1]))
try:
dnacol = reduce(listAdd,dnalst)
except TypeError:
dnacol = []
try:
rnacol = reduce(listAdd,rnalst)
except TypeError:
rnacol = []
try:
linecol = reduce(listAdd,linelst)
except TypeError:
linecol = []
try:
typecol = reduce(listAdd,typelst)
except TypeError:
typecol = []
try:
procol = reduce(listAdd,prolst)
except TypeError:
procol = []
feacol = reduce(listAdd,[dnacol,rnacol,linecol,typecol,procol])
return dnacol,rnacol,linecol,typecol,procol,feacol
def listAdd(a,b):
if a==[] or b==[]:
if a==[]:
return b
else:
return a
tmp = []
for x,y in zip(a,b):
try:
tmp.append(int(x)+int(y))
except ValueError:
tmp.append(-1)
return tmp
def changePOSandWS(lst,posdct,wsdct):
new_lst = []
for x in lst:
try:
tmp = posdct[x[1]]
x[1] = ['0' for itm in range(len(posdct))]
x[1][tmp] = '1'
except KeyError:
x[1] = ['0' for itm in range(len(posdct))]
pass
try:
tmp = wsdct[x[11]]
x[11] = ['0' for itm in range(len(wsdct))]
x[11][tmp] = '1'
except KeyError:
x[11] = ['0' for itm in range(len(wsdct))]
# ipdb.set_trace()
x = x[:1] + x[1] + x[2:11] + x[11] + x[12:]
new_lst.append(x)
return new_lst
def calFeature(matrix,feacol):
featuredct = {}
fealen = max([len(i) for i in matrix])
for j in range(fealen):
Sigma = 0
for i in matrix:
if len(i) < fealen:
continue
else:
Oij = i[j]
Eij = sum(i)*feacol[j]
try:
Sigma += (Oij - Eij)*(Oij - Eij)*1.0/Eij
except ZeroDivisionError:
Sigma = -1
featuredct[str(j)] = Sigma
sorteddict= sorted(featuredct.iteritems(), key=lambda d:d[1], reverse = True)
return sorteddict
def getTop(dct,num):
newdctlst = []
tmp = [int(x) for x,y in dct[:num]]
return tmp
def selectIndex(lst,indexlst):
newlst = []
for line in lst:
new = [line[0]] + [line[a+1] for a in indexlst] + [line[-1]]
newlst.append(new)
return newlst
def outFile(lst,filename):
with open(filename,'a') as f:
for line in lst:
# try:
f.write('\t'.join(map(str,line)) + '\n')
# except TypeError:
# pass
def outSeq(wsdct,posdct,filename):
'''create a file that indicates the index of each feature'''
lenws = len(wsdct)
lenpos = len(posdct)
defaultdct = {
'___token':0,
'___pos':1,
'___\-':2,
'___,':3,
'___[A-Z]':4,
'___[0-9]':5,
'___\\\\':6,
'___:':7,
'___;':8,
'___\[':9 ,
'___\(':10,
'___word_shape':11,
'___alpha|beta|':12,
'___rna':13,
'___cell':14,
'___gene':15,
'___jurkat':16,
'___transcript':17,
'___factor':18,
'___prot|mono|nucle|integr|il\-':19,
'___alpha|beta|...|il\-':20,
'___indivdualCapLetter':21,
'___Label':22,
}
for itm in defaultdct.keys():
if defaultdct[itm]>=2 and defaultdct[itm] <11:
defaultdct[itm] += lenpos -1
elif defaultdct[itm]>11:
defaultdct[itm] += lenpos + lenws -1
totaldct = dict(defaultdct.items()+wsdct.items()+posdct.items())
totaldct.pop('___pos')
totaldct.pop('___word_shape')
outlst = sorted(totaldct.items(),key=lambda d: d[1])
with open(filename,'a') as f:
for itm in outlst:
f.write(itm[0] + '\t' + str(itm[1]) + '\n')
return dict(outlst)
def outFea(feaIndex,totalfea,filename):
with open(filename,'a') as f:
for index in feaIndex:
for feature in totalfea.keys():
if totalfea[feature]+1 == index:
f.write(feature +'\t'+str(totalfea[feature])+'\n')
if __name__ == "__main__":
import sys
import time
import ipdb
starttime = time.time()
trainlst = getFile('GENIA-CRF-TRAIN-5.txt',sys.argv[2],sys.argv[3])
testlst = getFile('GENIA-CRF-TEST-5.txt',sys.argv[2],sys.argv[3])
#trainlst = getFile('GENIA-CRF-TRAIN-5.txt','DNA','protein')
#testlst = getFile('GENIA-CRF-TEST-5.txt','DNA','protein')
nedct={}
ne = set([x[-1] for x in trainlst])
nedct = {x for x in ne}
posdct={}
#mod is used to set the feature dict
pos = set(x[1] for x in trainlst)
posdctmod = {x:y for x,y in zip(pos,range(1,len(pos)+1))}
posdct = {x:y for x,y in zip(pos,range(len(pos)))}
ws = set([x[11] for x in trainlst])
wsdctmod = {x:y for x,y in zip(ws,range(len(pos)+10,len(ws)+10+len(pos)))}
wsdct = {x:y for x,y in zip(ws,range(len(ws)))}
totalfeadct = outSeq(wsdctmod,posdctmod,'totalfeatures'+'-'+sys.argv[2]+'-'+sys.argv[3]+'.txt')
#totalfeadct = outSeq(wsdctmod,posdctmod,'totalfeatures')
pw_trainlst = changePOSandWS(trainlst,posdct,wsdct)
pw_testlst = changePOSandWS(testlst,posdct,wsdct)
dnacol,rnacol,linecol,typecol,procol,feacol = featureSelect(pw_trainlst)
#add the colname
matrix = [dnacol,rnacol,linecol,typecol,procol]
#the feature dict with chi value
featuredct = calFeature(matrix,feacol)
#get top 15
featureIndex = getTop(featuredct,int(sys.argv[1])) # the index of feature finally selected
new_trainlst = selectIndex(pw_trainlst,featureIndex)
outFea(featureIndex,totalfeadct,'selectedfeatures'+'-'+sys.argv[1]+'-'+sys.argv[2]+'-'+sys.argv[3]+'.txt')
outFile(new_trainlst,'GENIA-CRF-TRAIN-5-' + sys.argv[1] + '-' + sys.argv[2] + '-' + sys.argv[3] +'.txt')
new_testlst = selectIndex(pw_testlst,featureIndex)
outFile(new_testlst,'GENIA-CRF-TEST-5-' + sys.argv[1] + '-' + sys.argv[2] + '-' + sys.argv[3] +'.txt')
endtime = time.time()
print endtime-starttime
| true
|
66a12d4dabead12ce7b1dee5533bcf513c1e7efc
|
Python
|
usman-tahir/rubyeuler
|
/selection_sort.py
|
UTF-8
| 466
| 3.5625
| 4
|
[] |
no_license
|
#!/usr/bin/env python
from copy import deepcopy
def selection_sort(array):
new_array = deepcopy(array)
for i in xrange(0,len(array)):
for j in xrange(i,len(array)):
if new_array[i] > new_array[j]:
new_array[i], new_array[j] = new_array[j], new_array[i]
return new_array
l = [26, 45, 4, 98, 769, 234, 24324, 78, 865, 0, 6, 123, 7, 14345, 5, \
12, 211, 1, 3215, 67, 8, 90, 9, 2345, 456]
print selection_sort(l)
| true
|
17021b5903df997dd916506a8e68c8e738ab914e
|
Python
|
Radu-Raicea/Stock-Analyzer
|
/flask/project/services/google_finance.py
|
UTF-8
| 3,659
| 2.90625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import re
from decimal import Decimal
from datetime import date
from pyquery import PyQuery
import requests
import json
GOOGLE_FINANCE_REPORT_TYPES = {
'inc': 'Income Statement',
'bal': 'Balance Sheet',
'cas': 'Cash Flow',
}
DATE = re.compile('.*(\d{4})-(\d{2})-(\d{2}).*')
class GoogleFinance(object):
STOCK_URL = 'https://finance.google.com/finance?q={}%3A{}&output=json'
FINANCIALS_URL = 'https://finance.google.com/finance?q={}%3A{}&fstype=ii'
def __init__(self, market, ticker):
self.market = market.upper()
self.ticker = ticker.upper()
self._stock_data = None
self._financial = None
@staticmethod
def _parse_number(number_string):
if number_string == '-':
return None
try:
return Decimal(number_string.replace(',', ''))
except Exception as e:
pass
return number_string
@staticmethod
def _parse_date(date_string):
m = DATE.match(date_string)
if m:
return date(*[int(e) for e in m.groups()])
return date_string
def _get_from_google(self):
return PyQuery(self.FINANCIALS_URL.format(self.market, self.ticker))
def _get_stock_data(self):
response = requests.get(self.STOCK_URL.format(self.market, self.ticker))
try:
data = json.loads(response.content[6:-2].decode('unicode_escape'))
_stock_data = data
stock_data = {}
stock_data['price'] = self._parse_number(data['l'])
stock_data['price_change'] = data['c']
stock_data['percent_change'] = data['cp']
stock_data['day_high'] = self._parse_number(data['hi'])
stock_data['day_low'] = self._parse_number(data['lo'])
stock_data['52_high'] = self._parse_number(data['hi52'])
stock_data['52_low'] = self._parse_number(data['lo52'])
stock_data['open'] = self._parse_number(data['op'])
stock_data['volume'] = data['vo']
stock_data['average_volume'] = data['avvo']
stock_data['market_cap'] = data['mc']
stock_data['price_to_earnings'] = self._parse_number(data['pe'])
stock_data['dividend'] = self._parse_number(data['ldiv'])
stock_data['yield'] = self._parse_number(data['dy'])
stock_data['earnings_per_share'] = self._parse_number(data['eps'])
stock_data['shares'] = data['shares']
return stock_data
except Exception as e:
pass
def _get_financial_table(self, report_type, term):
assert term in ('interim', 'annual')
assert report_type in ('inc', 'bal', 'cas')
if not self._financial:
self._financial = self._get_from_google()
div_id = report_type + term + 'div'
return self._financial('div#{} table#fs-table'.format(div_id))
def _statement(self, statement_type, term):
table = self._get_financial_table(statement_type, term)
statement_line = []
for row in table.items('tr'):
data = [self._parse_number(i.text()) for i in row.items('th, td')]
if not statement_line:
data = [self._parse_date(e) for e in data]
statement_line.append(data)
return statement_line
def income_statement(self, term='annual'):
return self._statement('inc', term)
def balance_sheet(self, term='annual'):
return self._statement('bal', term)
def cash_flow(self, term='annual'):
return self._statement('cas', term)
def stock_data(self):
return self._get_stock_data()
| true
|
2fcd21cb5f58329e9b5cec3a5f2dcc26adc7375f
|
Python
|
Spider251/python
|
/pbase/day09/code/keywords_give_args.py
|
UTF-8
| 204
| 3.1875
| 3
|
[] |
no_license
|
# keywords_give_args.py
#此示例示意关键字传参
def myfun1(a,b,c):
print("a的值是:",a)
print("b的值是:",b)
print("c的值是:",c)
myfun1(c = 300, b = 200, a = 100)
| true
|
765268893ba63101725420947a121724a53fb7ed
|
Python
|
santoshmurugan/Deep-Learning-COVID19-Detection
|
/dataloader.py
|
UTF-8
| 2,342
| 2.75
| 3
|
[] |
no_license
|
import os
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from sklearn.model_selection import train_test_split
import numpy as np
from PIL import Image
import torch
import torchvision.transforms as transforms
from pathlib import Path
def get_dataloaders(device):
'''
Return: (Training_TensorDataset, Test_TensorDataset)
'''
#Load all of the images into lists
base_path = Path(__file__).parent
covid_imgs_dir = "%s%s" % (base_path, '/data/CT_COVID')
covid_imgs = [os.path.join(covid_imgs_dir, img_path) for img_path in os.listdir(covid_imgs_dir)]
covid_labels = np.repeat(1, len(covid_imgs))
non_covid_dir = "%s%s" % (base_path, '/data/CT_NonCOVID')
non_covid_imgs = [os.path.join(non_covid_dir, img_path) for img_path in os.listdir(non_covid_dir)]
non_covid_labels = np.repeat(0, len(non_covid_imgs))
all_imgs = covid_imgs + non_covid_imgs
labels = np.append(covid_labels,non_covid_labels)
#Do a 70/30 train tests split
X_train, X_test, y_train, y_test = train_test_split(all_imgs, labels, test_size=0.3, random_state=42)
train_data = [np.array(transform(get_image(img))) for img in X_train]
test_data = [np.array(transform(get_image(img))) for img in X_test]
train_data = torch.tensor(train_data, dtype=torch.float32, device=device)
test_data = torch.tensor(test_data, dtype=torch.float32, device=device)
train_labels = torch.tensor(y_train, dtype=torch.float32, device=device)
test_labels = torch.tensor(y_test, dtype=torch.float32, device=device)
train_data = TensorDataset(train_data, train_labels)
test_data = TensorDataset(test_data, test_labels)
return train_data, test_data
def transform(image):
#Note: This is the normalization needed for AlexNet, may need to change depending on model
train_transformer = transforms.Compose([
transforms.Resize(256),
transforms.RandomResizedCrop((224),scale=(0.5,1.0)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
return train_transformer(image)
def get_image(file_path):
image = Image.open(file_path).convert("RGB") #Turns image to RGB as required
return image
| true
|
407c52cdc7910a9df20be5d1850da61010d8edcb
|
Python
|
sidtrip/hello_world
|
/CS106A/week5/sec5/heads_up.py
|
UTF-8
| 570
| 4.0625
| 4
|
[] |
no_license
|
import random
# Name of the file to read in!
FILE_NAME = 'cswords.txt'
def main():
# read the file
words_list = load_data()
# chosse a random word
while True:
#wait fo input
input('Press enter for next word: ')
#choose random number
choice = random.choice(words_list)
#display it to user
print(choice)
def load_data():
file = open('cswords.txt')
words = []
for line in file:
word = line.strip()
words.append(word)
return words
if __name__ == '__main__':
main()
| true
|
964339532b419da2f5583b9c75cede7194827662
|
Python
|
kwokmoonho/Game_Python
|
/Asteroid/game.py
|
UTF-8
| 7,446
| 3.65625
| 4
|
[] |
no_license
|
"""
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
Modified by: Kwok Moon Ho
Class: CS241
Added features:
1. background
2. machine gun
3. game over (after ship killed)
4. you win (after you kill all the asteriods)
5. draw score
"""
from global_constants import *
from bullet import Bullet
from asteriods import BigAsteriods
from ship import Ship
import random
import arcade
import math
class Game(arcade.Window):
"""
This class handles all the game callbacks and interaction
This class will then call the appropriate functions of
each of the above classes.
You are welcome to modify anything in this class.
"""
def __init__(self, width, height):
"""
Sets up the initial conditions of the game
:param width: Screen width
:param height: Screen height
"""
super().__init__(width, height)
self.held_keys = set()
self.score = 0
# TODO: declare anything here you need the game class to track
self.ship = Ship()
self.bullets = []
self.asteroids = []
self.create_asteriods()
def draw_background(self): ##draw the background
img = "images/background.png"
texture = arcade.load_texture(img)
width = texture.width
height = texture.height
alpha = 1
angle = 0
arcade.draw_texture_rectangle(width / 2, height / 2, width, height, texture, angle, alpha)
def on_draw(self):
"""
Called automatically by the arcade framework.
Handles the responsibility of drawing all elements.
"""
arcade.start_render()
# clear the screen to begin drawing
# TODO: draw each object
self.draw_background()
if self.ship.alive == True: ##only draw if the ship is still alive
self.ship.draw()
elif self.ship.alive == False: ##else, draw game over
self.draw_text()
for bullet in self.bullets:
bullet.draw()
if len(self.asteroids) > 0: ##if the list of the asteriods is 0, you win!
for asteriods in self.asteroids:
asteriods.draw()
else:
self.draw_win()
self.draw_score()
def draw_win(self):
text = "YOU WIN!!!"
start_x = 150
start_y = SCREEN_HEIGHT / 2
arcade.draw_text(text, start_x=start_x, start_y=start_y, font_size=100, color=arcade.color.WHITE)
def draw_score(self):
"""
Puts the current score on the screen
"""
score_text = "Score: {}".format(self.score)
start_x = 10
start_y = SCREEN_HEIGHT - 20
arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=18, color=arcade.color.WHITE)
def update(self, delta_time):
"""
Update each object in the game.
:param delta_time: tells us how much time has actually elapsed
"""
self.check_keys()
# TODO: Tell everything to advance or move forward one step in time
self.ship.advance()
for bullet in self.bullets:
bullet.advance()
for asteriod in self.asteroids:
asteriod.advance()
# TODO: Check for collisions
self.check_collisions()
self.cleanup_zombies()
def create_asteriods(self): ##create 5 big rock at the beginning of the game and called by the init
for i in range(INITIAL_ROCK_COUNT):
x = random.randint(0, SCREEN_WIDTH)
y = random.randint(0, SCREEN_HEIGHT)
angle = random.randint(0, 360)
dy = BIG_ROCK_SPEED * math.cos(math.radians(angle))
dx = BIG_ROCK_SPEED * math.sin(math.radians(angle))
rock = BigAsteriods(x, y, dx, dy)
self.asteroids.append(rock)
def draw_text(self):
score_text = "GAME OVER"
gun_text = "Try to hold W for machine gun on next game"
start_x = 100
start_y = SCREEN_HEIGHT / 2
arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=100, color=arcade.color.WHITE)
arcade.draw_text(gun_text, 50, SCREEN_HEIGHT / 2 - 50, font_size = 35, color=arcade.color.WHITE)
def check_collisions(self):
"""
Checks to see if bullets have hit targets.
Updates scores and removes dead items.
:return:
"""
for bullet in self.bullets: ##check the bullet and the asteriods
for asteriod in self.asteroids:
if bullet.alive and asteriod.alive:
too_close = bullet.radius + asteriod.radius
if (abs(bullet.center.x - asteriod.center.x) < too_close and
abs(bullet.center.y - asteriod.center.y) < too_close):
bullet.alive = False
self.score += 1
asteriod.hit(self.asteroids)
if self.ship.alive: ##check the asteriods and the ship
for asteriod in self.asteroids:
close = asteriod.radius + self.ship.radius
if(abs(asteriod.center.x - self.ship.center.x) < close and
abs(asteriod.center.y - self.ship.center.y) < close):
self.ship.alive = False
self.cleanup_zombies()
def cleanup_zombies(self): ##claen the memory of the list in bullet and the asteriod
"""
Removes any dead bullets or targets from the list.
:return:
"""
for bullet in self.bullets:
if not bullet.alive:
self.bullets.remove(bullet)
for asteriod in self.asteroids:
if not asteriod.alive:
self.asteroids.remove(asteriod)
def check_keys(self):
"""
This function checks for keys that are being held down.
You will need to put your own method calls in here.
"""
if arcade.key.LEFT in self.held_keys:
self.ship.turn_left()
if arcade.key.RIGHT in self.held_keys:
self.ship.turn_right()
if arcade.key.UP in self.held_keys:
self.ship.move()
if arcade.key.DOWN in self.held_keys:
self.ship.stop()
##Machine gun mode...
if arcade.key.W in self.held_keys:
bullet = Bullet(self.ship.center.x, self.ship.center.y, self.ship.direction.angle)
bullet.fire(self.ship.direction.angle)
self.bullets.append(bullet)
def on_key_press(self, key: int, modifiers: int):
"""
Puts the current key in the set of keys that are being held.
You will need to add things here to handle firing the bullet.
"""
if self.ship.alive:
self.held_keys.add(key)
if key == arcade.key.SPACE:
bulet = Bullet(self.ship.center.x, self.ship.center.y, self.ship.direction.angle)
bullet.fire(self.ship.direction.angle)
self.bullets.append(bullet)
def on_key_release(self, key: int, modifiers: int):
"""
Removes the current key from the set of held keys.
"""
if key in self.held_keys:
self.held_keys.remove(key)
# Creates the game and starts it going
window = Game(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run()
| true
|
5b4345d760b043700e9c19d34adaebd6f218f179
|
Python
|
daniel36933/repositorio-2
|
/Biography_info.py
|
UTF-8
| 1,020
| 4.28125
| 4
|
[] |
no_license
|
name = input("¿Cual es tu nombre?")#validación de solo letras.
Date = input("Dame el día, el mes y el año, solo en números, ejemplo: 29 01 2021")#validación de solo números.
Address = input("Dame la calle donde vives")#validación de solo letras y numeros.
Metas = input("Metas personales")#validación de solo letras.
print("-------------------------------------")
#name.isalpha()
#isdigist
#Condición 1--------------------
name2 = name.replace(" ","")
if name2.isalpha()==True:
print(name)
else:
print("Solo tienes que poner letras")
#Condición 2--------------------
Date2 = Date.replace(" ","")
if Date2.isdigit()==True:
print(Date)
else:
print("Solo tienes que poner números")
#Condición 3--------------------
Address2 = Address.replace(" ","")
if Address2.isalpha()==True:
print(Address)
else:
print("Solo números o letras")
#Condición 4--------------------
Metas2 = Metas.replace(" ","")
if Metas2.isalpha()==True:
print(Metas)
else:
print("Solo letras o números")
| true
|
aa03756ad49ec8831663d06a7367795f1df05b74
|
Python
|
tkyf/nlp100
|
/1chapter/07.py
|
UTF-8
| 220
| 3.59375
| 4
|
[] |
no_license
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
def make_sentence(x, y, z):
return "{}時の{}は{}".format(x, y, z)
def main():
print(make_sentence(12, '気温', 22.4))
if __name__ == '__main__':
main()
| true
|
5ee04d558cf91d4a733c00b4fb71c5165d8e3528
|
Python
|
hoangcuong93/hoangcuong9x-fundamental-c4e23
|
/hoangcuong9x-fundamental-c4e23/session2/inso.py
|
UTF-8
| 119
| 3.640625
| 4
|
[] |
no_license
|
n = int(input("n = "))
m = int(input("m = "))
for i in range(n, m + 1):
r = i % 2
if r == 0:
print(i)
| true
|
7588162202427dea680c8847a8e2cce5240ed2e6
|
Python
|
LyunJ/pythonStudy
|
/18_OOP/static_method_class_method.py
|
UTF-8
| 510
| 4.03125
| 4
|
[] |
no_license
|
# 정적 메소드
class Calc:
@staticmethod
def add(a, b):
return a + b
print(Calc().add(1, 2))
# 클래스 메소드
# self를 통하지 않고 바로 클래스가 메소드 호출
# 클래스 변수를 이용하는 메소드를 정의
class Person:
count = 0
def __init__(self):
Person.count += 1
@classmethod
def show_count(cls):
print('%d명 태어났습니다' % cls.count)
p1 = Person()
p2 = Person()
p3 = Person()
p4 = Person()
Person.show_count()
| true
|
df547fb5207882019a495ee1ea666f41f23a2acd
|
Python
|
kwmsmith/julia-shootout
|
/julia/julia_pure_python.py
|
UTF-8
| 1,164
| 2.953125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved. See LICENSE.txt for details.
#
# Author: Kurt W. Smith
# Date: 26 March 2012
#-----------------------------------------------------------------------------
# --- Python / Numpy imports -------------------------------------------------
import numpy as np
from time import time
def kernel(z, c, lim, cutoff=1e6):
''' Computes the number, `n`, of iterations necessary such that
|z_n| > `lim`, where `z_n = z_{n-1}**2 + c`.
'''
count = 0
while abs(z) < lim and count < cutoff:
z = z * z + c
count += 1
return count
def compute_julia(c, N, bound=2, lim=1000., kernel=kernel):
''' Pure Python calculation of the Julia set for a given `c`. No NumPy
array operations are used.
'''
julia = np.empty((N, N), dtype=np.uint32)
grid_x = np.linspace(-bound, bound, N)
grid_y = grid_x * 1j
c = complex(c)
t0 = time()
for i, x in enumerate(grid_x):
for j, y in enumerate(grid_y):
julia[i,j] = kernel(x+y, c, lim)
return julia, time() - t0
| true
|
9961b0e9c8b8c659429732422eadfb0660e50292
|
Python
|
krispharper/AdventOfCode
|
/2016/14/1.py
|
UTF-8
| 924
| 3.375
| 3
|
[] |
no_license
|
from hashlib import md5
def get_repeated_character(s, length):
for i in range(len(s) - length + 1):
if len(set(s[i:i + length])) == 1:
return s[i]
return None
def set_hashes(hashes, number_of_hashings):
for i in range(100000):
s = salt + str(i).encode('ascii')
for _ in range(number_of_hashings):
s = md5(s).hexdigest().encode('ascii')
hashes[i] = s.decode('ascii')
def find_index(salt, number_of_hashings):
hashes = {}
keys = set([])
set_hashes(hashes, number_of_hashings)
index = 0
while(len(keys) < 64):
c = get_repeated_character(hashes[index], 3)
if c:
for i in range(1000):
if c * 5 in hashes[index + i + 1]:
keys.add(hashes[index])
index += 1
print(index - 1)
salt = b'ngcjuoqr'
#salt = b'abc'
find_index(salt, 1)
find_index(salt, 2017)
| true
|
f87751af67ae80e268ab4789d25cf43c649c0195
|
Python
|
FlavioK/Pren1GR33
|
/python/alignmentCalculatorConfigurator.py
|
UTF-8
| 1,309
| 2.640625
| 3
|
[] |
no_license
|
__author__ = 'orceN'
import sys
import ConfigParser
import argparse
parser = ConfigParser.SafeConfigParser()
parser.read('alignmentCalculatorDefinitions.cfg')
argsparser = argparse.ArgumentParser(description='Configurator for alignmentCalculator definitions')
argsparser.add_argument('-g', '--get', nargs=2, action='store', metavar=('definitionGroup', 'definitionName'),
help='get the definition for defined definitionGroup and definitionName')
argsparser.add_argument('-s', '--set', nargs=3, action='store', metavar=('definitionGroup', 'definitionName', 'definitionValue'),
help='set the definition for defined definitionGroup and definitionName with defined definitionValue')
args = argsparser.parse_args()
if not(args.get is None) and not(args.set is None):
sys.exit("can't execute get and set command in combination")
elif(args.get is not None):
definitionGroup, definitionName = args.get
definitionValue = parser.get(definitionGroup, definitionName)
sys.exit(definitionValue)
elif(args.set is not None):
definitionGroup, definitionName, definitionValue = args.set
parser.set(definitionGroup, definitionName, definitionValue)
with open('alignmentCalculatorDefinitions.cfg', 'w') as alignmentDef:
parser.write(alignmentDef)
| true
|
aeffb30e6bb5e9344c68f1a40e62c82adfda7356
|
Python
|
kumc-bmi/i2p-transform
|
/ADD_SCILHS_100/query.py
|
UTF-8
| 8,442
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
from collections import OrderedDict
#import cx_Oracle as cx # Please uncomment this if using Oracle
import datetime
import logging
import os
import re
import sqlparse
import sys
import pymssql
class mockLog(object):
def p(self, s):
print s
def info(self, s):
p(s)
def debug(self, s):
ps(s)
def get_queries(log, sqldata):
''' get_queries - return individual queries from sql.
>>> log = mockLog()
Make sure we get the statements back with comments removed.
>>> q = """--start with comment
... /* This is a comment...with
... more than one line. */
... with agg as ( -- Inline comment
... select count(*) denom from demographics
... ),
... breakdown as (--another comment
... select sex, count(*) cnt
... from demographics
... group by sex
... )
... select breakdown.sex "Sex", breakdown.cnt "Count",
... round((breakdown.cnt / agg.denom) * 100) "Percent"
... from breakdown, agg;--srsly
...
... select * from some_other_table;"""
>>> for query in get_queries(log, q):
... print query
... # doctest: +NORMALIZE_WHITESPACE
with agg as (
select count(*) denom from demographics
),
breakdown as (
select sex, count(*) cnt
from demographics
group by sex
)
select breakdown.sex "Sex", breakdown.cnt "Count",
round((breakdown.cnt / agg.denom) * 100) "Percent"
from breakdown, agg
<BLANKLINE>
select * from some_other_table
Make sure that destructive stuff throws an exception.
>>> get_queries(log, """delete from important_table;""")
Traceback (most recent call last):
...
ValueError: Illegal token delete
>>> get_queries(log, """insert into important_table
... (col1, col2)
... values('a', 'b')""")
Traceback (most recent call last):
...
ValueError: Illegal token insert
>>> get_queries(log, """truncate table important_table""")
Traceback (most recent call last):
...
ValueError: Illegal token truncate
'''
def _allowed(token_list,
allowed_tok=((sqlparse.tokens.Keyword, 'with', False),
(sqlparse.tokens.Keyword, 'from', False),
(sqlparse.tokens.Keyword, 'order', False),
(sqlparse.tokens.Keyword, 'by', False),
(sqlparse.tokens.DML, 'select', False),
(sqlparse.tokens.Whitespace, '.*', True),
(sqlparse.tokens.Newline, '.*', True),
(sqlparse.tokens.Punctuation, '.*', True),
(sqlparse.tokens.Comment.Single, '.*', True),
(sqlparse.tokens.Wildcard, '.*', True))):
''' Make sure we're not doing anything destructive.
'''
for token in token_list:
for allowedt in allowed_tok:
if token.match(*allowedt):
break
else:
if(not isinstance(token, sqlparse.sql.IdentifierList) and
not isinstance(token, sqlparse.sql.Identifier) and
not isinstance(token, sqlparse.sql.Where) and
not isinstance(token, sqlparse.sql.Parenthesis) and
not (str(token.value).startswith("'") and str(token.value).endswith("'")) and #jgk - added to clumsily handle literal string
not (isinstance(token, sqlparse.sql.Function) and
(str(token.value).startswith('count') or
str(token.value).startswith('round')))):
# Useful for debug: import pdb; pdb.set_trace()
raise ValueError('Illegal token %s' % token)
statements = sqlparse.split(sqldata)
queries = list()
for stmt in statements:
if len(stmt) > 0:
# For each statement, tokenize and make sure it's allowed
parsed = sqlparse.parse(stmt)[0]
toks = [t for t in parsed.tokens
if not isinstance(t, sqlparse.sql.Comment)]
_allowed(toks)
# Then, put the query back together again
query = ''.join([str(t)
for t in toks]).replace(';', '').strip() + '\n'
# For some reason, I couldn't get inline comments out with sqlparse
for comment in re.findall('.*?(--.*?)\n', query):
query = query.replace(comment, '')
queries.append(query.strip().strip('\n'))
return queries
def run_file_queries(log, sqlfile_data, host, port, sid, db_type, user, passwd):
''' Return a list of dictionaries of all results of running all the
queries in the given file.
'''
queries = get_queries(log, sqlfile_data)
results = list()
# jgk: Added MSSQL option
if db_type<>'MSSQL':
dsn = cx.makedsn(host, int(port), sid)
conn = cx.connect(user=user,
password=passwd,
dsn=dsn)
cur = conn.cursor()
else:
conn = pymssql.connect(host=host, user=user, password=passwd, database=sid)
cur = conn.cursor()
for query in queries:
log.info('Executing:\n%s\n' % query)
cur.execute(query)
# Make a list of dictionaries: [{col_name:value_from_db},...]
qr = map(lambda row:
OrderedDict(zip([d[0]
for d in cur.description], row)),
[v for v in cur.fetchall()])
log.info('Query result:\n%s' % qr)
results.append(qr)
return results
def collapse_2dlist(list2d):
'''
>>> collapse_2dlist([[1,2], [3,4]])
[1, 2, 3, 4]
'''
return [j for i in list2d for j in i]
def keyed_results(log, results):
''' Assumes that the key "SECTION" exists
>>> log = mockLog()
>>> print keyed_results(log, [[OrderedDict([
... ('SECTION', 'Demographics'),
... ('Unique PATIDs', 726)])]])
... # doctest: +NORMALIZE_WHITESPACE
{'Demographics.Unique PATIDs': '726'}
>>> print keyed_results(log, [[OrderedDict([
... ('SECTION', 'Demographics'),
... ('Minimum BIRTH_DATE', datetime.datetime(1877, 9, 19, 0, 0)),
... ('Maximum BIRTH_DATE', datetime.datetime(2012, 2, 20, 0, 0))])]])
... # doctest: +NORMALIZE_WHITESPACE
{'Demographics.Minimum BIRTH_DATE': '1877-09-19 00:00:00',
'Demographics.Maximum BIRTH_DATE': '2012-02-20 00:00:00'}
>>> print keyed_results(log, [[OrderedDict([
... ('SECTION', 'Demographics'),
... ('Sex', 'F'),
... ('Count', 377),
... ('Percent', 52)]),
... OrderedDict([
... ('SECTION', 'Demographics'),
... ('Sex', 'M'),
... ('Count', 346),
... ('Percent', 48)])]])
... # doctest: +NORMALIZE_WHITESPACE
{'Demographics.Sex.M.Count': '346',
'Demographics.Sex.M.Percent': '48',
'Demographics.Sex.F.Percent': '52',
'Demographics.Sex.F.Count': '377'}
'''
all_results = list()
for qres in results:
for fields in qres:
keys = fields.keys()
assert(keys[0].upper() == 'SECTION') # jgk - added upper for sqlserver script
section = fields[keys[0]]
if len(keys) < 4:
start = 1
else:
section = '.'.join([section, keys[1], str(fields[keys[1]])])
start = 2
for i in range(start, len(keys)):
res = ('.'.join([section, keys[i]]), str(fields[keys[i]]))
all_results.append(res)
return dict(all_results)
if __name__ == '__main__':
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
sqlfile, host, port, sid, user_env, passwd_env = sys.argv[1:7]
with open(sqlfile, 'r') as f:
sqldata = f.read()
user, passwd = (os.environ[user_env], os.environ[passwd_env])
# Print the results for now
log.info(keyed_results(log,
run_file_queries(log, sqldata, host, port,
sid, user, passwd)))
| true
|
98a4cf4aa7e87c0e5918d5150582fc6479748b1a
|
Python
|
lukasz-migas/SimpleParam
|
/simpleparam/utilities.py
|
UTF-8
| 2,083
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
"""Utilities"""
import inspect
import numbers
def is_number(obj):
"""Check if value is a number"""
if isinstance(obj, numbers.Number):
return True
# The extra check is for classes that behave like numbers, such as those
# found in numpy, gmpy, etc.
elif hasattr(obj, "__int__") and hasattr(obj, "__add__"):
return True
return False
def classlist(class_):
"""
Return a list of the class hierarchy above (and including) the given class.
Same as inspect.getmro(class_)[::-1]
"""
return inspect.getmro(class_)[::-1]
def get_all_slots(class_):
"""
Return a list of slot names for slots defined in class_ and its
superclasses.
"""
# A subclass's __slots__ attribute does not contain slots defined
# in its superclass (the superclass' __slots__ end up as
# attributes of the subclass).
all_slots = []
parent_param_classes = [c for c in classlist(class_)[1::]]
for c in parent_param_classes:
if hasattr(c, "__slots__"):
all_slots += c.__slots__
return all_slots
def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance)) if hasattr(instance, slot)]
# CLS_MATCH = {"Integer": Integer, "Number": Number, "String": String,
# "Choice": Choice, "Option": Option, "Boolean": Boolean, "Range": Range,
# "Color": Color}
# def _validate_parameter(values):
# """Validate and create parameter
# Parameters
# ----------
# values : dict
# dictionary containing standard Parameter values
# Returns
# -------
# Parameter
# Parameter object based on values defined in the `values` object
# """
# obj_cls = values.get("kind", None)
# try:
# return cls_match.get(obj_cls, None)
# except ValueError:
# return None
| true
|
acadd4a3d5ef978b8e0b2a292c07bb7fc35d0862
|
Python
|
hycesar/ls_ProtocolosComunicacao
|
/old_version/client.py
|
UTF-8
| 7,117
| 2.6875
| 3
|
[] |
no_license
|
# terminal
import os
# constants
import constant
# tcp
import socket
# crypto suport
import cript
# passwords
from getpass import getpass
# intrusion
import time
# decode
import base64
class Client:
def __init__(self):
self.CONN()
def CONN(self):
print("Abrindo socket...")
self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Usando endereço...{} na porta...{}".format(
socket.gethostbyname(socket.gethostname()), constant.PORT))
self.tcp.connect((socket.gethostbyname(
socket.gethostname()), constant.PORT))
if self.CONNTEST() and self.CHAPTEST() and self.AESTEST(self.DHKETEST()):
print('Conexão efetuada com sucesso.\n')
def CONNTEST(self):
print("\nMy Three-Way Handshake =P")
testMsg = b'-Fala, benca!'
print(testMsg.decode('utf-8'))
self.tcp.sendall(testMsg)
testMsg = self.tcp.recv(constant.BUFFSIZE)
print(testMsg.decode('utf-8'))
if testMsg.decode('utf-8') == "--Dahle.":
testMsg = b'-Bora, baratinar :)'
self.tcp.sendall(testMsg)
print(testMsg.decode('utf-8'))
print("\nPing efetuado com sucesso.")
return True
return False
def CHAPTEST(self):
return self.CHAP(False)
def CHAP(self, real):
print("\nChallenge-Handshake Authentication Protocol - CHAP")
nonce = self.tcp.recv(constant.NONCESIZE)
print("\nRecebendo nonce para login...{}".format(base64.b85encode(nonce)))
if real == True:
msg = input("Insira login>>> ")
else:
msg = "12345678901"
hashmsg = cript.hash(cript.hash(msg.encode()), nonce)
self.tcp.sendall(hashmsg)
print("Enviando hash {} de login ...{}".format(
base64.b85encode(hashmsg), msg))
nonce = self.tcp.recv(constant.NONCESIZE)
print("\nRecebendo nonce para senha...{}".format(base64.b85encode(nonce)))
if real == True:
msg = getpass("Insira senha>>> ")
else:
msg = "123456"
hashmsg = cript.hash(cript.hash(msg.encode()), nonce)
self.tcp.sendall(hashmsg)
print("Enviando hash {} de senha ...{}".format(
base64.b85encode(hashmsg), msg))
msg = self.tcp.recv(constant.BUFFSIZE).decode('utf-8')
if msg == "Olá admin! Bem-vindo, você está autenticado...":
print(msg)
return True
else:
print("Falha no login e senha. Tente novamente!")
return False
def DHKETEST(self):
return self.DHKE()
def DHKE(self):
print("\nDiffie Hellman Key Exchange - DHKE")
pubkeyServer = self.tcp.recv(constant.BUFFSIZE)
print("\nRecebendo chave pública do servidor {}.".format(
base64.b85encode(pubkeyServer)))
p = cript.DH_init()
pubkeyClient = cript.DH_send(p)
self.tcp.sendall(pubkeyClient.to_bytes(constant.DIFFSIZE, 'big'))
print("\nEnviando chave pública do cliente {}.".format(
base64.b85encode(pubkeyClient.to_bytes(constant.DIFFSIZE, 'big'))))
sharekey = cript.DH_recv(
p, int.from_bytes(pubkeyServer, byteorder='big'))
print("\nCalculando chave compartilhada... {}".format(
base64.b85encode(sharekey.encode())))
nonce = self.tcp.recv(constant.NONCESIZE)
print("\nRecebendo nonce...{}".format(base64.b85encode(nonce)))
clientResponse = cript.hash(sharekey.encode(), nonce)
self.tcp.sendall(clientResponse)
print("\nEnviando resposta...{}".format(
base64.b85encode(clientResponse)))
serverResponse = self.tcp.recv(constant.BUFFSIZE).decode('utf-8')
if "Compartilhamento de chaves concluído com sucesso." == serverResponse:
print(serverResponse)
return sharekey
else:
print(serverResponse)
time.sleep(cript.randint(5, 10))
return False
def AESTEST(self, sharekey):
print("\nMy Three-Way Handshake - AES Version - CLIENTE")
msg = b"-Bote feh, Vei."
print("\n", msg)
ciphertext = cript.encript(sharekey, msg)
print("Enviando mensagem ao servidor {}.".format(ciphertext))
self.tcp.sendall(ciphertext)
msg = cript.decript(sharekey, self.tcp.recv(constant.BUFFSIZE))
print("\nMensagem recebida: {}".format(msg.decode('utf-8')))
if msg == b"--Deeeeeu a bixiga!":
msg = b"-Mermao, muito donzelo."
print("\n", msg)
ciphertext = cript.encript(sharekey, msg)
print("Enviando mensagem ao servidor{}.".format(ciphertext))
self.tcp.sendall(ciphertext)
print("\nComunicação segura por AES efetuada com sucesso.")
return True
return False
def insert(self): # insere eleitores no banco de dados
# self.tcp.send(cript.encript(1))
self.tcp.sendall(b'1')
print('Digite seu CPF\n')
cpf = input()
cpf = cript.hash(cpf.encode())
self.tcp.sendall(cpf.encode('utf-8'))
print('Digite uma senha\n')
senha = input()
senha = cript.hash(senha.encode())
self.tcp.sendall(senha.encode('utf-8'))
print(self.tcp.recv(1024).decode('utf-8'))
def vote(self):
self.tcp.sendall(b'2')
print('Digite seu CPF\n')
cpf = input()
cpf = cript.hash(cpf.encode())
self.tcp.sendall(cpf.encode('utf-8'))
print('Digite sua senha\n')
senha = input()
senha = cript.hash(senha.encode())
self.tcp.sendall(senha.encode('utf-8'))
votou = self.tcp.recv(1024)
# votou = cript.decript(votou)
if(votou == False):
print('Usuario ja votou/nao cadastrado\n')
else:
print('Digite seu voto\n')
#voto = input()
# voto = cript.encript(voto)
# self.tcp.sendall(voto.encode('utf-8'))
# print('FIM')
self.tcp.close()
def close(self):
print("Fim da execução...")
self.tcp.close()
def run(self):
run = True
executions = 0
while(run):
print(executions)
msg = input("Insira comando>>> ")
if msg == "_votar":
self.vote
elif msg == "_inserir":
self.insert
elif msg == "Sair":
run = False
print("Enviando comando ao servidor...")
self.tcp.sendall(msg.encode())
else:
print("Enviando comando ao servidor...")
self.tcp.sendall(msg.encode())
def main():
os.system('cls' if os.name == 'nt' else 'clear')
print("Criando instância do cliente...")
s = Client()
s.run()
s.close()
if __name__ == "__main__":
print("Executando cliente pelo terminal...")
main()
else:
print("Não usou terminal, apenas importou módulo.")
| true
|
6af0e2a9782f95623a1ea89a33885a8d70e3c1a9
|
Python
|
Romalouz/Automation
|
/media/pc/manager.py
|
UTF-8
| 1,272
| 2.515625
| 3
|
[] |
no_license
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Title: manager.py
# Package: Pc
# Author: Romain Gigault
import socket
import struct
from media import media
class PCManager(object):
def wake_on_lan(self,macaddress):
""" Switches on remote computers using WOL. """
error = False
# Check macaddress format and try to compensate.
if len(macaddress) == 12:
pass
elif len(macaddress) == 12 + 5:
sep = macaddress[2]
macaddress = macaddress.replace(sep, '')
else:
#raise ValueError('Incorrect MAC address format')
error = True
# Pad the synchronization stream.
data = ''.join(['FFFFFFFFFFFF', macaddress * 20])
send_data = ''
# Split up the hex values and pack.
for i in range(0, len(data), 2):
send_data = ''.join([send_data,
struct.pack('B', int(data[i: i + 2], 16))])
# Broadcast it to the LAN.
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(send_data, ('<broadcast>', 7))
except:
error = True
return error
| true
|
dfc8f9e07351ce4e516775cc986b05b7b1f41d2b
|
Python
|
jpnewman/print_photo_exif_info
|
/helpers.py
|
UTF-8
| 3,117
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import exifread
from mezmorize import Cache
CACHE = Cache(CACHE_TYPE='filesystem', CACHE_DIR='cache')
# https://github.com/drewsberry/gpsextract/blob/master/gpsread.py
def ratio_to_float(ratio):
"""ratio_to_float."""
# Takes exif tag value ratio as input and outputs float
if not isinstance(ratio, exifread.utils.Ratio):
raise ValueError("You passed something to ratio_to_float that isn't "
"a GPS ratio.")
# GPS metadata is given as a number and a density
return ratio.num / ratio.den
# https://github.com/drewsberry/gpsextract/blob/master/gpsread.py
def tag_to_float(gps_tag):
"""tag_to_float."""
# Takes GPS exif lat or long tag as input and outputs as simple float in
# degrees
if gps_tag is None:
return None
if not isinstance(gps_tag, exifread.classes.IfdTag):
raise ValueError("You passed something to tag_to_float that isn't an "
"EXIF tag.")
_gps_ang = [ratio_to_float(ratio) for ratio in gps_tag.values]
_gps_float = _gps_ang[0] + _gps_ang[1] / 60 + _gps_ang[2] / 3600
return _gps_float
# https://programminghistorian.org/en/lessons/transliterating
cyrillic_translit = {
u'\u0410': 'A', u'\u0430': 'a',
u'\u0411': 'B', u'\u0431': 'b',
u'\u010d': 'C',
u'\u0412': 'V', u'\u0432': 'v',
u'\u0413': 'G', u'\u0433': 'g',
u'\u0414': 'D', u'\u0434': 'd',
u'\u0415': 'E', u'\u0435': 'e',
u'\u0416': 'Zh', u'\u0436': 'zh',
u'\u0417': 'Z', u'\u0437': 'z',
u'\u0418': 'I', u'\u0438': 'i',
u'\u0419': 'I', u'\u0439': 'i',
u'\u041a': 'K', u'\u043a': 'k',
u'\u041b': 'L', u'\u043b': 'l',
u'\u041c': 'M', u'\u043c': 'm',
u'\u041d': 'N', u'\u043d': 'n',
u'\u041e': 'O', u'\u043e': 'o',
u'\u00f3': 'o',
u'\u041f': 'P', u'\u043f': 'p',
u'\u0420': 'R', u'\u0440': 'r',
u'\u0421': 'S', u'\u0441': 's',
u'\u0422': 'T', u'\u0442': 't',
u'\u0423': 'U', u'\u0443': 'u',
u'\u0424': 'F', u'\u0444': 'f',
u'\u0425': 'Kh', u'\u0445': 'kh',
u'\u0426': 'Ts', u'\u0446': 'ts',
u'\u0427': 'Ch', u'\u0447': 'ch',
u'\u0428': 'Sh', u'\u0448': 'sh',
u'\u0429': 'Shch', u'\u0449': 'shch',
u'\u042a': '"', u'\u044a': '"',
u'\u042b': 'Y', u'\u044b': 'y',
u'\u042c': "'", u'\u044c': "'",
u'\u042d': 'E', u'\u044d': 'e',
u'\u042e': 'Iu', u'\u044e': 'iu',
u'\u042f': 'Ia', u'\u044f': 'ia',
u'\u017e': 'z',
u'\u00ed': 'i',
u'\u00e1': 'a',
u'\u00e3': 'a',
u'\u00f1': 'n'
}
# https://programminghistorian.org/en/lessons/transliterating
def transliterate(word, translit_table):
converted_word = ''
for char in word:
transchar = ''
if char in translit_table:
transchar = translit_table[char]
else:
transchar = char
converted_word += transchar
return converted_word
@CACHE.memoize()
def get_location_from_lat_lon(geolocator, lat, lon, timeout=25):
"""get_location_from_lat_lon."""
location = geolocator.reverse("{0}, {1}".format(lat, lon), timeout=timeout)
return location
| true
|
3c664c9b2609e81502df7123b64a19c695c9e13c
|
Python
|
moe-auda/pythonProject1
|
/app6.py
|
UTF-8
| 78
| 2.90625
| 3
|
[] |
no_license
|
#tuples cant be modified like lists
coordinates = (4, 5)
print(coordinates[0])
| true
|
863c256d9b9aae675365769bc7021f6724e83fe1
|
Python
|
Edogawa-Konan/code_in_school
|
/network/HW5/udp_scan.py
|
UTF-8
| 1,245
| 2.578125
| 3
|
[] |
no_license
|
# -*- coding:utf-8 -*-
# -*- by prime -*-
import socket
import struct
class udp_scan:
def __init__(self,hostname,timeout=3):
self.host=hostname
self.sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.sock.settimeout(timeout)
def scan(self):
for port in [53]:
try:
self.sock.sendto(b"",(socket.gethostbyname(self.host),port))
self.sock.recvfrom(256)
except socket.timeout:
print('端口{}没有回复udp报文'.format(port))
self.icmp_receive(port)
continue
def icmp_receive(self,port):
icmp=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP)
icmp.settimeout(5)
try:
recPacket, addr = icmp.recvfrom(256)
except:
print('端口{}没有回复ICMP报文'.format(port))
return
icmpHeader = recPacket[20:28] #IP数据包头部20个字节
head_type, code, checksum, packetID, sequence = struct.unpack("bbHHh", icmpHeader)
print('ICMP报文类型:{},返回代码:{}'.format(head_type,code))
icmp.close()
if __name__ == '__main__':
t=udp_scan('www.baidu.com')
t.scan()
| true
|
54f650a5625234e04442667debb69d10e645e31d
|
Python
|
bayramtuccar/PythonNote
|
/hackerrank/countingValleys.py
|
UTF-8
| 2,372
| 3.3125
| 3
|
[] |
no_license
|
#!/bin/python3
import sys
UP_INPUT_TEXT = "U"
DOWN_INPUT_TEXT = "D"
EQUEL_TEXT = "_"
UP_TEXT = "/"
DOWN_TEXT = "\\"
DRAW_MODE_ON = False
def inc_dec_index(cur_text, new_text):
' Calculate index shift'
inc_idx = 0
cur_char = cur_text[cur_text.__len__() - 1]
if cur_char.__eq__(new_text):
if new_text.__eq__(UP_TEXT):
inc_idx += 1
elif new_text.__eq__(DOWN_TEXT):
inc_idx -= 1
elif cur_char.__eq__(EQUEL_TEXT) and new_text.__eq__(DOWN_TEXT):
inc_idx -= 1
return inc_idx
def drawingValleys(n, s):
' Draw the path '
cur_idx = 0
text_dic = {0: EQUEL_TEXT}
for idx in range(n):
new_text = None
cur_char = s[idx]
if UP_INPUT_TEXT.__eq__(cur_char):
new_text = UP_TEXT
elif DOWN_INPUT_TEXT.__eq__(cur_char):
new_text = DOWN_TEXT
inc_idx = 0
try:
cur_text = text_dic[cur_idx]
inc_idx = inc_dec_index(cur_text, new_text)
cur_idx += inc_idx
text_dic[cur_idx] = text_dic[cur_idx] + new_text
except:
new_text = (idx + 1) * " " + new_text
text_dic[cur_idx] = new_text
for key in text_dic.keys():
if key != cur_idx:
text_dic[key] = text_dic[key] + " "
text_dic[0] = text_dic[0] + "_"
keys = text_dic.keys()
s_keys = sorted(keys, reverse=True)
res_text = ""
for s_key in s_keys:
res_text += text_dic[s_key] + "\n"
return res_text
def countingValleys(n, s):
' Count '
i_ar = []
for s_char in s:
if s_char.__eq__(UP_INPUT_TEXT):
i_ar.append(1)
elif s_char.__eq__(DOWN_INPUT_TEXT):
i_ar.append(-1)
count_valley = 0
sum = 0
in_valley = False
for i_mem in i_ar:
if sum == 0 and i_mem == -1:
in_valley = True
if in_valley and sum == -1 and i_mem == 1:
count_valley += 1
in_valley = False
sum += i_mem
return count_valley
if __name__ == "__main__":
n = int(input().strip())
s = input().strip()
if DRAW_MODE_ON:
result = drawingValleys(n, s)
print(result)
else:
result = countingValleys(n, s)
print(result)
| true
|
2038f5b93c7987a1284d279f6feac4fc4ee33424
|
Python
|
gloryxiao/python-core
|
/src/py2/base_dev/with_clause.py
|
UTF-8
| 681
| 3.25
| 3
|
[] |
no_license
|
#!/user/bin/env python
# coding=utf-8
import traceback
class func(object):
def __enter__(self):
# raise Exception("haha")
pass
def __exit__(self, type, value, trace):
print type
print value
print trace
print traceback.format_exc(trace)
# return True # 使用返回值True捕获with中抛出的不同的异常,异常不会抛出with上下文
return 1 # 同上
# return 0 # 使用返回值False(0)(None)抛出异常,异常会抛出with上下文
if __name__ == "__main__":
a = None
with func() as f:
raise Exception("bbb")
a = 1
print a
| true
|
f8703a82ad999125a182712b7f86e6f72192a498
|
Python
|
vyahello/upgrade-python-kata
|
/kata/08/decorators.py
|
UTF-8
| 1,966
| 4.21875
| 4
|
[
"MIT"
] |
permissive
|
"""
You have to write a bunch of decorators to trace execution.
-----------------------------------
For doctests run following command:
python -m xdoctest -v decorators.py
or
python3 -m xdoctest -v decorators.py
For manual testing run:
python decorators.py
"""
from typing import Callable, Generator, Any
from functools import wraps
_Generator = Generator[str, None, None]
_CallableGenerator = Callable[[], _Generator]
def trace(func: Callable[[Any], Any]) -> _CallableGenerator:
"""Traces function execution."""
@wraps(func)
def wrapper(*args, **kwargs) -> _Generator:
name: str = func.__name__
yield f"Entering {name} function with [{args} {kwargs}] arguments"
yield f"Result is '{func(*args, **kwargs)}'"
yield f"Exiting {name} function"
return wrapper
def multiply_by(multiplier: int) -> Callable[[Any], Any]:
"""Multiplies a number."""
def decorator(func: Callable[[Any], Any]) -> _CallableGenerator:
@wraps(func)
def wrapper(*args, **kwargs):
func_name: str = func.__name__
yield f'Calling "{func_name}({args[0]}, {args[1]})" function'
yield f'"{func_name}" function is multiplied by {multiplier}'
yield f"Result is {func(*args, **kwargs) * multiplier}"
return wrapper
return decorator
@trace
def say_hello(word: str) -> str:
"""Says hello.
Examples:
>>> tuple(say_hello("Python"))
>>> ("Entering say_hello function with [('Python',) {}] arguments", "Result is 'Hello Python'", 'Exiting say_hello function')
"""
return f"Hello {word}"
@multiply_by(multiplier=3)
def add(a: int, b: int) -> int:
"""Adds two items.
Examples:
>>> tuple(add(2, 3))
>>> ('Calling "add(2, 3)" function', '"add" function is multiplied by 3', 'Result is 15')
"""
return a + b
if __name__ == "__main__":
print(tuple(say_hello("Python")))
print(tuple(add(2, 3)))
| true
|
1f984b41d7e53cdb6e4b74ac9094e2411d83ce83
|
Python
|
huyaoyu/numpy_2_pointcloud
|
/scripts/CameraDescriptor.py
|
UTF-8
| 1,317
| 2.640625
| 3
|
[] |
no_license
|
import json
import numpy as np
from pyquaternion import Quaternion
class CameraDescriptor(object):
def __init__(self):
super(CameraDescriptor, self).__init__()
self.id = -1
self.centroid = None
self.quaternion = None
def get_id(self):
return self.id
def get_centroid(self):
return self.centroid
def get_quaternion(self):
return self.quaternion
def read_cam_proj_csv(fn):
pc = np.loadtxt(fn, delimiter=",").astype(np.float32)
camProjs = []
for i in range( pc.shape[0] ):
cd = CameraDescriptor()
cd.id = int(pc[i, 0])
cd.centroid = pc[i, 5:8]
q = pc[i, 1:5]
cd.quaternion = Quaternion( w=q[0], x=q[1], y=q[2], z=q[3] )
camProjs.append(cd)
return camProjs
def read_cam_proj_json(fn, rootElement="camProjs"):
camProjs = []
with open(fn, "r") as fp:
jFp = json.load(fp)
jCamProjs = jFp["camProjs"]
for cp in jCamProjs:
cd = CameraDescriptor()
cd.id = cp["id"]
cd.centroid = np.array( cp["T"], dtype=np.float32 )
q = cp["Q"]
cd.quaternion = Quaternion( w=q[0], x=q[1], y=q[2], z=q[3] )
camProjs.append(cd)
fp.close()
return camProjs
| true
|
068f71938b6e302a0346180afa4907994f18655c
|
Python
|
gabriellaec/desoft-analise-exercicios
|
/backup/user_138/ch153_2020_04_13_20_21_31_494396.py
|
UTF-8
| 424
| 2.640625
| 3
|
[] |
no_license
|
def agrupa_por_idade(dict1):
dict2={}
lista=[]
for k in dict1.keys():
if k<=11:
lista.append(k)
dict2['criança']=lista
elif k<=17:
lista.append(k)
dict2['adolescente']=lista
elif k<=59:
lista.append(k)
dict2['adulto']=lista
else:
lista.append(k)
dict2['idoso']=lista
return dict2
| true
|
f9cecdd5440c7a202d3ef2ad4ae8f2640c71fb44
|
Python
|
qmnguyenw/python_py4e
|
/geeksforgeeks/python/python_all/83_6.py
|
UTF-8
| 2,490
| 4.09375
| 4
|
[] |
no_license
|
Python | Frequency of numbers in String
Sometimes, while working with Strings, we can have a problem in which we need
to check how many of numerics are present in strings. This is a common problem
and have application across many domains like day-day programming and data
science. Lets discuss certain ways in which this task can be performed.
**Method #1 : Usingre.findall() + len()**
The combination of above functions can be used to perform this task. In this,
we check for all numbers and put in list using findall() and the count is
extracted using len().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + len()
import re
# initializing string
test_str = "geeks4feeks is No. 1 4 geeks"
# printing original string
print("The original string is : " + test_str)
# Frequency of numbers in String
# Using re.findall() + len()
res = len(re.findall(r'\d+', test_str))
# printing result
print("Count of numerics in string : " + str(res))
---
__
__
**Output :**
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3
**Method #2 : Usingsum() + findall()**
The combination of above functions can also be used to solve this problem. In
this, we cumulate the sum using sum(). The task of findall() is to find all
the numerics.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + sum()
import re
# initializing string
test_str = "geeks4feeks is No. 1 4 geeks"
# printing original string
print("The original string is : " + test_str)
# Frequency of numbers in String
# Using re.findall() + sum()
res = sum(1 for _ in re.finditer(r'\d+', test_str))
# printing result
print("Count of numerics in string : " + str(res))
---
__
__
**Output :**
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
| true
|
9dddf912168b4a540ea7a4cf8f12d1f6d654393f
|
Python
|
knwnw/yandex-algorithmic-training
|
/lesson4/f.py
|
UTF-8
| 448
| 3.46875
| 3
|
[] |
no_license
|
import sys
data = sys.stdin.read()
d = {}
for line in data.strip().split('\n'):
name, item, quantity = line.strip().split()
if name not in d:
d[name] = {item: int(quantity)}
else:
if item not in d[name]:
d[name][item] = int(quantity)
else:
d[name][item] += int(quantity)
for name in sorted(d):
print(f'{name}:')
for item in sorted(d[name]):
print(item, d[name][item])
| true
|
1943c8b6c5135b29865b9fb6716d7a8295e42888
|
Python
|
PaulJermann/ProjetPythonOrbitales
|
/1sFiona(prefix).py
|
UTF-8
| 1,182
| 2.953125
| 3
|
[] |
no_license
|
import numpy
from math import pi
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
#on cree plein de valeurs pour faire la grille
dz=0.5
zmin=0
zmax=20
x = np.arange(zmin,zmax,dz)
y = np.arange(zmin,zmax,dz)
z = np.arange(zmin,zmax,dz)
X,Y,Z = np.meshgrid(x,y,z)
#on veut travailler en 3D donc on se place en coordonnées sphériques
r = numpy.sqrt(x ** 2 + y ** 2 + z ** 2)
theta = numpy.arccos(z/r)
phi = numpy.arctan(y/x)
a0 = 0.529 * 10**(-10) #valeur du rayon de Bohr
R = (1/a0)**3/2 * 2 * numpy.exp(-r/a0) # partie radiale 1s
#on calcule la fonction d'onde soit R*Y cf doc
WF = R * 1/(4 * np.pi )
#tracé du résultat en 3D
fig = plt.figure()
ax = fig.gca(projection='3d') # Affichage en 3D
ax.plot_surface(x, y, z, cmap=cm.coolwarm, linewidth=0) # Tracé d'une
surface
plt.title("Tracé d'une surface")
graphx = r * np.sin(theta)* np.cos(phi)
graphy = r * np.sin(phi) * np.sin(phi)
graphz = r * np.cos(phi)
ax.set_xlabel('graphx')
ax.set_ylabel('graphy')
ax.set_zlabel('graphz')
plt.tight_layout()
plt.show()
| true
|
3c229e2dffa84990d1840a32a9446bef9117e58c
|
Python
|
JoyD424/mesh_repair
|
/viewCrossSections.py
|
UTF-8
| 16,426
| 3.34375
| 3
|
[] |
no_license
|
import sys, math, pygame, OpenGL, copy
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
# Constants
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
# Basic Colors
black = [0.0, 0.0, 0.0]
white = [1.0, 1.0, 1.0]
red = [1.0, 0.0, 0.0]
############################################ CLASS DEFINITIONS: ############################################
class Graph:
def __init__(self, listVertices, listFaces, listTetrahedra, listWindingNums):
self.vertices = listVertices
self.faces = listFaces # a face contains 3 elements, each pointing to an index in listVertices. Faces are triangles, CCW orientation
self.tetrahedra = listTetrahedra # a tetrahedra contains 4 elements, each an index for listVertices.
self.windingNumbers = listWindingNums # Calculated winding number corresponding to each tetrahedra in th elist of tetrahedra
class Instance:
def __init__(self, occurences, w):
self.occurences = occurences
self.windingNum = w
############################################ READING FUNCTIONS: ############################################
# Process txt file with mesh description
# (vertices, tetrahedra, and winding numbers)
def readTxtFile(f):
# Process vertices
vertices = []
len = f.readline()
for i in range(0, int(len)):
posn = f.readline().split()
p = (float(posn[0]), float(posn[1]), float(posn[2]))
vertices.append(p)
# print vertices # TEST
# Process faces
faces = []
len = len = int(f.readline())
for i in range(0, len):
faceLst = f.readline().split()
face = (int(faceLst[0]), int(faceLst[1]), int(faceLst[2]))
faces.append(face)
# print faces # TEST
# Process tetrahedra
tet = []
len = int(f.readline())
for i in range(0, len):
t = f.readline().split()
index = (int(t[0]), int(t[1]), int(t[2]), int(t[3]))
tet.append(index)
# print tet # TEST
# Process winding numbers
w = []
len = int(f.readline())
for i in range(0, len):
winding = f.readline()
w.append(float(winding))
# print w # TEST
return vertices, tet, faces, w
#################### FIND EXTERIOR FACES: ####################
# Find all the faces of a tetrahedron
def getFaces(tetrahedron):
lst = [(int(tetrahedron[3]), int(tetrahedron[0]), int(tetrahedron[2])), (int(tetrahedron[0]), int(tetrahedron[1]), int(tetrahedron[2])), (int(tetrahedron[3]), int(tetrahedron[2]), int(tetrahedron[1])), (int(tetrahedron[3]), int(tetrahedron[1]), int(tetrahedron[0]))]
return lst
# Create a dictionary (key = normalized face, value = Instance)
def createDictionary(faces, winding):
d = dict()
for f in faces:
# print f # TEST
f = list(f)
f.sort()
f = tuple(f)
if d.has_key(f):
d[f].occurences += 1
else:
d[f].occurences = 1
d[f].windingNum = winding
return d
def exteriorFaces(elems, windingNums):
d = dict()
index = 0
for tet in elems:
facesOfTet = getFaces(tet)
for f in facesOfTet:
# print f # TEST
f = list(f)
f.sort()
f = tuple(f)
if d.has_key(f):
d[f].occurences += 1
else:
d[f] = Instance(1, windingNums[index])
index += 1
repairedFaces = []
wn = []
for key, val in d.iteritems():
if val.occurences == 1:
repairedFaces.append(key)
wn.append(val.windingNum)
return repairedFaces, wn
############################################ SHAPE PROCESSING ############################################
# Takes in a list of max and mins
# Translates the original list of postions to origin
def translateToOrigin(xList, yList, zList, vertices):
# print(vertices) # TEST
bbox = []
for x in xList:
for y in yList:
for z in zList:
posn = [x, y, z]
bbox.append(posn)
# print(bbox) # TEST
# Find centroid of bbox
bbox.sort(key=lambda x: x[0])
centerX = bbox[0][0] + ((bbox[7][0] - bbox[0][0]) / 2)
bbox.sort(key=lambda x: x[1])
centerY = bbox[0][1] + ((bbox[7][1] - bbox[0][1]) / 2)
bbox.sort(key=lambda x: x[2])
centerZ = bbox[0][2] + ((bbox[7][2] - bbox[0][2]) / 2)
# print "Centroid:", (centerX, centerY, centerZ) # TEST
# Translate everything in the vertices list to origin
# centered around the centroid of bbox
vertices = map(lambda x: (x[0] - centerX, x[1] - centerY, x[2] - centerZ), vertices)
# print(vertices) #TEST
bbox = map(lambda x: (x[0] - centerX, x[1] - centerY, x[2] - centerZ), bbox)
return bbox, vertices
# Scale the list of vertices so that it fits in a 10x10x10 box
def scale(bbox, vertices, xList, yList, zList):
# print "Bbox:", bbox # TEST
# print "Vertices:", vertices # TEST
# Find the scaling factor
list = [xList[0], xList[1], yList[0], yList[1], zList[0], zList[1]]
list.sort(key=lambda x: abs(x), reverse=True)
parse = str(abs(list[0]))
# print parse # TEST
numBeforePeriod = 0
for char in parse:
if char == '.':
break
numBeforePeriod += 1
scaleFactor = math.pow(.1, numBeforePeriod - 1)
# print "Scale Factor:", scaleFactor # TEST
vertices = map(lambda x: (x[0] * scaleFactor, x[1] * scaleFactor, x[2] * scaleFactor), vertices)
bbox = map(lambda x: (x[0] * scaleFactor, x[1] * scaleFactor, x[2] * scaleFactor), bbox)
return bbox, vertices
# Fit mesh to screen by applying transformations
def processShape(icoVertices):
length = len(icoVertices)
# print "Length icoVertices:", str(length) # TEST
vertices = copy.copy(icoVertices)
# print vertices # TEST
icoVertices.sort(key=lambda x: x[1])
# print vertices # TEST
yList = (icoVertices[length - 1][1], icoVertices[0][1])
icoVertices.sort(key=lambda x: x[0], reverse=True)
xList = (icoVertices[length - 1][0], icoVertices[0][0])
icoVertices.sort(key=lambda x: x[2], reverse=True)
zList = (icoVertices[length - 1][2], icoVertices[0][2])
# print xList, yList, zList # TEST
# print vertices # TEST
bbox, vertices = translateToOrigin(xList, yList, zList, vertices)
# print(vertices) # TEST
# print(bbox) # TEST
bbox, vertices = scale(bbox, vertices, xList, yList, zList)
# bbox = [] # TEST
return bbox, vertices
# Calculate the center of mass of a tetrahedra of the CDT
def calculateCenterMass(t, vertices):
v1 = vertices[t[0]]
v2 = vertices[t[1]]
v3 = vertices[t[2]]
v4 = vertices[t[3]]
x = (v1[0] + v2[0] + v3[0] + v4[0]) / 4
y = (v1[1] + v2[1] + v3[1] + v4[1]) / 4
z = (v1[2] + v2[2] + v3[2] + v4[2]) / 4
return (x, y, z)
# DEFAULT: Get rid of tets with +z coordinate
# ELSE: cuts along any axis
def sortTets(cdtTets, processedVertices, windingNums, cutOff, threshold):
"""tetList = []
wnList = []
index = 0
for t in cdtTets:
cm = calculateCenterMass(t, processedVertices)
# Z-axis: if cm[2] <= cutOff:
# X-axis: if cm[0] <= cutOff:
# if cm[1] <= cutOff: # Y-axis
if cm[2] <= cutOff:
tetList.append(t)
wnList.append(windingNums[index])
index += 1"""
tetList = []
wnList = []
index = 0
for t in cdtTets:
cm = calculateCenterMass(t, processedVertices)
# Z-axis: if cm[2] <= cutOff:
# X-axis: if cm[0] <= cutOff:
# if cm[1] <= cutOff: # Y-axis
if cm[2] <= cutOff:
tetList.append(t)
wnList.append(windingNums[index])
elif windingNums[index] >= threshold:
tetList.append(t)
wnList.append(windingNums[index])
index += 1
return tetList, wnList
######################################## RENDERING FUNCTIONS: ########################################
# Calculate Distance
def distance(posn1, posn2):
dist = math.sqrt(math.pow(posn2[0] - posn1[0], 2) + math.pow(posn2[1] - posn1[1], 2) + math.pow(posn2[2] - posn1[2], 2))
return dist
# Color conversion:
# Get rbg value of the winding number --> convert to openGL
# Color scale:
# Pink (5) --> Red (1) --> Yellow (1/2) --> Green (1/4) --> Sky Blue (0) --> Navy (-1/2) --> Purple (-5)
# (255, 0, 255) <-- (255,0,0) <-- (255, 255, 0) <-- (0, 255, 0) <-- (0, 255, 255) <-- (0, 0, 255) <-- (123, 0, 255)
def assignRGBValue(n):
def incrementValue(i):
return i/255
if n > 1:
# print("N: " + str(n)) # TEST
n = n - 1
# print("IncrementValue: " + str(incrementValue(2.0))) # TEST
blueValue = int(n / incrementValue(1.0))
rgb = [1.0, 0.0, (blueValue / 255.0)]
# print(rgb) # TEST
elif n > .5:
n = n - .5
greenValue = 255 - int(round(n / incrementValue(.5)))
# print("Green value: " + str(greenValue)) # TEST
rgb = [1.0, float(greenValue / 255.0), 0.0]
"""print greenValue
print float(greenValue / 255.0)"""
elif n > .25:
n = n - .25
redValue = int(round(n / incrementValue(.25)))
rgb = [float(redValue / 255.0), 1.0, 0.0]
elif n > 0:
blueValue = 255 - int(round(n / incrementValue(.25)))
rgb = [0.0, 1.0, float(blueValue / 255.0)]
elif n > -.5:
greenValue = 255 + int(round(n / incrementValue(.5)))
rgb = [0.0, float(greenValue / 255.0), 1.0]
elif n >= -1:
n = n + .5
# print("N: " + str(n)) # TEST
redValue = -1 * int(round(n / (.5/123)))
# print("RedValue: " + str(redValue)) # TEST
rgb = [float(redValue / 255.0), 0.0, 1.0]
# print(rgb) # TEST
else:
print(n)
print("ERROR: WINDING NUMBER NOT IN COLOR RANGE!")
rgb = [0.0, 0.0, 0.0]
return rgb
# Returns a list of faces of the tetrahedron
def getFacesWN(tetrahedron):
lst = [(tetrahedron[3], tetrahedron[0], tetrahedron[2]), (tetrahedron[0], tetrahedron[1], tetrahedron[2]), (tetrahedron[3], tetrahedron[2], tetrahedron[1]), (tetrahedron[3], tetrahedron[1], tetrahedron[0])]
return lst
# Draws the tet mesh as separate tetrahedrons
# MAY NOT HAVE CONSISTENT ORIENTATION, HAS OVERLAPPING FACES OOPS
def Tetrahedron(vertices, faces, windingList): #isFirst):
glBegin(GL_TRIANGLES)
listFaces = []
index = 0
for f in faces:
color = assignRGBValue(windingList[index])
glColor3fv(color)
listFaces.append(f)
for vertex in f:
glVertex3fv(vertices[vertex])
index += 1
glEnd()
"""glBegin(GL_LINES)
glColor3fv(black)
for face in listFaces:
edges = [(face[0], face[1]), (face[1], face[2]), (face[0], face[2])]
for e in edges:
glVertex3fv(vertices[e[0]])
glVertex3fv(vertices[e[1]])
glEnd()"""
return
"""# Draws the tet mesh as separate tetrahedrons
# MAY NOT HAVE CONSISTENT ORIENTATION, HAS OVERLAPPING FACES OOPS
def Tetrahedron(vertices, tetrahedra, windingList):
glBegin(GL_TRIANGLES)
listFaces = []
index = 0
for t in tetrahedra:
color = assignRGBValue(windingList[index])
glColor3fv(color)
faces = getFaces(t)
for face in faces:
listFaces.append(face)
for vertex in face:
glVertex3fv(vertices[vertex])
index += 1
glEnd()
glBegin(GL_LINES)
glColor3fv(black)
for face in listFaces:
edges = [(face[0], face[1]), (face[1], face[2]), (face[0], face[2])]
for e in edges:
glVertex3fv(vertices[e[0]])
glVertex3fv(vertices[e[1]])
glEnd()
return"""
# Draws the bbox of the tet mesh
def BBox(bbox):
squares = [(2, 3), (3, 1), (1, 0), (0, 2), (1, 5), (5, 4), (4, 0), (0, 1), (5, 1), (1, 3), (3, 7), (7, 5), (4, 5), (5, 7), (7, 6), (6, 4), (2, 0), (0, 4), (4, 6), (6, 2), (7, 3), (3, 2), (2, 6), (6, 7)]
glBegin(GL_LINES)
glColor3fv(black)
for edge in squares:
glVertex3fv(bbox[edge[0]])
glVertex3fv(bbox[edge[1]])
glEnd()
return
# Visualization of winding number and mesh
def render(cdtMesh):
## ONLY RENDER THE MESH ITSELF:
"""index = 0
tetrahedra = []
wns = []
for t in cdtMesh.tetrahedra:
if cdtMesh.windingNumbers[index] >= .50:
tetrahedra.append(t)
wns.append(cdtMesh.windingNumbers[index])
index += 1
cdtMesh.tetrahedra = tetrahedra
cdtMesh.windingNumbers = wns"""
pygame.init()
display = (SCREEN_HEIGHT, SCREEN_WIDTH)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
pygame.display.set_caption("View + Cut Mesh")
glClearColor(1.0, 1.0, 1.0, 0.0)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
lightdiffuse = [1.0, 1.0, 1.0, 1.0]
lightposition = [1.0, 1.0, 1.0, 1.0]
lightambient = [0.30, 0.30, 0.30, 0.30]
lightspecular = [1.0, 1.0, 1.0, 1.0]
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightdiffuse)
glLightfv(GL_LIGHT1, GL_POSITION, lightposition)
glLightfv(GL_LIGHT1, GL_AMBIENT, lightambient)
glMaterialfv(GL_FRONT, GL_DIFFUSE, lightdiffuse)
glMaterialfv(GL_FRONT, GL_SPECULAR, lightspecular)
glEnable(GL_LIGHT1)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
# Process shape (fit within a 10 by 10 cube, translate to origin)
bbox, vertices = processShape(cdtMesh.vertices)
glTranslatef(0.0,0.0, -40)
zLengthBbox = distance(bbox[0], bbox[4]) # depth of bbox for cutting along z-axis
# xLengthBbox = distance(bbox[4], bbox[5])
# yLengthBbox = distance(bbox[3], bbox[1])
# print zLengthBbox # TEST
# print "Render Vertices:", vertices
# print "Render bbox:", bbox
# print(vertices) # TEST
# Process tets for exterior faces and corresponding winding numbers
faces, windingNums = exteriorFaces(cdtMesh.tetrahedra, cdtMesh.windingNumbers)
# isFirst = True
count = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_DOWN:
glRotatef(-20, 0, 0, 0)
elif event.key == K_UP:
glRotatef(20, 0, 0, 0)
elif event.key == K_RIGHT:
glRotatef(20, 0, 1, 0)
elif event.key == K_LEFT:
glRotatef(-20, 0, 1, 0)
elif event.key == K_SPACE:
# print count # TEST
cutOff = bbox[4][2] + count * -.01 * zLengthBbox
# cutOff = bbox[5][0] + count * -.01 * xLengthBbox
# cutOff = bbox[3][1] + count * -.01 * yLengthBbox
# print cutOff # TEST
tetrasToDisplay, newWindingNums = sortTets(cdtMesh.tetrahedra, vertices, cdtMesh.windingNumbers, cutOff, .38) # FOR TORUS
"""cdtMesh.tetrahedra = tetrasToDisplay
cdtMesh.windingNumbers = newWindingNums"""
faces, windingNums = exteriorFaces(tetrasToDisplay, newWindingNums)
count += 1
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
Tetrahedron(vertices, faces, windingNums)
"""Tetrahedron(vertices, cdtMesh.tetrahedra, cdtMesh.windingNumbers)"""
BBox(bbox)
pygame.display.flip()
# isFirst = False
return
def main():
# Process Mesh
name = raw_input("Mesh info (.txt): ")
f = open(name + ".txt", 'r')
v, t, _, w = readTxtFile(f)
cdtMesh = Graph(v, [], t, w)
# Default view: cut plane along x-axis, i.e., only display tets
# whose CM are along the negative z axis
# _, vertices = processShape(cdtMesh.vertices)
# tetrasToDisplay, newWindingNums = sortTets(cdtMesh.tetrahedra, vertices, cdtMesh.windingNumbers)
# Rendering
# cdtMesh.vertices = vertices
# cdtMesh.tetrahedra = tetrasToDisplay
# cdtMesh.windingNumbers = newWindingNums
render(cdtMesh)
return
if __name__ == "__main__":
main()
| true
|
066b2482b35e20b95f13883eacc41a3241945a10
|
Python
|
andersonpablo/Exercicios_Python
|
/Aula07/avaliando02-area-circulo.py
|
UTF-8
| 633
| 4.71875
| 5
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# 2. Faça um algoritmo para calcular a área de um círculo, dado o valor do seu raio, que deve ser positivo
# (maior que 0). A fórmula da área do círculo é: area = 3.14 * (raio ** 2).
# Lê o valor do raio
raio = float(input("Digite o raio do círculo: "))
# Verifica se o valor é positivo
if raio > 0:
# Se for positivo, calcula a área conforme a fórmula do enunciado da questão
area = 3.14 * (raio ** 2)
# Imprime o resultado
print("A área do círculo é: ", area)
else:
# Se o raio for negativo, imprime a mensagem abaixo
print("O valor do raio precisa ser positivo!")
| true
|
6fef3a4904fbfcbcd1e8f9579f0a070a4c234c47
|
Python
|
hllj/projectai1
|
/algorithm.py
|
UTF-8
| 927
| 2.5625
| 3
|
[] |
no_license
|
from environment import Environment
import matplotlib.pyplot as plt
WMAX = 1e3
dx = [-1, 0, 1, 1, 1, 0, -1, -1]
dy = [1, 1, 1, 0, -1, -1, -1, 0]
class Algorithm():
def __init__(self, start_point, end_point, ENV):
self.E = ENV
self.start_point = start_point
self.end_point = end_point
self.path = []
self.fre = {}
self.trace = {}
self.timeProcessing = 0
self.cost = 0
def draw_start_end(self):
plt.scatter(self.start_point[0], self.start_point[1])
plt.scatter(self.start_point[0], self.start_point[1] + 0.5, marker="$S$")
plt.scatter(self.end_point[0], self.end_point[1])
plt.scatter(self.end_point[0], self.end_point[1] + 0.5, marker="$G$")
def imitate_environment(self, a_id):
self.E.draw_environment(a_id)
self.draw_start_end()
if (len(self.E.place) > 0):
self.E.draw_place()
| true
|
8b8fab712fac9120708b388d86594de7a05f5370
|
Python
|
neuroph12/nlpy
|
/nltks/ppattachment.py
|
UTF-8
| 459
| 2.640625
| 3
|
[] |
no_license
|
# Prepositional Phrase Attachment Corpus
from collections import defaultdict
import nltk
entries = nltk.corpus.ppattach.attachments('training')
table = defaultdict(lambda: defaultdict(set))
for entry in entries:
key = entry.noun1 + '-' + entry.prep + '-' + entry.noun2
table[key][entry.attachment].add(entry.verb)
for key in sorted(table):
if len(table[key]) > 1:
print(key, 'N:', sorted(table[key]['N']), 'V:', sorted(table[key]['V']))
| true
|
b89aed7f77928761291eb0f9fc0ea5bfe7ff3246
|
Python
|
augus2349/CYPFranciscoMC
|
/tira.py
|
UTF-8
| 118
| 2.65625
| 3
|
[] |
no_license
|
if a > 6:
if a==10:
print("jdvjrfj")
else:
print("ijvoerfrfok")
else:
print("juifegoirj")
| true
|
16ba5e6ae3a0ae742c81a7005655f7daef4d3b55
|
Python
|
davidgascon/qr_reader-scanner
|
/misc/last_name_cleanser.py
|
UTF-8
| 1,599
| 3.875
| 4
|
[] |
no_license
|
#used to clean the data from the original last names csv.
#initially I used pandas, but I quickly learned it would be easy to work with the csv file rather than the data type that pandas imported it as. I realized this when I tried to clean each name.
#The main difference between this and first name cleanser is how the names were initially stored and the seperators in the csv's.
import csv
clean_last_names = [] #creates a list of clean last names
with open('original_last_names.csv') as csvfile: #opens the file
last_names = csv.reader(csvfile) #reads the file
print(last_names)
for name in last_names: #the inital rows are formatted like 1. Gascon . For each row
name = str(name) #Sets the datatype for that row to a string rather than a list item
name = name.split(" ") #The spaces are between the period and the first character of each name. Split the name here. name[1] should be the last name. Right now we have something close to Gascon'] . the '] comes from changing the row to a string
name = name[1] #sets the name we're working with to the second half of the split. It's just easier for me to do this. I bet I could've combined this with the above line if I tried hard enough
name = name.split("'") #since our strings are now Gascon'] , split the string at the '.
print(name[0]) #we really only care about the first half of the split
clean_last_names.append(name[0]) #add to the clean list
print(name)
print(clean_last_names)
#writes the list to a txt file.
file = open("last_names.txt", "w+")
for item in clean_last_names:
file.write(f"{item},")
file.close()
| true
|
53ab30afc8a4fb2995f283e3460c71128fdb6720
|
Python
|
plusline/picoctf-2018-writeup
|
/General Skills/script me/script_me_solution.py
|
UTF-8
| 851
| 2.71875
| 3
|
[] |
no_license
|
proble= '((())()) + (()()()) + (()) + () + (()()()(())()()) + (()) + (((()())()())()) + ()() + (()) + (()()()()()()()())'
proble=proble.split(" + ")
num=[]
for one in proble:
count=0
max_c=0
for i in range(len(one)):
if one[i]=='(':
count+=1
elif one[i]==')':
count-=1
max_c=max(max_c,count)
num=num+[max_c]
def combine(str1,str2,num1,num2):
if num1<num2:
return '('+str1+str2[1:]
elif num1>num2:
return str1[0:-1]+str2+')'
elif num1==num2:
return str1+str2
ans=proble[0]
num_total=num[0]
for i in range(1,len(proble),1):
ans=combine(ans,proble[i],num_total,num[i])
#print(ans)
num_total=max(num_total,num[i])
print("answer:",ans)
#flag: picoCTF{5cr1pt1nG_l1k3_4_pRo_0466cdd7}
| true
|
f08062b63a8db10fb4299d10ab978ca911f72bf6
|
Python
|
kpatel1293/CodingDojo
|
/DojoAssignments/Python/PythonFundamentals/Assignments/8_MultiplicationTable.py
|
UTF-8
| 1,150
| 4.40625
| 4
|
[] |
no_license
|
# Optional Assignment: Multiplication Table
# Create a program that prints a multiplication table in your console.
# Your table should look like the following example:
'''
x 1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 6 7 8 9 10 11 12
2 2 4 6 8 10 12 14 16 18 20 22 24
3 3 6 9 12 15 18 21 24 27 30 33 36
4 4 8 12 16 20 24 28 32 36 40 44 48
5 5 10 15 20 25 30 35 40 45 50 55 60
6 6 12 18 24 30 36 42 48 54 60 66 72
7 7 14 21 28 35 42 49 56 63 70 77 84
8 8 16 24 32 40 48 56 64 72 80 88 96
9 9 18 27 36 45 54 63 72 81 90 99 108
10 10 20 30 40 50 60 70 80 90 100 110 120
11 11 22 33 44 55 66 77 88 99 110 121 132
12 12 24 36 48 60 72 84 96 108 120 132 144
'''
# What is the most efficient way to produce the above output?
# Hint: Don't worry about getting it perfectly spaced, just ensure
# all the values are properly output!
print ' x 1 2 3 4 5 6 7 8 9 10 11 12'
for e in range(1,13):
s = ''
for f in range(0,13):
if f is 0:
s += ' ' + str(e)
else:
s += ' ' + str(f * e)
print s
| true
|
ea647e87cb34bd0c884183daf2802c52617dae8c
|
Python
|
Truncuso/astar_pathfinding_node_networks
|
/extract_canvas.py
|
UTF-8
| 3,153
| 2.828125
| 3
|
[] |
no_license
|
import base64
import time
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
from PIL import Image
from PIL import ImageDraw
def test_url():
options = Options()
user = "i7 8700" # change this to your windows username
options.add_argument("user-data-dir=C:\\Users\\" + user "\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1")
driver = webdriver.Chrome(executable_path=r"C:\Users\\" + user + "\\Downloads\chromedriver.exe", chrome_options=options)
driver.get("http://curran.github.io/HTML5Examples/canvas/smileyFace.html")
canvas = driver.find_element_by_css_selector("#canvas")
# get the canvas as a PNG base64 string
canvas_base64 = driver.execute_script("return arguments[0].toDataURL('image/png').substring(21);", canvas)
# decode
canvas_png = base64.b64decode(canvas_base64)
# save to a file
with open(r"canvas.png", 'wb') as f:
f.write(canvas_png)
def osrs_canvas_scrape():
options = Options()
user = "i7 8700" # change this to your windows username
options.add_argument("user-data-dir=C:\\Users\\" + user "\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1")
driver = webdriver.Chrome(executable_path=r"C:\Users\\" + user + "\\Downloads\chromedriver.exe", chrome_options=options)
driver.set_window_size(10000, 10000)
driver.get("https://www.osrsmap.net/")
canvas = driver.find_element_by_id("map")
time.sleep(1.5)
driver.find_element_by_id("show-labels").click()
# get the canvas as a PNG base64 string
time.sleep(1.5)
x = 1000
i = 1
while x < 4500:
y = 2500
b = 1
while y < 4500:
driver.get("https://www.osrsmap.net/#area=main&x=" + str(x) + "&y=" + str(y) + "&zoom=100")
time.sleep(0.1)
canvas_base64 = driver.execute_script("return arguments[0].toDataURL('image/png').substring(21);", canvas)
# decode
canvas_png = base64.b64decode(canvas_base64)
# save to a file
with open(r"images/osrs_map_canvas_" + str(i) + "_" + str(b) + ".png", 'wb') as f:
f.write(canvas_png)
y += 200
b += 1
x += 600
i += 1
print('*** Program Started ***')
image_name_output = '02_create_blank_image_01.png'
mode = 'RGB' # for color image “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images.
size = (12000, 7250)
color = (0, 0, 0)
im = Image.new(mode, size, color)
im.save(image_name_output )
#im.show()
img0 = Image.open(r"02_create_blank_image_01.png")
x = 2
x_pos = 0
while x < 6:
y = 9
y_pos = 0
while y > 0:
img = Image.open(r"images/osrs_map_canvas_" + str(x) + "_" + str(y) + ".png")
img0.paste(img, (x_pos, y_pos))
y_pos += 800
print("x:", x, " | y:", y)
y -= 1
x_pos += 2400
x += 1
print('*** Program Ended ***')
img0.save("osrs_map_merged.png")
#img0.show()
#test_url()
#osrs_canvas_scrape()
| true
|
da1e7e801bd7723189f8748e77f9a463fd50d73e
|
Python
|
KocUniversity/comp100-2021f-ps0-olordevilg
|
/main.py
|
UTF-8
| 140
| 3.28125
| 3
|
[] |
no_license
|
import numpy
x = int(input("Enter x: "))
y = int(input("Enter y: "))
l = float(numpy.log2(x))
i = int("78457")
print(x**y)
print(l)
print(i)
| true
|
73143e1fcecb4f4a8a3e4dcac5fa6c360d7335e0
|
Python
|
tnakaicode/jburkardt-python
|
/i4lib/i4_huge.py
|
UTF-8
| 1,157
| 2.6875
| 3
|
[] |
no_license
|
#! /usr/bin/env python
#
def i4_huge ( ):
#*****************************************************************************80
#
## I4_HUGE returns a "huge" I4.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 04 April 2013
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Output, integer VALUE, a huge integer.
#
value = 2147483647
return value;
def i4_huge_test ( ) :
#*****************************************************************************80
#
## I4_HUGE_TEST tests I4_HUGE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 09 May 2013
#
# Author:
#
# John Burkardt
#
import platform
print ( '' )
print ( 'I4_HUGE_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' I4_HUGE returns a huge integer.' )
print ( '' )
i = i4_huge ( )
print ( ' I4_HUGE() = %d' % ( i ) )
#
# Terminate.
#
print ( '' )
print ( 'I4_HUGE_TEST' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
i4_huge_test ( )
timestamp ( )
| true
|
0c16acea5a110f65daa313af62e16d8053c0eb42
|
Python
|
Chadtech/ChadTech-vSatz
|
/subbrackets.py
|
UTF-8
| 1,944
| 2.78125
| 3
|
[] |
no_license
|
whichChar=brackets__leftparentheses
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__rightparentheses
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__leftbracket
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit]:
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__rightbracket
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit]:
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__leftcurly
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__rightcurly
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__leftchevron
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].append(whichChar)
whichChar=brackets__rightchevron
for yit in range(len(whichChar.keys)):
if event.key in whichChar.keys[yit] and whichChar.keys[yit].issubset(keys):
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].pop(len(charray.charen[curChar-1][2])-1)
charray.charen[curChar-1][2].append(whichChar)
| true
|
de7656c0458db1e1fdf9f35071d4ab0324f8f030
|
Python
|
adityatrivedi94/insertionsort
|
/insertionsort.py
|
UTF-8
| 286
| 3.640625
| 4
|
[] |
no_license
|
def insertionsort(arr):
for i in range(1,len(arr)):
key =arr[i]
j=i-1
while j>=0 and key <arr[j] :
arr[j+1] =arr[j]
j -= 1
arr[j+1] =key
#Driver code to test
arr =[12,11,13,5,6]
insertionsort(arr)
print ("sorted arry is:")
for i in range(len(arr)):
print ("%d" %arr[i])
| true
|
05f5610f032c1923ed4cdabe6915deaaec7a573d
|
Python
|
UCL-EO/gurl
|
/gurl/list_file.py
|
UTF-8
| 11,085
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from pathlib import PosixPath, _PosixFlavour, PurePath
from pathlib import Path
from urlpath import URL
import sys
import stat
'''
listfile utilities class based on list
This is a particular type of list where we
assume all items are filenames, URLs or similar objects.
The class ensures that Paths to ant parent
directories are generated if possible. Read and
Write permissions are nioted in the class, as are
existence and whether or not it is a directory.
Treats input as a flat list of filenames and provides
information on permissions etc.
If name is set as keyword, then any items
that are directories have the name appended
The return value is a list of resolved Path objects.
'''
__author__ = "P. Lewis"
__email__ = "p.lewis@ucl.ac.uk"
__date__ = "28 Aug 2020"
__copyright__ = "Copyright 2020 P. Lewis"
__license__ = "MIT License"
class ListPath(list):
'''
listfile utilities class based on list
Treats input as a flat list of filenames and provides
information on permissions etc.
If name is set as keyword, then any items
that are directories have the name appended
'''
def __init__(self,*args,**kwargs):
'''
Generate list of filenames and associated data
Arguments:
list or list-like items. A string is *not* treated
as a list of characters, but as a filename. Any ragged list
is flattened.
The items can be directory or file names.
If they are directory names, then if kwargs['name']
is set, this is taken as the filename.
Permissions etc are set for ease of access (see self.report())
Keywords:
unique: if True, then remove duplicates from list
name: str to be used if items are directories
'''
args = self.flatten_list(*args)
if 'name' in kwargs.keys():
self.name = kwargs['name']
listfile = self.name_resolve(args,name=self.name)
else:
self.name = None
listfile = self.resolve(args)
# make sure it is flat
arr = np.array(listfile,dtype=np.object)
listfile = [Path(i) for i in list(arr.ravel())]
if ('unique' in kwargs) and (kwargs['unique'] is True):
listfile = self.remove_duplicates(listfile)
# set list
super(ListPath, self).__init__(listfile)
# get read/write permissions
self.list_info()
def len(self):
return len(self)
def type(self):
'''
return types for all members in list
'''
return [type(i) for i in self]
def joinpath(self,*args):
'''
Path.joinpath for all items
'''
for i,j in enumerate(self):
self[i] = self[i].joinpath(*args)
def parents(self):
'''
parents for all elements
'''
for i,j in enumerate(self):
self[i] = self[i].parent
def absolute(self):
'''
Path.absolute for all items
'''
for i,j in enumerate(self):
self[i] = self[i].absolute()
def resolve(self,listfile):
'''
resolve raggedy listfile into
list of absolute filenames as PosixPath type
Arguments:
listfile : One of:
- None
- string
- PosixPath
- urlpath.URL
- list (or numpy array) of filenames
Returns:
listfile : list of absolute filenames as mixed
urlpath.URL/PosixPath type
'''
if type(listfile) is np.ndarray:
listfile = listfile.as_list()
if type(listfile) is list:
listfile = [str(f) for f in listfile if f]
elif type(listfile) is str:
listfile = [listfile]
elif type(listfile) is PosixPath:
listfile = [listfile.as_posix()]
else:
self.msg("unrecognised type for resolve:listfile")
self.msg(f"{type(listfile)}")
#listfile = self.remove_duplicates(listfile)
listfile = [Path(f).expanduser().absolute().resolve() for f in listfile]
return listfile
def name_resolve(self,*listfile,name='file.dat'):
'''
resolve listfile to ensure all items
are filenames, not directories. And make sure
that directory structure exists.
If they are directories, then add name to them.
Arguments:
*listfile : tuple of files
Keywords:
name : use this as a filename
if you happen to be a directory.
Default file.dat
Returns:
listfile : list of filenames
'''
if name == None:
name='file.dat'
if listfile is None:
return None
listfile = self.resolve(*listfile)
for i,f in enumerate(listfile):
# in case its a dir accidently
if f.exists() and f.is_dir():
f = Path(f,name)
# check that parent is a directory
# this check shouldnt be needed
# but keep for historical reasons
parent = f.parent
if parent.exists() and (not parent.is_dir()):
try:
parent.unlink()
except:
print(f"Parental problem: {parent}")
print(f"Error in lists."+\
f"name_resolve({str(listfile)},name={name})")
sys.exit(1)
try:
parent.mkdir(parents=True,exist_ok=True)
except:
pass
listfile[i] = f
return listfile
def flatten_list(self,_2d_list):
'''
based on
https://stackabuse.com/python-how-to-flatten-list-of-lists/
'''
flat_list = []
# Iterate through the outer list
if type(_2d_list) is str:
return self.flatten_list([_2d_list])
for element in _2d_list:
if type(element) is list:
# If the element is of type list, iterate through the sublist
for item in element:
if type(item) is str:
item = [item]
if type(item) is list:
flat_list.extend(self.flatten_list(item))
else:
flat_list.append(item)
else:
flat_list.append(element)
return flat_list
def list_info(self):
'''
resolve self and get read and write permissions.
If a file doesn't yet exist, then write permission
is assumed, so long as the user has write
permission to the directory.
Sets:
self.isfile- Bool Ture if object if file
self.isdir - Bool Ture if object if directory
self.exists- Bool Ture if object exists
self.read - Bool list of user read permissions
self.write - Bool list of user write permissions
self.parentwrite
- Bool list of user write permissions
for the parent directory
'''
listfile = np.array(self,dtype=np.object)
readlist = np.zeros_like(listfile).astype(np.bool)
writelist = np.zeros_like(listfile).astype(np.bool)
isdir = np.zeros_like(listfile).astype(np.bool)
isfile = np.zeros_like(listfile).astype(np.bool)
exists = np.zeros_like(listfile).astype(np.bool)
parentwrite= np.zeros_like(listfile).astype(np.bool)
# get permissions
for i,f in enumerate(listfile):
f = Path(f)
if f.exists():
exists[i] = True
if f.is_dir():
isdir[i] = True
else:
isfile[i] = True
st_mode = f.stat().st_mode
readlist[i] = bool((st_mode & stat.S_IRUSR) /stat.S_IRUSR )
writelist[i] = bool((st_mode & stat.S_IWUSR) /stat.S_IWUSR )
parent = f.parent
st_mode = parent.stat().st_mode
parentwrite[i] = bool((st_mode & stat.S_IWUSR) /stat.S_IWUSR )
else:
parent = f.parent
try:
# file doesnt yet exist, so make directory
# and set writelist[i] if parent is writeable
parent.mkdir(parents=True,exist_ok=True)
st_mode = parent.stat().st_mode
writelist[i] = bool((st_mode & stat.S_IWUSR) /stat.S_IWUSR )
isfile[i] = True
parentwrite[i] = writelist[i]
except:
# file doesnt yet exist, and we cant make
# the parent, so this is not going to
# be writeable
writelist[i] = False
self.exists = exists
self.isdir = isdir
self.isfile = isfile
self.read = readlist
self.write = writelist
self.parentwrite = parentwrite
return
def remove_duplicates(self,listfile):
'''
remove duplicates in self and return
new ListPath
'''
if len(listfile) == 0:
return listfile
return ListPath(np.unique(np.array(listfile,dtype=np.object)).ravel())
def report(self,stderr=sys.stderr):
print(f'info: read : {self.read}',file=stderr)
print(f'info: write : {self.write}',file=stderr)
print(f'info: isdir : {self.isdir}',file=stderr)
print(f'info: isfile: {self.isfile}',file=stderr)
print(f'info: exists: {self.exists}',file=stderr)
def test1():
msg = '''
Test for a mixed bag of directories and files
The result should be a flattened list
'''
print(msg)
xin = [['.',['..'],'a b',['.','demo.ipynb',['notebooks/demo.ipynb']]],'hello']
xout = ListPath(xin)
print(f'{xin} -> {xout}')
xout.report()
def test2():
msg = '''
give it a string. We want this maintained as
a string, not split into chars (as with normal list)
'''
print(msg)
xin = 'hello world'
xout = ListPath(xin)
print(f'{xin} -> {xout}')
xout.report()
def test3():
msg = '''
Remove duplicates test
'''
print(msg)
xin = ['hello world',['.','./hello world'],'.']
xout = ListPath(xin,unique=True)
print(f'{xin} -> {xout}')
xout.report()
def test4():
msg = '''
test write permission and use of name= kwarg
'''
print(msg)
xin = ['/tmp','/doesnt exist/x']
xout = ListPath(xin,name='tester.dat')
print(f'{xin} -> {xout}')
xout.report()
def main():
# tests
test1()
test2()
test3()
test4()
if __name__ == "__main__":
main()
| true
|
e3307335edc442870675beb9473e81003477868f
|
Python
|
openpolis/pandaSDMX
|
/pandasdmx/message.py
|
UTF-8
| 5,382
| 2.71875
| 3
|
[
"Python-2.0",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
"""Classes for SDMX messages.
:class:`Message` and related classes are not defined in the SDMX
:doc:`information model <implementation>`, but in the
:ref:`SDMX-ML standard <formats>`.
pandaSDMX also uses :class:`DataMessage` to encapsulate SDMX-JSON data returned
by data sources.
"""
from typing import (
List,
Text,
Union,
)
from pandasdmx.model import (
_AllDimensions,
AgencyScheme,
CategoryScheme,
Codelist,
ConceptScheme,
ContentConstraint,
DataSet,
DataflowDefinition,
DataStructureDefinition,
Dimension,
InternationalString,
Item,
ProvisionAgreement,
)
from pandasdmx.util import BaseModel, DictLike, summarize_dictlike
from requests import Response
def _summarize(obj, fields):
"""Helper method for __repr__ on Header and Message (sub)classes."""
for name in fields:
attr = getattr(obj, name)
if attr is None:
continue
yield f'{name}: {attr!r}'
class Header(BaseModel):
"""Header of an SDMX-ML message.
SDMX-JSON messages do not have headers.
"""
#: (optional) Error code for the message.
error: Text = None
#: Identifier for the message.
id: Text = None
#: Date and time at which the message was generated.
prepared: Text = None
#: Intended recipient of the message, e.g. the user's name for an
#: authenticated service.
receiver: Text = None
#: The :class:`.Agency` associated with the data :class:`~.source.Source`.
sender: Union[Item, Text] = None
def __repr__(self):
"""String representation."""
lines = ['<Header>']
lines.extend(_summarize(self, self.__fields__.keys()))
return '\n '.join(lines)
class Footer(BaseModel):
"""Footer of an SDMX-ML message.
SDMX-JSON messages do not have footers.
"""
#:
severity: Text
#: The body text of the Footer contains zero or more blocks of text.
text: List[InternationalString] = []
#:
code: int
class Message(BaseModel):
class Config:
# for .response
arbitrary_types_allowed = True
# NB this is required to prevent “unhashable type: 'dict'” in pydantic
validate_assignment = False
#: :class:`Header` instance.
header: Header = Header()
#: (optional) :class:`Footer` instance.
footer: Footer = None
#: :class:`requests.Response` instance for the response to the HTTP request
#: that returned the Message. This is not part of the SDMX standard.
response: Response = None
def __str__(self):
return repr(self)
def __repr__(self):
"""String representation."""
lines = [
f'<pandasdmx.{self.__class__.__name__}>',
repr(self.header).replace('\n', '\n '),
]
lines.extend(_summarize(self, ['footer', 'response']))
return '\n '.join(lines)
class ErrorMessage(Message):
pass
class StructureMessage(Message):
#: Collection of :class:`.CategoryScheme`.
category_scheme: DictLike[str, CategoryScheme] = DictLike()
#: Collection of :class:`.Codelist`.
codelist: DictLike[str, Codelist] = DictLike()
#: Collection of :class:`.ConceptScheme`.
concept_scheme: DictLike[str, ConceptScheme] = DictLike()
#: Collection of :class:`.ContentConstraint`.
constraint: DictLike[str, ContentConstraint] = DictLike()
#: Collection of :class:`.DataflowDefinition`.
dataflow: DictLike[str, DataflowDefinition] = DictLike()
#: Collection of :class:`.DataStructureDefinition`.
structure: DictLike[str, DataStructureDefinition] = DictLike()
#: Collection of :class:`.AgencyScheme`.
organisation_scheme: DictLike[str, AgencyScheme] = DictLike()
#: Collection of :class:`.ProvisionAgreement`.
provisionagreement: DictLike[str, ProvisionAgreement] = DictLike()
def __repr__(self):
"""String representation."""
lines = [super().__repr__()]
# StructureMessage contents
for attr in self.__dict__.values():
if isinstance(attr, DictLike) and attr:
lines.append(summarize_dictlike(attr))
return '\n '.join(lines)
class DataMessage(Message):
"""Data Message.
.. note:: A DataMessage may contain zero or more :class:`.DataSet`, so
:attr:`data` is a list. To retrieve the first (and possibly only)
data set in the message, access the first element of the list:
``msg.data[0]``.
"""
#: :class:`list` of :class:`.DataSet`.
data: List[DataSet] = []
#: :class:`.DataflowDefinition` that contains the data.
dataflow: DataflowDefinition = DataflowDefinition()
# TODO infer the observation dimension from the DSD, e.g.
# - If a *TimeSeriesDataSet, it's the TimeDimension,
# - etc.
observation_dimension: Union[_AllDimensions, List[Dimension]] = None
# Convenience access
@property
def structure(self):
"""DataStructureDefinition used in the :attr:`dataflow`."""
return self.dataflow.structure
def __repr__(self):
"""String representation."""
lines = [super().__repr__()]
# DataMessage contents
if self.data:
lines.append('DataSet ({})'.format(len(self.data)))
lines.extend(_summarize(self, ('dataflow', 'observation_dimension')))
return '\n '.join(lines)
| true
|
42c92713692c46014fd5afe1119718ec94eca313
|
Python
|
theodormanolescu/hero
|
/domain/character/took_damage.py
|
UTF-8
| 360
| 2.9375
| 3
|
[] |
no_license
|
from application.event_interface import EventInterface
class TookDamage(EventInterface):
def __init__(self, character: 'Character', value: int):
"""
:type character: domain.character.character.Character
"""
self.character = character
self.value = value
def get_name(self) -> str:
return 'took_damage'
| true
|
cf894985f1626978a8bf442a0c32c5a2f088d827
|
Python
|
Ge0f3/CTCI-Prep
|
/ch_1_Arrays_Strings/set_zero/set_zero.py
|
UTF-8
| 938
| 3.5625
| 4
|
[] |
no_license
|
import unittest
#O(MxN) solution with additional memory
def setZero(matrix):
row , cols = set(), set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if(matrix[i][j]) == 0:
row.add(i)
cols.add(j)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i in row or j in cols:
matrix[i][j] = 0
matrix = [
[1,1,1],
[1,0,1],
[1,1,1]
]
class Test(unittest.TestCase):
str1 = [('abcd'), ('s4fad'), ('')]
str2 = [('23ds2'), ('hb 627jh=j ()')]
def test_unique(self):
for test_string in self.str1:
res = isunique(test_string)
self.assertTrue(res)
for test_string in self.str2:
res = isunique(test_string)
self.assertFalse(res)
if __name__ == '__main__':
setZero(matrix)
print(matrix)
| true
|
98e83161276ee4a51afdb8a487d9135a0c690379
|
Python
|
belozi/Python-Programs
|
/MITx 6.00.1x/lecture_5/L5_problem_8a.py
|
UTF-8
| 419
| 3.34375
| 3
|
[] |
no_license
|
def isIn(char, aStr):
if aStr == "":
return False
guess = len(aStr)/2
if aStr[guess] == "":
return False
elif aStr[guess] == char:
return True
elif char > aStr[-1] or char < aStr[0]:
return False
elif aStr[guess] > char:
aStr = aStr[:guess]
else:
aStr = aStr[guess:]
return isIn(char, aStr)
print isIn("a", "")
| true
|
6f54d1b329cb64a75cb415c7bc15de9d87f4506c
|
Python
|
markymauro13/CSIT104_05FA19
|
/10-28-19/function2.py
|
UTF-8
| 64
| 3.265625
| 3
|
[] |
no_license
|
def sum(num1, num2):
total = num1 + num2
print(sum(1,2))
| true
|
823522176229d2f8028517876a8962eccf12bdf4
|
Python
|
nataliadolina/WebServer
|
/index1.py
|
UTF-8
| 5,943
| 2.578125
| 3
|
[] |
no_license
|
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return "<h1>Привет, Яндекс!</h1>"
@app.route('/image_sample')
def image():
return '''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<title>Это Риана</title>
</head>
<body>
<div class="alert alert-primary" role="alert">
<img src="{}" alt="это сова">
</div>
</body>
</html>'''.format(url_for('static', filename='img/bird.jpeg'))
@app.route('/bootstrap_sample')
def sample():
return '''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<title>Bootstrap – знакомство</title>
</head>
<body>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</nav>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="{}">
</div>
<div class="item">
<img src="{}">
</div>
<div class="item">
<img src="{}">
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</html>'''.format(url_for('static', filename='img/bird.jpeg'),
url_for('static', filename='img/fox.jpg'), url_for('static',
filename='https://sweetpanda.ru/wp-content/uploads/2016/10/gettyimages-73726710.jpg'))
if __name__ == '__main__':
app.run(port=8080, host='127.0.0.1')
| true
|
efca31bd1595a76df6cc5de9c173d058329823c4
|
Python
|
mek4nr/GANG-siteweb
|
/gangauth/utils.py
|
UTF-8
| 2,399
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from random import choice, shuffle
from string import (
ascii_letters,
ascii_lowercase,
ascii_uppercase,
digits,
punctuation
)
from django.template.loader import get_template
from django.template import Context
from gangauth.models import EmailCheck
from gangdev.utils import send_mail
from gangdev.settings.base import DOMAIN_NAME
LENGTH = 10
MIN_LOWERCASE = 2
MIN_UPPERCASE = 2
MIN_DIGITS = 2
MIN_SPECIAL = 1
def send_new_password(user):
password = mkpasswd()
user.set_password(password)
user.save()
htmly = get_template("emails/forgot_password_email.html")
context = {
"password": password,
"url": DOMAIN_NAME
}
html_content = htmly.render(Context(context))
mail = {
"subject": "Password forgot",
"body": html_content,
"to": [user.email],
}
send_mail(**mail)
def mkpasswd(length=LENGTH,
min_lower=MIN_LOWERCASE,
min_upper=MIN_UPPERCASE,
min_digits=MIN_DIGITS,
min_special=MIN_SPECIAL):
"""
Generate password
:param length: Size of password
:param min_lower: Min char on lower case
:param min_upper: Min char on lower case
:param min_digits: Min digits
:param min_special: Min special char
:return: Password
"""
lower = [choice(ascii_lowercase) for i in range(min_lower)]
upper = [choice(ascii_uppercase) for i in range(min_upper)]
nums = [choice(digits) for i in range(min_digits)]
special = [choice(punctuation) for i in range(min_special)]
minimum = min_lower + min_upper + min_digits + min_special
remaining = (length - minimum) if length > minimum else 0
rest = [choice(ascii_letters) for i in range(remaining)]
result = upper + lower + nums + special + rest
shuffle(result)
return ''.join(result)
def email_for_active_count(user):
"""
Send mail with active link
"""
email_check = EmailCheck.objects.create(user=user)
htmly = get_template("emails/active_email.html")
context = {
"email": user.email,
"active_link": email_check.active_link()
}
html_content = htmly.render(Context(context))
# Setup mail with all data need it
mail = {
"subject": "Welcome to IBISC Platform",
"body": html_content,
"to": [user.email],
}
send_mail(**mail)
| true
|
04ab60844602197d9706bb3e2321106cd5874244
|
Python
|
BeeRedRnD/Financial-Data-Analysis-Python
|
/app.py
|
UTF-8
| 3,710
| 2.75
| 3
|
[] |
no_license
|
import matplotlib
matplotlib.use
import matplotlib.pyplot as mpl
import pandas as pd
# Just making the plots look better
mpl.style.use('ggplot')
mpl.rcParams['figure.figsize'] = (8,6)
mpl.rcParams['font.size'] = 12
def header(msg):
print('*' * 150)
print('[ ' + msg + ' ]')
# Read the Fair Users CSV file into a dataframe
fair_users_filename = 'fair_users.csv'
fair_users_df = pd.read_csv(fair_users_filename)
# Read the Fraudster Users CSV file into a dataframe
fraud_users_filename = 'fraud_users.csv'
fraud_users_df = pd.read_csv(fraud_users_filename)
# Read the Transactions by Fair Users CSV file into a dataframe
transactions_fair_users_filename = 'transactions_by_fair_users.csv'
transactions_fair_users_df = pd.read_csv(transactions_fair_users_filename)
# Read the Transactions by Fraudster Users CSV file into a dataframe
transactions_fraud_users_filename = 'transactions_by_fraudsters.csv'
transactions_fraud_users_df = pd.read_csv(transactions_fraud_users_filename)
# Print the first and last 5 rows from the Fair Users data frame
header("Top 5 rows of Fair Users")
print(fair_users_df.head())
print('*' * 150)
header("Last 5 rows of Fair Users")
print(fair_users_df.tail())
print('*' * 150)
# Print the first and last 5 rows from the Fraudsters Users data frame
header("Top 5 rows of Fraudster Users")
print(fraud_users_df.head())
print('*' * 150)
header("Last 5 rows of Fraudsters Users")
print(fraud_users_df.tail())
print('*' * 150)
#Print statistical summary of columns of Fair Users
header("Statistical Summary of Fair Users")
print(fair_users_df.describe())
print('*' * 150)
#Print statistical summary of columns of Fraudster Users
header("Statistical Summary of Fraudster Users")
print(fraud_users_df.describe())
print('*' * 150)
# 1. Comparison between Countries of Fair and Fraudster Users Bar Charts below
fair_users_df['country'].value_counts().plot.bar();
mpl.show()
fraud_users_df['country'].value_counts().plot.bar();
mpl.show()
# 2. Comparison between KYC (Know your customer) of Fair and Fraudster Users Bar Charts below
fair_users_df['kyc'].value_counts().plot.bar();
mpl.show()
fraud_users_df['kyc'].value_counts().plot.bar();
mpl.show()
# 3. Comparison between Birth Year of Fair and Fraudster Users Bar Charts below
fair_users_df['birth_year'].value_counts().plot.bar();
mpl.show()
fraud_users_df['birth_year'].value_counts().plot.bar();
mpl.show()
# 4. Comparison between State of Transactions made by Fair and Fraudster Users
transactions_fair_users_df['state'].value_counts().plot.bar();
mpl.show()
transactions_fraud_users_df['state'].value_counts().plot.bar();
mpl.show()
# 5. Comparison between Amount Spent by Fair and Fraudster Users
transactions_fair_users_df['amount'].plot.line();
mpl.show()
transactions_fraud_users_df['amount'].plot.line();
mpl.show()
# 6. Comparison between Merchant Category of Fair and Fraudster Users
transactions_fair_users_df['merchant_category'].value_counts().plot.bar();
mpl.show()
transactions_fraud_users_df['merchant_category'].value_counts().plot.bar();
mpl.show()
print(fair_users_df['failed_sign_in_attempts'].corr(transactions_fraud_users_df['amount']))
# print(df[df['STATE'] == 'LOCKED'].tail(5))
#
# print(df['STATE'].corr(df['PHONE_COUNTRY']))
# print(df['KYC'].value_counts())
#
# df['KYC'].value_counts().plot.bar();
# mpl.show()
#
# df['BIRTH_YEAR'].value_counts().plot.bar();
# mpl.show()
#
# df['COUNTRY'].value_counts().plot.bar();
# mpl.show()
# Correlation between Merchant Country and State of Transaction for Fair and Fraudster Users
# transactions_fair_users_df.plot.scatter(x='merchant_country', y='state');
# mpl.show()
#print(transactions_fraud_users_df.corr())
| true
|
eec2179d6cf208a99d337f119e260253ba3bae88
|
Python
|
590shun/video_summarizer
|
/utils/eval.py
|
UTF-8
| 5,622
| 2.703125
| 3
|
[] |
no_license
|
import os
import sys
import math
import numpy as np
from scipy import stats
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.knapsack import knapsack_ortools
"""
From original implementations of Kaiyang Zhou and Jiri Fajtl
https://github.com/KaiyangZhou/pytorch-vsumm-reinforce
https://github.com/ok1zjf/VASNet
"""
def upsample(scores, n_frames, positions):
"""Upsample scores vector to the original number of frames.
Input
scores: (n_steps,)
n_frames: (1,)
positions: (n_steps, 1)
Output
frame_scores: (n_frames,)
"""
frame_scores = np.zeros((n_frames), dtype=np.float32)
if positions.dtype != int:
positions = positions.astype(np.int32)
if positions[-1] != n_frames:
positions = np.concatenate([positions, [n_frames]])
for i in range(len(positions) - 1):
pos_left, pos_right = positions[i], positions[i+1]
if i == len(scores):
frame_scores[pos_left:pos_right] = 0
else:
frame_scores[pos_left:pos_right] = scores[i]
return frame_scores
def generate_scores(probs, n_frames, positions):
"""Set score to every original frame of the video for comparison with annotations.
Input
probs: (n_steps,)
n_frames: (1,)
positions: (n_steps, 1)
Output
machine_scores: (n_frames,)
"""
machine_scores = upsample(probs, n_frames, positions)
return machine_scores
def evaluate_scores(machine_scores, user_scores, metric="spearmanr"):
"""Compare machine scores with user scores (keyframe-based).
Input
machine_scores: (n_frames,)
user_scores: (n_users, n_frames)
Output
avg_corr, max_corr: (1,)
"""
n_users, _ = user_scores.shape
# Ranking correlation metrics
if metric == "kendalltau":
f = lambda x, y: stats.kendalltau(stats.rankdata(-x), stats.rankdata(-y))[0]
elif metric == "spearmanr":
f = lambda x, y: stats.spearmanr(stats.rankdata(-x), stats.rankdata(-y))[0]
else:
raise KeyError(f"Unknown metric {metric}")
# Compute correlation with each annotator
corrs = [f(machine_scores, user_scores[i]) for i in range(n_users)]
# Mean over all annotators
avg_corr = np.mean(corrs)
return avg_corr
def generate_summary(scores, cps, n_frames, nfps, positions, proportion=0.15, method="knapsack"):
"""Generate keyshot-based video summary i.e. a binary vector.
Input
scores: predicted importance scores
cps: change points, 2D matrix, each row contains a segment
n_frames: original number of frames
nfps: number of frames per segment
positions: positions of subsampled frames in the original video
proportion: length of video summary (compared to original video length)
method: defines how shots are selected, ['knapsack', 'rank']
Output
summary: binary vector of shape (n_frames,)
"""
n_segs = cps.shape[0]
frame_scores = upsample(scores, n_frames, positions)
seg_score = []
for seg_idx in range(n_segs):
start, end = int(cps[seg_idx, 0]), int(cps[seg_idx, 1]+1)
scores = frame_scores[start:end]
seg_score.append(float(scores.mean()))
limits = int(math.floor(n_frames * proportion))
if method == 'knapsack':
picks = knapsack_ortools(seg_score, nfps, n_segs, limits)
elif method == 'rank':
order = np.argsort(seg_score)[::-1].tolist()
picks = []
total_len = 0
for i in order:
if total_len + nfps[i] < limits:
picks.append(i)
total_len += nfps[i]
else:
raise KeyError(f"Unknown method {method}")
# This first element should be deleted
summary = np.zeros((1), dtype=np.float32)
for seg_idx in range(n_segs):
nf = nfps[seg_idx]
if seg_idx in picks:
tmp = np.ones((nf), dtype=np.float32)
else:
tmp = np.zeros((nf), dtype=np.float32)
summary = np.concatenate((summary, tmp))
# Delete the first element
summary = np.delete(summary, 0)
return summary
def evaluate_summary(machine_summary, user_summary):
"""Compare machine summary with user summary (keyshot-based).
Input
machine_summary: (n_frames,)
user_summary: (n_users, n_frames)
Output
avg_f_score, max_f_score: (1,)
"""
machine_summary = machine_summary.astype(np.float32)
user_summary = user_summary.astype(np.float32)
n_users, n_frames = user_summary.shape
# binarization
machine_summary[machine_summary > 0] = 1
user_summary[user_summary > 0] = 1
if len(machine_summary) > n_frames:
machine_summary = machine_summary[:n_frames]
elif len(machine_summary) < n_frames:
zero_padding = np.zeros((n_frames - len(machine_summary)))
machine_summary = np.concatenate([machine_summary, zero_padding])
f_scores = []
prec_arr = []
rec_arr = []
for user_idx in range(n_users):
gt_summary = user_summary[user_idx, :]
overlap_duration = (machine_summary * gt_summary).sum()
precision = overlap_duration / (machine_summary.sum() + 1e-8)
recall = overlap_duration / (gt_summary.sum() + 1e-8)
if precision == 0 and recall == 0:
f_score = 0.
else:
f_score = (2 * precision * recall) / (precision + recall)
f_scores.append(f_score)
prec_arr.append(precision)
rec_arr.append(recall)
avg_f_score = np.mean(f_scores)
max_f_score = np.max(f_scores)
return avg_f_score, max_f_score
| true
|
25d040fdb410c8f06770877724cf345431f6a0d1
|
Python
|
joepearson95/CloudComputing-AutoDeployment
|
/bucket.py
|
UTF-8
| 800
| 3.125
| 3
|
[] |
no_license
|
# Imports for creating a random string in order to allow the bucket to be unique
import random
import string
# Function that takes in an integer that specifies the length of the random string generated
def random_string(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
# Function to generate the bucket. Uses the random_string function and the name specified
# in the yaml file to generate a name for the bucket itself.
def GenerateConfig(context):
name = ''.join(random_string(4) + context.env['name'])
resources = [{
'name': name,
'type': 'storage.v1.bucket',
'properties': {
'project': context.env['project'],
'name': name
}
}]
return {'resources': resources}
| true
|
4bcd871d5d857828c34970321723f24c9fe34935
|
Python
|
arty-hlr/CTF-writeups
|
/2019/Insomnihack/curlpipebash/writeup.py
|
UTF-8
| 648
| 2.78125
| 3
|
[] |
no_license
|
import requests
headers = {
"User-Agent": "curl/7.61.0" # if it looks like curl and talks like curl...
}
def main():
url = "https://curlpipebash.teaser.insomnihack.ch/print-flag.sh"
r = requests.get(url, headers=headers, stream=True)
for l in r.iter_lines():
print("print-flag got line: {}".format(l))
if "curl" in l and "shame" not in l: # We want to curl all new urls, but not the wall of shame one!
new_link = l.split(" ")[2] # who needs regex?..
print("Requesting new url: {}".format(new_link))
requests.get(new_link, headers=headers)
if __name__ == "__main__":
main()
| true
|
5ddafff479459935ed9654091e92d62c24079ec2
|
Python
|
ruslankrivoshein/gcp_sdk
|
/infra/bigquery/cl_direction/cl_direction_schema.py
|
UTF-8
| 1,163
| 2.78125
| 3
|
[] |
no_license
|
import os
import time
from dotenv import load_dotenv
from google.cloud import bigquery
def create_dm_direction_schema():
load_dotenv()
client = bigquery.Client()
dataset_id = os.environ.get("DATASET_ID")
project_id = os.environ.get("PROJECT_ID")
table_name = 'cl_direction'
query = f"""
SELECT table_name
FROM {dataset_id}.INFORMATION_SCHEMA.TABLES;
"""
query_job = client.query(query)
tables = [table.table_name for table in query_job]
if table_name in tables:
print(f"Table {table_name} is already existing")
else:
query = f"""
CREATE TABLE {dataset_id}.{table_name}(
id INT,
value STRING
);
"""
query_job = client.query(query)
print(f"Table {table_name} was successfully created.")
time.sleep(5)
query = f"""
INSERT {dataset_id}.{table_name} values (1, 'in'), (2, 'out');
"""
query_job = client.query(query)
print(f"Dimension {table_name} was successfully generated.")
if __name__ == "__main__":
create_dm_direction_schema()
| true
|
c23b06c09ade82274a8f6118fce9169f6dd0c3a0
|
Python
|
Chalol/Pygame-calculator
|
/calculator_by_Pygame ver.2.py
|
UTF-8
| 10,578
| 3.09375
| 3
|
[] |
no_license
|
# This code is about calculator by PyGame for calculate
# This is second version
# for subject Software development and practice I
# Code by 6001012630021 Chanakan Thimkham
# Ref. of my code :
# Module : https://www.pygame.org/docs/
# Change button color : https://bit.ly/2p3bSUI
# Github : https://github.com/Chalol/Pygame-calculator
# my blog about Pygame calculator : https://bit.ly/2MjUXGU
import pygame, sys
from pygame.locals import *
from Button import *
pygame.init() # initialize pygame
#color
colormbred = (208,23,42)
coloryellow = (255,191,23)
colormbblue = (178,232,232)
colormbgreen = (90,224,58)
colorsofty = (255,248,183)
colorwhite = (255,255,255)
colorblack = (0,0,0)
DISP = pygame.display.set_mode((350,475)) #set width and height of display
pygame.display.set_caption('PYGAME Calculator')
fontText = pygame.font.SysFont('Arial',30) #set font and font size that will show on screen
sound_button = pygame.mixer.Sound('beep.wav')
DISP.fill(colorblack) #set screen color
width = 80
height = 60
# set x,y,width,height,color and text on each button
num0 = buttonnum(95,410,width,height,(colormbred),'0')
num1 = buttonnum(10,345,width,height,(colormbred),'1')
num2 = buttonnum(95,345,width,height,(colormbred),'2')
num3 = buttonnum(180,345,width,height,(colormbred),'3')
num4 = buttonnum(10,280,width,height,(colormbred),'4')
num5 = buttonnum(95,280,width,height,(colormbred),'5')
num6 = buttonnum(180,280,width,height,(colormbred),'6')
num7 = buttonnum(10,215,width,height,(colormbred),'7')
num8 = buttonnum(95,215,width,height,(colormbred),'8')
num9 = buttonnum(180,215,width,height,(colormbred),'9')
sym_sum = buttonnum(10,150,width,height,(colormbgreen),'+')
sym_mi = buttonnum(95,150,width,height,(colormbgreen),'-')
sym_mul = buttonnum(180,150,width,height,(colormbgreen),'*')
sym_div = buttonnum(265,150,width,height,(colormbgreen),'/')
sym_clear = buttonnum(265,280,width,height,(colormbgreen),'C')
sym_dot = buttonnum(265,345,width,height,(colormbgreen),'•')
sym_open = buttonnum(10,410,width,height,(colormbgreen),'(')
sym_close = buttonnum(180,410,width,height,(colormbgreen),')')
sym_del = buttonnum(265,215,width,height,(colormbgreen),'Del')
ans = buttonnum(265,410,width,height,(coloryellow),'=')
def cal_loop():
ty = True
Num = " "
while ty:
# set button change color
num0.btnum()
num1.btnum()
num2.btnum()
num3.btnum()
num4.btnum()
num5.btnum()
num6.btnum()
num7.btnum()
num8.btnum()
num9.btnum()
sym_sum.btsym()
sym_mi.btsym()
sym_mul.btsym()
sym_div.btsym()
sym_clear.btsym()
sym_dot.btsym()
sym_open.btsym()
sym_close.btsym()
sym_del.btsym()
ans.btans()
for e in pygame.event.get():
if e.type == pygame.QUIT:
ty = False
if e.type == pygame.KEYDOWN: # Keyboard input
if e.key == K_0: # put 0 on keyboard then show 0
Num += '0'
if e.key == K_1: # put 1 on keyboard then show 1
Num += '1'
if e.key == K_2: # put 2 on keyboard then show 2
Num += '2'
if e.key == K_3: # put 3 on keyboard then show 3
Num += '3'
if e.key == K_4: # put 4 on keyboard then show 4
Num += '4'
if e.key == K_5: # put 5 on keyboard then show 5
Num += '5'
if e.key == K_6: # put 6 on keyboard then show 6
Num += '6'
if e.key == K_7: # put 7 on keyboard then show 7
Num += '7'
if e.key == K_8: # put 8 on keyboard then show 8
Num += '8'
if e.key == K_9: # put 9 on keyboard then show 9
Num += '9'
if e.key == K_EQUALS: # put + on keyboard then show +
Num += '+'
if e.key == K_MINUS: # put - on keyboard then show -
Num += '-'
if e.key == K_RSHIFT: # put shift on keyboard then show *
Num += '*'
if e.key == K_SLASH: # put / on keyboard then show /
Num += '/'
if e.key == K_PERIOD: # put . on keyboard then show .
Num += '.'
if e.key == K_z: # put z on keyboard then show (
Num += '('
if e.key == K_x: # put x on keyboard then show )
Num += ')'
if e.key == K_DELETE: # put delete on keyboard for delete
Num = Num[:-1]
if e.key == K_SPACE: # put space bar on keyboard for show answer
if Num == ' ': # if Num is blank then pass
pass
elif Num[-1] == '+' or Num[-1] == '-' or Num[-1] == '*' or Num[-1] == '/': # if the last one is operand then show error
try:
Num = eval(Num)
except:
Num = "Error the last one"
elif '/0' in Num: # if divide by zero then show error
Num = "Can't divide by 0"
elif '++' in Num or '--' in Num or'**' in Num or '//' in Num: #if has operand more than 1 then show error
Num = 'operation Error'
else:
Num = str(eval(Num))
# Show input and answer on screen
show = fontText.render(str(Num), True,colorblack)
DISP.blit(show, (20,55))
if e.type == pygame.MOUSEBUTTONDOWN: # Mouse click input
mouse = pygame.mouse.get_pos() # get mouse position
# test if a point is inside a rectangle
if num0.finalbut().collidepoint(mouse): # if click on button 0 then show 0
Num += '0'
if num1.finalbut().collidepoint(mouse): # if click on button 1 then show 1
Num += '1'
if num2.finalbut().collidepoint(mouse): # if click on button 2 then show 2
Num += '2'
if num3.finalbut().collidepoint(mouse): # if click on button 3 then show 3
Num += '3'
if num4.finalbut().collidepoint(mouse): # if click on button 4 then show 4
Num += '4'
if num5.finalbut().collidepoint(mouse): # if click on button 5 then show 5
Num += '5'
if num6.finalbut().collidepoint(mouse): # if click on button 6 then show 6
Num += '6'
if num7.finalbut().collidepoint(mouse): # if click on button 7 then show 7
Num += '7'
if num8.finalbut().collidepoint(mouse): # if click on button 8 then show 8
Num += '8'
if num9.finalbut().collidepoint(mouse): # if click on button 9 then show 9
Num += '9'
if sym_sum.finalbut().collidepoint(mouse): # if click on button + then show +
Num += '+'
if sym_mi.finalbut().collidepoint(mouse): # if click on button - then show -
Num += '-'
if sym_mul.finalbut().collidepoint(mouse): # if click on button * then show *
Num += '*'
if sym_div.finalbut().collidepoint(mouse): # if click on button / then show /
Num += '/'
if sym_dot.finalbut().collidepoint(mouse): # if click on button . then show .
Num += '.'
if sym_open.finalbut().collidepoint(mouse): # if click on button ( then show (
Num += '('
if sym_close.finalbut().collidepoint(mouse): # if click on button ) then show )
Num += ')'
if sym_clear.finalbut().collidepoint(mouse): # if click on button C then show nothing
Num = ' '
if sym_del.finalbut().collidepoint(mouse): # if click on button Del then show delete
Num = Num[:-1]
if ans.finalbut().collidepoint(mouse): # if click on button = then show answer
if Num == ' ': # if Num is blank then pass
pass
elif Num[-1] == '+' or Num[-1] == '-' or Num[-1] == '*' or Num[-1] == '/': # if the last one is operand then show error
try:
Num = eval(Num)
except:
Num = "Error at the last one"
elif '/0' in Num: # if divide by zero then show error
Num = "Can't divide by 0"
elif '++' in Num or '--' in Num or'**' in Num or '//' in Num: #if has operand more than 1 then show error
Num = 'operation Error'
else:
Num = str(eval(Num))
sound_button.play()
# text not out of the screen
if len(Num) >= 22:
Num = Num[:-1]
pygame.draw.rect(DISP,colorsofty,(10,30,330,90))
show = fontText.render(str(Num), True,colorblack)
DISP.blit(show, (20,55))
pygame.display.update() # Update portions of the screen
cal_loop() # call function to run programme
pygame.quit() # uninitialize all pygame modules
quit()
| true
|
de6aa463ee47ffa87cad71c27d15cd9f386c660b
|
Python
|
Programacion-Algoritmos-18-2/ejercicio-extra-clase-s7-JosePullaguariQ
|
/principal.py
|
UTF-8
| 778
| 3.609375
| 4
|
[] |
no_license
|
#Importamos todas la clases que vamos a utilizar
from modelado.mimodelo import *
listaDatos = [88, 55,0, 7, 2, 56, 34, 1, 99, 15] #Creamos una lista con los elementos a ordenar
objOr = Ordenamiento(listaDatos) #Creamos un objeto tipo Ordenamiento para obtener los metodos que ordenan
print("Arreglo desordenado")
print(listaDatos,"\n"); #Presentamos primero la lista desordenada
op = int(input("Ordenamiento por seleccion(1) Insercion(2)\n"))
if (op == 1):
print("Ordenamiento por Selección")
objOr.ordenamientoSeleccion() #Por metodo de seleccion
if (op == 2):
print("Ordenamiento por Inserción")
objOr.ordenamientoInsercion() #Por metodo de insercion
print("\nArreglo Ordenado") #Lista ordenada
print(objOr)
| true
|
da978a1a566f71514527a52823680d9f75b69115
|
Python
|
falcondai/influence-game
|
/main/login.py
|
UTF-8
| 2,130
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
from flask.ext.login import LoginManager, UserMixin
from bson.objectid import ObjectId
from Crypto import Random, Hash
from main import app
from database import mongo
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, user_dict=None, **kwargs):
if not user_dict:
user_dict = kwargs
self.id = unicode(user_dict[u'_id'])
self.name = user_dict['name']
self.salt = user_dict['salt']
self.password_hash = user_dict['password_hash']
self.graph_id = unicode(user_dict['graph_id'])
self.obj = user_dict
@staticmethod
def create_user(name, password, salt_byte_length=32):
try:
# create an empty graph and obtain its id
gid = mongo.db.graphs.insert({}, j=True)
salt = Random.get_random_bytes(salt_byte_length).encode('hex')
return mongo.db.users.insert({
'name': name,
'salt': salt,
'password_hash': User.hash_password(salt, password),
'active': True,
'graph_id': gid
}, j=True)
except:
return None
@staticmethod
def find_user_by_id(user_id):
user_record = mongo.db.users.find_one({u'_id': ObjectId(user_id)})
if user_record:
return User(user_record)
return None
@staticmethod
def find_user_by_name(username):
user_record = mongo.db.users.find_one({u'name': username})
if user_record:
return User(user_record)
return None
@staticmethod
def authenticate_user(username, password):
user = User.find_user_by_name(username)
if user and User.hash_password(user.salt, password) == user.password_hash:
return user
return None
@staticmethod
def hash_password(salt, password):
return Hash.SHA256.new(salt + password).hexdigest()
@login_manager.user_loader
def load_user(user_id):
return User.find_user_by_id(user_id)
| true
|
c97701752538fe3fb147c21cac3a9174259973eb
|
Python
|
mhgd3250905/CleanWaterSpiderOnPython
|
/Spiders/HXSpider.py
|
UTF-8
| 1,971
| 2.640625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
from Bmob import BmobUtils
from HtmlUtils import HtmlGetUtils,HtmlPostUtils
from ListHtmlSpider import HXHtmlDealUtils
from ContentSpider import ContentHtmlSpider
class HX:
#http://wap.ithome.com/ithome/getajaxdata.aspx?page=2&type=wapcategorypage
def startSpider(self):
'''
针对虎嗅网的爬虫
:return:
'''
#首先删除表
# BmobUtils.deleteBmobClass("HXBean")
#虎嗅网分为两个部分:
#第一部分 当日新闻爬取
# 主要是对URL:https://m.huxiu.com/ 【get】的分析
#第二部分 往期新闻爬取
# 主要是对URl:https://m.huxiu.com/maction/article_list 【post {page:'i'}】的分析
#
for i in range(1,11):
if i==1:
dataList=self.HXFirstListSpider()
else:
dataList=self.HXSecondListSpider(i)
# contentList = ContentHtmlSpider.getContentIndex(dataList, 'WX')
BmobUtils.insertListBmob('HXBean', dataList)
# BmobUtils.insertContentBmob('HXContentBean', contentList)
print("经过不懈的努力,开哥爬下了虎嗅网第 %d 页" % i)
def HXFirstListSpider(self):
'''
虎嗅网第一部分爬虫
:param url:
:return: List<HXBean>
'''
url = 'https://m.huxiu.com/'
print(url)
html = HtmlGetUtils.getHtml(url)
# print(html)
datalist = HXHtmlDealUtils.dealFirstHtml(html)
return datalist
def HXSecondListSpider(self,index):
'''
虎嗅网第二部分爬虫
:param url:
:return: List<HXBean>
'''
url='https://m.huxiu.com/maction/article_list'
data={
'page':index
}
html= HtmlPostUtils.postHtml(url,data=data,type='HX')
dataList=HXHtmlDealUtils.dealSecondHtml(html)
return dataList
| true
|
c5968e3405970ac08b154248564b2ff0d4b55ab0
|
Python
|
YuenyongPhookrongnak/01_TradingSeries
|
/Part5_6_live_trading.py
|
UTF-8
| 4,365
| 2.640625
| 3
|
[] |
no_license
|
import pandas as pd
from binance.client import Client
from binance_keys import api_key, secret_key
from datetime import datetime, timedelta
import time
from binance.exceptions import *
from auxiliary_functions import *
client = Client(api_key, secret_key)
symbols = ['BTC','ETH','LTC']
start_n_hours_ago = 48
balance_unit = 'USDT'
first = True
BUY_AMOUNT_USDT = 100
precision = {}
for symbol in symbols:
precision[symbol] = client.get_symbol_info(f'{symbol}USDT')['quotePrecision']
while True:
if (datetime.now().second % 10 == 0) or first:
if (datetime.now().minute == 0 and datetime.now().second == 10) or first:
# refresh data
first = False
df = gather_data(symbols,48)
states = get_states(df,symbols)
print('Current state of the market:')
print(states)
print('\n')
try:
if balance_unit == 'USDT': # looking to buy
for symbol in symbols:
ask_price = float(client.get_orderbook_ticker(symbol = f'{symbol}USDT')['askPrice'])
lower_band = df[f'{symbol}_lower_band'].iloc[-1]
if ask_price < lower_band and states[symbol] == 'inside': #buy signal
######################
print(f'Buy order placed:')
buy_order = client.order_limit_buy(symbol=f'{symbol}USDT',
quantity=truncate(BUY_AMOUNT_USDT / ask_price, precision[symbol]),
price = ask_price)
print(buy_order)
start = datetime.now()
while True:
time.sleep(1)
buy_order = client.get_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
seconds_since_buy = (datetime.now() - start).seconds
# resolve buy order
if float(buy_order['executedQty']) == 0 and seconds_since_buy > 60*60:
# no fill
client.cancel_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
print('Order not filled after 1 hour, cancelled.')
print('\n')
break
if float(buy_order['executedQty']) != 0 and float(buy_order['executedQty']) != float(buy_order['origQty']) and seconds_since_buy > 60*60:
# partial fill
client.cancel_order(symbol=buy_order['symbol'], orderId=buy_order['orderId'])
balance_unit = symbol
print('Order partially filled after 1 hour, cancelled the rest and awaiting sell signal.')
print('\n')
break
if float(buy_order['executedQty']) == float(buy_order['origQty']):
# completely filled
balance_unit = symbol
print('Order filled:')
print(buy_order)
print('\n')
break
######################
if balance_unit != 'USDT': # looking to sell
bid_price = float(client.get_orderbook_ticker(symbol = f'{balance_unit}USDT')['bidPrice'])
upper_band = df[f'{balance_unit}_upper_band'].iloc[-1]
if bid_price > upper_band and states[balance_unit] == 'inside': #sell signal
######################
client.order_market_sell(symbol=buy_order['symbol'],
quantity=truncate(float(buy_order['executedQty']), precision[buy_order['symbol'].replace('USDT','')]))
######################
balance_unit = 'USDT'
time.sleep(1)
except BinanceAPIException as e:
print(e.status_code)
print(e.message)
| true
|
5c1cbeffe05d59bec786a8ed43e962ec0fce3db5
|
Python
|
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
|
/answers/Utkarsh Srivastava/Day 16/Question 2.py
|
UTF-8
| 100
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
arr = input().split()
for i in range(len(arr)):
if(arr[i]=='1'):
print(i)
break
| true
|
22bf867b4a239fa914d7b4dbef15f2a8b0a59bde
|
Python
|
auralshin/competetive-code-hacktoberfest
|
/python/bst_bfs_dfs.py
|
UTF-8
| 2,707
| 4.4375
| 4
|
[] |
no_license
|
'''
Binary Search Tree (BST)
new data < node goto left child
new data > node goto right child
### INPUT ###
7
3
5
2
1
4
6
7
### OUTPUT ###
Height of tree is 3
3
2 5
1 4 6
7
BFS is 3 2 5 1 4 6 7
DFS is 3 2 1 5 4 6 7
'''
# create a node, assign children to None
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
# insert new data
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
# get the height of the BST
maxHeight = 0
height = 0
def getHeight(self,root):
if root.left:
self.height += 1
if self.height > self.maxHeight:
self.maxHeight = self.height
self.getHeight(root.left)
self.height -= 1
if root.right:
self.height += 1
if self.height > self.maxHeight:
self.maxHeight = self.height
self.getHeight(root.right)
self.height -= 1
return self.maxHeight
# Breadth First Search (aka level order)
# output print space seperated 'explored' values
def bfs(self, root):
queue = []
bfs_search = []
# append root
if root != None:
queue.append(root)
# while there are nodes to process
while len(queue) > 0:
# dequeue the list (FIFO)
n = queue.pop(0)
# process tree data
bfs_search.append(n.data)
# enqueue child elements from next level in order (L->R)
if n.left != None:
queue.append(n.left)
if n.right != None:
queue.append(n.right)
print(f'bfs result: {bfs_search}')
# Depth First Search (aka pre-order)
dfs_search = []
def dfs(self, root):
if root != None:
# process tree data
self.dfs_search.append(root.data)
# process child elements
self.dfs(root.left)
self.dfs(root.right)
T=int(input())
myTree=Solution()
root=None
# populate the BST
for i in range(T):
data=int(input())
root=myTree.insert(root,data) # root of bst is returned (eg. node which containts self.data = 3)
# get height of the BST
height=myTree.getHeight(root)
print(f'Height = {height}')
myTree.bfs(root)
myTree.dfs(root)
print(f'dfs result {myTree.dfs_search}')
| true
|
b958357fd362d138d39bdaef9b3fbc5a4301b9d5
|
Python
|
mmisono/kvm-bpf-tools
|
/kvm_vmexit_time.py
|
UTF-8
| 3,631
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python
from __future__ import print_function
from collections import defaultdict
from time import sleep
from bcc import BPF
from exit_reason import EXIT_REASON
text = """
struct tmp{
u64 time;
int nested;
unsigned int exit_reason;
};
struct value{
u64 cumulative_time;
u64 count;
};
BPF_HASH(start_time, u64, struct tmp);
BPF_HASH(counts, unsigned int, struct value);
BPF_HASH(counts_nested, unsigned int, struct value);
TRACEPOINT_PROBE(kvm, kvm_exit) {
u64 id = bpf_get_current_pid_tgid();
struct tmp zero = {.time=0, .nested=0, .exit_reason=0};
struct tmp *val = start_time.lookup_or_init(&id, &zero);
val->time = bpf_ktime_get_ns();
val->exit_reason = args->exit_reason;
val->nested = 0;
return 0;
}
TRACEPOINT_PROBE(kvm, kvm_nested_vmexit) {
u64 id = bpf_get_current_pid_tgid();
struct tmp *val = start_time.lookup(&id);
if (val != 0){
val->nested = 1;
}else{
// something wrong
}
return 0;
}
TRACEPOINT_PROBE(kvm, kvm_entry) {
u64 id = bpf_get_current_pid_tgid();
struct tmp *st = start_time.lookup(&id);
if (st != 0){
unsigned int exit_reason = st->exit_reason;
struct value zero = {.cumulative_time = 0, .count = 0};
struct value* val;
if(st->nested == 0){
val = counts.lookup_or_init(&exit_reason, &zero);
}else{
val = counts_nested.lookup_or_init(&exit_reason, &zero);
}
val->cumulative_time += bpf_ktime_get_ns() - st->time;
val->count += 1;
}
return 0;
}
"""
def main():
# load BPF program
b = BPF(text=text)
print("Tracing... Hit Ctrl-C to end.")
try:
sleep(99999999)
except KeyboardInterrupt:
pass
print()
result = {}
for table_name in ("counts", "counts_nested"):
cs = b.get_table(table_name)
result[table_name] = {}
for k, v in cs.items():
k, c, t = k.value, v.count, v.cumulative_time
result[table_name][EXIT_REASON[k]] = {"count": c, "cumul_time": t}
print("{:3s} {:18s} {:>8s} {:>10s} {:>8s} {:>10s} {:>8s} {:>10s}".format(
"", "Exit reason", "Total", "(Avg Time)", "L1", "(Avg Time)", "L2", "(Avg Time)"))
l1_total = 1
l2_total = 0
l1_time_total = 0
l2_time_total = 0
for i, e in enumerate(EXIT_REASON):
cc = 0
ct = 0
c_avg = 0
cnc = 0
cnt = 0
cn_avg = 0
if e in result["counts"]:
c = result["counts"][e]
cc, ct = c["count"], c["cumul_time"]
c_avg = ct / float(cc)
if e in result["counts_nested"]:
cn = result["counts_nested"][e]
cnc, cnt = cn["count"], cn["cumul_time"]
cn_avg = cnt / float(cnc)
if cc > 0 or cnc > 0:
t = cc + cnc
t_avg = (ct + cnt) / float(cc + cnc)
print("{:3d} {:18s} {:8d} ({:8.0f}) {:8d} ({:8.0f}) {:8d} ({:8.0f})".format(
i, e, t, t_avg, cc, c_avg, cnc, cn_avg))
l1_total += cc
l2_total += cnc
l1_time_total += ct
l2_time_total += cnt
print("{:3s} {:18s} {:8d} ({:8.0f}) {:8d} ({:8.0f}) {:8d} ({:8.0f})".format("", "Total (Avg Time)", l1_total + l2_total, (l1_time_total + l2_time_total) / (l1_total + l2_total),
l1_total, l1_time_total / l1_total,
l2_total, l2_time_total / l2_total))
if __name__ == "__main__":
main()
| true
|
184a066403ee51e61081305137c56b9813e3c9d0
|
Python
|
tpqls0327/Algorithm
|
/Baekjoon/stack/10828_스택_D.py
|
UTF-8
| 407
| 3.25
| 3
|
[] |
no_license
|
import sys
input = sys.stdin.readline
n = int(input())
arr = []
for _ in range(n):
tmp = input().split()
if tmp[0] == 'push':
arr.append(int(tmp[1]))
elif tmp[0] == 'pop':
print(arr.pop() if arr else -1)
elif tmp[0] == 'top':
print(arr[-1] if arr else -1)
elif tmp[0] == 'size':
print(len(arr))
elif tmp[0] == 'empty':
print(0 if arr else 1)
| true
|
e9d727b6163054843f89a7604cf1ad748653747a
|
Python
|
antweer/learningcode
|
/intro2python/objectexercises/e1objectbasics.py
|
UTF-8
| 607
| 3.75
| 4
|
[] |
no_license
|
#!/usr/bin/env python3
class Person():
def __init__(self, name, email, phone):
self.name= name
self.email= email
self.phone = phone
def greet(self, other_person):
print("Hello {}, I am {}!".format(other_person.name, self.name))
if __name__ == "__main__":
sonny = Person("Sonny", "sonny@hotmail.com", "483-485-4948")
jordan = Person("Jordan", "jordan@aol.com", "495-586-3456")
sonny.greet(jordan)
jordan.greet(sonny)
print("{}: {} & {}".format(sonny.name, sonny.email, sonny.phone))
print("{}: {} & {}".format(jordan.name, jordan.email, jordan.phone))
| true
|
a34a819bce16a38a33f0d794ef29fee033b111ff
|
Python
|
Recorichardretardo/python-pickiling
|
/JSON/deserialization/deserialization-from-string/Examples/Example1/app.py
|
UTF-8
| 199
| 2.84375
| 3
|
[] |
no_license
|
import json
json_string = '''{"name":"Mark","age":22,"spec":"math","fee":1000.0, "isPass":true, "backlogs": null}'''
student = json.loads(json_string)
print(type(student))
print(student["name"])
| true
|
352fcbc13257c2e89ded905cf005b82c41a6f307
|
Python
|
fariszahrah/crypto-twitter
|
/phase-0/cluster.py
|
UTF-8
| 1,155
| 3.375
| 3
|
[] |
no_license
|
"""
Cluster data.
"""
'''
creates partitions using the community module
'''
import community
import pickle
import networkx as nx
import matplotlib.pyplot as plt
from collections import Counter
def partition(graph):
'''
takes a graph and returns a dict of nodes to their parition
'''
partition = community.best_partition(graph)
return partition
def graph_part(graph, part, filename):
values = [part.get(node) for node in graph.nodes()]
nx.draw_spring(graph, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.savefig(filename, pad_inches=4)
def main():
graph = nx.read_gpickle('./graph.gpickle')
part = partition(graph)
print('Graph partitioned into {0} communities'.format(len(set(part.values()))))
with open('partition.pickle', 'wb') as handle:
pickle.dump(part, handle, protocol=pickle.HIGHEST_PROTOCOL)
c = Counter(part.values())
avg_sive = 0
for i in c:
avg_sive += (c[i]/len(c))
print('Cluster average size: {0}'.format(round(avg_sive)))
graph_part(graph,part,'network.png')
if __name__ == "__main__":
main()
| true
|
b3976c96d3a7ae065120e89594495951a23174f9
|
Python
|
the-louie/pylobot
|
/plugins/snow.py
|
UTF-8
| 717
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# coding: utf-8
from commands import Command
class Snow(Command):
def __init__(self):
self.op_channel = '#dreamhack.op2'
self.swarm_channel = '#dreamhack.swarm'
self.output_channel = '#dreamhack.c&c'
def on_privmsg(self, event):
"""
Expose some functions
"""
client = event['client']
source = event['source']
target = event['target']
message = event['message']
if source is None: # unknown source, unknown error
return None
if target is not None: # target isn't me
return None
if source.in_channel(self.op_channel) or source.in_channel(self.swarm_channel): # it's an op or a bot
return
output = "<%s> %s" % (source.nick, message)
client.tell(self.output_channel, output)
| true
|
be19a8ace9aea2e7515da92e499cabc83a908471
|
Python
|
hellion86/pythontutor-lessons
|
/3. Вычисления/Улитка.py
|
UTF-8
| 769
| 3.921875
| 4
|
[] |
no_license
|
'''
Условие
Улитка ползет по вертикальному шесту высотой h метров, поднимаясь за день на a метров, а за ночь спускаясь на b метров. На какой день улитка доползет до вершины шеста?
Программа получает на вход натуральные числа h, a, b.
Программа должна вывести одно натуральное число. Гарантируется, что a>b.
'''
h = int(input())
a = int(input())
b = int(input())
shag = 0
count = 0
while shag <= h:
shag = shag + a
count = count + 1
if shag >= h:
print(count)
break
else:
shag = shag - b
| true
|
a9d5ca74de085233c7d5aadd12b5d0b3df4aa9fe
|
Python
|
Oiapokxui/fiddlingwithgspread
|
/gcloud.py
|
UTF-8
| 3,426
| 3.1875
| 3
|
[] |
no_license
|
import gspread
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials
class SheetHandler :
"""
Class responsible for loading into memory the sheet from Google Spreadsheets,
and update it.
...
Attributes:
service_account (gspread.Client) : Client object for authentication.
sheet (gspread.models.Spreadsheet): Sheet object of the manipulated spreadsheet.
resources (dict) : Dictionary of resources useful to this class.
"""
service_account = None
sheet = None
resources = {
'sheet_name' : "engenharia_de_software",
'credential_file_path' : "credencial.json",
'sheet_url' : 'https://docs.google.com/spreadsheets/d/1L6m6HIJV3rjxMTVjjAQlilGBG3kUSWuU8QSN2Bb5Rec/edit?usp=sharing'
}
def __init__(self):
"""
Constructs a SheetHandler using the class' resources.
"""
print("Fetching sheet from google drive")
self.service_account = gspread.service_account(filename=self.resources['credential_file_path'])
self.sheet = self.service_account.open_by_url(self.resources['sheet_url'])
def get_sheet_as_dataframe(self):
"""
Transform this Spreadsheet object into a Pandas.DataFrame object.
"""
print("Transforming sheet into a pandas' dataframe")
sheet_vals = self.sheet.worksheet(self.resources['sheet_name']).get_all_values()
sheet_as_dataframe = pd.DataFrame(sheet_vals[3:], columns=sheet_vals[2])
cols_types_dict = {
'Matricula' : 'int32',
'Aluno' : 'string',
'Faltas' : 'float32',
'P1' : 'float32',
'P2' : 'float32',
'P3' : 'float32',
}
sheet_as_dataframe = sheet_as_dataframe.astype(cols_types_dict)
return sheet_as_dataframe
def get_lectures_number(self):
"""
Extracts the number of lectures on a semester from the class' sheet
"""
print("Retrieving total number of lectures per semester")
sheet_vals = self.sheet.worksheet("engenharia_de_software").get_all_values()
second_line = sheet_vals[1]
lectures_text = second_line[0]
lectures_quant = lectures_text.split(" ")[-1]
return lectures_quant
def update_cells(self, column_cells_range, new_values):
"""
Updates cells on column_cells_range from class' spreadsheet with new_values
"""
worksheet = self.sheet.worksheet(self.resources['sheet_name'])
cells = worksheet.range(column_cells_range)
for ind, new_value in enumerate(new_values):
cells[ind].value = new_value
worksheet.update_cells(cells)
def update_status_column(self, new_statuses):
"""
Update "Situação" column from class' spreadsheet with
new_statuses as new values
"""
print("Updating values of column \"Situação\"")
cells = 'G4:G27'
self.update_cells(cells, new_statuses)
def update_marks_approval_column(self, new_marks):
"""
Update "Nota para Aprovação Final" column from class' spreadsheet
with new_marks as new values
"""
print("Updating values of column \"Nota para Aprovação Final\"")
cells = 'H4:H27'
self.update_cells(cells, new_marks)
| true
|
61c04abd3a73c2bfb783688ac4da8c4ca98abfb5
|
Python
|
dawnonme/Eureka
|
/main/leetcode/739.py
|
UTF-8
| 317
| 2.921875
| 3
|
[] |
no_license
|
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack, ans = [], [0] * len(T)
for i, t in enumerate(T):
while stack and stack[-1][0] < t:
_, idx = stack.pop()
ans[idx] = i - idx
stack.append((t, i))
return ans
| true
|
46ff34546994118a42cf86fddfe10363e90d301f
|
Python
|
RedditRook/20171800022d02
|
/수업내용/200917/마우스입력처리.py
|
UTF-8
| 782
| 2.890625
| 3
|
[] |
no_license
|
from pico2d import *
os.chdir('C:\\Users\\user\\Desktop\\대학\\2d게임프로그래밍\\resource')
width = 1280
height = 1024
def handle_events():
global running,x,y
events =get_events()
for event in events:
if event.type ==SDL_QUIT:
runnig =False
elif event.type ==SDL_MOUSEMOTION:
x,y=event.x, height -1 - event.y
elif event.type ==SDL_KEYDOWN and event.key ==SDLK_ESCAPE:
running =False
open_canvas(width,height)
grass = load_image('grass.png')
character = load_image('character.png')
running =True
x=get_canvas_width()//2
dx=0
while running:
clear_canvas()
grass.draw(400,30)
grass.draw (800,30)
character.draw(x,90)
update_canvas()
handle_events()
x +=dx
close_canvas()
| true
|
91a62a371db819d2988c5c16c2fe300fc5b12f09
|
Python
|
FangyangJz/Black_Horse_Python_Code
|
/第二章 python核心/HX01_python高级编程/hx17_内建函数.py
|
UTF-8
| 1,595
| 3.90625
| 4
|
[] |
no_license
|
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Fangyang time:2018/3/30
# range
# python2 中直接返回一个列表, python3中是一个迭代值
# python2中为了解决上面的问题,用xrange, 更节省空间
# map
# map(function, sequence[,sequence,...]) -> list
x = map(lambda x:x**x, [1,2,3])
print([i for i in x])
x = map(lambda x,y : x+y, [1,2,3],[4,5,6])
print([i for i in x])
#####################################################
def f1(x, y):
return (x, y)
l1 = [0, 1, 2, 3, 4, 5, 6]
l2 = ['Sun', 'M', 'T', 'W', 'T', 'F', 'S']
l3 = map(f1, l1, l2)
print(list(l3))
######################################################
# filter
print(list(filter(lambda x:x%2, [1,2,3,4])))
print(list(filter(None, 'she'))) # None表示不过滤, 全取
###################################################
# reduce
# 在Python 3里,reduce()函数已经被从全局名字空间里移除了,
# 它现在被放置在fucntools模块里用的话要 先引入
from functools import reduce
# 先1和2, 然后 结果和3, 然后 结果和4
print(reduce(lambda x,y : x+y, [1,2,3,4]))
# 5给x 1给y, 结果6给x 2给y, 结果8给x 3给y, 结果11给x 4给y
print(reduce(lambda x,y : x+y, [1,2,3,4],5))
print(reduce(lambda x,y : x+y, ['aa','bb','cc'],'dd'))
########################################################
# sort sorted()
a = [112,23,43,52,62,34,67,89,21]
a.sort()
print(a)
a.sort(reverse=True)
print(a)
a = [112,23,43,52,62,34,67,89,21]
aa1 = sorted(a)
print(aa1)
print('-'*50)
a = [112,23,43,52,62,34,67,89,21]
aa1 = sorted(a,reverse=1)
print(aa1)
# 字母也可以排序
| true
|
9f190e3d63bdfa7db7abffa34e91b7fd4e90556e
|
Python
|
Zeniuus/pyvalidator
|
/tests/field/test_integer.py
|
UTF-8
| 2,320
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import pytest
from pyvalidator import field
def test_integer_type():
spec = field.Integer()
assert spec.validate_field(3)
assert spec.validate_field(3)
assert spec.validate_field('3')
assert spec.validate_field(0)
assert spec.validate_field('0')
assert spec.validate_field(-3)
assert spec.validate_field('-3')
with pytest.raises(AssertionError):
spec.validate_field('haha')
with pytest.raises(AssertionError):
spec.validate_field('3.3')
with pytest.raises(AssertionError):
spec.validate_field(None)
def test_integer_nullable():
spec = field.Integer(nullable=True)
assert spec.validate_field(None)
def test_integer_positive():
spec = field.Integer(positive=True)
assert spec.validate_field(3)
with pytest.raises(AssertionError):
spec.validate_field(0)
with pytest.raises(AssertionError):
spec.validate_field('0')
with pytest.raises(AssertionError):
spec.validate_field(-3)
with pytest.raises(AssertionError):
spec.validate_field('-3')
def test_integer_nonnegative():
spec = field.Integer(nonnegative=True)
assert spec.validate_field(3)
assert spec.validate_field(0)
assert spec.validate_field('0')
with pytest.raises(AssertionError):
spec.validate_field(-3)
with pytest.raises(AssertionError):
spec.validate_field('-3')
def test_integer_min():
spec = field.Integer(min=3)
assert spec.validate_field(3)
assert spec.validate_field('3')
assert spec.validate_field(6)
assert spec.validate_field('6')
with pytest.raises(AssertionError):
spec.validate_field(2)
with pytest.raises(AssertionError):
spec.validate_field('2')
with pytest.raises(AssertionError):
spec.validate_field(0)
with pytest.raises(AssertionError):
spec.validate_field('0')
def test_integer_max():
spec = field.Integer(max=3)
assert spec.validate_field(3)
assert spec.validate_field('3')
assert spec.validate_field(2)
assert spec.validate_field('2')
with pytest.raises(AssertionError):
spec.validate_field(6)
with pytest.raises(AssertionError):
spec.validate_field('6')
assert spec.validate_field(0)
assert spec.validate_field('0')
| true
|
68b6a46507e7b9f1c1f777ae93be10f864568ea4
|
Python
|
MariannaPyrih/pr1
|
/2programm.py
|
UTF-8
| 134
| 3.375
| 3
|
[] |
no_license
|
import math
x=0
i=0
while x<=0.5:
y= (2.5*(pow(x,3)))/(math.exp(2*x)+2)
i=i+1
print ('y[',i,']= ' , y)
x+=0.1
print()
| true
|
491f91c83329be0be650c4c87aa27b8f743dbf51
|
Python
|
lucassimon/flask-lab
|
/tests/apps/test_responses.py
|
UTF-8
| 6,206
| 2.609375
| 3
|
[] |
no_license
|
import pytest
from apps.responses import Response
class TestRespNotAllowedUser:
def test_should_response_raises_an_error_when_resource_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response(None)
assert e.value.__str__() == "O parâmetro resource precisa ser um string"
def test_should_response_raises_an_error_when_msg_parameter_is_not_str(
self, client
):
with pytest.raises(ValueError) as e:
Response("Auth").notallowed_user(None)
assert e.value.__str__() == "O parâmetro msg precisa ser um string"
def test_should_response_correctly_when_it_is_called(self, client):
response = Response("Auth").notallowed_user()
res = response.json
assert response.status_code == 401
assert res["message"] == "Este usuário não possui permissões necessárias."
assert res["resource"] == "Auth"
class TestRespDataInvalid:
def test_should_raises_an_error_when_error_parameter_is_not_dict(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").data_invalid(None, "Some text")
assert e.value.__str__() == "O parâmetro errors precisa ser um dict"
def test_should_raises_an_error_when_msg_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").data_invalid({}, None)
assert e.value.__str__() == "O parâmetro msg precisa ser um string"
def test_should_response_correctly_when_it_is_called(self, client):
error = {"some-field": "some error"}
response = Response("Auth").data_invalid(error)
res = response.json
assert response.status_code == 400
assert res["message"] == "Ocorreu um erro nos campos informados."
assert res["resource"] == "Auth"
assert res["errors"] == error
class TestRespDoesNotExist:
def test_should_raises_an_error_when_description_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").does_not_exist(None)
assert e.value.__str__() == "O parâmetro description precisa ser um string"
def test_should_response_correctly_when_it_is_called(self, client):
error = "Some description"
response = Response("Auth").does_not_exist(error)
res = response.json
assert response.status_code == 404
assert res["message"] == f"Este(a) {error} não existe."
assert res["resource"] == "Auth"
class TestRespException:
def test_should_raises_an_error_when_msg_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").exception(None, "some description")
assert e.value.__str__() == "O parâmetro msg precisa ser um string"
def test_should_raises_an_error_when_description_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").exception("Some message", None)
assert e.value.__str__() == "O parâmetro description precisa ser um string"
def test_should_response_correctly_when_it_is_called(self, client):
error = "Some description"
response = Response("Auth").exception(description=error)
res = response.json
assert response.status_code == 500
assert res["message"] == "Ocorreu um erro no servidor. Contate o administrador."
assert res["resource"] == "Auth"
class TestRespAlreadyExists:
def test_should_raises_an_error_when_description_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").already_exists(None)
assert e.value.__str__() == "O parâmetro description precisa ser um string"
def test_should_response_correctly_when_it_is_called(self, client):
error = "Some description"
response = Response("Auth").already_exists(description=error)
res = response.json
assert response.status_code == 409
assert res["message"] == f"Já existe um(a) {error} com estes dados."
assert res["resource"] == "Auth"
class TestRespOk:
def test_should_raises_an_error_when_message_parameter_is_not_str(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").ok(message=None)
assert e.value.__str__() == "O parâmetro message precisa ser um string"
def test_should_raises_an_error_when_status_parameter_is_not_int(self, client):
with pytest.raises(ValueError) as e:
Response("Auth").ok(message="Some message", status="Some status error")
assert e.value.__str__() == "O parâmetro status precisa ser um int"
def test_should_response_correctly_when_it_is_called(self, client):
msg = "Success"
response = Response("Auth").ok(message=msg)
res = response.json
assert response.status_code == 200
assert res["message"] == msg
assert res["resource"] == "Auth"
def test_should_response_correctly_with_dict_data_argument(self):
msg = "Success"
data = {"foo": "bar"}
response = Response("Auth").ok(message=msg, data=data)
res = response.json
assert response.status_code == 200
assert res["message"] == msg
assert res["resource"] == "Auth"
assert res["data"] == data
def test_should_response_correctly_with_list_data_argument(self):
msg = "Success"
data = [{"foo": "bar"}]
response = Response("Auth").ok(message=msg, data=data)
res = response.json
assert response.status_code == 200
assert res["message"] == msg
assert res["resource"] == "Auth"
assert res["data"] == data
def test_should_response_correctly_with_extra_argument(self):
msg = "Success"
data = {"foo": "bar"}
extra = {"ping": "pong"}
response = Response("Auth").ok(message=msg, data=data, **extra)
res = response.json
assert response.status_code == 200
assert res["message"] == msg
assert res["resource"] == "Auth"
assert res["data"] == data
assert res["ping"] == "pong"
| true
|
262e375da3e842fb2ea9040dcb7e741143822cc7
|
Python
|
shrkw/sqlite3_paramstyle
|
/tests/test_sqlite3.py
|
UTF-8
| 1,599
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
# coding:utf-8
from __future__ import division, print_function, absolute_import
import pytest
import sqlite3paramstyle
@pytest.fixture
def conn():
return sqlite3paramstyle.connect(":memory:")
@pytest.fixture
def cur():
return sqlite3paramstyle.connect(":memory:").cursor()
def test_cursor_execute_without_param(cur):
cur.execute("select 1")
assert cur.fetchall() == [(1,)]
def test_cursor_execute_with_qmark_param(cur):
cur.execute("select ?", ("a",))
assert cur.fetchall() == [("a",)]
def test_cursor_execute_with_printf_param(cur):
cur.execute("select %s, %s", ("foo", "bar"))
assert cur.fetchall() == [("foo", "bar")]
def test_cursor_execute_with_named_param(cur):
cur.execute("select :who", {"who": "bc"})
assert cur.fetchall() == [("bc",)]
def test_cursor_execute_with_pyformat_param(cur):
cur.execute("select %(who)s, %(age)s", {"who": "bc", "age": 20})
assert cur.fetchall() == [("bc", 20)]
def test_cursor_execute_percent(cur):
cur.execute("select '%%', %s", ("a",))
assert cur.fetchall() == [("%", "a",)]
def cursor_executemany(cur, symbol):
def char_generator():
yield ("abc",)
yield ("bar",)
cur.execute("create table sample (notes text)")
cur.executemany("insert into sample values (%s)" % symbol, char_generator())
cur.execute("select notes from sample")
assert cur.fetchall() == [("abc",), ("bar",)]
def test_cursor_executemany_with_qmark_param(cur):
cursor_executemany(cur, "?")
def test_cursor_executemany_with_printf_param(cur):
cursor_executemany(cur, "%s")
| true
|
b44fe441c51084b47c0d63efd8b7a03f0430b406
|
Python
|
ahao214/HundredPY
|
/CrazyPython/07/gobang.py
|
UTF-8
| 404
| 3.71875
| 4
|
[] |
no_license
|
import sys
try:
a = int(sys.argv[1])
b = int(sys.argv[2])
c = a / b
print("你输入的两个数相除的结果是:", c)
except IndexError:
print("索引错误:运行程序时输入的参数个数不对")
except ValueError:
print("数值错误:程序只能接受整数参数")
except ArithmeticError:
print("算术错误")
except Exception:
print("未知异常")
| true
|
1b65f5655d634de0091e9ac8c518a79a89dfa343
|
Python
|
Connerhaar/CSE212-Final-Project
|
/Final_Project/Python_Files/Sample_answer1.py
|
UTF-8
| 514
| 3.765625
| 4
|
[] |
no_license
|
def undo_example():
print("To continue writing hit enter twice, to undo hit enter and then type (u)")
sentence = (input('Please start writing: '))
stack = sentence.split()
while True:
choice = input("")
if choice == '':
phrase = " ".join(stack)
new = input(f'{phrase} ').split()
stack.extend(new)
elif choice == 'u':
stack.pop()
print(*stack)
else:
return False
undo_example()
| true
|
3c560c1f86bbafbedb91a0d5dfa4db9a30ac4fc0
|
Python
|
haoqihua/Crypto-Project
|
/demo.py
|
UTF-8
| 4,579
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
import rsa
import pyaes
import os
import OT
from random import *
# A 256 bit (32 byte) key
key = os.urandom(16)
#print key
print("Assuming Auctioneer and all biders are authenticated\n")
(public_A, private_A) = rsa.newkeys(512)
(public_B, private_B) = rsa.newkeys(512)
(public_C, private_C) = rsa.newkeys(512)
print("Sending bidder A,B,C's public RSA keys to the auctioneet\n")
print("Bidder A initializes the function table f(x,y,z)\n")
func_x_y_z=[]
aes = pyaes.AESModeOfOperationCTR(key)
for i in range (32):
for j in range(32):
a=aes.encrypt(str(i))
b=aes.encrypt(str(j))
func_x_y_z.append((a,b))
A_prince=randint(0,31)
print( "The Auctioneer's key is used to encrypt all entries in the function table\n")
print("Using OT to present the function table to bidder B\n")
unique_bs=OT.get_unique_keys(func_x_y_z)
print("With Y chosen, bidder B will present the function table to C via OT")
#containers
B_price=randint(0,31)
rsa_public_key_containers=[]
rsa_private_key_containers=[]
aes_key=0
iv=0
encrypted_aes_keys=[]
decrypted_aes_keys=[]
encrypted_function_outcomes=[]
decrypted_function_outcomes=[]
unique_bs=[]
unique_bs=OT.get_unique_keys(func_x_y_z)
rsa_public_key_containers,rsa_private_key_containers=OT.generate_rsa_keys(func_x_y_z,unique_bs)
aes_key=OT.generate_aes_key()
encrypted_aes_keys=OT.encrypt_aes_key_using_rsa(aes_key,aes.encrypt(B_price),rsa_public_key_containers,len(func_x_y_z))
decrypted_aes_keys=OT.decrypt_aes_key_using_rsa(encrypted_aes_keys,rsa_private_key_containers)
encrypted_function_outcomes=OT.encrypt_function_outcome_using_aes(func_x_y_z,decrypted_aes_keys)
decrypted_function_outcomes=OT.decrypt_function_outcome_using_aes(encrypted_function_outcomes,aes_key)
senderA=OT.SENDER(func_x_y_z)
# B_prince=randint(0,31)
receiverA=OT.RECEIVER(aes.encrypt(B_price))
rsa_public_key_containers=senderA.send_rsa_public_keys()
print(rsa_public_key_containers)
encrypted_aes_keys=receiverA.send_encrypted_aes_keys(rsa_public_key_containers,len(rsa_public_key_containers))
encrypted_function_outcomes=senderA.send_encrypted_results(encrypted_aes_keys)
receiverA.decrypt_function_results(encrypted_function_outcomes)
# problem here: because we are using 2^5 options for each bidder, the OT with rsa encryptionbecause
# too much for computation and the program runs a while.
C_price=randint(0,31)
func_y_z=[]
for k in range(len(encrypted_function_outcomes)):
if encrypted_function_outcomes[k][0]==aes.encrypt(C_price):
for j in range(32):
func_y_z.append(encrypted_function_outcomes[k][j])
# SENDING TO
#containers
rsa_public_key_containers_c=[]
rsa_private_key_containers_c=[]
aes_key_c=0
# iv=0
encrypted_aes_keys_c=[]
decrypted_aes_keys_c=[]
encrypted_function_outcomes_c=[]
decrypted_function_outcomes_c=[]
unique_bs_c=[]
unique_bs_c=OT.get_unique_keys(func_y_z)
rsa_public_key_containers_c,rsa_private_key_containers_c=OT.generate_rsa_keys(func_y_z,unique_bs_c)
aes_key_c=OT.generate_aes_key()
encrypted_aes_keys_c_c=OT.encrypt_aes_key_using_rsa(aes_key_c,aes.encrypt(C_price),rsa_public_key_containers_c,len(func_y_z))
decrypted_aes_keys_c=OT.decrypt_aes_key_using_rsa(encrypted_aes_keys_c,rsa_private_key_containers_c)
encrypted_function_outcomes_c=OT.encrypt_function_outcome_using_aes(func_y_z,decrypted_aes_keys_c)
decrypted_function_outcomes_c=OT.decrypt_function_outcome_using_aes(encrypted_function_outcomes_c,aes_key_c)
senderB=OT.SENDER(func_y_z)
receiverC=OT.RECEIVER(aes.encrypt(C_price))
rsa_public_key_containers_c=senderB.send_rsa_public_keys()
encrypted_aes_keys_c=receiverC.send_encrypted_aes_keys(rsa_public_key_containers_c,len(rsa_public_key_containers_c))
encrypted_function_outcomes_c=senderB.send_encrypted_results(encrypted_aes_keys_c)
receiverC.decrypt_function_results(encrypted_function_outcomes_c)
print("The Auctioneer receives the encrypted results and compare them")
compare=[]
for q in range(len(encrypted_function_outcomes_c)):
compare.append((int(aes.decrypt(encrypted_function_outcomes_c[q][0])),int(aes.decrypt(encrypted_function_outcomes_c[q][1]))))
maxi=compare[0][0]
for count in range (len(compare)):
if compare[count][0]>maxi:
maxi=compare[count][0]
print ("The auctioneer broadcast the highest bid price")
print (maxi)
# (bob_pub, bob_priv) = rsa.newkeys(512)
# (bob_pub1, bob_priv1) = rsa.newkeys(512)
# # print( bob_pub)
# message = 'hello Bob!'
# # print(message)
# # print( bob_pub)
# # print( bob_priv)
# crypto = rsa.encrypt(key, bob_pub)
# message = rsa.decrypt(crypto, bob_priv)
# # print(message)
| true
|
44ef1f42ade58d7f275e272738838d5dc4f1111f
|
Python
|
manellbh/nltk-cheatsheet
|
/chap3-processing-raw-text/chap3.py
|
UTF-8
| 1,876
| 2.65625
| 3
|
[] |
no_license
|
from __future__ import division
import nltk,re, pprint
from urllib import urlopen
"""P.24: convert text hAck3r using regular expressions and substitution"""
def hacker(s):
s = s.lower()
if re.search('ate', s):
s = s.replace('ate', '8')
if re.search('e', s):
s = s.replace('e', '3')
if re.search('i', s):
s = s.replace('i', '1')
if re.search('o', s):
s = s.replace('o', '0')
if re.search('1', s):
s = s.replace('1', '|')
if re.search('s', s):
s = s.replace('s', '5')
if re.search('.', s):
s = s.replace('.', '5w33t!')
return s
print hacker('hacker')
"""P. 39: Soundex algorithm """
def soundex(s):
original = s
first = s[0]
s = s[1:]
found = re.findall(r'[bfpv]', s)
for v in found:
s = s.replace(v, '1')
found = re.findall(r'[cgjkqsxz]', s)
for v in found:
s = s.replace(v, '2')
found = re.findall(r'[dt]', s)
for v in found:
s = s.replace(v, '3')
found = re.findall(r'[l]', s)
for v in found:
s = s.replace(v, '4')
found = re.findall(r'[mn]', s)
for v in found:
s = s.replace(v, '5')
found = re.findall(r'[r]', s)
for v in found:
s = s.replace(v, '6')
found = re.findall(r'([0-9]+)\1', s)
for v in found:
s = re.sub(r'([0-9]+)\1', r'\1', s)
while re.findall(r'([0-9])[wh]\1', s):
s = re.sub(r'([0-9])[wh]\1', r'\1', s)
found = re.findall(r'[aeiouyhw]', s)
for v in found:
s = s.replace(v, '')
while len(s) < 3:
s = s + '0'
s = first+s
return s
print soundex('Tymczak')
"""P. 37: Remove HTML tags from at html file and normalize whitespace"""
def remove_tags(site):
url = site
html = urlopen(url).read()
raw = nltk.clean_html(html)
tokens = nltk.word_tokenize(raw)
ct = 0
for t in tokens:
if t.find(r'^<head'+r'>$') and t.find(r'^</head'+r'>$'):
tokens.pop(ct)
ct += 1
# for t in tokens:
# print t, len(t)
text = nltk.Text(tokens)
return text
print remove_tags('http://www.google.com')
| true
|
5737d364b5e42baabf913aa3649df40bdbca2367
|
Python
|
ege-psd/Toolkit
|
/Python Projects/kisiler-veriler.py
|
UTF-8
| 486
| 3.21875
| 3
|
[
"Unlicense"
] |
permissive
|
file = open('kisiler-veriler.txt','a')
while True:
file = open('kisiler-veriler.txt','a')
print('Selam,Hoşgeldin.')
isim = input('İsminizi Giriniz: ')
soyisim = input('Soyisminizi Giriniz: ')
yas = input('Yaşınızı Giriniz: ')
file.write('\nİsminiz: ')
file.write(isim)
file.write('\nSoyisminiz: ')
file.write(soyisim)
file.write('\nYaşınız: ')
file.write(yas)
print('Teşekkürler!\nKayıt Başarılı.')
file.close()
| true
|
ceb2a89900e549a3ef3d2cd77a15f5ce1d29176a
|
Python
|
edwardfc24/kruskal-repository
|
/kruskal.py
|
UTF-8
| 1,919
| 3.59375
| 4
|
[] |
no_license
|
from operator import itemgetter
class Kruskal:
def __init__(self):
self.nodes = {}
self.order = {}
def prepare_structure(self, node):
self.nodes[node] = node # {2: 2, 5: 5}
self.order[node] = 0 # {2: 0, 5:0}
# {'a': 'd'}
# {'d': 'd'}
# {'f': 'd'}
def find_node(self, node):
if self.nodes[node] != node:
self.nodes[node] = self.find_node(self.nodes[node])
return self.nodes[node]
# {'a': 0}
# {'d': 1}
# {'f': 0 }
def verify_union(self, origin, destination):
init_node = self.find_node(origin)
final_node = self.find_node(destination)
if init_node != final_node:
if self.order[init_node] > self.order[final_node]:
self.nodes[final_node] = init_node
else:
self.nodes[init_node] = final_node
if self.order[init_node] == self.order[final_node]:
self.order[final_node] += 1
# nodes ['a', 'b', 'c'... , 'z']
# array [ 0 , 1 , 2]
# edges ['a', 'g', 2]
def apply_kruskal(self, nodes, edges):
met = [] # Árbol de Expansion Mínima
# met => [['a', 'd', 5], ['d', 'f', 6]]
for node in nodes:
self.prepare_structure(node)
# Ordenamos las aristas de acuerdo al peso de menor a mayor
edges.sort(key = itemgetter(2))
# Recorremos las aristas para determinar el camino más eficiente a todos los nodos
for edge in edges:
# String origin = edge[0];
# String destination = edge[1];
# int weight = edge[2];
origin, destination, weight = edge
# a g
if self.find_node(origin) != self.find_node(destination):
self.verify_union(origin, destination)
met.append(edge)
return met
| true
|
5c3b83bb87f213ab21c3cfd0bd4a7c19e5f28d0a
|
Python
|
daniel-reich/ubiquitous-fiesta
|
/pmYNSpKyijrq2i5nu_15.py
|
UTF-8
| 501
| 3.0625
| 3
|
[] |
no_license
|
from itertools import product
def darts_solver(sections, darts, target):
# product creates iterable of all combinations of possible scores for given number of darts, add to set
# to remove duplicates, filter only those which add up to target and sort in ascending order of each dart's score
sets = sorted([t for t in set(tuple(sorted(p)) for p in product(sections, repeat=darts)) if sum(t) == target])
form = '-'.join(['{}']*darts)
return [s for s in map(lambda s: form.format(*s), sets)]
| true
|
df858b6616204d51bd380dabab6b8572bc4c1e42
|
Python
|
AsanalievBakyt/classwork
|
/ranges.py
|
UTF-8
| 322
| 2.921875
| 3
|
[] |
no_license
|
list_num = []
ranges = [[1,2,4], [2,3,100],[7,8,20]]
for i in range(len(ranges)):
max_num = 0
min_num = 10000000
elem = ranges[i]
for num in elem:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
list_num.append([min_num, max_num])
print(list_num)
| true
|
c274afd9d62f7e03dc9b63c31e8813237295720c
|
Python
|
MarioViamonte/Curso_Python
|
/exercicio/exercicio4.py
|
UTF-8
| 111
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
'''
for / while
0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
'''
for p, r in enumerate(range(10,1,-1)):
print(p,r)
| true
|
aedd61fc82fd7fb35352638bb26cd7b7f3c3ae66
|
Python
|
pannuprabhat/IntelligentTrafficManaagementSystem
|
/hardware.py
|
UTF-8
| 931
| 3.109375
| 3
|
[] |
no_license
|
import serial #Serial imported for Serial communication
import time #Required to use delay functions
while True:
try:
ArduinoSerial = serial.Serial('com5',9600,timeout = 1)
break
except:
print ("Unable to connect to the device.")
time.sleep(2)
continue
def setLight(lane):
while True:
try:
if lane == 1 :
ArduinoSerial.write(str.encode('1'))
elif lane ==2:
ArduinoSerial.write(str.encode('2'))
elif lane ==3:
ArduinoSerial.write(str.encode('3'))
elif lane ==4:
ArduinoSerial.write(str.encode('4'))
elif lane==0:
ArduinoSerial.write(str.encode('0'))
break
except:
print ("Error in communicating to the device...")
time.sleep (2)
continue
| true
|
011b874418b7f870af762cee3dfeff440a937bcc
|
Python
|
owasp-sbot/OSBot-Utils
|
/_to_remove/sync.py
|
UTF-8
| 1,527
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# legacy code, was created when trying to minimise dependencies, but it is
# beter to use the @sync attribute from syncer module
# # based on code from https://github.com/miyakogi/syncer/blob/master/syncer.py
#
# import sys
# from functools import singledispatch, wraps
# import asyncio
# import inspect
# import types
# from typing import Any, Callable, Generator
#
#
# PY35 = sys.version_info >= (3, 5)
#
# def _is_awaitable(co: Generator[Any, None, Any]) -> bool:
# if PY35:
# return inspect.isawaitable(co)
# else:
# return (isinstance(co, types.GeneratorType) or
# isinstance(co, asyncio.Future))
#
#
# @singledispatch
# def sync(co: Any):
# raise TypeError('Called with unsupported argument: {}'.format(co))
#
#
# @sync.register(asyncio.Future)
# @sync.register(types.GeneratorType)
# def sync_co(co: Generator[Any, None, Any]) -> Any:
# if not _is_awaitable(co):
# raise TypeError('Called with unsupported argument: {}'.format(co))
# return asyncio.get_event_loop().run_until_complete(co)
#
#
# @sync.register(types.FunctionType)
# @sync.register(types.MethodType)
# def sync_fu(f: Callable[..., Any]) -> Callable[..., Any]:
# if not asyncio.iscoroutinefunction(f):
# raise TypeError('Called with unsupported argument: {}'.format(f))
#
# @wraps(f)
# def run(*args, **kwargs):
# return asyncio.get_event_loop().run_until_complete(f(*args, **kwargs))
# return run
#
#
# if PY35:
# sync.register(types.CoroutineType)(sync_co)
| true
|
58dab21e2bb1d2891a364cfcbe364ea2143d7bd0
|
Python
|
tamique-debrito/coupled_pcla_numpy
|
/blur_function.py
|
UTF-8
| 3,723
| 2.78125
| 3
|
[] |
no_license
|
import numpy as np
from scipy.signal import convolve2d
from utils import normalize_prob
WINDOW_OPTIONS = {'hann': np.hanning}
def make_window(win_size, win_padding, win_type):
assert win_type in WINDOW_OPTIONS, f"Unsupported window type {win_type}"
base = WINDOW_OPTIONS[win_type](win_size)
return np.concatenate((base, np.zeros(win_padding)))
class BlurFn:
def __init__(self, blur_filter, norm_axis=None):
self.blur_filter = blur_filter
self.norm_axis = norm_axis
def __call__(self, spec):
blurred = convolve2d(spec, self.blur_filter, mode='same')
if self.norm_axis is not None:
return normalize_prob(blurred, ax=self.norm_axis)
else:
return blurred
# Heuristic blur functions, as copying approach in the paper appeared to cause some artifacts in the filters
def make_blur_functions(win_size_t, win_size_f, fft_size, stride, win_type='hann', show_progress=False):
"""
win_size_t < win_size_f
"""
if show_progress:
print("\rCreating blur functions", end='')
win_diff = win_size_f - win_size_t
strides_per_window = (win_size_f - win_size_t) // stride + 1 # how many times win_size_t can fit into win_size_f
blur_t_size = strides_per_window
blur_filter_t = np.hanning(blur_t_size)
blur_f_size = int(np.ceil(fft_size / win_size_t * 8 + 1))
blur_filter_f = np.hanning(blur_f_size)
blur_filter_t = np.expand_dims(blur_filter_t, 1)
blur_filter_f = np.expand_dims(blur_filter_f, 0)
if show_progress:
print("\rDone creating blur functions")
return BlurFn(blur_filter_t, 0), \
BlurFn(blur_filter_f, 1)
# Attempt at copying approach in paper's matlab code for creating blur functions, but this seems to cause artifacts
# This may be because of the difference between matlab's 'mldivide' and numpy's 'linalg.lstsq'
def _make_blur_functions(win_size_t, win_size_f, fft_size, stride, win_type='hann', show_progress=False):
"""
win_size_t < win_size_f
"""
if show_progress:
print("\rCreating blur functions", end='')
win_diff = win_size_f - win_size_t
strides_per_window = (win_size_f - win_size_t) // stride + 1 # how many times win_size_t can fit into win_size_f
blur_t_size = strides_per_window
win_t = make_window(win_size_t, win_padding=win_diff, win_type=win_type)
win_f = make_window(win_size_f, win_padding=0, win_type=win_type)
overlapping_windows_t = np.empty((win_size_f, blur_t_size))
for i in range(blur_t_size):
overlapping_windows_t[:, i] = np.roll(win_t, stride * i)
# Finding the filter by approximately combining the filters sometimes creates incorrect filters, especially when t-blur size is large
# blur_filter_t = np.linalg.lstsq(overlapping_windows_t, win_f, rcond=None)[0]
blur_filter_t = np.hanning(blur_t_size)
win_t_fft = np.fft.fftshift(abs(np.fft.fft(win_t, n=fft_size)))
win_f_fft = np.fft.fftshift(abs(np.fft.fft(win_f, n=fft_size)))
blur_f_size = int(np.ceil(fft_size / win_size_t * 8 + 1))
if blur_f_size % 2 == 0:
blur_f_size += 1
fft_offset = -(blur_f_size - 1) // 2
overlapping_windows_f_fft = np.empty((fft_size, blur_f_size))
for i in range(blur_f_size):
overlapping_windows_f_fft[:, i] = np.roll(win_f_fft, fft_offset + i)
blur_filter_f = np.linalg.lstsq(overlapping_windows_f_fft, win_t_fft, rcond=None)[0]
blur_filter_t = np.expand_dims(blur_filter_t, 1)
blur_filter_f = np.expand_dims(blur_filter_f, 0)
if show_progress:
print("\rDone creating blur functions")
return BlurFn(blur_filter_t, 0), \
BlurFn(blur_filter_f - blur_filter_f.min(), 1)
| true
|
70f2d560c555fd01fb886e044a6cba9ab66725da
|
Python
|
epitts1013/RoomAdventure
|
/RoomAdventureRevolutions.py
|
UTF-8
| 26,846
| 3.46875
| 3
|
[] |
no_license
|
###########################################################################################
# Name: Eric Pitts
# Date: 3/21/18
# Description: Room Adventure Revolutions
###########################################################################################
###IMPORTS#################################################################################
from Tkinter import *
###CLASSES#################################################################################
# the room class
# serves as template for individual rooms
class Room(object):
#Constructor
def __init__(self, name, image):
# rooms have a name, an image (the name of a file), exits (e.g., south), exit locations
# (e.g., to the south is room n), items (e.g., table), item descriptions (for each item),
# and grabbables (things that can be taken into inventory)
self.name = name
self.image = image
self.exits ={}
self.items = {}
self.grabbables = []
self.events = []
#Accessors and Mutators
#name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
#image
@property
def image(self):
return self._image
@image.setter
def image(self, value):
self._image = value
#exits
@property
def exits(self):
return self._exits
@exits.setter
def exits(self, value):
self._exits = value
#items
@property
def items(self):
return self._items
@items.setter
def items(self, value):
self._items = value
#grabbables
@property
def grabbables(self):
return self._grabbables
@grabbables.setter
def grabbables(self, value):
self._grabbables = value
#events
@property
def events(self):
return self._events
@events.setter
def events(self, val):
self._events = val
# adds an exit to the room
# the exit is a string (e.g., "north")
# the room is an instance of a room
def addExit(self, exit, room):
# append the exit and room to the appropriate dictionary
self._exits[exit] = room
# adds an item to the room
# the item is a string (e.g., table)
# the desc is a string that describes the item (e.g., it is made of wood)
def addItem(self, item, desc):
# append the item and description to the appropriate dictionary
self._items[item] = desc
# adds a grabbable item to the room
# the item is a string (e.g., key)
def addGrabbable(self, item):
# append the item to the list
self._grabbables.append(item)
# removes a grabbable item from the room
# the item is a string (e.g., key)
def delGrabbable(self, item):
# remove the item from the list
self._grabbables.remove(item)
def addEvent(self, trigger, dObject, effect):
self.events.append(Event(trigger, dObject, effect))
# returns a string description of the room
def __str__(self):
# first, the room name
s = "You are in {}.\n".format(self.name)
# next, the items in the room
s += "You see: "
for item in self.items.keys():
s += item + " "
s += "\n"
# next, the exits from the room
s += "Exits: "
for exit in self.exits.keys():
s += exit + " "
return s
# the event class
# serves as a template for [use] events
# accepts trigger item, item trigger is used on, and a string that will be executed when the event is called
class Event(object):
#Constructor
def __init__(self, trigger, dObject, effect):
self.trigger = trigger #item used to trigger event
self.dObject = dObject #item in room that trigger is used on
self.effect = effect #effects of the action input as a list of strings
#accessors and mutators
#location
@property
def location(self):
return self._location
@location.setter
def location(self, val):
self._location = val
#triggerItem
@property
def trigger(self):
return self._trigger
@trigger.setter
def trigger(self, val):
self._trigger = val
#dObject
@property
def dObject(self):
return self._dObject
@dObject.setter
def dObject(self, val):
self._dObject = val
#effect
@property
def effect(self):
return self._effect
@effect.setter
def effect(self, val):
self._effect = val
# the game class
# inherits from the Frame class of Tkinter
# sets up game and GUI
class Game(Frame):
#Constructor
def __init__(self, parent):
# call the constructor in the superclass
Frame.__init__(self, parent)
# creates the rooms
def createRooms(self):
#create room objects
front = Room("Front Yard", "front.gif")
exercise = Room("Exercise Room", "exercise.gif")
foyer = Room("Foyer", "foyer.gif")
garage = Room("Garage", "garage.gif")
kitchen = Room("Kitchen", "kitchen.gif")
living = Room("Living Room", "living.gif")
laundry = Room("Laundry Room", "laundry.gif")
guest = Room("Guest Bedroom", "guest.gif")
bed = Room("Bedroom", "bed.gif")
bath = Room("Bathroom", "bath.gif")
secret = Room("Secret Room", "secret.gif")
#rooms are added to a list for access by events
Game.rooms = []
Game.rooms.append(front) #index 0
Game.rooms.append(exercise) #index 1
Game.rooms.append(foyer) #index 2
Game.rooms.append(garage) #index 3
Game.rooms.append(kitchen) #index 4
Game.rooms.append(living) #index 5
Game.rooms.append(laundry) #index 6
Game.rooms.append(guest) #index 7
Game.rooms.append(bed) #index 8
Game.rooms.append(bath) #index 9
Game.rooms.append(secret) #index 10
#create room exits
exercise.addExit("north", kitchen)
exercise.addExit("east", foyer)
foyer.addExit("north", living)
foyer.addExit("west", exercise)
garage.addExit("north", laundry)
kitchen.addExit("north", guest)
kitchen.addExit("east", living)
kitchen.addExit("south", exercise)
living.addExit("north", bed)
living.addExit("east", laundry)
living.addExit("south", foyer)
living.addExit("west", kitchen)
laundry.addExit("north", bath)
laundry.addExit("south", garage)
laundry.addExit("west", living)
guest.addExit("south", kitchen)
bed.addExit("south", living)
bed.addExit("east", bath)
bath.addExit("south", laundry)
bath.addExit("west", bed)
#create room items
front.addItem("door-mat", "Lifting it up reveals a key")
front.addItem("door", "The front door. It can't be opened.")
front.addItem("tutorial", "This game makes use of 4 action verbs: go, look, take, and use.\nFor go, look, and take, use the format [verb][noun].\
\n For \"use\" use the format [use][object to be used][object you are acting on].\
\nFor example \"use key door\". Items being used must be in player inventory.")
exercise.addItem("weight-rack", "A rack with several dumbells of various weights placed on it.")
exercise.addItem("treadmill", "A ten speed treadmill with incline controls.")
exercise.addItem("elliptical", "Simulates walking up stairs without the high impact.")
exercise.addItem("punching-bag", "For when you need to let all that anger out. A few pairs of boxing gloves sit next to it.")
exercise.addItem("mini-fridge", "It's full of Gatorade.")
exercise.addItem("scale", "For weighing yourself after exercise, not that there is any immediate effect. I wonder how much the dumbells weigh?")
foyer.addItem("rug", "It's fairly plush under your feet.")
foyer.addItem("door-mat", "It's covered in dirt, I suppose that is its purpose.")
foyer.addItem("door", "It's where you came in from, but you shouldn't leave yet.")
garage.addItem("car", "It's a Dodge Charger. You see a key though the window.")
garage.addItem("truck", "It's a Dodge Ram.")
garage.addItem("work-bench", "It has several tools on it, like hammers and wrenches.")
garage.addItem("breaker-box", "Contains several switches for controlling the power.")
garage.addItem("garage-door", "It seems to be locked tight, not getting out this way.")
kitchen.addItem("table", "A dining table, with several dishes on it. A ham rests on top of it.")
kitchen.addItem("ham", "A smoked ham. A knife rests next to it, perhaps you could cut off a piece.")
kitchen.addItem("fridge", "A refrigerator full of boring foods.")
kitchen.addItem("oven", "An electric oven, looks like it has been recently used.")
kitchen.addItem("stove", "An electric stove.")
living.addItem("sofa", "A comfy sofa, it sits in front of the fireplace.")
living.addItem("fireplace", "A fire burns, it casts a warm glow across the room.")
living.addItem("television", "A 32\" flatscreen. A remote rests in front of it.")
living.addItem("recliner", "A La-Z-Boy recliner, looks comfortable.")
living.addItem("floor-rug", "Covers a large portion of the floor, but I don't care for the color.")
living.addItem("dvd-rack", "Has a wide array of movies.")
living.addItem("hatch", "A hatch is on the ceiling, it has seven keyholes.")
laundry.addItem("washing-machine", "A front loading washing machine with a clear window. Its fun to watch these things sometimes.")
laundry.addItem("dryer", "Used for drying clothes. Loud. Less fun to watch than a washing machine.")
laundry.addItem("laundry-basket", "Could be used to hold clothes, but the clothes are in the washer already.")
laundry.addItem("shelf", "Shelves many items, such as detergent.")
guest.addItem("bed", "A comfy looking double bed with two pillows.")
guest.addItem("dresser", "A dresser with clothes in it and a mirror on top.")
guest.addItem("coat-rack", "A lone jacket rests on it, a key sits in the pocket.")
guest.addItem("tv", "A small box television, nothing fancy.")
bed.addItem("bed", "A bed in the bedroom, who would have guessed?")
bed.addItem("wardrobe", "Full of clothes.")
bed.addItem("ceiling-fan", "Large, spinning, wooden blades for moving the air around.")
bed.addItem("desk", "Contains papers and writing utinsils. On the top rests a laptop, but the battery is dead.")
bed.addItem("safe", "A locked safe.")
bed.addItem("night-stand", "A lamp rests on top, in the drawer is a battery.")
bath.addItem("toilet", "An uninspired, white, porcelain bowl full of water and [expletive].")
bath.addItem("shower", "A shower sounds nice, but God only knows how to operate this thing.")
bath.addItem("sink", "It seems to be clogged.")
secret.addItem("a-beautiful-view", "A breathtaking view of the night sky, a fitting reward for you hard work. The only thing left is to exit the game.")
#create room grabbables
front.addGrabbable("key")
exercise.addGrabbable("boxing-gloves")
exercise.addGrabbable("dumbell")
exercise.addGrabbable("gatorade")
garage.addGrabbable("hammer")
garage.addGrabbable("wrench")
kitchen.addGrabbable("knife")
living.addGrabbable("remote")
laundry.addGrabbable("detergent")
guest.addGrabbable("key")
bed.addGrabbable("battery")
#create room events
front.addEvent("key", "door", ["Game.rooms[0].addExit(\"north\", Game.rooms[2])", "Game.rooms[0].items[\"door\"] = \"The front door\"",\
"Game.inventory.remove(\"key\")", "response = \"The door unlocks\""])
exercise.addEvent("dumbell", "scale", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"dumbell\")",\
"response = \"Placing the dumbell on the scale opened up a compartment on the scale revealing a key. You take the key.\""])
garage.addEvent("hammer", "car", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"hammer\")",\
"response = \"You use the hammer to smash in the window and take the key. You discard the hammer.\"",\
"Game.rooms[3].items[\"car\"] = \"A Dodge Charger with a broken window\""])
kitchen.addEvent("knife", "ham", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"knife\")",\
"response = \"You use the to cut into the ham, but find a key inside it. You discard the knife.\"",\
"Game.rooms[4].items[\"ham\"] = \"A smoked ham that has been cut into.\""])
laundry.addEvent("detergent", "washing-machine", ["Game.inventory.append(\"wet-clothes\")", "Game.inventory.remove(\"detergent\")",\
"response = \"You wash the clothes, but now you have a bunch of wet clothes. You discard the detergent.\""])
laundry.addEvent("wet-clothes", "dryer", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"wet-clothes\")",\
"response = \"You dry the wet clothes, and inside the laundry you find a key.\""])
bed.addEvent("battery", "laptop", ["Game.inventory.append(\"combination\")", "Game.inventory.remove(\"battery\")",\
"response = \"You could have just as easily have charged the battery, but okay. On the computer you see a combination.\"",\
"Game.rooms[8].items[\"desk\"] = \"Contains papers and writing utinsils. On the top rests a laptop.\""])
bed.addEvent("combination", "safe", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"combination\")",\
"response = \"You open the safe with the combination from the computer. Inside you find a key.\"",\
"Game.rooms[8].items[\"safe\"] = \"An unlocked safe\""])
bath.addEvent("wrench", "sink", ["Game.inventory.append(\"key\")", "Game.inventory.remove(\"wrench\")",\
"response = \"You use the wrench to open the pipes, and inside you find a key. You discard the wrench.\"",\
"Game.rooms[9].items[\"sink\"] = \"An unclogged sink.\""])
#set front as current room at beginning of the game
Game.currentRoom = front
#initialize inventory
Game.inventory = []
# sets up the GUI
def setupGUI(self):
#organize the GUI
self.pack(fill=BOTH, expand=1)
#setup input box (Tkinter Entry)
#binds return key to the process function
#fills bottom row of GUI, is focused automatically
Game.player_input = Entry(self, bg="white")
Game.player_input.bind("<Return>", self.process)
Game.player_input.pack(side=BOTTOM, fill=X)
Game.player_input.focus()
#setup image on left side (Tkinter label)
#image doesn't determine widget size
img = None
Game.image = Label(self, width=WIDTH / 2, image=img)
Game.image.image = img
Game.image.pack(side=LEFT, fill=Y)
Game.image.pack_propagate(False)
#setup console output on right
#text will be placed in a frame
text_frame = Frame(self, width=WIDTH / 2)
#Tkinter Text
#disabled by default
#widget doesn't control frame size
Game.text = Text(text_frame, bg="lightgrey", state=DISABLED)
Game.text.pack(fill=Y, expand=1)
text_frame.pack(side=RIGHT, fill=Y)
text_frame.pack_propagate(False)
# sets the current room image
def setRoomImage(self):
if (Game.currentRoom == None):
#if dead, set to skull
Game.img = PhotoImage(file="skull.gif")
else:
#otherwise set to image of current room
Game.img = PhotoImage(file=Game.currentRoom.image)
#display the image on the left of GUI
Game.image.config(image=Game.img)
Game.image.image = Game.img
# sets the status displayed on the right of the GUI
def setStatus(self, status):
#enable text widget, clear it, set it, and disable it
Game.text.config(state=NORMAL)
Game.text.delete("1.0", END)
if (Game.currentRoom == None):
#if dead, don't withold this vital information from the player and their loved ones
Game.text.insert(END, "You are dead. The only thing you can do now is quit.\n")
else:
#otherwise, display status
Game.text.insert(END, str(Game.currentRoom) + "\nYou are carrying: " + str(Game.inventory) + "\n\n" + status)
Game.text.config(state=DISABLED)
# plays the game
def play(self):
# add the rooms to the game
self.createRooms()
# configure the GUI
self.setupGUI()
# set the current room
self.setRoomImage()
# set the current status
self.setStatus("")
# processes the player's input
def process(self, event):
#grab player input from input field
action = Game.player_input.get()
#set user input to lower case
action = action.lower()
#set default response
response = "I don't understand. Try [verb][noun] for verbs go, look, and take. Try [verb][item to use][item to be used on] for use."
#exit game if player wants to quit (quit actions are "quit" or "exit"
if (action == "quit" or action == "exit"):
exit(0)
#if player is dead
if (Game.currentRoom == None):
#clear player input
Game.player_input.delete(0, END)
return
#split user input into words
words = action.split()
#the game only understands two word inputs
if (len(words) == 2):
#isolate verb and noun
verb = words[0]
noun = words[1]
#if verb is go
if (verb == "go"):
#set default response
response = "Invalid exit."
#check for valid exits in current room
if (noun in Game.currentRoom.exits):
#if room found, change currentRoom to specified room
Game.currentRoom = Game.currentRoom.exits[noun]
#set response if successful
response = "Room changed."
#if verb is look
elif(verb == "look"):
#set default response
response = "I don't see that item."
#check for valid items in current room
if (noun in Game.currentRoom.items):
#if found, set response to item description
response = Game.currentRoom.items[noun]
#if verb is take
elif(verb == "take"):
#set a default response
response = "I don't see that item."
#check for valid grabbables in room
for grabbable in Game.currentRoom.grabbables:
#if valid grabbable is found
if (noun == grabbable):
#add grabbable item to players inventory
Game.inventory.append(grabbable)
#remove grabbable from room
Game.currentRoom.delGrabbable(grabbable)
#set response if successful
response = "Item grabbed."
#no need to check for more grabbables
break
#display response on right of GUI
#display room image on left of GUI
#clear input
self.setStatus(response)
self.setRoomImage()
Game.player_input.delete(0, END)
elif (len(words) == 3):
#check for correct usage
verb = words[0]
if (verb == "use"):
#if [use] is verb, proceed
trigger = words[1]
dObject = words[2]
#set default response
response = "Can only use items in inventory."
#checks for using all keys on living room hatch
if ((Game.currentRoom == Game.rooms[5]) and (trigger == "key" or trigger == "keys") and (dObject == "hatch")):
keyCount = 0
#checks all items in inventory
for item in Game.inventory:
if item == "key":
#totals up number of keys
keyCount += 1
#if you have all the keys, opens the hatch, otherwise nothing happens
if keyCount == 7:
Game.rooms[5].addExit("hatch", Game.rooms[10])
response = "Using all seven keys, you open the hatch."
else:
response = "You lack the required number of keys."
elif (trigger in Game.inventory):
#set default response
response = "Can't use that item that way."
for event in Game.currentRoom.events:
if ((trigger == event.trigger) and (dObject == event.dObject)):
for string in event.effect:
exec(string)
#display response on right of GUI
#display room image on left of GUI
#clear input
self.setStatus(response)
self.setRoomImage()
Game.player_input.delete(0, END)
###FUNCTIONS################################################################################
###MAIN#####################################################################################
# the default size of the GUI is 800x600
WIDTH = 800
HEIGHT = 600
# create the window
window = Tk()
window.title("Room Adventure")
# create the GUI as a Tkinter canvas inside the window
g = Game(window)
# play the game
g.play()
# wait for the window to close
window.mainloop()
| true
|
d903c2a059552b88dab2f0663a6145afe387e587
|
Python
|
javatican/migulu_python
|
/class1/print1.py
|
UTF-8
| 194
| 3.09375
| 3
|
[] |
no_license
|
print('Single Quotes')
print("double quotes")
print('can do this',5)
#print('cannot do this:'+5)
#print('Can't do this')
print('you\'ll have success here')
print("you'll have success here too")
| true
|
cf2697278e7127d6a01344eeccae534e92fdc742
|
Python
|
graycarl/iamhhb-ddd
|
/iamhhb/libs/database.py
|
UTF-8
| 1,968
| 2.984375
| 3
|
[] |
no_license
|
import sqlite3
class DB(object):
"""DataBase Connection Manager"""
def __init__(self, filename):
self.filename = filename
self._conn = None
@property
def conn(self):
if not self._conn:
self._conn = sqlite3.connect(self.filename)
# about the `Row`: http://bit.ly/2obFAEW
self._conn.row_factory = sqlite3.Row
return self._conn
def query(self, sql, args=(), one=False):
result = self.conn.execute(sql, args)
rows = result.fetchall()
result.close()
return (rows[0] if rows else None) if one else rows
def query_by_id(self, tablename, id):
sql = 'SELECT * FROM `{}` WHERE id = ?'.format(tablename)
return self.query(sql, (id,), one=True)
def insert(self, tablename, columns):
cur = self.conn.cursor()
if isinstance(columns, dict):
cnames = columns.keys()
sql = 'INSERT INTO `{}` ({}) VALUES ({})'.format(
tablename,
', '.join(map(lambda c: '`%s`' % c, cnames)),
', '.join(map(lambda c: '?', cnames))
)
args = [columns[c] for c in cnames]
cur.execute(sql, args)
return cur.lastrowid
else:
raise NotImplementedError
def update_by_id(self, tablename, id, columns):
if isinstance(columns, dict):
cnames = columns.keys()
sql = 'UPDATE `{}` SET {} where id=?'.format(
tablename,
', '.join(map(lambda c: '`%s`=?' % c, cnames))
)
args = [columns[c] for c in cnames] + [id]
return self.conn.execute(sql, args)
else:
raise NotImplementedError
def commit(self):
self.conn.commit()
def rollback(self):
self.conn.rollback()
def close(self):
if self.conn:
self.conn.close()
self._conn = None
| true
|
89087d63cd10f008fb3a9ce9d92c31539f858fbc
|
Python
|
nico35490/AI_TP
|
/text_preprocessing.py
|
UTF-8
| 243
| 3.046875
| 3
|
[] |
no_license
|
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven (miles it\'s %to go, yet. Onward! 3.88')
"""
['Eighty', 'seven', 'miles', 'it', 's', 'to', 'go', 'yet', 'Onward', '3', '88']
"""
| true
|
6516f52dc32ec5074c6a711a5c4bf2ce945a5e62
|
Python
|
Flamcom27/ATM
|
/main.py
|
UTF-8
| 1,474
| 3.625
| 4
|
[] |
no_license
|
def get_banknotes(dict_bank, sum):
list_of_banknotes = []
def function(banknote):
nonlocal sum
nonlocal list_of_banknotes
nonlocal dict_bank
banknotes = sum // banknote
amount = dict_bank.get(f'{banknote}$')
dict_bank.update({f'{banknote}$': amount - banknotes})
list_of_banknotes.append(f'{banknote}$ x {banknotes}')
sum -= banknotes * banknote
return None
for i in (3, 2, 1):
while len(str(sum)) >= i:
if i == 3:
function(100)
elif i == 2:
while len(str(sum)) == i:
for j in (50, 20, 10):
if sum >= j:
if len(str(sum)) == 1:
break
function(j)
else:
continue
elif i == 1:
while len(str(sum)) == i:
for j in (5, 2, 1):
if sum == 0:
return list_of_banknotes
elif sum >= j:
function(j)
else:
continue
dict_bank = {f'{i}$': 100 for i in (
1, 2, 5, 10, 20, 50, 100
)}
sum = int(input('введите сумму, которую хотите вывести: '))
my_list = get_banknotes(dict_bank, sum)
print(my_list)
print(dict_bank)
| true
|
f58cbe495a085818b7f706e50708444e5c0a94af
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p03402/s686109800.py
|
UTF-8
| 805
| 3.359375
| 3
|
[] |
no_license
|
import sys
input = sys.stdin.readline
def main():
A, B = [int(x) for x in input().split()]
C = []
for i in range(100):
if i < 50:
C.append(["#"] * 100)
else:
C.append(["."] * 100)
whitecnt = 1
blackcnt = 1
for i in range(1, 50, 2):
if whitecnt == A:
break
for j in range(1, 100, 2):
C[i][j] = '.'
whitecnt += 1
if whitecnt == A:
break
for i in range(51, 100, 2):
if blackcnt == B:
break
for j in range(1, 100, 2):
C[i][j] = '#'
blackcnt += 1
if blackcnt == B:
break
print(100, 100)
for c in C:
print("".join(c))
if __name__ == '__main__':
main()
| true
|
5fe1e01e04e82389d3db170e7350bbe79cb9453f
|
Python
|
Aasthaengg/IBMdataset
|
/Python_codes/p02267/s813407248.py
|
UTF-8
| 252
| 2.9375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
def main():
s_length = raw_input()
s = set(raw_input().strip().split(' '))
t_length = raw_input()
t = set(raw_input().strip().split(' '))
print len(s.intersection(t))
if __name__ == '__main__':
main()
| true
|
eebe2a1ad849056da389a0746b9a19ef51a70463
|
Python
|
HongHanh120/generate-image-captcha
|
/scripts/generate_split_captcha.py
|
UTF-8
| 6,037
| 2.578125
| 3
|
[] |
no_license
|
import os
import random
import string
import bcrypt
from PIL import Image, ImageFilter
from PIL.ImageDraw import Draw
from PIL.ImageFont import truetype
from io import BytesIO
from datetime import datetime
from captcha_web_services.models import ImgCaptcha
import django
os.environ["DJANGO_SETTINGS_MODULE"] = "generate_captcha.settings"
django.setup()
DIR = '/home/hanh/Desktop/generate/generate_captcha/'
DATA_DIR = os.path.join(DIR, 'data')
FONTS = os.listdir(os.path.join(DATA_DIR, 'fonts'))
IMAGE_DIR = os.path.join(DIR, 'images')
FONT_SIZE = [64, 68]
DEFAULT_FONTS = []
for font in FONTS:
DEFAULT_FONTS.append(os.path.join(os.path.join(DATA_DIR, 'fonts'), font))
class Captcha(object):
def write(self, chars, output, format='png'):
im = self.generate_image(chars)
return im.save(output, format=format)
class ImageCaptcha(Captcha):
def __init__(self, width=270, height=100, fonts=None, font_sizes=None):
self._width = width
self._height = height
self._fonts = fonts or DEFAULT_FONTS
self._font_sizes = font_sizes or FONT_SIZE
self._truefonts = []
@property
def truefonts(self):
if self._truefonts:
return self._truefonts
self._truefonts = tuple([
truetype(n, random.choice(FONT_SIZE))
for n in self._fonts
])
return self._truefonts
@staticmethod
def draw_grid(image, background, line_width=4):
w, h = image.size
line_color = background
# draw grid
x_start = 0
x_end = w
y_start = 0
y_end = h
step_width_size = int(w / random.randint(5, 8))
step_height_size = int(h / random.randint(3, 5))
draw = Draw(image)
for x in range(0, w, step_width_size):
xy = ((x, y_start), (x, y_end))
draw.line(xy, fill=line_color, width=line_width)
for y in range(0, h, step_height_size):
xy = ((x_start, y), (x_end, y))
draw.line(xy, fill=line_color, width=line_width)
return image
def create_captcha_image(self, chars, background):
image = Image.new('RGBA', (self._width, self._height), background)
draw = Draw(image)
def draw_character(c):
font = random.choice(self.truefonts)
w, h = draw.textsize(c, font=font)
color = random_color(10, 200, random.randint(220, 225))
x = 0
y = 0
outline_color = random_color(10, 200, random.randint(220, 225))
border_width = 2
im = Image.new('RGBA', (w + border_width, h + border_width))
Draw(im).text((x - border_width, y), c, font=font, fill=outline_color)
Draw(im).text((x, y - border_width), c, font=font, fill=outline_color)
Draw(im).text((x + border_width, y), c, font=font, fill=outline_color)
Draw(im).text((x, y + border_width), c, font=font, fill=outline_color)
Draw(im).text((x + border_width, y - border_width), c, font=font, fill=outline_color)
Draw(im).text((x - border_width, y - border_width), c, font=font, fill=outline_color)
Draw(im).text((x - border_width, y + border_width), c, font=font, fill=outline_color)
Draw(im).text((x + border_width, y + border_width), c, font=font, fill=outline_color)
Draw(im).text((x, y), c, font=font, fill=color)
im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)
im = im.crop(im.getbbox())
# remove transparency
alpha = im.convert('RGBA').split()[-1]
bg = Image.new('RGBA', im.size, background + (255,))
bg.paste(im, mask=alpha)
# bg.save('bg.png', format='png')
im = bg
# wrap
data = (x, y,
-x, h - y,
w + x, h + y,
w - x, -y)
im = im.resize((w, h))
im = im.transform((w, h), Image.QUAD, data)
return im
images = []
for c in chars:
images.append(draw_character(c))
text_width = sum([im.size[0] for im in images])
width = max(text_width, self._width)
image = image.resize((width, self._height))
average = int(text_width / len(chars))
offset = int(average * 0.1) + 5
for im in images:
w, h = im.size
image.paste(im, (offset, int((self._height - h) / 2)), mask=None)
offset += w
if width > self._width:
image = image.resize((self._width, self._height))
return image
def generate_image(self, chars):
background = random_color(238, 255)
im = self.create_captcha_image(chars, background)
self.draw_grid(im, background)
im = im.filter(ImageFilter.SMOOTH)
return im
def random_color(start, end, opacity=None):
red = random.randint(start, end)
green = random.randint(start, end)
blue = random.randint(start, end)
if opacity is None:
return red, green, blue
return red, green, blue, opacity
def random_string():
random_letter = (random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
return ''.join(random_letter)
captcha = random_string().encode()
# print(captcha)
img = ImageCaptcha(fonts=[random.choice(DEFAULT_FONTS)])
created_date = datetime.now().strftime("%c")
converted_date = int(datetime.strptime(created_date, "%c").timestamp())
image_name = "split_captcha_" + str(converted_date) + ".png"
abs_image_path = os.path.join(IMAGE_DIR, os.path.join('split', image_name))
print(abs_image_path)
hashed_captcha = bcrypt.hashpw(captcha, bcrypt.gensalt())
img_captcha = ImgCaptcha(
captcha_text=hashed_captcha.decode(),
# captcha_text=captcha.decode(),
image_url=abs_image_path,
style="split captcha",
created_date=created_date,
validated=False,
).save()
img.write(captcha.decode(), abs_image_path)
| true
|
63cb62a826eddabc88b3fce1c451342df12f66c8
|
Python
|
juliahwang/WeatherSoundTest
|
/django_apps/utils/etc/mp3.py
|
UTF-8
| 1,285
| 2.625
| 3
|
[] |
no_license
|
import os
import eyed3
current = os.getcwd()
def find_mp3(current): # 추후에 media root로 고정(mp3저장되는 위치로)
# TODO DB에 넣도록, model에 필요한 필드 정보 추가, img 저장위치에 대한 고찰
# chdir를 이용하여 glob을 이용해볼까? -> 차선책
"""
current 폴더 안에 있는 모든 mp3의 정보 앨범이미지 가져온다.
:param current: 작업 폴더
:return: None
"""
for path, dirs, files in os.walk(current):
if files:
for f in files:
name = os.path.splitext(f)
if name[1] == ".mp3": # 추후에 mp3정보는 뺴와야하니까. mp3판단 부터
audio = eyed3.load(os.path.join(path, f))
album = audio.tag.album
if not os.path.isfile(album + ".jpg"):
img = audio.tag.images[0].image_data
address = path + "/images/"
if not os.path.isdir(address): # 폴더 x시 생성, 나중에 mp3한폴더에?
os.mkdir(address)
with open(address + "/{}.jpg".format(album), "wb") as f: # 추후 image저장위치 지정 다시
f.write(img)
| true
|
9041e6442350c283f163cb60e87e6982178a6b62
|
Python
|
Akshu1723/guvi
|
/codekata/fibanocci.py
|
UTF-8
| 140
| 3.296875
| 3
|
[] |
no_license
|
nks=int(input())
aks=1
bks=1
print(aks,bks,end=" ")
while(nks-2):
ck=aks+bks
aks=bks
bks=ck
print(ck,end=" ")
nks=nks-1
| true
|
8fd2da5ad9d4a57e6a2b808f017a3df2bd0e206d
|
Python
|
saint333/python_basico_1
|
/condicionales/2_ejercicio.py
|
UTF-8
| 459
| 3.78125
| 4
|
[] |
no_license
|
#Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas.
contraseña="holamundo123"
contra=input("Escriba tu contraseña: ")
if contra.lower()==contraseña.lower():
print("contraseña valida")
else:
print("contraseña invalida")
| true
|