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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e73ae82d3026f03fe0b18ec32ac02a8f54d425cc
|
Python
|
ValDagon/computer-switch
|
/server.py
|
UTF-8
| 602
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
import socket
SERVER_ADDRESS = ('192.168.56.1', 8686)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(1)
print("Server is running")
while True:
connection, address = server_socket.accept()
message = connection.recv(1024)
if str(message) == "b'sleep'":
print("i'm sleeped")
elif str(message) == "b'shutdown'" or str(message) == "b'sd'":
print("i'm power off")
else:
print("Unknown command", str(message))
connection.send(bytes("OK", encoding='UTF-8'))
connection.close()
| true
|
9c486ec84fc0a3cc914faf715b312de5c56c8890
|
Python
|
phamvankien/pypowersystem
|
/methods/cSimulation.py
|
UTF-8
| 3,722
| 2.65625
| 3
|
[] |
no_license
|
#Libraries
from scipy.sparse.linalg import inv
from scipy.sparse.linalg import spsolve
from scipy.sparse import identity
from scipy.sparse import hstack
from scipy.sparse import vstack
from scipy.sparse import csc_matrix
from numpy import r_
from numpy import zeros
from numpy import empty
from numpy import Inf
from numpy.linalg import norm
from numpy import vstack as npvstack
from progress.bar import IncrementalBar
def cSimulation(system, dae, tMax = 1, dT = 10e-3, iterMax = 10, tol = 1e-12, event = None, control= None):
#How often the control is to be executed...
if control:
tControl = control.tControl
sControl = round(tControl/dT)
#Number of elements
nx = dae.nx
ny = dae.ny
nu = dae.nu
#Number of steps
nStep = round(tMax/dT)
#Identity matrix
Ix = identity(nx)
#Initialize time
t = 0
#Initialize Output
dae.xOut = zeros((nStep,nx))
dae.yOut = zeros((nStep,ny))
dae.uOut = zeros((nStep,nu))
dae.tOut = zeros(nStep)
#Initialize flag event: Used to indicate that an event has ocurred...
flagEvent = False
#Progress bar
progressbar = IncrementalBar('Simulation progress', max = nStep)
#Start simulation!!!
for step in range(nStep):
#Show Progress
progressbar.next()
#Eval event
if event:
flagEvent = event(t, dT)
#If an event an ocurred update system
if flagEvent:
#Topology
system.makeYbus()
print('\n **********************An event has ocurred**********************\n')
# Inform the control agents about the change in topology
if control:
control.computeAll(system, dae)
#ReinitFlag
flagEvent = False
#Eval control
if control and step%sControl == 0:
control.execute(system, dae)
#Compute matrices
dae.reInitG()
dae.reInitF()
system.computeF(dae)
system.computeG(dae, system.Ybus)
#Current state
ft = 1 * dae.f
gt = 1 * dae.g
xt = 1 * dae.x
yt = 1 * dae.y
ut = 1 * dae.u
#Store Results
dae.xOut[step, :] = 1 * dae.x
dae.yOut[step, :] = 1 * dae.y
dae.uOut[step, :] = 1 * dae.u
dae.tOut[step] = 1 * t
#Solve this integration step using Newton-Rhapson method
converged = False
nIter = 0
while not converged:
nIter += 1
#Compute matrices
dae.reInitG()
dae.reInitF()
system.computeF(dae)
system.computeG(dae, system.Ybus)
xi = 1 * dae.x
fi = 1 * dae.f
fxi = 1 * dae.fx
fyi = 1 * dae.fy
gi = 1 * dae.g
gxi = 1 * dae.gx
gyi = 1 * dae.gy
qi = xi - xt - 0.5*dT*(fi + ft)
Ac = hstack([
vstack([Ix - 0.5*dT*fxi, gxi]),
vstack([-0.5*dT*fyi, gyi])
])
phi = r_[qi, gi]
#Compute update term
dz = -1*spsolve(csc_matrix(Ac), phi)
dx = dz[range(nx)]
dy = dz[range(nx, nx+ny)]
#Compute norm.
normF = norm(dz, Inf)
if normF < tol:
converged = True
dae.x = dae.x + dx
dae.y = dae.y + dy
#If there is not convergence rise exception
if not converged:
raise Exception('Dynamic simulation did not converged')
#Update time
t += dT
| true
|
2c61bff48777b4342bf44acc6a23f1a724d6f945
|
Python
|
kmcclean/PressYourBuncoLuck
|
/src/Players.py
|
UTF-8
| 696
| 3.359375
| 3
|
[] |
no_license
|
# this class holds all of the information on the players.
class Players:
def __init__(self, name, rounds_won, points_this_round, is_computer):
self.player_name = name
self.rounds = rounds_won
self.points = points_this_round
self.is_comp = is_computer
# This increases the number of rounds won by the player.
def won_round(self):
self.rounds += 1
# resets the score to zero.
def reset_points(self):
self.points = 0
# Changes the score by a bunco result.
def buncoed(self):
self.points = 21
# adds the new points onto the score.
def scored_points(self, new_points):
self.points += new_points
| true
|
5a739bf4769943f35f477d6488b225c4248b4923
|
Python
|
hakanmhmd/messenger_bot
|
/messengerbot/bot.py
|
UTF-8
| 4,686
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
import os
import requests
import apiai
import json
from sys import argv
from wit import Wit
from bottle import Bottle, request, debug
from dotenv import load_dotenv
# Setup Bottle Server
debug(True)
app = Bottle()
# Facebook Messenger GET Webhook
@app.get('/webhook')
def messenger_webhook():
"""
A webhook to return a challenge
"""
verify_token = request.query.get('hub.verify_token')
# check whether the verify tokens match
if verify_token == FB_VERIFY_TOKEN:
# respond with the challenge to confirm
challenge = request.query.get('hub.challenge')
return challenge
else:
return 'Invalid Request or Verification Token'
# Facebook Messenger POST Webhook
@app.post('/webhook')
def messenger_post():
"""
Handler for webhook (currently for postback and messages)
"""
print('In webhook post')
data = request.json
if data['object'] == 'page':
for entry in data['entry']:
# get all the messages
messages = entry['messaging']
for message in messages:
if 'message' in message:
# We retrieve the Facebook user ID of the sender
fb_id = message['sender']['id']
# We retrieve the message content
text = message['message']['text']
processMessage(fb_id, text)
else:
# Returned another event
return 'Received Different Event'
return None
# Fetch image from getty
def fetch_image_by_text(searchQuery):
# GET request to getty
url = GETTY_URL + searchQuery
response = requests.get(url, headers={'Api-Key': GETTY_TOKEN})
parsedResp = json.loads(response.content)
# Get the required parameters
imageUri = parsedResp['images'][0]['display_sizes'][0]['uri']
return imageUri
def send_image_message(sender_id, imageUri):
print('In send image message')
"""
Function for returning image response to messenger
"""
data = {
'recipient': {'id': sender_id},
'message': {'attachment': {'type': 'image', 'payload': {'url': imageUri}}}
}
# Setup the query string with your PAGE TOKEN
qs = 'access_token=' + FB_PAGE_TOKEN
# Send POST request to messenger
resp = requests.post('https://graph.facebook.com/me/messages?' + qs,
json=data)
return resp.content
def send_text_message(sender_id, text):
print('In send text message')
"""
Function for returning text response to messenger
"""
data = {
'recipient': {'id': sender_id},
'message': {'text': text}
}
# Setup the query string with your PAGE TOKEN
qs = 'access_token=' + FB_PAGE_TOKEN
# Send POST request to messenger
resp = requests.post('https://graph.facebook.com/me/messages?' + qs,
json=data)
return resp.content
def processMessage(fb_id, input):
print('In process message')
request = ai.text_request()
request.lang = 'en'
request.session_id = 'messengerbot'
request.query = input
response = request.getresponse()
parsedResp = json.loads(response.read())
print parsedResp
result = parsedResp.get('result')
if result is None:
return ''
fulfillment = result.get('fulfillment')
if fulfillment is None:
return ''
speech = fulfillment.get('speech')
if speech is None:
return ''
metadata = result.get('metadata')
intentName = metadata.get('intentName')
if intentName is None:
print('Sending message... ')
send_text_message(fb_id, speech)
elif intentName == 'images.search':
print('Sending image... ')
searchQuery = result['parameters']['image_name']
if searchQuery == '':
return send_text_message(fb_id, 'I could not find any images.')
imageUri = fetch_image_by_text(searchQuery)
send_image_message(fb_id, imageUri)
if __name__ == '__main__':
load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
# Messenger API parameters
FB_PAGE_TOKEN = os.environ.get('FB_PAGE_TOKEN')
# A user secret to verify webhook get request.
FB_VERIFY_TOKEN = os.environ.get('FB_VERIFY_TOKEN')
#getty api
GETTY_TOKEN = os.environ.get('GETTY_KEY')
GETTY_URL = 'https://api.gettyimages.com/v3/search/images?fields=id,title,thumb,referral_destinations&sort_order=best&phrase='
# Api.ai token for NLP
API_AI_TOKEN = os.environ.get('API_AI_TOKEN')
# AI instance
ai = apiai.ApiAI(API_AI_TOKEN)
# Run Server
app.run(host='0.0.0.0', port=8000, reloader=True)
| true
|
8dc1aeb75e88323f7be38163f737458e5e7a21c6
|
Python
|
CaesarZhang070497/audios
|
/wavenet/decoder.py
|
UTF-8
| 7,436
| 2.8125
| 3
|
[] |
no_license
|
from itertools import product
from typing import List, Optional
import torch
from torch import nn
from torch.nn import functional as F
from tqdm import trange
from .modules import BlockWiseConv1d, DilatedQueue
class WaveNetDecoder(nn.Module):
"""
WaveNet as described NSynth [http://arxiv.org/abs/1704.01279].
This WaveNet has some differences to the original WaveNet. Namely:
· It uses a conditioning on all layers, input always the same
conditioning, added to the dilated values (features and gates) as well
as after the final skip convolution.
· The skip connection does not start at 0 but comes from a 1×1
Convolution from the initial Convolution.
"""
def __init__(self,
n_layers: int = 10,
n_blocks: int = 3,
width: int = 512,
skip_width: int = 256,
channels: int = 1,
quantization_channels: int = 256,
bottleneck_dims: int = 16,
kernel_size: int = 3,
gen: bool = False):
"""
:param n_layers: Number of layers in each block
:param n_blocks: Number of blocks
:param width: The width/size of the hidden layers
:param skip_width: The width/size of the skip connections
:param channels: Number of input channels
:param quantization_channels: Number of final output channels
:param bottleneck_dims: Dim/width/size of the conditioning, output
of the encoder
:param kernel_size: Kernel-size to use
:param gen: Is this generation ?
"""
super(WaveNetDecoder, self).__init__()
self.width = width
self.n_stages, self.n_layers = n_blocks, n_layers
# The compound dilation (input to last layer in each block):
self.scale_factor = 2 ** (n_layers - 1)
self.receptive_field = 2 ** n_layers * n_blocks
self.quantization_channels = quantization_channels
self.gen = gen
self.kernel_size = kernel_size
self.initial_dilation = BlockWiseConv1d(in_channels=channels,
out_channels=width,
kernel_size=kernel_size,
block_size=1,
causal=True)
self.initial_skip = BlockWiseConv1d(width, skip_width, 1)
self.dilations = self._make_conv_list(width, 2 * width, kernel_size,
not gen)
self.conds = self._make_conv_list(bottleneck_dims, 2 * width, 1, False)
self.residuals = self._make_conv_list(width, width, 1, False)
self.skips = self._make_conv_list(width, skip_width, 1, False)
self.queues = []
for _, l in product(range(self.n_stages), range(self.n_layers)):
self.queues.append(
DilatedQueue(size=(kernel_size - 1) * 2 ** l + 1,
channels=width, dilation=2 ** l)
)
self.upsampler = nn.Upsample(scale_factor=self.scale_factor,
mode='nearest')
self.final_skip = nn.Sequential(
nn.ReLU(),
BlockWiseConv1d(skip_width, skip_width, 1)
)
self.final_cond = BlockWiseConv1d(bottleneck_dims, skip_width, 1)
self.final_quant = nn.Sequential(
nn.ReLU(),
BlockWiseConv1d(skip_width, quantization_channels, 1)
)
def _make_conv_list(self, in_channels: int, out_channels: int,
kernel_size: int, dilate: bool) -> nn.ModuleList:
"""
A little helper function for generating lists of Convolutions. Will
give list of n_blocks × n_layers number of convolutions. If kernel_size
is bigger than one we use the BlockWise Convolution and calculate the
block size from the power-2 dilation otherwise we always use the same
1×1-conv1d.
:param in_channels:
:param out_channels:
:param kernel_size:
:param dilate: Whether to dilate in each step
:return: ModuleList of len self.n_blocks * self.n_layers
"""
module_list = []
for _, layer in product(range(self.n_stages), range(self.n_layers)):
block_size = 2 ** layer if dilate else 1
module_list.append(BlockWiseConv1d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
block_size=block_size,
causal=kernel_size != 1))
return nn.ModuleList(module_list)
def forward(self, x: torch.Tensor, embedding: torch.Tensor,
conditionals: Optional[List[torch.Tensor]] = None) \
-> torch.Tensor:
"""
:param x:
:param embedding:
:param conditionals: (Optional) contains list of all upsampled
conditionals. Used for generation. If given do not give an
embedding.
:return:
"""
x = self.initial_dilation(x)
skip = self.initial_skip(x)
conds = conditionals or self.conds
layers = (self.dilations, conds, self.residuals, self.skips,
self.queues)
for l_dilation, cond, l_residual, l_skip, queue in zip(*layers):
if self.gen:
queue.enqueue(x.squeeze())
dilated = queue.dequeue(num_deq=self.kernel_size)
dilated = dilated.unsqueeze(0)
else:
dilated = x
dilated = l_dilation(dilated)
if self.gen:
dilated = dilated[:, :, 1].unsqueeze(-1)
if conditionals:
dilated = dilated + cond
else:
dilated = dilated + self.upsampler(cond(embedding))
filters = torch.sigmoid(dilated[:, :self.width, :])
gates = torch.tanh(dilated[:, self.width:, :])
pre_res = filters * gates
x = x + l_residual(pre_res) # Is this correct????
skip = skip + l_skip(pre_res)
skip = self.final_skip(skip)
if conditionals:
skip = skip + conds[-1]
else:
skip = skip + self.upsampler(self.final_cond(embedding))
quant_skip = self.final_quant(skip)
return quant_skip
def generate(self, x: torch.Tensor, conditionals, length: int, device: str,
temp: float = 1.):
for queue in self.queues:
queue.reset(device)
rem_length = length - x.numel()
# Fill queues with initial values
for i in trange(x.numel() - 1):
inp = x[0, 0, i:i + 1].view(1, 1, 1)
_ = self(inp, None, conditionals)
generation = torch.zeros(length)
for i in trange(rem_length):
logits = self(inp, None, conditionals).squeeze()
if temp > 0:
prob = F.softmax(logits / temp, dim=0)
c = torch.multinomial(prob, 1).float()
else:
c = torch.argmax(logits).float()
c = (c - 128.) / 128.
generation[i] = c.cpu()
inp = c.view(1, 1, 1)
return generation
| true
|
3e0da2e2699ec60bf41ebdf072838ac3b4163c8c
|
Python
|
DaHuO/Supergraph
|
/codes/CodeJamCrawler/16_0_1_neat/16_0_1_Kiiwi_a.py
|
UTF-8
| 639
| 3.015625
| 3
|
[] |
no_license
|
file = open('A-large.in')
out = open('output.in', 'w')
T = int(file.readline().strip())
case = 1
for cases in range(T):
input_line = file.readline().strip().split(" ")
N = int(input_line[0])
digit_list = []
i = 1
while len(digit_list) < 10:
n = N*i
if n == 0:
n = 'INSOMNIA'
break
n_string = str(n)
for digit in n_string:
if digit not in digit_list:
digit_list.append(digit)
if len(digit_list) == 10:
break
i += 1
out.write("Case #%i: %s\n" % (case, n))
case += 1
| true
|
ac8fc701cc95a5f76ed9de7987ed601e1990e8c7
|
Python
|
Sahanave/Millionsongdataset_UCI
|
/Part-2.py
|
UTF-8
| 2,076
| 2.796875
| 3
|
[] |
no_license
|
# coding: utf-8
# In[3]:
#import the libraries
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import cross_validation
from statistics import mode
from sklearn.linear_model import SGDRegressor
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
import numpy
from scipy import sparse
from sklearn.svm import LinearSVR
from sklearn import preprocessing
from sklearn.metrics import make_scorer
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestRegressor
#loading the dataset
f = open("/Users/sahanavenkatesh/Desktop/Semester-2 US/Machine Learning/Project/raw_data.txt")
dataset = numpy.loadtxt(f,delimiter=",")
train_dataset=dataset[0:463714,:]
test_dataset=dataset[463715:515344,:]
X_train=train_dataset[:,1:91]
X_trainsub=train_dataset[:,1:13]
y_train=train_dataset[:,0]
X_test=test_dataset[:,1:91]
X_testsub=test_dataset[:,1:13]
y_test=test_dataset[:,0]
scaler = preprocessing.StandardScaler().fit(train_dataset)
train_dataset=scaler.transform(train_dataset)
train2_dataset=train_dataset[0:463714,:]
cross_val_data=train_dataset[363715:463714,:]
X_train=train2_dataset[:,1:91]
X_trainsub=train2_dataset[:,1:12]
y_train=train2_dataset[:,0]
#Model no 5 Extratrees Classifier
clf = RandomForestRegressor(n_estimators=20,criterion='mse', max_features='sqrt')
#Usually above 10 is good in most cases.
clf = clf.fit(X_train, y_train)
#################
X_crossval=cross_val_data[:,1:91]
y_true=cross_val_data[:,0]
y_predict=clf.predict(X_crossval)
y_true=1998.3+y_true*10.93#scaling it back to measure the absolute error
y_predict=1998.3+y_predict*10.93#scaling it back to measure the absolute error
error_rf=mean_absolute_error(y_true, y_predict)
sq_error_rf=mean_squared_error(y_true, y_predict)
print('values for rf absolute error(years) and mean_squared_error(years)',error_rf)
print(sq_error_rf)
| true
|
9fdafc26664d41cfb5a8f1696626363704309cf8
|
Python
|
Erick-rick/Python
|
/Exercicios II/Ex_01.py
|
UTF-8
| 144
| 3.484375
| 3
|
[] |
no_license
|
print ('**-- Conta de Luz --**')
cl = int(input ('Digite o valor da conta de luz :'))
if (cl > 50):
print ('Você esta gastando muito!')
| true
|
1565c55ec5fb3e17adb280790dc6237751b082c2
|
Python
|
monci07/AI
|
/Primer bloque/1249134_primerEje.py
|
UTF-8
| 578
| 3.875
| 4
|
[] |
no_license
|
#funcion que invierte la lista
def rev(lista):
reversa = []
#el ciclo empieza en el ultimo elemento de la lista, para ir decrementando mientras sea mayor a -1
for i in range(len(lista)-1, -1, -1):
reversa.append(lista[i])
return reversa
lista1=[]
listaR=[]
bandera = 's'
#se empiezan a tomar datos mientras que el usuario quiera
while bandera == 's':
lista1.append(int(input("Introdusca un numero:")))
bandera = input("Quieres ingresar otro? (s/n)")
listaR=rev(lista1)
print("Lista original: "+ str(lista1))
print("Lista inversa: "+ str(listaR))
| true
|
a6b24b10fc3650e2e65e2c9cf5a500c97fb39fd0
|
Python
|
rzwck/c1-form-reader
|
/read-C1-form.py
|
UTF-8
| 20,438
| 2.546875
| 3
|
[] |
no_license
|
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import warnings
warnings.filterwarnings("ignore")
import matplotlib.image as mpimg
import numpy as np
import cv2
from pyimagesearch import *
from keras.models import load_model
def read_box(window):
# input image is black over white background
window = window.copy()
# image is now white over black background
window = cv2.bitwise_not(window)
h = window.shape[0]
w = window.shape[1]
# clean left borders
for i in range(5):
filled = sum(window[:,i:i+1]!=0) / h
if filled > 0.45:
window = cv2.line(window, (i,0), (i,h),0,1)
# clean top borders
for i in range(5):
filled = (window[i:i+1,:]!=0).sum() / w
if filled > 0.45:
window = cv2.line(window, (0,i), (w,i),0,1)
# clean right borders
for i in range(5):
filled = sum(window[:,w-i-1:w-i]!=0) / h
if filled > 0.45:
window = cv2.line(window,(w-1-i,0),(w-1-i,h),0,1)
# clean bottom borders
for i in range(5):
filled = (window[h-i-1:h-i,:]!=0).sum() / w
if filled > 0.45:
window = cv2.line(window, (0,h-i-1), (w,h-i-1),0,1)
lineThickness = 1
window = cv2.line(window, (0,0), (window.shape[1],0),0, lineThickness)
window = cv2.line(window, (0,0), (0,window.shape[0]),0, lineThickness)
window = cv2.line(window, (window.shape[1]-1,0), (window.shape[1]-1,window.shape[0]),0, lineThickness)
window = cv2.line(window, (0,window.shape[0]-1), (window.shape[1],window.shape[0]-1),0, lineThickness)
contours, h = cv2.findContours(window.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
full_area = window.shape[0] * window.shape[1]
min_x = window.shape[1]
min_y = window.shape[0]
max_x = 0
max_y = 0
mask = np.ones(window.shape[:2], dtype="uint8")
for cnt in contours:
area = cv2.contourArea(cnt)
if area <= 2:
_ = cv2.drawContours(mask, [cnt], -1, 0, -1)
continue
rect = cv2.boundingRect(cnt)
if (rect[2]*rect[3])/full_area >= 0.95: continue
if rect[3] == window.shape[0] or rect[2] == window.shape[1]:
_ = cv2.drawContours(mask, [cnt], -1, 0, -1)
continue
if rect[0] < min_x:
min_x = rect[0]
if rect[0]+rect[2] > max_x:
max_x = rect[0]+rect[2]
if rect[1] < min_y:
min_y = rect[1]
if rect[1]+rect[3] > max_y:
max_y = rect[1]+rect[3]
digit_region = (min_x,min_y, max_x-min_x,max_y-min_y)
max_rect = digit_region
window = cv2.bitwise_and(window, window, mask=mask)
window = window[max_rect[1]:max_rect[1]+max_rect[3], max_rect[0]:max_rect[0]+max_rect[2]]
desired = 56
if window.shape[0] < 28 and window.shape[1] < 28:
desired = 28
top = bottom = (desired - window.shape[0]) // 2
left = right = (desired - window.shape[1]) // 2
if top+bottom+window.shape[0] < desired:
top += 1
if left+right+window.shape[1] < desired:
left += 1
window = cv2.copyMakeBorder(window,top,bottom,left,right,cv2.BORDER_CONSTANT,0)
if window.shape != (28,28):
window = cv2.resize(window, (28,28), interpolation=cv2.INTER_AREA)
return window
def adjust_borders(window):
win = window.copy()
w = win.shape[1]
h = win.shape[0]
# adjust left
left_border = 0
for i in range(10):
filled = sum(win[:,i:i+1]!=0) / h
if filled > 0.9: left_border = i+1
win = win[:,left_border:]
# adjust top
top_border = 0
for i in range(10):
filled = (win[i:i+1,:]!=0).sum() / w
if filled > 0.9: top_border = i+1
win = win[top_border:,:]
# adjust right
right_border = 0
for i in range(10):
filled = sum(win[:,w-i-1:w-i]!=0) / h
if filled > 0.9: right_border = i+1
win = win[:,:w-right_border]
# adjust bottom
bottom_border = 0
for i in range(10):
filled = (win[h-i-1:h-i,:]!=0).sum() / w
if filled > 0.9: bottom_border = i+1
win = win[:h-bottom_border,:]
return (left_border,top_border,right_border,bottom_border)
def get_boxes(window, topleft_xy,min_vertical,min_horizontal,minLineLength,maxLineGap,min_w,min_h):
pivot_x, pivot_y = topleft_xy
window_edges = cv2.Canny(window, 100, 150)
lines = cv2.HoughLinesP(window_edges, 1, np.pi / 180, 15, np.array([]),minLineLength, maxLineGap)
ys1 = []
ys2 = []
xs = [[],[],[],[]]
boxes = [[],[],[]]
for line in lines:
ln = line[0]
# vertical lines
if abs(ln[0]-ln[2])<=3 and abs(ln[1]-ln[3]) >= min_vertical:
if ln[0] < 0.36*window_edges.shape[1]:
xs[0].append(ln[0])
elif ln[0] < 0.6*window_edges.shape[1]:
xs[1].append(ln[0])
elif ln[0] < 0.83*window_edges.shape[1]:
xs[2].append(ln[0])
elif ln[0] > 0.89*window_edges.shape[1]:
xs[3].append(ln[0])
# horizontal lines
if abs(ln[1]-ln[3])<=3 and abs(ln[0]-ln[2]) >= min_horizontal:
if ln[1] < window_edges.shape[0]/2:
ys1.append(ln[1])
else:
ys2.append(ln[1])
if not ys1 or not ys2:
return boxes
y1 = max(ys1)
y2 = min(ys2)
if xs[0] and xs[1]:
boxes[0] = [max(xs[0]), y1, abs(min(xs[1])-max(xs[0])), abs(y2-y1)]
if xs[1] and xs[2]:
boxes[1] = [max(xs[1]), y1, abs(min(xs[2])-max(xs[1])), abs(y2-y1)]
if xs[2] and xs[3]:
boxes[2] = [max(xs[2]), y1, abs(min(xs[3])-max(xs[2])), abs(y2-y1)]
# validate box width and height
for i in range(3):
if not boxes[i]: continue
# validate box width
if boxes[i][2] < min_w-5 or boxes[i][2] > min_w+5:
boxes[i][2] = min_w
# validate box height
if boxes[i][3] < min_h-5 or boxes[i][3] > min_h+5:
boxes[i][3] = min_h
if not boxes[0]:
# missing left box
if boxes[1]:
boxes[0] = list(boxes[1])
boxes[0][0] = boxes[1][0] - boxes[1][2]
elif boxes[2]:
boxes[0] = list(boxes[2])
boxes[0][0] = boxes[2][0] - 2*boxes[2][2]
if not boxes[1]:
# missing middle box
if boxes[0]:
boxes[1] = list(boxes[0])
boxes[1][0] = boxes[0][0] + boxes[0][2]
elif boxes[2]:
boxes[1] = list(boxes[2])
boxes[1][0] = boxes[2][0] - boxes[2][2]
if not boxes[2]:
# missing right box
if boxes[1]:
boxes[2] = list(boxes[1])
boxes[2][0] = boxes[1][0] + boxes[1][2]
elif boxes[0]:
boxes[2] = list(boxes[0])
boxes[2][0] = boxes[0][0] + 2*boxes[0][2]
# make sure there is no overlap between boxes horizontally
if boxes[0] and boxes[1] and boxes[1][0] < boxes[0][0] + boxes[0][2]:
boxes[1][0] = boxes[0][0] + boxes[0][2]
if boxes[1] and boxes[2] and boxes[2][0] < boxes[1][0] + boxes[1][2]:
boxes[2][0] = boxes[1][0] + boxes[1][2]
# adjust boxes boundaries
for box in boxes:
if not box: continue
(thresh, box_window_bw) = cv2.threshold(window, 215, 255, cv2.THRESH_BINARY)
box_window = box_window_bw[box[1]:box[1]+box[3], box[0]:box[0]+box[2]]
box_window = cv2.bitwise_not(box_window)
w = box_window.shape[1]
h = box_window.shape[0]
(left,top,right,bottom) = adjust_borders(box_window)
adjusted_box = box_window[top:h-bottom, left:w-right]
box[0] += pivot_x+left
box[1] += pivot_y+top
box[2] = adjusted_box.shape[1]
box[3] = adjusted_box.shape[0]
return boxes
def get_vote_box(window, topleft_xy,min_wh):
min_w, min_h = min_wh
return get_boxes(window, topleft_xy, 0.5*window.shape[0], 0.5*window.shape[1], 50, 20, min_w,min_h)
def get_ballot_box(window, topleft_xy,min_wh):
min_w, min_h = min_wh
return get_boxes(window, topleft_xy, 0.4*window.shape[0], 0.4*window.shape[1], 20, 10,min_w,min_h)
def get_squares(image_bw, min_side, max_side):
contours, h = cv2.findContours(image_bw,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
full_area = image_bw.shape[0] * image_bw.shape[1]
squares = []
for cnt in contours:
area = cv2.contourArea(cnt)
rects = cv2.boundingRect(cnt)
if area/full_area >= 0.9: continue
if rects[2] < min_side or rects[3] < min_side: continue
if rects[2] > max_side or rects[3] > max_side: continue
if abs(rects[3]-rects[2]) >= 2: continue
squares.append(rects)
return squares
def get_marker_box(window, min_side, max_side):
thres = 250
boxes = []
min_box = ()
min_area = max_side*max_side
full_area = window.shape[0] * window.shape[1] * 255
while thres > 100:
(thres, window_bw) = cv2.threshold(window, thres, 255, cv2.THRESH_BINARY)
boxes = get_squares(window_bw, min_side, max_side)
if len(boxes) == 1:
box_area = boxes[0][2]*boxes[0][3]
occupied = window_bw.sum()/full_area
if box_area < min_area and occupied >= 0.75:
min_area = box_area
min_box = boxes[0]
thres -= 5
return min_box
def find_markers(image, min_side, max_side):
image_grayed = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
marker_w, marker_h = 100,100
h = image.shape[0]
w = image.shape[1]
markers = {}
# top-left marker
pivot_x,pivot_y = (0,0)
window = image_grayed[pivot_y:marker_h,pivot_x:marker_w]
window = cv2.copyMakeBorder(window,1,1,1,1,cv2.BORDER_CONSTANT,value=255)
box = get_marker_box(window, min_side,max_side)
if box:
markers['top-left'] = (pivot_x+box[0],pivot_y+box[1],box[2],box[3])
# bot-left marker
pivot_x,pivot_y = 0, h-marker_h
window = image_grayed[pivot_y:,pivot_x:marker_w]
window = cv2.copyMakeBorder(window,1,1,1,1,cv2.BORDER_CONSTANT,value=255)
box = get_marker_box(window, min_side,max_side)
if box:
markers['bot-left'] = (pivot_x+box[0],pivot_y+box[1],box[2],box[3])
# top-right marker
pivot_x,pivot_y = (w-marker_w,0)
window = image_grayed[pivot_y:marker_h,pivot_x:]
window = cv2.copyMakeBorder(window,1,1,1,1,cv2.BORDER_CONSTANT,value=255)
box = get_marker_box(window, min_side,max_side)
if box:
markers['top-right'] = (pivot_x+box[0],pivot_y+box[1],box[2],box[3])
# bot-right marker
pivot_x,pivot_y = (w-marker_w,h-marker_h)
window = image_grayed[pivot_y:,pivot_x:]
window = cv2.copyMakeBorder(window,1,1,1,1,cv2.BORDER_CONSTANT,value=255)
box = get_marker_box(window, min_side,max_side)
if box:
markers['bot-right'] = (pivot_x+box[0],pivot_y+box[1],box[2],box[3])
if len(markers) == 3:
if 'top-left' not in markers:
dy = markers['bot-right'][1] - markers['bot-left'][1]
dx = markers['bot-right'][0] - markers['bot-left'][0]
tl_x = markers['top-right'][0] - dx
tl_y = markers['top-right'][1] - dy
markers['top-left']=(tl_x,tl_y,28,28)
elif 'top-right' not in markers:
dy = markers['bot-right'][1] - markers['bot-left'][1]
dx = markers['bot-right'][0] - markers['bot-left'][0]
tr_x = markers['top-left'][0] + dx
tr_y = markers['top-left'][1] + dy
markers['top-right']=(tr_x,tr_y,28,28)
elif 'bot-left' not in markers:
dy = markers['top-right'][1] - markers['top-left'][1]
dx = markers['top-right'][0] - markers['top-left'][0]
bl_x = markers['bot-right'][0] - dx
bl_y = markers['bot-right'][1] - dy
markers['bot-left']=(bl_x,bl_y,28,28)
elif 'bot-right' not in markers:
dy = markers['top-right'][1] - markers['top-left'][1]
dx = markers['top-right'][0] - markers['top-left'][0]
br_x = markers['bot-left'][0] + dx
br_y = markers['bot-left'][1] + dy
markers['bot-right']=(br_x,br_y,28,28)
return markers
def scan_boxes(boxes, boxes_window_bw):
count_str = ''
confidence = True
boxes28 = []
for box in boxes:
window = boxes_window_bw[box[1]:box[1]+box[3], box[0]:box[0]+box[2]]
window = read_box(window)
boxes28.append(window)
if window.sum() < 10:
char = '0'
count_str += '0'
continue
window = window.reshape((1, 28, 28, 1))
pred = model_hyphen.predict_classes(window)
if pred[0] == 1:
char = '-'
else:
pred = modelX.predict_classes(window)
if pred[0] == 1:
char = 'X'
else:
pred = model_mnist.predict_classes(window)[0]
pred2 = model_dki17.predict_classes(window)[0]
if pred != pred2:
confidence = False
char = str(pred)
count_str += char
if count_str[2] == 'X':
count_str = 'XXX'
elif count_str[1] == 'X':
count_str = 'X' + count_str[1:]
return count_str, confidence, boxes28
def scan_form(img_file, img_file_out):
# ### Load Formulir-C1 Scanned Images
image = mpimg.imread(img_file)
# ### Find 4 box markers
markers = find_markers(image, min_side=20, max_side=50)
if len(markers) != 4: raise Exception("Unable find corner markers")
# ## Perspective Transform based on Markers
pts = [markers[x][:2] for x in markers]
pts = np.array(pts, dtype = "float32")
trans_img = four_point_transform(image, pts)
trans_img_grayed = cv2.cvtColor(trans_img, cv2.COLOR_RGB2GRAY)
form_height = trans_img.shape[0]
form_width = trans_img.shape[1]
# ### Get votes boxes
pivot_x, pivot_y = round(form_width*0.8),round(form_height*0.14)
window = trans_img_grayed[pivot_y:round(form_height*0.29),pivot_x:]
min_w = round(form_width*0.04)
min_h = round(form_height*0.05)
win01 = window[:window.shape[0]//2,:]
boxes01 = get_vote_box(win01, (pivot_x,pivot_y), (min_w,min_h))
if not all(boxes01): raise Exception("Unable to find digit positions for votes #01")
win02 = window[window.shape[0]//2:,:]
boxes02 = get_vote_box(win02, (pivot_x,pivot_y+window.shape[0]//2),(min_w,min_h))
if not all(boxes02): raise Exception("Unable to find digit positions for votes #02")
# ### Get ballots boxes
pivot_x, pivot_y = round(form_width*0.8),round(form_height*0.37)
window = trans_img_grayed[pivot_y:round(form_height*0.55),pivot_x:]
min_w = round(form_width*0.041)
min_h = round(form_height*0.025)
win_valid = window[:round(0.23*window.shape[0]),:]
win_invalid = window[round(0.37*window.shape[0]):round(0.65*window.shape[0]),:]
win_total = window[round(0.78*window.shape[0]):,:]
boxes_valid = get_ballot_box(win_valid,(pivot_x, pivot_y),(min_w,min_h))
if not all(boxes_valid): raise Exception("Unable to find digit positions for valid ballots count")
boxes_invalid = get_ballot_box(win_invalid,(pivot_x, round(0.37*window.shape[0])+pivot_y),(min_w,min_h))
if not all(boxes_invalid): raise Exception("Unable to find digit positions for invalid ballots count")
boxes_total = get_ballot_box(win_total,(pivot_x, round(0.78*window.shape[0])+pivot_y),(min_w,min_h))
if not all(boxes_total): raise Exception("Unable to find digits for total ballots count")
# ### Read hand written digits
confidence = {'votes01':True,'votes02':True,'valid_ballots':True,'invalid_ballots':True,'total_ballots':True}
validity = {k:False for k in confidence}
clone = trans_img.copy()
clone_grayed = cv2.cvtColor(clone, cv2.COLOR_RGB2GRAY)
(thresh, clone_bw) = cv2.threshold(clone_grayed, 215, 255, cv2.THRESH_BINARY)
suara01, confidence['votes01'], digits_01 = scan_boxes(boxes01, clone_bw.copy())
suara02, confidence['votes02'], digits_02 = scan_boxes(boxes02, clone_bw.copy())
suara_sah,confidence['valid_ballots'], digits_valid = scan_boxes(boxes_valid, clone_bw.copy())
suara_tidak_sah,confidence['invalid_ballots'], digits_invalid = scan_boxes(boxes_invalid, clone_bw.copy())
total_suara,confidence['total_ballots'], digits_total = scan_boxes(boxes_total, clone_bw.copy())
# ## Validation and correction
try:
votes01 = int(suara01.replace('X','0'))
votes02 = int(suara02.replace('X','0'))
nb_valid = int(suara_sah.replace('X','0'))
nb_invalid = int(suara_tidak_sah.replace('X','0'))
nb_total = int(total_suara.replace('X','0'))
except:
raise Exception("Unable to read form: %s" % img_file)
if nb_valid == votes01 + votes02:
validity['votes01'] = validity['votes02'] = validity['valid_ballots'] = True
if nb_total == nb_invalid + nb_valid:
validity['valid_ballots'] = validity['invalid_ballots'] = validity['total_ballots'] = True
if nb_total == votes01 + votes02 - nb_invalid:
validity['votes01'] = validity['votes02'] = validity['invalid_ballots'] = validity['total_ballots'] = True
valid_conf = {x:validity[x] or confidence[x] for x in validity}
if not valid_conf['votes01'] and valid_conf['votes02'] and valid_conf['valid_ballots']:
votes01 = nb_valid-votes02
valid_conf['votes01'] = True
if not valid_conf['votes02'] and valid_conf['votes01'] and valid_conf['valid_ballots']:
votes02 = nb_valid - votes01
valid_conf['votes02'] = True
# one value still invalid or low confidence
if sum(valid_conf.values())==4:
if not valid_conf['valid_ballots']:
nb_valid = votes01 + votes02
valid_conf['valid_ballots'] = True
if not valid_conf['invalid_ballots']:
nb_invalid = nb_total - nb_valid
valid_conf['invalid_ballots'] = True
if not valid_conf['total_ballots']:
nb_total = nb_valid + nb_invalid
valid_conf['total_ballots'] = True
# ### Draw CNN 28x28 digits
digit_box = [(digits_01,boxes01),(digits_02,boxes02),(digits_valid,boxes_valid),(digits_invalid,boxes_invalid),(digits_total,boxes_total)]
for digits, boxes in digit_box:
width = boxes[2][0]+boxes[2][2] - boxes[0][0]
for j, box in enumerate(boxes):
s_img = digits[j]
x_offset=box[0] - width
y_offset=box[1]-45
clone_grayed[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
# convert back to RGB
clone = cv2.cvtColor(clone_grayed,cv2.COLOR_GRAY2RGB)
# ### Draw boxes
for box in (boxes01+boxes02+boxes_valid+boxes_invalid+boxes_total):
_ = cv2.rectangle(clone, (box[0], box[1]), (box[0] + box[2], box[1] + box[3]), (0,255,0), 2)
# ## Draw numbers
count_box = [(votes01,boxes01),(votes02,boxes02),(nb_valid,boxes_valid),(nb_invalid,boxes_invalid),(nb_total,boxes_total)]
for count, boxes in count_box:
count_str = str(count).zfill(3)
for j, box in enumerate(boxes):
char = count_str[j]
_ = cv2.rectangle(clone, (box[0],box[1]-45), (box[0]+30,box[1]-5), (0, 0, 255), -1)
_ = cv2.putText(clone,char,(box[0],box[1]-10), cv2.FONT_HERSHEY_PLAIN,3,(255,255,255),2)
# ## Save image
mpimg.imsave(img_file_out,clone)
return {"01": votes01,
"02":votes02,
"valid":nb_valid,
"invalid":nb_invalid,
"total":nb_total}
import glob, os
if __name__ == "__main__":
# ### Load Classifiers
model_dki17 = load_model('classifiers/digits_recognizer.h5')
model_mnist = load_model('classifiers/mnist_classifier.h5')
model_hyphen = load_model('classifiers/hyphen_classifier.h5')
modelX = load_model('classifiers/X_classifier.h5')
files = glob.glob('test_images/test*.jpg')
for file in files:
if '_out' in file: continue
nameonly = os.path.splitext(file)[0]
try:
results = scan_form("%s.jpg" % nameonly, "%s_out.jpg" % nameonly)
print(file, results)
except Exception as e:
print("Form %s is unreadable: %s" % (file, e))
| true
|
48bd6197674262811f0e2c7a3f639aa72293b41e
|
Python
|
6564200/Channel4-TV-Prog
|
/doctoxml.py
|
UTF-8
| 3,307
| 3.015625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import os
import sys
import re
from datetime import datetime
import xml.etree.cElementTree as ET
month = (('января', '1'), ('февраля', '2'), ('марта', '3'), ('апреля', '4'), ('мая', '5'), ('июня', '6'), ('июля', '7'), ('августа', '8'), ('сентября', '9'), ('октября', '10'), ('ноября', '11'), ('декабря', '12'))
def main():
if len(sys.argv) < 2:
print("NO Argument! DOC file!")
sys.exit()
print("Process DOC to XML ", sys.argv[1])
doc_file = sys.argv[1]
result = os.system('antiword -m cp1251.txt ' + doc_file + ' > ' + doc_file[:-3] + 'txt')
text = open(doc_file[:-3] + 'txt').readlines()
print("---------------------------------------------------------")
tcls = []
text = [line.rstrip() for line in text]
for t in text:
if (len(t.strip().strip(".").strip()) > 1): ## ----------- убираем пустое и лишнее
tcls.append(t.strip().strip(".").strip())
textcls = []
timeRe = re.compile('\d\d\\.\d\d') #
dayRe = re.compile('\d\s\w+,\s\d+\s\w+') # 1 Понедельник, 27 января
ageRe = re.compile('\(\d*\+\)') # (16+) (6+)
## -------------- убираем переносы
i = 0
for t in tcls:
time = timeRe.findall(t)
age = ageRe.findall(t)
if (len(time) > 0 and len(age) == 0):
tcls[i] = tcls[i] + tcls[i+1]
tcls.pop(i+1)
elif (len(time) == 0 and len(age) == 0):
day = re.findall('воскресенье,|суббота,|пятница,|понедельник,|вторник,|среда,|четверг,', str(t).lower())
if (len(day) == 0):
tcls[i] = ''
i += 1
tcls = [t for t in tcls if t]
tree = ET.Element("TVPrograms")
## -------------------------------- prsing
for t in tcls:
day = re.findall('воскресенье,|суббота,|пятница,|понедельник,|вторник,|среда,|четверг,', str(t).lower())
if (len(day) > 0): ### ---------------------- разбираем дату
tma = t[t.find(",")+1:].strip()
for old, new in month:
tma = tma.replace(old, new)
tma = tma + " " + datetime.now().strftime("%Y")
date = datetime.strptime(tma, "%d %m %Y" ).strftime("%d-%m-%Y")
print(date)
TVDay = ET.SubElement(tree, "TVDay")
ET.SubElement(TVDay, "Date").text = datetime.strptime(tma, "%d %m %Y" ).strftime("%d-%m-%Y")
TVList = ET.SubElement(TVDay, "TVList")
else: ### --------------- разбираем строки
time = timeRe.findall(t)
age = ageRe.findall(t)
prg = str(t)[str(t).find("«"):str(t).rfind("(")]
#print(t)
print(time, age, prg)
TVProgram = ET.SubElement(TVList, "TVProgram")
ET.SubElement(TVProgram, "Time").text = str(time)
ET.SubElement(TVProgram, "ProgramName").text = str(prg)
ET.SubElement(TVProgram, "ProgramAge").text = str(age)
root = ET.ElementTree(tree)
root.write("doc" + (datetime.now()).strftime('%m_%d_%Y') + ".xml", encoding="utf-8")
if __name__ == "__main__":
main()
| true
|
7425bb4c2c7077b8037d080c073c559834c4e1be
|
Python
|
johntomyang/stockopr
|
/selector/plugin/dynamical_system.py
|
UTF-8
| 1,629
| 2.6875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import pandas as pd
from util.macd import macd
from util.macd import ema
def function(ema_, macd_):
if ema_ and macd_:
return 1
if not ema_ and not macd_:
return -1
return 0
def dynamical_system(quote, n=13):
ema13 = ema(quote['close'], n)['ema']
# ema26 = ema(quote['close'], 26)
# print(ema13.iloc[-1])
# print(ema13.values[-1])
histogram = pd.Series(macd(quote['close'])[2])
ema13_shift = ema13.shift(periods=1)
dlxt_ema = ema13 > ema13_shift
quote_copy = quote.copy()
quote_copy.loc[:, 'dlxt_ema13'] = dlxt_ema.values
quote_copy.loc[:, 'macd'] = histogram
histogram_shift = histogram.shift(periods=1)
dlxt_macd = histogram > histogram_shift
quote_copy.loc[:, 'dlxt_macd'] = dlxt_macd.values
# df.city.apply(lambda x: 1 if 'ing' in x else 0)
# quote_copy_copy = quote_copy.copy()
quote_copy.loc[:, 'dlxt'] = quote_copy.apply(lambda x: function(x.dlxt_ema13, x.dlxt_macd), axis=1)
return quote_copy
# ema_ = ema13.iloc[-1] > ema13.iloc[-2]
# macd_ = histogram[-1] > histogram[-2]
# if ema_ and macd_:
# return 1
#
# if not ema_ and not macd_:
# return -1
#
# return 0
def dynamical_system_green(quote):
quote = dynamical_system(quote)
return True if quote['dlxt'][-1] == 1 else False
def dynamical_system_red(quote):
quote = dynamical_system(quote)
return True if quote['dlxt'][-1] == -1 else False
def dynamical_system_blue(quote):
quote = dynamical_system(quote)
return True if quote['dlxt'][-1] == 0 else False
| true
|
081995cb84d92813f5117283b373d3446242d212
|
Python
|
ylee22/labeler_project
|
/media/post_file_upload.py
|
UTF-8
| 338
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import requests
import os
def upload_file(filename):
url = 'http://localhost:8000/images/'
local_path = os.getcwd()
with open(filename, 'rb') as file:
file_data = {'file': (filename, file), 'file_name': filename}
resp = requests.post(url, files = file_data)
print(resp)
upload_file('HUNT0133.jpg')
| true
|
fbf698d362102c1e1c27c3128f7080c27c068b95
|
Python
|
jfriedly/foreign-currency
|
/create_country.py
|
UTF-8
| 3,634
| 3.171875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
import argparse
import os
import sys
import constants
import models
def parse_args():
description = ("Add a new country to the collection, creating all the "
"metadata.")
argparser = argparse.ArgumentParser(description=description)
argparser.add_argument("short_name",
type=str,
nargs='?',
default='',
help="Short name of country")
args = argparser.parse_args()
return args
def parse_bool(instring):
instring = instring.lower()
if 'y' in instring and 'n' not in instring:
return True
if 'n' in instring and not 'y' in instring:
return False
print "Could not parse %s into a boolean" % instring
prompt = "Try again, or press Ctrl-C to exit [y|n]: "
return parse_bool(raw_input(prompt))
def create_subdivision(big_unit, small_unit, value):
""" Create a subdivision dict for totalling
For more info on subdivision dicts, see the module docs for ``total``,
but the tl;dr is there are <value> <small_units> in a <big_unit>.
Ex: There are <100> <cents> in a <dollar>.
"""
division = {
big_unit: {
"subunit": small_unit,
"value": value
}
}
return division
def read_denomination():
name = raw_input("Denomination names (most recent first): ")
if not name:
return None
code = raw_input(" ISO-4217 code: ").upper()
obsolete = parse_bool(raw_input(" Obsolete? [y|n] "))
subunits = []
while True:
subunit = raw_input(" Subunits (largest first): ")
if not subunit:
break
subunits.append(subunit)
smallest_unit = subunits[-1]
divisions = create_subdivision(smallest_unit, smallest_unit, 1)
subunits.reverse()
for i, unit in enumerate(subunits[:-1]):
bigger_unit = subunits[i+1]
value = int(raw_input(" How many %s in %s? " %
(unit, bigger_unit)))
divisions.update(create_subdivision(bigger_unit, unit, value))
subunits.reverse()
return dict(name=name,
code=code,
subunits=subunits,
divisions=divisions,
obsolete=obsolete)
def read_input(short_name):
long_name = short_name.replace('-', ' ').title()
long_name_prompt = "Country name (long) [%s]: " % long_name
long_name = raw_input(long_name_prompt) or long_name
denominations = []
while True:
denomination = read_denomination()
if not denomination:
break
denominations.append(denomination)
if denominations[0]['obsolete']:
confirm_prompt = ("Newest denomination is obsolete. Is this "
"correct? [y|n] ")
confirm = parse_bool(raw_input(confirm_prompt))
if not confirm:
denominations[0]['obsolete'] = False
country = models.Country.from_dict(dict(short_name=short_name,
long_name=long_name,
denominations=denominations,
inventory=[]))
country.save()
def main():
args = parse_args()
short_name = args.short_name or raw_input("Country name (short): ")
path = os.path.join(constants.COUNTRY_DIR, short_name + ".json")
if os.path.exists(path):
print "Country %s already exists!" % short_name
sys.exit(1)
read_input(short_name)
if __name__ == "__main__":
main()
| true
|
4768a3d3ce5ce6c08d7de73e4593fa311aef9c9f
|
Python
|
EmilyStohl/ProjectEuler
|
/21-40/P27.py
|
UTF-8
| 574
| 3.171875
| 3
|
[] |
no_license
|
# Project Euler - Problem 27
# 1/10/17
import math
def TestPrime(n):
Top = math.ceil(math.sqrt(n))
for i in range(2,int(Top)+1):
if n%i == 0:
return False
return True
MaxN = 0
MaxA = -2000
MaxB = -2000
for a in range(-999, 1000):
for b in range(-1000, 1001):
Stop = False
n = 0
while Stop == False:
TestNum = n**2+(a*n)+(b)
if TestNum < 2:
Stop = True
else:
if TestPrime(TestNum) == True:
if n > MaxN:
MaxN = n
MaxA = a
MaxB = b
else:
Stop = True
n = n+1
print MaxA*MaxB
print MaxN
print MaxA, MaxB
| true
|
201aab77ddc33788e59c7c02938d5aadb555fbc4
|
Python
|
clemigg/INF8808_Projet
|
/Source/helper.py
|
UTF-8
| 2,284
| 2.84375
| 3
|
[] |
no_license
|
'''
This file contains some helper functions to help display the map.
'''
import plotly.graph_objects as go
def adjust_map_style(fig):
'''
Sets the mapbox style of the map.
Args:
fig: The current figure
Returns:
fig: The updated figure
'''
fig.update_layout(mapbox_style='white-bg')
return fig
def adjust_map_sizing(fig):
'''
Sets the sizing of the map.
Args:
fig: The current figure
Returns:
fig: The updated figure
'''
fig.update_layout(mapbox_center=go.layout.mapbox.Center(
lat=45.569260,
lon=-73.707014))
fig.update_layout(mapbox_zoom=9.5)
fig.update_layout(height=725, width=1000)
fig.update_layout(margin_l=0)
return fig
def adjust_map_info(fig):
'''
Adjusts the various info displayed on the map.
Args:
fig: The current figure
Returns:
fig: The updated figure
'''
fig.update_layout(legend_x=0.055,
legend_y=0.95)
fig.update_layout(title_xref='paper', title_y=0.5)
title = 'Explorez les rues pietonnes de Montréal'
info = 'Cliquez sur un marqueur pour plus d\'information.'
fig.update_layout(title=title,
title_font_family='Oswald',
title_font_color='black',
title_font_size=28)
fig.update_layout(annotations=[dict(xref='paper',
yref='paper',
x=0.055, y=1.08,
showarrow=False,
text=info,
font_family='Open Sans Condensed',
font_color='black',
font_size=18)])
fig.update_layout(legend_title_text='Légende',
legend_title_font_family='Open Sans Condensed',
legend_title_font_color='black',
legend_title_font_size=16,
legend_font_family='Open Sans Condensed',
legend_font_color='black',
legend_font_size=16)
return fig
| true
|
a6818c5b873f3fa9173b9ec52d50bf028ef3d225
|
Python
|
azakimi123/Python
|
/flower.py
|
UTF-8
| 195
| 3.703125
| 4
|
[] |
no_license
|
import turtle
import math
bob = turtle.Turtle()
bob.color("red", "yellow")
bob.speed(10)
bob.begin_fill()
for i in range(50):
bob.forward(200)
bob.left(168.5)
bob.end_fill()
turtle.done()
| true
|
3acd8780955897049b51d620742901cff47b0785
|
Python
|
dennisnderitu254/CodeCademy-Py
|
/chapter_08_Taking_a_Vacation/16_Paying_Up.py
|
UTF-8
| 333
| 3.546875
| 4
|
[] |
no_license
|
def hotel_cost(nights):
return nights * 140
bill = hotel_cost(5)
def add_monthly_interest(balance):
return balance * (1 + (0.15 / 12))
def make_payment(payment, balance):
balance = add_monthly_interest(balance - payment)
print "You still owe:", balance
return balance
print make_payment(bill / 2 + 100, bill)
| true
|
7cd3f94c63144251bb32bcde0422a2b7534492db
|
Python
|
kojh0111/Data-Structure-and-Algorithms
|
/10_Binary_Search/1300.py
|
UTF-8
| 455
| 3.5625
| 4
|
[] |
no_license
|
"""
- K번째 수
이분탐색 문제/ 각 열별로 mid보다 작은 수 갯수를 파악하여 k보다 많아지면 답 출력
"""
import sys
input = sys.stdin.readline
N = int(input())
k = int(input())
left = 1
right = k
while left <= right:
mid = (left + right) // 2
cnt = 0
for i in range(1, N + 1):
cnt += min(mid // i, N)
if cnt < k:
left = mid + 1
else:
ans = mid
right = mid - 1
print(ans)
| true
|
a567d445fd5560ec97bef9dffed71d95bedb404d
|
Python
|
ElChurco/Introprogramacion
|
/Grafica/Clase_2.py
|
UTF-8
| 500
| 3.640625
| 4
|
[] |
no_license
|
Ax = int(input("Ingrese un numero para Ax: "))
Ay = int(input("Ingrese un numero para Ay: "))
Bx = int(input("Ingrese un numero para Bx: "))
By = int(input("Ingrese un numero para By: "))
Cx = int(input("Ingrese un numero para Cx: "))
Cy = int(input("Ingrese un numero para Cy: "))
base = Cx - Ax
altura = By - Ay
import math
hipo = math.sqrt((altura*altura)+(base*base))
perimetro = base + altura + hipo
area = base * altura / 2
print (f"El perimetro es {perimetro}")
print (f"El area es {area}")
| true
|
dcaf28137a2d41d14feab9257c00934766b683ae
|
Python
|
5l1v3r1/mr_london
|
/app/model/textgen.py
|
UTF-8
| 5,514
| 2.953125
| 3
|
[] |
no_license
|
import pickle
import numpy as np
class LiteTextGen:
def __init__(self, fn=None):
self.maxlen = 20
self.generated = ''
self.primer = "I want to have a big"
self.LSTM = LiteLSTM()
if fn is None:
fn = "app/model/lstm_weights.pkl"
self.load_model(fn)
def load_model(self, fn):
[weights, meta] = pickle.load(open(fn, 'rb'), encoding='latin1')
self.LSTM.load_weights(weights)
self.char_indices = meta['char_indices']
self.indices_char = meta['indices_char']
def clean_slate():
self.generated = ''
self.primer = "This primer has 20 c"
def predict(self, primer = None, length = 1, stream=True, diversity = 0.2):
if primer is None or stream:
pass
elif type(primer) is not str:
raise ValueError("Primer must be a string")
else:
self.primer = ' ' * (self.maxlen - len(primer)) + primer
self.primer = self.primer[-20:]
assert 1 <= length <= 1000, "Length of string to generate must be between 1 and 1000"
self.primer = self.primer.lower()
for i in range(length):
X = self.vectorize_primer()
next_index = self.LSTM.predict_i(X, diversity)
next_char = self.indices_char[next_index]
self.generated += next_char
self.primer = self.primer[1:] + next_char
if stream:
return next_char
self.generated = self.generated
txt = self.generated.split('\n')
return txt
def vectorize_primer(self):
X = np.zeros((1, self.maxlen, len(self.char_indices)))
for t, char in enumerate(self.primer):
X[0, t, self.char_indices[char] ] = 1.
return X
class LiteLSTM:
def __init__(self):
self.layers = []
def load_weights(self, weights):
assert not self.layers, "Weights can only be loaded once!"
for k in range(len(weights.keys())):
self.layers.append(weights['layer_{}'.format(k)])
def predict_i(self, X, diversity):
assert not not self.layers, "Weights must be loaded before making a prediction!"
h = self.lstm_layer(X, layer_i=0, seq=True) ; X = h
h = self.dropout(X, .2) ; X = h
h = self.lstm_layer(X, layer_i = 2, seq=False) ; X = h
h = self.dropout(X, .2) ; X = h
h = self.dense(X, layer_i = 4) ; X = h
h = self.softmax_2D(X) ; X = h[0] #convert it from a [n,1] tensor to a [n] vector
i = self.sample(X, diversity)
return i
def predict_classes(self, X):
assert not not self.layers, "Weights must be loaded before making a prediction!"
h = self.lstm_layer(X, layer_i=0, seq=False) ; X = h
h = self.repeat_vector(X, 4) ; X = h
h = self.lstm_layer(X, layer_i=2, seq=True) ; X = h
h = self.timedist_dense(X, layer_i=3) ; X = h
h = self.softmax_2D(X) ; X = h
preds = self.classify(X) ; X = h
return preds
def lstm_layer(self, X, layer_i=0, seq=False):
X = np.flipud(np.rot90(X))
#load weights
w = self.layers[layer_i]
W_i = w["W_i"] ; U_i = w["U_i"] ; b_i = w["b_i"] #[n,m] ; [m,m] ; [m]
W_f = w["W_f"] ; U_f = w["U_f"] ; b_f = w["b_f"]
W_c = w["W_c"] ; U_c = w["U_c"] ; b_c = w["b_c"]
W_o = w["W_o"] ; U_o = w["U_o"] ; b_o = w["b_o"]
#create each of the x input vectors for the LSTM
xi = np.dot(X, W_i) + b_i
xf = np.dot(X, W_f) + b_f
xc = np.dot(X, W_c) + b_c
xo = np.dot(X, W_o) + b_o
hprev = np.zeros((1, len(b_i))) #[1,m]
Cprev = np.zeros((1, len(b_i))) #[1,m]
[output, memory] = self.nsteps(xi, xf, xo, xc, hprev, Cprev, U_i, U_f, U_o, U_c)
if seq:
return np.flipud(np.rot90(output))
output = np.reshape(output[-1,:,:],(1,output.shape[1], output.shape[2]))
return np.flipud(np.rot90(output))
def nsteps(self, xi, xf, xo, xc, hprev, Cprev, U_i, U_f, U_o, U_c):
nsteps = xi.shape[0] # should be n long
output = np.zeros_like(xi) # [n,1,m]
memory = np.zeros_like(xi) # [n,1,m]
for t in range(nsteps):
xi_t = xi[t,:,:] ; xf_t = xf[t,:,:] ; xc_t = xc[t,:,:] ; xo_t = xo[t,:,:] # [1,m] for all
i_t = self.hard_sigmoid(xi_t + np.dot(hprev, U_i)) #[1,m] + [m]*[m,m] -> [1,m]
f_t = self.hard_sigmoid(xf_t + np.dot(hprev, U_f)) #[1,m] + [m]*[m,m] -> [1,m]
o_t = self.hard_sigmoid(xo_t + np.dot(hprev, U_o)) #[1,m] + [m]*[m,m] -> [1,m]
c_t = f_t*Cprev + i_t * np.tanh(xc_t + np.dot(hprev, U_c)) #[1,m]*[m] + [1,m] * [1,m] -> [1,m]
h_t = o_t * np.tanh(c_t) #[1,m]*[1,m] (elementwise)
output[t,:,:] = h_t ; memory[t,:,:] = c_t
hprev = h_t # [1,m]
Cprev = c_t # [1,m]
return [output, memory]
def dense(self, X, layer_i=0):
w = self.layers[layer_i]
W = w["W_i"]
b = w["U_i"]
output = np.dot(X, W) + b
return output
def timedist_dense(self, X, layer_i=0):
w = self.layers[layer_i]
W = w["W_i"]
b = w["U_i"]
output = np.tanh(np.dot(np.flipud(np.rot90(X)), W) + b)
return np.flipud(np.rot90(output))
@staticmethod
def sigmoid(x):
return 1.0/(1.0+np.exp(-x))
@staticmethod
def hard_sigmoid(x):
slope = 0.2
shift = 0.5
x = (x * slope) + shift
x = np.clip(x, 0, 1)
return x
@staticmethod
def repeat_vector(X, n):
y = np.ones((X.shape[0], n, X.shape[2])) * X
return y
@staticmethod
def softmax_2D(X):
w = X[0,:,:]
w = np.array(w)
maxes = np.amax(w, axis=1)
maxes = maxes.reshape(maxes.shape[0], 1)
e = np.exp(w - maxes)
dist = e / np.sum(e, axis=1, keepdims=True)
return dist
@staticmethod
def classify(X):
return X.argmax(axis=-1)
@staticmethod
def sample(X, temperature=1.0):
# helper function to sample an index from a probability array
X = np.log(X) / temperature
X = np.exp(X) / np.sum(np.exp(X))
return np.argmax(np.random.multinomial(1, X, 1))
@staticmethod
def dropout(X, p):
retain_prob = 1. - p
X *= retain_prob
return X
| true
|
36d59ac3249af68b210cf0a0cea088b7a6ca6dff
|
Python
|
optimusMY/PYTHON
|
/TkinterExamples/loginpage.py
|
UTF-8
| 2,033
| 3.109375
| 3
|
[] |
no_license
|
from tkinter import * # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3
from tkinter import messagebox
import tkinter
# creating a window
wnd = Tk()
wnd.geometry("300x100")
label_1 = Label(wnd, text="Name")
label_2 = Label(wnd, text="Password")
entry_1 = Entry(wnd)
entry_2 = Entry(wnd)
label_1.grid(row=0, sticky=E)
label_2.grid(row=1, sticky=E)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
'''CLASSIC WAY TO ADD AN ACTION TO BUTTON AND CHECKBUTTON USING COMMAND PARAM
def ChkBtn_CallBack():
msg = messagebox.showinfo("Welcome", "You will be kept logged in!")
checkButton1 = Checkbutton(wnd, text="Keep me logged in", command=ChkBtn_CallBack)
checkButton1.grid(columnspan=2)
def But_RegisterCallBack():
msg = messagebox.showinfo("Welcome", "Registry Successful")
But_register = Button(wnd, text="Register", command=But_RegisterCallBack)
But_register.grid(columnspan=3)
'''
'''NOW WE CAN USE EVENT BINDING WAY TO ADD AN ACTION TO BUTTON AND THE OTHER WIDGETS
EVENT IS USEFUL WHEN YOU BIND A WIDGET TO IT
'''
def ChkBtn_CallBack(event):
msg = messagebox.showinfo("Welcome", "You will be kept logged in!")
checkButton1 = Checkbutton(wnd, text="Keep me logged in")
checkButton1.bind("<Button-2>", ChkBtn_CallBack) # designated to wheelbuttonclick event
checkButton1.grid(row=2, columnspan=2)
def But_LoginCallBack():
msg = messagebox.showinfo("Welcome", "Login Successful")
But_login = Button(wnd, text=" Login ", command=But_LoginCallBack)
But_login.grid(row=3, column=0)
def But_RegisterCallBack(event):
msg = messagebox.showinfo("Welcome", "Registry Successful")
But_register = Button(wnd, text="Register")
But_register.bind("<Button-1>", But_RegisterCallBack) # designated to leftclick event
But_register.grid(row=3, column=1)
But_passMiss = Button(wnd, text="Pass Miss", command=wnd.quit)
But_passMiss.grid(row=3, column=2)
wnd.mainloop()
| true
|
7f91122ca1353c7938198324b9b633232268541c
|
Python
|
LauraBritoMedina/EyeTracking_DimRed_SmartFlat
|
/Random_Forest.py
|
UTF-8
| 5,173
| 3.109375
| 3
|
[] |
no_license
|
"""
===================================================
Random Forest
===================================================
Applies random forest to the data in path:
Inputs:
path: Folder containing features
a : Index of the data to preprocess. It can be:
0 = Initial Calibration
1 = Final Calibration
2 = Initial Fixation
3 = Final Fixation
4 = Mixing
5 = Reading
tp : Percentage of the testing set over the data
c : Penalty of the SVM
N : Number of most important features to process
Outputs:
svmt : Training time of the SVM
atr : Training accuracy
ate : Testing accuracy
"""
#print (__doc__)
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import input_data_txt
from time import time
def exec_(a, tp, c, N, path, clf):
# Obtain the data from the tables
_data_, _labels_, features_ = input_data_txt.tune(path)
X=_data_[a]
y = _labels_[a]
features = features_[a]
# Number of samples
n_samples = len(X)
# Number of features
n_features = len(features)
# the label to predict is 0 or 1 by now
#n_classes = len(y.unique())
#print ("Total dataset size:")
#print ("n_samples: %d" % n_samples)
#print ("n_features: %d" % n_features)
#print ("n_classes: %d" % n_classes)
###############################################################################
# Split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=tp)
###############################################################################
########################################
# Standarizing the features #
########################################
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = pd.DataFrame(sc.fit_transform(X_train), columns=features)
X_test = pd.DataFrame(sc.transform(X_test), columns=features)
########################################
# Applying Random Forest #
########################################
feat_labels = features
forest = RandomForestClassifier(n_estimators=10000,
random_state=10,
n_jobs=-1)
forest.fit(X_train,y_train)
importances = forest.feature_importances_
indices = np.argsort(importances)[::-1]
#for f in range(X_train.shape[1]):
# print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f],importances[indices[f]]*100))
plt.title('Feature Relative Importance')
plt.bar(range(X_train.shape[1]),
importances[indices],
color='grey',
align='center')
plt.xticks(range(X_train.shape[1]),
feat_labels, rotation=90)
plt.xlim([-1, X_train.shape[1]])
plt.tight_layout()
plt.show()
########################################
# Classification #
########################################
if clf == 'svm':
###############################################
# Training SVM with N most important features #
###############################################
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
idx=indices[:N] #Index
svm = SVC(kernel='rbf', C=c)
t0 = time()
svm.fit(X_train.iloc[:, idx], y_train)
svmt=time() - t0
#print ("SVM Training done in %0.9fs" % svmt)
y_pred=svm.predict(X_train.iloc[:,idx])
#print('Training set:')
atr=accuracy_score(y_train, y_pred)
#print('Accuracy of', N, 'features: %.2f' % atr)
y_pred=svm.predict(X_test.iloc[:,idx])
#print('Testing set:')
ate=accuracy_score(y_test, y_pred)
#print('Accuracy of', N, 'features: %.2f' % ate)
return svmt, atr, ate
elif clf == 'lda':
###############################################
# Training SVM with N most important features #
###############################################
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import accuracy_score
idx=indices[:N] #Index
lda = LinearDiscriminantAnalysis(n_components=2)
t0 = time()
lda.fit_transform(X_train.iloc[:, idx], y_train)
svmt=time() - t0
#print ("SVM Training done in %0.9fs" % svmt)
y_pred=lda.predict(X_train.iloc[:,idx])
#print('Training set:')
atr=accuracy_score(y_train, y_pred)
#print('Accuracy of', N, 'features: %.2f' % atr)
y_pred=lda.predict(X_test.iloc[:,idx])
#print('Testing set:')
ate=accuracy_score(y_test, y_pred)
#print('Accuracy of', N, 'features: %.2f' % ate)
return svmt, atr, ate
| true
|
3cfb6073d8bf213c167ba27752288f8b5ba10c4d
|
Python
|
hemanthgr19/practise
|
/sumof arr.py
|
UTF-8
| 116
| 3.078125
| 3
|
[] |
no_license
|
def _sum(arr,n):
return (sum(arr))
arr = []
arr = [12,3,56,23,78,42]
n = len(arr)
ans = _sum(arr,n)
print(ans)
| true
|
e17be6e38065793ee1c5769ddffcfa3961a57a5c
|
Python
|
lacriment/Jordamach
|
/jordamach/app.py
|
UTF-8
| 4,363
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QTableWidgetItem
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)
from ui.design import Ui_MainWindow
from linear_regression import Regrezio
class App(QMainWindow):
def __init__(self):
super(App, self).__init__()
# Set up the user interface from Designer.
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.model_type = 'lin-lin'
self.r = Regrezio(model=self.model_type)
self.modelled = False
self.msg = QMessageBox()
self.ui.tableWidget.setColumnCount(6)
self.ui.tableWidget.setHorizontalHeaderLabels(['Y', 'X1', 'X2', 'X3', 'X4', 'X5'])
self.ui.tableWidget.setRowCount(50)
# Connect up the buttons.
self.ui.btn_fitModel.clicked.connect(self.fit_model)
self.ui.btn_plot.clicked.connect(self.plot_model)
self.ui.btn_clear.clicked.connect(self.clear_table)
self.ui.btn_predict.clicked.connect(self.predict_value)
self.ui.btn_exit.clicked.connect(QtCore.QCoreApplication.instance().quit)
self.ui.cb_funcType.currentIndexChanged.connect(self.set_model_type)
def set_model_type(self):
self.model_type = self.ui.cb_funcType.currentText().lower()
print(model_type)
self.r = Regrezio(model=self.model_type)
def keyPressEvent(self, event):
row = self.ui.tableWidget.currentRow()
col = self.ui.tableWidget.currentColumn()
if event.key() == QtCore.Qt.Key_Backspace or event.key() == QtCore.Qt.Key_Delete:
self.ui.tableWidget.setItem(row, col, QTableWidgetItem(""))
def fit_model(self):
row_count = 50
y = []
x = []
for row in range(0, row_count):
a = self.ui.tableWidget.item(row, 0)
if a is not None:
try:
if a.text() != "":
y.append(float(a.text()))
except ValueError:
self.ui.statusBar.showMessage("Please enter numerical data into the table!")
b = self.ui.tableWidget.item(row, 1)
if b is not None:
try:
if b.text() != "":
x.append(float(b.text()))
except ValueError:
self.ui.statusBar.showMessage("Please enter numerical data into the table!")
y = np.array([[i] for i in y])
x = np.array([[i] for i in x])
if len(x) > 1 and len(y) > 1 and len(y) == len(x):
self.r.fit(x, y)
self.r.predict(self.r.x)
self.ui.lbl_model.\
setText("ŷ = %s + %s * X1" %
(round(float(self.r.intercept), 4), round(float(self.r.coefficients[0]), 4)))
self.ui.lbl_rsqr.setText(str(round(self.r.score, 4)))
self.modelled = True
self.ui.statusBar.showMessage('Successfully accomplished.')
else:
self.modelled = False
self.ui.statusBar.showMessage("Every column should have same number of data!")
def plot_model(self):
if self.modelled:
y = np.array([i[0] for i in self.r.y])
x = np.array([i[0] for i in self.r.x])
ax = sns.regplot(x=x, y=y, color="g")
plt.show()
else:
self.ui.statusBar.showMessage("Model must have been fit to make a plot.")
def predict_value(self):
if self.modelled:
val = float(self.ui.txt_predict.text())
predicted_val = self.r.y_func(val)
self.ui.lbl_predict.setText(str(round(float(predicted_val), 4)))
else:
self.ui.statusBar.showMessage("Model must have been fit to make a prediction.")
def clear_table(self):
self.ui.tableWidget.clear()
self.ui.tableWidget.setColumnCount(6)
self.ui.tableWidget.setHorizontalHeaderLabels(['Y', 'X1', 'X2', 'X3', 'X4', 'X5'])
self.ui.tableWidget.setRowCount(50)
self.ui.lbl_model.setText("ŷ = ")
self.ui.lbl_predict.clear()
self.ui.lbl_rsqr.clear()
def main():
app = QApplication(sys.argv)
form = App()
form.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
| true
|
05c8ec32ce255a6ef1b0de6585100eb8eb2e7657
|
Python
|
Keimoshi/Learing
|
/9.类/9-3.py
|
UTF-8
| 1,117
| 3.828125
| 4
|
[] |
no_license
|
class User():
def __init__(self, first_name, last_name, age, skill):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.skill = skill
self.login_attempts = 0
def describe_user(self):
print(
"--------" + self.first_name + self.last_name + "--------" +
"\n姓:" + self.first_name +
"\n名:" + self.last_name +
"\n年龄 " + self.age +
"\n天赋: " + self.skill
)
def read_login_attempts(self):
print(self.login_attempts)
def increment_login_attempts(self):
self.login_attempts += 1
def set_login_attempts(self):
self.login_attempts = 0
def greet_user(self):
full_name = self.first_name + self.last_name
print("欢迎回到欲望都市," + full_name + "!")
login_user = User("王", "大力", "33", "能长能短")
#login_user.describe_user()
for i in range(10):
login_user.increment_login_attempts()
login_user.read_login_attempts()
login_user.set_login_attempts()
login_user.read_login_attempts()
| true
|
d8bbceb3ba28bfddeaf18e6bc7c885431c387cde
|
Python
|
EoJin-Kim/CodingTest
|
/BFS/02CompetitiveInfection.py
|
UTF-8
| 792
| 2.96875
| 3
|
[] |
no_license
|
from collections import deque
n,k = map(int,input().split())
graph=[]
data=[]
for i in range(n):
graph.append(list(map(int,input().split())))
for j in range(n):
if graph[i][j] != 0:
data.append((graph[i][j],0, i, j))
s,x,y = map(int,input().split())
'''
n,k=3,3
graph=[[1,0,2],[0,0,0],[3,0,0]]
s,x,y=2,3,2
'''
data.sort()
q=deque(data)
dx=[-1,0,1,0]
dy=[0,1,0,-1]
def bfs(seconds):
while q:
type,time,x,y =q.popleft()
if seconds<=time:
break;
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx>=0 and nx<n and ny>=0 and ny<n:
if graph[nx][ny]==0:
graph[nx][ny]=type
q.append((type,time+1,nx,ny))
bfs(s)
print(graph[x-1][y-1])
| true
|
88ad9de71cc641777e1035b602ebf5c2e06dc73e
|
Python
|
ashmorecartier/pyjunk
|
/src/Zbrac.py
|
UTF-8
| 6,057
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
#! /bin/env python3
# -*- coding: utf-8 -*-
################################################################################
#
# This file is part of PYJUNK.
#
# Copyright © 2021 Marc JOURDAIN
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the “Software”),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# You should have received a copy of the MIT License
# along with PYJUNK. If not, see <https://mit-license.org/>.
#
################################################################################
"""
Zbrac.py rassemble la définition des classes:
Zbrac
"""
import sys
import pathlib
#----- constantes pour finir le programme
NORMAL_TERMINATION = 0
ABNORMAL_TERMINATION = 1
#----- Classe permettant de calculer un encadrement de la solution à partir d'un point
class Zbrac:
"""
Classe Zbrac
============
La classe Zbrac permet d'obtenir un encadrement de la solution
d'une fonction à partir d'un seul point fX.
il est souhaitable que la fonction soit gentiment monotone
on applique la technique suivante :
dans un diagramme x-fx selon C ou D
|
*/ | /*
-------
/* | */
|
:Example:
>>> def f(x): return (2.*x-1.)*(2.*x+1.)
>>> Zc = Zbrac(f)
>>> Zc.solve(5., 'C')
0
>>> Zc.getFresult()
(0.625, 0.3125)
>>> Zc.getNiters()
5
.. seealso::
.. warning::
.. note::
.. todo::
"""
__iter = 20
__factor = 2.
__sens1 = {'C':1./__factor, 'D':__factor}
__sens2 = {'C':__factor, 'D':1./__factor}
#-----
def __init__(self, func, *param) -> None:
self.func = func
self.param = param
self.nError = 0
self.nIter = 0
self.fX0 = 0.
self.fX1 = 0.
self.fY0 = 0.
self.fY1 = 0.
#-----
def solve(self, fX: float, sSens: str) -> int:
"""
lance le solveur avec un paramètre
:param fX: borne
:type fX: float
:param sSens: sens 'C' croissant 'D' décroissant
:type sSens: string
:return: 0 ok 1 pas ok
:rtype: int
>>> def f(x): return (2.*x-1.)*(2.*x+1.)
>>> Zc = Zbrac(f)
>>> Zc.solve(5., 'E')
Mauvaise indication du sens
1
>>> Zc.solve(5., 'C')
0
>>> Zc.solve(-5., 'D')
0
"""
if sSens not in ('C', 'D'):
print(f'Mauvaise indication du sens')
self.nError = 1
return self.nError
self.nIter = 1
self.fX0 = fX
self.fY0 = self.func(self.fX0, *self.param)
while self.nIter < Zbrac.__iter:
if self.fX0*self.fY0 > 0.:
self.fX1 = self.fX0*Zbrac.__sens1[sSens]
else:
self.fX1 = self.fX0*Zbrac.__sens2[sSens]
self.fY1 = self.func(self.fX1, *self.param)
self.nIter += 1
if self.fY0*self.fY1 > 0.:
self.fX0 = self.fX1
self.fY0 = self.fY1
else:
self.nError = 0
return self.nError
print(f'Maximum number of iterations exceeded in zbrac')
self.nError = 1
return self.nError
#-----
def getFresult(self) -> (float, float):
"""
retourne le résultat
nécessite d'avoir lancer le solve et d'avoir tester le code erreur
:param: aucun
:return: le résultat
:rtype: liste de 2 float
>>> def f(x): return (2.*x-1.)*(2.*x+1.)
>>> Zc = Zbrac(f)
>>> Zc.solve(5., 'C')
0
>>> Zc.getFresult()
(0.625, 0.3125)
>>> Zc.solve(-5., 'D')
0
>>> Zc.getFresult()
(-0.625, -0.3125)
"""
return (self.fX0, self.fX1)
#-----
def getNiters(self) -> int:
"""
retourne le nombre d'itérations effectuées
nécessite d'avoir lancer le solve et d'avoir tester le code erreur
:param: aucun
:return: le nombre d'itérations
:rtype: int
>>> def f(x): return (2.*x-1.)*(2.*x+1.)
>>> Zc = Zbrac(f)
>>> Zc.solve(5., 'C')
0
>>> Zc.getNiters()
5
>>> Zc.solve(-5., 'D')
0
>>> Zc.getNiters()
5
"""
return self.nIter
#----- start here
if __name__ == '__main__':
import doctest
(failureCount, testCount) = doctest.testmod(verbose=False)
print(f'nombre de tests : {testCount:>3d}, nombre d\'erreurs : {failureCount:>3d}', end='')
if failureCount != 0:
print(f' --> Arrêt du programme {pathlib.Path(__file__)}')
sys.exit(ABNORMAL_TERMINATION)
else:
print(f' --> All Ok {pathlib.Path(__file__)}')
sys.exit(NORMAL_TERMINATION)
| true
|
e5ac3ca3af1b173570d5c68178628409ec19d6e2
|
Python
|
CNLiiserp/CA3bouton
|
/vdcc_dat/genStimVid.py
|
UTF-8
| 1,358
| 2.59375
| 3
|
[] |
no_license
|
from pylab import *
# Note: stimuli are 5 ms wide.
n = 20 # n = number of pules in tetanic pulse
nBurst = 2 # number of bursts
isi = 10e-3 # isi = Inter-Spike Interval in burst
ibi = 5 # inter-burst internal (sec)
infile=[0]*9
outfile=[0]*9
infile[0]="VDCC_PQ_C01.dat"
infile[1]="VDCC_PQ_C10.dat"
infile[2]="VDCC_PQ_C12.dat"
infile[3]="VDCC_PQ_C21.dat"
infile[4]="VDCC_PQ_C23.dat"
infile[5]="VDCC_PQ_C32.dat"
infile[6]="VDCC_PQ_C34.dat"
infile[7]="VDCC_PQ_C43.dat"
infile[8]="VDCC_PQ_Ca.dat"
# Generate outfile
for (i,f) in enumerate(infile):
f = f.split(".")[0]+"_"
#outfile[i] = "ptp/"+f+str(n)+"_"+str(int(1/isi))+"hz_train.dat"
outfile[i] = f+"n_"+str(n)+"_nB_"+str(nBurst)+"_isi_"+str(int(1000*isi))+"ms_ibi_"+str(ibi)+"s_burstTrain.dat"
print outfile[i]
# Generate Stim for PTP
for i in range(len(infile)):
tdelay = 0
ofile = open(outfile[i], 'w')
for nb in range(nBurst): #4, 6, 10, 15, 20, 30]:
tdelay += nb*ibi
# Read The Stim
idata = genfromtxt(infile[i])
# Post-Tetanic Pulse with number of spikes n and interspike interval isi
for j in range(n):
#print tdelay
for k in range(len(idata)):
ofile.write(str(idata[k][0]+tdelay)+"\t"+str(idata[k][1])+"\n")
tdelay += isi if j<n-1 else 0
| true
|
20dbacad7bd4d5d763a4d08e1a244fbf4bee5e1f
|
Python
|
Rafsun83/Python-Basic-practice-Code-With-OOP
|
/pytest.py
|
UTF-8
| 183
| 2.90625
| 3
|
[] |
no_license
|
import pytest
@pytest.mark.one
def test_method1():
x = 10
y = 20
assert x == y
@pytest.mark.two
def test_method2():
a = 20
b = 15
assert a == b+5
| true
|
0d8f22a63a5f28a2ee356b8843efa9d135142511
|
Python
|
wkentaro/effective-python
|
/chapter5/0039_thread_cooperation/sample2.py
|
UTF-8
| 563
| 2.515625
| 3
|
[] |
no_license
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from Queue import deque
from Queue import Queue
import time
from threading import Lock
from threading import Thread
def main():
queue = Queue()
def consumer():
print('Consumer waiting')
queue.get()
print('Consumer done')
thread = Thread(target=consumer)
thread.start()
print('Producer putting')
queue.put(object())
thread.join()
print('Producer done')
if __name__ == '__main__':
main()
| true
|
4ccae33d43c0a8d04e71dc447288afb1ee70f3ef
|
Python
|
ptsiampas/Exercises_Learning_Python3
|
/12_Modules/Exercise_12.11.7.py
|
UTF-8
| 465
| 3.5
| 4
|
[] |
no_license
|
from unit_tester import test
def myreplace(old, new, s):
""" Replace all occurrences of old with new in s. """
if old == " ":
return new.join(s.split())
return new.join(s.split(old))
test(myreplace(",", ";", "this, that, and some other thing"),
"this; that; and some other thing")
test(myreplace(" ", "**","Words will now be separated by stars."),
"Words**will**now**be**separated**by**stars.")
| true
|
464da1f0054ec13f521918dc212374add49631d3
|
Python
|
physcode/capitainterview
|
/joinscript.py
|
UTF-8
| 2,140
| 3.46875
| 3
|
[] |
no_license
|
##Script written in Python3 - Nikolaos Palamidas##
def LEFTJOIN(Lfilename,Rfilename,LEFT_ON,RIGHT_ON,destination,delimiter = ","):
"""Takes arguments of a file name for the left and right tables
(in working directory). Left joins according to the LEFT_ON and RIGHT_ON columns of each specified by zero indexed number.
Delimiter is set to a comma as default"""
dataL = open(Lfilename,"r")
dataR = open(Rfilename,"r")
listL = []
listR = []
joinedlist = []
def csvtoarray(file,array,delim):
"""Takes a file delimited by some delim character (csv by default)
and returns a list of lists(array) of the file"""
line = ''
for line in file:
line = line.strip('\n')
splitstring = line.split(delim)
array.append(splitstring)
csvtoarray(dataL,listL,delimiter)
csvtoarray(dataR,listR,delimiter)
def JOIN(LEFT,RIGHT,L_ON,R_ON,RESULT):
"""Takes a left and right array and left joins them according to
the zero indexed ON keys. Returns a RESULT array"""
for L in LEFT:
countmatch = 0
for R in RIGHT:
if L[L_ON] == R[R_ON]:
countmatch = countmatch + 1
RESULT.append(L+R)
if countmatch == 0:
RESULT.append(L+['NULL','NULL'])
keys = LEFT[0] + RIGHT[0]
RESULT[0] = keys
JOIN(listL,listR,LEFT_ON,RIGHT_ON,joinedlist)
def concatlist(lst):
"""Concatenates all the lists in a string in preparation
for loading into the final csv file"""
result = ''
for element in lst:
result += delimiter + str(element)
result = result[1:]
return result
dest = open(destination,'w')
for row in joinedlist:
dest.write(str(concatlist(row))+'\n')
dest.close()
#END OF LEFTJOIN FUNCTION
#Left join the test files using the PD columns
LEFTJOIN("test_data_01.csv","test_data_02.csv",1,0,"joined.csv")
input("SUCCESS!!! joined.csv can now be found in the working directory...")
| true
|
1e9a383d814c3724d7194c175eaa543959cadfcc
|
Python
|
monini13/NucleiSegmentationAI
|
/gui.py
|
UTF-8
| 3,721
| 2.53125
| 3
|
[] |
no_license
|
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import os
from PIL import Image, ImageTk
from predict import predict, get_actual_mask
from scipy.io import loadmat
import matplotlib.pyplot as plt
import numpy as np
class Window(Frame):
def __init__(self, weights_path, master=None):
Frame.__init__(self, master)
self.master = master
self.pos = []
self.master.title("Nuclei Segmentation")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label="Select Image", command=self.uploadImage)
file.add_command(label="Predict", command=self.show_prediction)
menu.add_cascade(label="File", menu=file)
self.canvas = tk.Canvas(self)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.image = None
self.image2 = None
self.weights_path = weights_path
frm = Frame(self.master)
frm.pack(side=BOTTOM, padx=15, pady=15)
btn1 = Button(frm, text="Select Image", command=self.uploadImage)
btn1.pack(side=tk.LEFT)
btn2 = Button(frm, text="Predict", command = self.show_prediction)
btn2.pack(side=tk.LEFT, padx=30)
def uploadImage(self):
filename = filedialog.askopenfilename(initialdir=os.getcwd())
if not filename:
return
img = Image.open(filename).convert("RGB")
if not img:
return
#feed input into model here, output into ./result.png
self.predicted_mask = predict(self.weights_path,img) # PIL Image
base_name = os.path.basename(filename)
base_name = os.path.splitext(base_name)[0]
labels_list = os.listdir('./Test/Labels')
label = base_name + ".mat"
label = loadmat('./Test/Labels/'+label)
true_mask = get_actual_mask(label)
self.true_mask = Image.fromarray(np.uint8(true_mask*255)).convert('RGB')
img = img.resize((400, 400))
w, h = img.size
width, height = root.winfo_width(), root.winfo_height()
self.render = ImageTk.PhotoImage(img)
if self.image:
self.canvas.delete(self.text)
self.image = self.canvas.create_image((w / 3, h / 3), image=self.render)
self.canvas.move(self.image, 80, 0)
self.text = self.canvas.create_text(170,380, fill="black",font="Times 20 bold",
text="Input: " + base_name)
def show_prediction(self):
if not hasattr(self, 'predicted_mask'):
return
load = self.predicted_mask
load = load.resize((400, 400))
load_true_mask = self.true_mask
load_true_mask = load_true_mask.resize((400, 400))
w, h = load.size
width, height = root.winfo_screenmmwidth(), root.winfo_screenheight()
self.render2 = ImageTk.PhotoImage(load_true_mask)
self.image2 = self.canvas.create_image((w / 3, h / 3), image=self.render2)
self.canvas.move(self.image2, 500, 0)
self.canvas.create_text(620,380, fill="black",font="Times 20 bold",
text="True Mask")
self.render3 = ImageTk.PhotoImage(load)
self.image3 = self.canvas.create_image((w / 3, h / 3), image=self.render3)
self.canvas.move(self.image3, 930, 0)
self.canvas.create_text(1050,380, fill="black",font="Times 20 bold",
text="Predicted Mask")
if __name__ == "__main__":
root = tk.Tk()
root.title("Nuclei Segmentation")
root.geometry('1280x600')
weights_path = "./weights_3channel_dropout_1"
app = Window(weights_path,root)
root.mainloop()
| true
|
2688632cebd70d447b46da4738d33a6c270d5b60
|
Python
|
feliciahsieh/holbertonschool-higher_level_programming
|
/0x03-python-data_structures/5-no_c.py
|
UTF-8
| 147
| 3.0625
| 3
|
[] |
no_license
|
#!/usr/bin/python3
def no_c(my_string):
n = ""
for x in my_string:
if x != 'c' and x != 'C':
n = n + x
return(n)
| true
|
3a927b053ea3ecb83d1b941be27a72431f10f78d
|
Python
|
gdfelt/competition
|
/euler/python3/euler007.py
|
UTF-8
| 392
| 3.921875
| 4
|
[] |
no_license
|
#!/usr/bin/env python3
"""
Project Euler Problem 7
=======================
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10001st prime number?
"""
import utils
def main():
p_count = 0
num = 1
while p_count < 10001:
num +=1
if utils.is_prime(num):
p_count+=1
print(str(num))
if __name__ == "__main__":
main()
| true
|
bf1fffad2fd1f28181a83fe31352c58ab53b9c31
|
Python
|
Noverish/Face-Recognition
|
/src/extraction/__init__.py
|
UTF-8
| 822
| 2.828125
| 3
|
[] |
no_license
|
import os
def extract(input_path):
input_path = os.path.abspath(input_path)
image_paths = []
labels = []
person_names = sorted([x for x in os.listdir(input_path) if os.path.isdir(os.path.join(input_path, x))])
for i in range(len(person_names)):
person_name = person_names[i]
person_path = os.path.join(input_path, person_name)
image_names = sorted([x for x in os.listdir(person_path) if os.path.isfile(os.path.join(person_path, x))])
for image_name in image_names:
image_path = os.path.join(person_path, image_name)
ext = os.path.splitext(image_path)[1].lower()
if ext in ['.jpg', '.png']:
image_paths.append(image_path)
labels.append(person_name)
return image_paths, labels, person_names
| true
|
52ed2e0c7f94bc60e699ea15838178a7eed0c65f
|
Python
|
Gitikameher/Emotion-classification
|
/data_loader.py
|
UTF-8
| 1,629
| 3.59375
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 17:31:49 2019
@author: meher
"""
from os import listdir
from PIL import Image
import numpy as np
# The relative path to your CAFE-Gamma dataset
data_dir = "./CAFE/"
# Dictionary of semantic "label" to emotions
emotion_dict = {"h": "happy", "ht": "happy with teeth", "m": "maudlin",
"s": "surprise", "f": "fear", "a": "anger", "d": "disgust", "n": "neutral"}
def load_data(data_dir="./CAFE/"):
""" Load all PGM images stored in your data directory into a list of NumPy
arrays with a list of corresponding labels.
Args:
data_dir: The relative filepath to the CAFE dataset.
Returns:
images: A list containing every image in CAFE as an array.
labels: A list of the corresponding labels (filenames) for each image.
"""
# Get the list of image file names
all_files = listdir(data_dir)
# Store the images as arrays and their labels in two lists
images = []
labels = []
for file in all_files:
# Load in the files as PIL images and convert to NumPy arrays
img = Image.open(data_dir + file)
images.append(np.array(img))
labels.append(file)
print("Total number of images:", len(images), "and labels:", len(labels))
return images, labels
def display_face(img):
""" Display the input image and optionally save as a PNG.
Args:
img: The NumPy array or image to display
Returns: None
"""
# Convert img to PIL Image object (if it's an ndarray)
if type(img) == np.ndarray:
print("Converting from array to PIL Image")
img = Image.fromarray(img)
# Display the image
img.show()
| true
|
417f56cb5af06e3784bb33bddf1b1efb7647f204
|
Python
|
incalia/schedy-client
|
/schedy/pbt.py
|
UTF-8
| 2,388
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
#: Minimize the objective
MINIMIZE = 'min'
#: Maximize the objective
MAXIMIZE = 'max'
class Truncate(object):
_EXPLOIT_STRATEGY_NAME = 'truncate'
def __init__(self, proportion=0.2):
'''
Truncate exploit strategy: if the selected candidate job is in the
worst n%, use a candidate job in the top n% instead.
Args:
proportion (float): Proportion of jobs that are considered to be
"best" jobs, and "worst" jobs. For example, if ``proportion =
0.2``, if the selected candidate job is in the bottom 20%, it
will be replaced by a job in the top 20%. Must satisfy ``0 <
proportion <= 0.5``.
'''
self.proportion = proportion
def _get_params(self):
return self.proportion
@classmethod
def _from_params(cls, params):
proportion = float(params)
return cls(proportion)
def __eq__(self, other):
return type(self) == type(other) and \
self.proportion == other.proportion
class Perturb(object):
_EXPLORE_STRATEGY_NAME = 'perturb'
def __init__(self, min_factor=0.8, max_factor=1.2):
'''
Perturb explore strategy: multiply the designated hyperparameter by a
random factor, sampled from a uniform distribution.
Args:
min_factor (float): Minimum value for the factor (inclusive).
max_factor (float): Maximum value for the factor (exclusive).
'''
self.min_factor = min_factor
self.max_factor = max_factor
def _get_params(self):
return {
'minFactor': float(self.min_factor),
'maxFactor': float(self.max_factor),
}
@classmethod
def _from_params(cls, params):
min_factor = float(params['minFactor'])
max_factor = float(params['maxFactor'])
return cls(min_factor, max_factor)
def __eq__(self, other):
return type(self) == type(other) and \
self.min_factor == other.min_factor and \
self.max_factor == other.max_factor
_EXPLOIT_STRATEGIES = {strat._EXPLOIT_STRATEGY_NAME: strat for strat in [
Truncate
]}
_EXPLORE_STRATEGIES = {strat._EXPLORE_STRATEGY_NAME: strat for strat in [
Perturb
]}
| true
|
91253ec84fe1dcdbaaffb95f39338e8bde793233
|
Python
|
PDXDevCampJuly/Nehemiah-Newell
|
/Python/Bank/Bank.py
|
UTF-8
| 2,334
| 3.484375
| 3
|
[] |
no_license
|
###
# Defines the Bank
###
from Person import Person
class Bank(object):
"""Bank information stored here"""
def __init__(self):
self.customers = {}
self.vault = -10.00
self.savings_interest = .3
def new_customer(self, name, email):
self.customers[email] = Person(name, email)
def remove_customer(self, email):
del self.customers[email]
def show_customer_info(self, email):
self.customers[email].banking()
def show_all_customers(self):
for customer in self.customers:
print("{}.\n email: {}\n".format(self.customers[customer].first_name + " " + self.customers[customer].last_name, customer))
def customer_deposit(self, email, accountNumber, amount):
self.customers[email].accounts[accountNumber].deposit(amount)
def customer_withdraw(self, email, accountNumber, amount):
self.customers[email].accounts[accountNumber].withdraw(amount)
def make_customer_account(self, email, amount, accountType="Checking Account"):
self.customers[email].open_account(amount, accountType)
def remove_customer_account(self, email, accountNumber):
self.customers[email].close_account(accountNumber)
def monthly_interest(self):
for customer in self.customers:
for saving in self.customers[customer].accounts:
saving.interest(self.savings_interest)
def customer_worth(self,email):
value = 0.0
for saving in self.customers[email].accounts:
value += saving.check_balance()
print("{} is worth ${:,.2f}".format(self.customers[email].first_name + " " + self.customers[email].last_name, value))
# def menu(self):
# article = "Wecome to Banking Services! \nWould you like to (a)dd a customer \n(r)emove a customer \na(d)d a account \n(c)lose a account \ncalculate the (w)orth of a customer \nget customer (i)nfo \n dep(o)set or withdraw."
# flag = True
# while flag == True:
# theInput = input("Please enter the desired service: ")
#
# if theInput.lower() == 'a':
#
# elif theInput.lower() == 'r':
#
# elif theInput.lower() == 'd':
#
# elif theInput.lower() == 'c':
#
# elif theInput.lower() == 'w':
#
# elif theInput.lower() == 'i':
#
# elif theInput.lower() == 'o':
# start asking for information from the user
theInput = input("Please enter a action ")
# and concantitate it.
article += theInput + "."
# and output
print("\n\n")
print(article)
print("\n\n")
| true
|
32fb36b6bcd783a31dc7ebb20a2c48b7e1dfda58
|
Python
|
davidvlaminck/OTLMOW
|
/src/OTLMOW/OTLModel/Datatypes/TimeField.py
|
UTF-8
| 3,937
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import logging
import random
from datetime import time, datetime, date
from OTLMOW.Facility.Exceptions.CouldNotConvertToCorrectTypeError import CouldNotConvertToCorrectTypeError
from OTLMOW.OTLModel.BaseClasses.OTLField import OTLField
class TimeField(OTLField):
"""Beschrijft een tekstregel volgens http://www.w3.org/2001/XMLSchema#string."""
naam = 'Time'
objectUri = 'http://www.w3.org/2001/XMLSchema#time'
definition = 'Beschrijft een datum volgens http://www.w3.org/2001/XMLSchema#time.'
label = 'Tijd'
usagenote = 'https://www.w3.org/TR/xmlschema-2/#time'
@classmethod
def convert_to_correct_type(cls, value, log_warnings=True):
if value is None:
return None
if isinstance(value, bool):
raise CouldNotConvertToCorrectTypeError(f'{value} could not be converted to correct type (implied by {cls.__name__})')
if isinstance(value, time):
return value
if isinstance(value, datetime):
if log_warnings:
logging.warning(
'Assigned a datetime to a time datatype. Automatically converted to the correct type. Please change the type')
return time(value.hour, value.minute, value.second)
if isinstance(value, date):
if log_warnings:
logging.warning(
'Assigned a date to a time datatype. Automatically converted to the correct type. Please change the type')
return time(0, 0, 0)
if isinstance(value, int):
if log_warnings:
logging.warning(
'Assigned a int to a date datatype. Automatically converted to the correct type. Please change the type')
timestamp = datetime.fromtimestamp(value)
return time(timestamp.hour, timestamp.minute, timestamp.second)
if isinstance(value, str):
try:
dt = datetime.strptime(value, "%H:%M:%S")
if log_warnings:
logging.warning(
'Assigned a string to a time datatype. Automatically converted to the correct type. Please change the type')
return time(dt.hour, dt.minute, dt.second)
except ValueError:
try:
dt = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
if log_warnings:
logging.warning(
'Assigned a string to a time datatype. Automatically converted to the correct type. Please change the type')
return time(dt.hour, dt.minute, dt.second)
except ValueError:
try:
dt = datetime.strptime(value, "%d/%m/%Y %H:%M:%S")
if log_warnings:
logging.warning(
'Assigned a string to a time datatype. Automatically converted to the correct type. Please change the type')
return time(dt.hour, dt.minute, dt.second)
except Exception:
raise CouldNotConvertToCorrectTypeError(f'{value} could not be converted to correct type (implied by {cls.__name__})')
raise CouldNotConvertToCorrectTypeError(f'{value} could not be converted to correct type (implied by {cls.__name__})')
@staticmethod
def validate(value, attribuut):
if value is not None and not isinstance(value, time):
raise TypeError(f'expecting datetime in {attribuut.naam}')
return True
@staticmethod
def value_default(value):
if value is None:
return None
return value.strftime("%H:%M:%S")
def __str__(self):
return OTLField.__str__(self)
@classmethod
def create_dummy_data(cls):
return time(hour=random.randint(0, 23), minute=random.randint(0, 59), second=random.randint(0, 59))
| true
|
88a87965df6f7089c0217116783c45aedffb054a
|
Python
|
jingong171/jingong-homework
|
/张庭康/2017310416张庭康金工17-1第四次作业/2017310416张庭康金工17-1第四次作业/作业1.py
|
UTF-8
| 611
| 4.4375
| 4
|
[] |
no_license
|
from random import randint
#导入模块random中生成随机数的函数
class Die():
"""打印位于1和骰子面数之间的随机数"""
def __init__(self,sides=6):
self.sides = sides
"""创建一个名为sides(面数)的属性"""
def roll_die(self):
print("面数为"+str(self.sides)+"的骰子投掷十次的结果为:",end=' ')
for i in range(10):
print(str(randint(1,self.sides))+",",end=' ')
"""打印位于1和骰子面数之间的随机数"""
#创建对象:不同面数的骰子,并打印十个随机数
dice1=Die()
dice1.roll_die()
| true
|
9e7904301dc6474e8dc333a7ab4f5aa8914e9fbb
|
Python
|
holoviz/datashader
|
/datashader/layout.py
|
UTF-8
| 8,967
| 3.34375
| 3
|
[] |
permissive
|
"""Assign coordinates to the nodes of a graph.
"""
from __future__ import annotations
import numpy as np
import param
import scipy.sparse
class LayoutAlgorithm(param.ParameterizedFunction):
"""
Baseclass for all graph layout algorithms.
"""
__abstract = True
seed = param.Integer(default=None, bounds=(0, 2**32-1), doc="""
Random seed used to initialize the pseudo-random number
generator.""")
x = param.String(default='x', doc="""
Column name for each node's x coordinate.""")
y = param.String(default='y', doc="""
Column name for each node's y coordinate.""")
source = param.String(default='source', doc="""
Column name for each edge's source.""")
target = param.String(default='target', doc="""
Column name for each edge's target.""")
weight = param.String(default=None, allow_None=True, doc="""
Column name for each edge weight. If None, weights are ignored.""")
id = param.String(default=None, allow_None=True, doc="""
Column name for a unique identifier for the node. If None, the
dataframe index is used.""")
def __call__(self, nodes, edges, **params):
"""
This method takes two dataframes representing a graph's nodes
and edges respectively. For the nodes dataframe, the only
column accessed is the specified `id` value (or the index if
no 'id'). For the edges dataframe, the columns are `id`,
`source`, `target`, and (optionally) `weight`.
Each layout algorithm will use the two dataframes as appropriate to
assign positions to the nodes. Upon generating positions, this
method will return a copy of the original nodes dataframe with
two additional columns for the x and y coordinates.
"""
return NotImplementedError
class random_layout(LayoutAlgorithm):
"""
Assign coordinates to the nodes randomly.
Accepts an edges argument for consistency with other layout algorithms,
but ignores it.
"""
def __call__(self, nodes, edges=None, **params):
p = param.ParamOverrides(self, params)
np.random.seed(p.seed)
df = nodes.copy()
points = np.asarray(np.random.random((len(df), 2)))
df[p.x] = points[:, 0]
df[p.y] = points[:, 1]
return df
class circular_layout(LayoutAlgorithm):
"""
Assign coordinates to the nodes along a circle.
The points on the circle can be spaced either uniformly or randomly.
Accepts an edges argument for consistency with other layout algorithms,
but ignores it.
"""
uniform = param.Boolean(True, doc="""
Whether to distribute nodes evenly on circle""")
def __call__(self, nodes, edges=None, **params):
p = param.ParamOverrides(self, params)
np.random.seed(p.seed)
r = 0.5 # radius
x0, y0 = 0.5, 0.5 # center of unit circle
circumference = 2 * np.pi
df = nodes.copy()
if p.uniform:
thetas = np.arange(circumference, step=circumference/len(df))
else:
thetas = np.asarray(np.random.random((len(df),))) * circumference
df[p.x] = x0 + r * np.cos(thetas)
df[p.y] = y0 + r * np.sin(thetas)
return df
def _extract_points_from_nodes(nodes, params, dtype=None):
if params.x in nodes.columns and params.y in nodes.columns:
points = np.asarray(nodes[[params.x, params.y]])
else:
points = np.asarray(np.random.random((len(nodes), params.dim)), dtype=dtype)
return points
def _convert_graph_to_sparse_matrix(nodes, edges, params, dtype=None, format='csr'):
nlen = len(nodes)
if params.id is not None and params.id in nodes:
index = dict(zip(nodes[params.id].values, range(nlen)))
else:
index = dict(zip(nodes.index.values, range(nlen)))
if params.weight and params.weight in edges:
edge_values = edges[[params.source, params.target, params.weight]].values
rows, cols, data = zip(*((index[src], index[dst], weight)
for src, dst, weight in edge_values
if src in index and dst in index))
else:
edge_values = edges[[params.source, params.target]].values
rows, cols, data = zip(*((index[src], index[dst], 1)
for src, dst in edge_values
if src in index and dst in index))
# Symmetrize matrix
d = data + data
r = rows + cols
c = cols + rows
# Check for nodes pointing to themselves
loops = edges[edges[params.source] == edges[params.target]]
if len(loops):
if params.weight and params.weight in edges:
loop_values = loops[[params.source, params.target, params.weight]].values
diag_index, diag_data = zip(*((index[src], -weight)
for src, dst, weight in loop_values
if src in index and dst in index))
else:
loop_values = loops[[params.source, params.target]].values
diag_index, diag_data = zip(*((index[src], -1)
for src, dst in loop_values
if src in index and dst in index))
d += diag_data
r += diag_index
c += diag_index
M = scipy.sparse.coo_matrix((d, (r, c)), shape=(nlen, nlen), dtype=dtype)
return M.asformat(format)
def _merge_points_with_nodes(nodes, points, params):
n = nodes.copy()
n[params.x] = points[:, 0]
n[params.y] = points[:, 1]
return n
def cooling(matrix, points, temperature, params):
dt = temperature / float(params.iterations + 1)
displacement = np.zeros((params.dim, len(points)))
for iteration in range(params.iterations):
displacement *= 0
for i in range(matrix.shape[0]):
# difference between this row's node position and all others
delta = (points[i] - points).T
# distance between points
distance = np.sqrt((delta ** 2).sum(axis=0))
# enforce minimum distance of 0.01
distance = np.where(distance < 0.01, 0.01, distance)
# the adjacency matrix row
ai = matrix[i].toarray()
# displacement "force"
dist = params.k * params.k / distance ** 2
if params.nohubs:
dist = dist / float(ai.sum(axis=1) + 1)
if params.linlog:
dist = np.log(dist + 1)
displacement[:, i] += (delta * (dist - ai * distance / params.k)).sum(axis=1)
# update points
length = np.sqrt((displacement ** 2).sum(axis=0))
length = np.where(length < 0.01, 0.01, length)
points += (displacement * temperature / length).T
# cool temperature
temperature -= dt
class forceatlas2_layout(LayoutAlgorithm):
"""
Assign coordinates to the nodes using force-directed algorithm.
This is a force-directed graph layout algorithm called
`ForceAtlas2`.
Timothee Poisot's `nxfa2` is the original implementation of this
algorithm.
.. _ForceAtlas2:
http://journals.plos.org/plosone/article/file?id=10.1371/journal.pone.0098679&type=printable
.. _nxfa2:
https://github.com/tpoisot/nxfa2
"""
iterations = param.Integer(default=10, bounds=(1, None), doc="""
Number of passes for the layout algorithm""")
linlog = param.Boolean(False, doc="""
Whether to use logarithmic attraction force""")
nohubs = param.Boolean(False, doc="""
Whether to grant authorities (nodes with a high indegree) a
more central position than hubs (nodes with a high outdegree)""")
k = param.Number(default=None, doc="""
Compensates for the repulsion for nodes that are far away
from the center. Defaults to the inverse of the number of
nodes.""")
dim = param.Integer(default=2, bounds=(1, None), doc="""
Coordinate dimensions of each node""")
def __call__(self, nodes, edges, **params):
p = param.ParamOverrides(self, params)
np.random.seed(p.seed)
# Convert graph into sparse adjacency matrix and array of points
points = _extract_points_from_nodes(nodes, p, dtype='f')
matrix = _convert_graph_to_sparse_matrix(nodes, edges, p, dtype='f')
if p.k is None:
p.k = np.sqrt(1.0 / len(points))
# the initial "temperature" is about .1 of domain area (=1x1)
# this is the largest step allowed in the dynamics.
temperature = 0.1
# simple cooling scheme.
# linearly step down by dt on each iteration so last iteration is size dt.
cooling(matrix, points, temperature, p)
# Return the nodes with updated positions
return _merge_points_with_nodes(nodes, points, p)
| true
|
5985af30ebc10a5f053ac9966866553034bc285e
|
Python
|
alexaoh/algdat
|
/Exercise1/take_pieces.py
|
UTF-8
| 122
| 3.421875
| 3
|
[] |
no_license
|
def take_pieces(n_pieces):
for i in range(1,8):
if (n_pieces - i) % 8 == 1:
return i
return 2
| true
|
0c72752f6c8f1044dee082c1bce65bbfb06ac9fc
|
Python
|
mmunar97/inPYinting
|
/inPYinting/algorithms/exemplar_based/exemplar_based_inpainting.py
|
UTF-8
| 11,317
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import numpy
import sys
import time
from typing import List, Tuple
from inPYinting.algorithms.exemplar_based.exemplar_based_utils import *
from inPYinting.base.result import InpaintingResult
class ExemplarBasedInpainter:
def __init__(self, image, mask):
self.__image = image
self.__original_mask = ExemplarBasedInpainter.__reverse_mask(image=mask)
self.__mask = ExemplarBasedInpainter.__reverse_mask(image=mask)
def inpaint(self, tau: int = 170, size: int = 3) -> InpaintingResult:
elapsed_time = time.time()
result, _ = self.__inpaint(tau, size)
elapsed_time = time.time() - elapsed_time
return InpaintingResult(inpainted_image=result, elapsed_time=elapsed_time)
def inpaint_with_steps(self, tau: int, size: int = 3) -> Tuple[InpaintingResult, List[numpy.ndarray]]:
elapsed_time = time.time()
result, steps = self.__inpaint(tau, size)
elapsed_time = time.time() - elapsed_time
return InpaintingResult(inpainted_image=result, elapsed_time=elapsed_time), steps
def __inpaint(self, tau: int, size: int) -> Tuple[numpy.ndarray, List[numpy.ndarray]]:
omega, confidence = self.__compute_previous_terms(tau)
source, original = numpy.copy(confidence), numpy.copy(confidence)
im = numpy.copy(self.__image)
data = numpy.ndarray(shape=self.__image.shape[:2])
inpainted_finished = False
steps: int = 0
image_steps = []
while not inpainted_finished:
steps += 1
print(f"Inpainting with Exemplar-Based – Step {steps}")
xsize, ysize = source.shape
grayscale_image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
gradient_x = numpy.float32(cv2.convertScaleAbs(cv2.Scharr(grayscale_image, cv2.CV_32F, 1, 0)))
gradient_y = numpy.float32(cv2.convertScaleAbs(cv2.Scharr(grayscale_image, cv2.CV_32F, 0, 1)))
gradient_x[self.__mask == 1] = 0
gradient_y[self.__mask == 1] = 0
gradient_x, gradient_y = gradient_x / 255, gradient_y / 255
d_omega, normal = ExemplarBasedInpainter.__compute_boundary(self.__mask, source)
confidence, data, index = ExemplarBasedInpainter.__compute_priority(im, size, self.__mask, d_omega, normal,
data, gradient_x, gradient_y,
confidence)
list, pp = ExemplarBasedInpainter.__get_patch(d_omega, index, im, original, self.__mask, size)
im, gradient_x, gradient_y, confidence, source, self.__mask = ExemplarBasedInpainter.__update(im,
gradient_x,
gradient_y,
confidence,
source,
self.__mask,
d_omega, pp,
list, index,
size)
inpainted_finished = True
for x in range(xsize):
for y in range(ysize):
if source[x, y] == 0:
inpainted_finished = False
image_steps.append(im)
return im, image_steps
@staticmethod
def __reverse_mask(image: numpy.ndarray):
"""
Converts a mask with black background and white lost pixels into an image with white background and black pixels
to recover.
Args:
image: A two dimensional image, representing the mask with the lost pixels.
Returns:
A two dimensional image, representing the mask with the lost pixels marked with black.
"""
return 255-image
def __compute_previous_terms(self, tau: int) -> Tuple[List, numpy.ndarray]:
"""
Computes the list of pixels to be corrected and the matrix of confidence of the image.
Args:
tau: A threshold to indicate the limit to modify the mask.
Returns:
A tuple of two elements: the list of pixels and the matrix of confidence.
"""
omega = []
confidence = numpy.copy(self.__mask)
for x in range(self.__image.shape[0]):
for y in range(self.__image.shape[1]):
mask_value = self.__mask[x, y]
if mask_value < tau:
omega.append([x, y])
self.__image[x, y] = [255, 255, 255]
self.__mask[x, y] = 1
confidence[x, y] = 0
else:
self.__mask[x, y] = 0
confidence[x, y] = 1
return omega, confidence
@staticmethod
def __compute_boundary(mask: numpy.ndarray, source: numpy.ndarray):
"""
Computes the boundary pixels.
"""
d_omega = []
normal = []
laplacian = cv2.filter2D(mask, cv2.CV_32F, get_laplacian_operator())
gradient_x = cv2.filter2D(source, cv2.CV_32F, get_derivative_x_operator())
gradient_y = cv2.filter2D(source, cv2.CV_32F, get_derivative_y_operator())
xsize, ysize = laplacian.shape
for x in range(xsize):
for y in range(ysize):
if laplacian[x, y] > 0:
d_omega += [(y, x)]
dx = gradient_x[x, y]
dy = gradient_y[x, y]
norm = (dy ** 2 + dx ** 2) ** 0.5
if norm != 0:
normal += [(dy / norm, -dx / norm)]
else:
normal += [(dy, -dx)]
return d_omega, normal
@staticmethod
def __generate_patch_coordinates(image: numpy.ndarray, size: int, point: Tuple[int, int]):
"""
Computes the extreme points of a patch.
"""
px, py = point
xsize, ysize, c = image.shape
x3 = max(px - size, 0)
y3 = max(py - size, 0)
x2 = min(px + size, ysize - 1)
y2 = min(py + size, xsize - 1)
return (x3, y3), (x2, y2)
@staticmethod
def __compute_confidence(confidence, image, size, mask, d_omega):
"""
Computes the confidence.
"""
for k in range(len(d_omega)):
px, py = d_omega[k]
patch = ExemplarBasedInpainter.__generate_patch_coordinates(image=image, size=size, point=d_omega[k])
x3, y3 = patch[0]
x2, y2 = patch[1]
i = 0
size_psi_p = ((x2 - x3 + 1) * (y2 - y3 + 1))
for x in range(x3, x2 + 1):
for y in range(y3, y2 + 1):
if mask[y, x] == 0:
i += confidence[y, x]
confidence[py, px] = i / size_psi_p
return confidence
@staticmethod
def __compute_data(d_omega, normal, data, gradient_x, gradient_y):
for k in range(len(d_omega)):
x, y = d_omega[k]
n_x, n_y = normal[k]
data[y, x] = (((gradient_x[y, x] * n_x)**2 + (gradient_y[y, x] * n_y)**2)**0.5) / 255.0
return data
@staticmethod
def __compute_priority(image, size, mask, d_omega, normal, data, gradient_x, gradient_y, confidence):
conf = ExemplarBasedInpainter.__compute_confidence(confidence, image, size, mask, d_omega)
dat = ExemplarBasedInpainter.__compute_data(d_omega, normal, data, gradient_x, gradient_y)
index = 0
maxi = 0
for i in range(len(d_omega)):
x, y = d_omega[i]
P = conf[y, x] * dat[y, x]
if P > maxi:
maxi = P
index = i
return conf, dat, index
@staticmethod
def __get_patch(d_omega, cible_index, im, original, mask, size):
mini = minvar = sys.maxsize
source_patch = []
p = d_omega[cible_index]
patch = ExemplarBasedInpainter.__generate_patch_coordinates(im, size, p)
x1, y1 = patch[0]
x2, y2 = patch[1]
x_size, y_size, c = im.shape
counter, cibles, ciblem, xsize, ysize = ExemplarBasedInpainter.__crible(y2-y1+1, x2-x1+1, x1, y1, mask)
for x in range(x_size - xsize):
for y in range(y_size - ysize):
if ExemplarBasedInpainter.__is_patch_complete(x, y, xsize, ysize, original):
source_patch += [(x, y)]
for (y, x) in source_patch:
R = V = B = ssd = 0
for (i, j) in cibles:
ima = im[y + i, x + j]
omega = im[y1 + i, x1 + j]
for k in range(3):
difference = float(ima[k]) - float(omega[k])
ssd += difference ** 2
R += ima[0]
V += ima[1]
B += ima[2]
ssd /= counter
if ssd < mini:
variation = 0
for (i, j) in ciblem:
ima = im[y + i, x + j]
differenceR = ima[0] - R / counter
differenceV = ima[1] - V / counter
differenceB = ima[2] - B / counter
variation += differenceR ** 2 + differenceV ** 2 + differenceB ** 2
if ssd < mini or variation < minvar:
minvar = variation
mini = ssd
pointPatch = (x, y)
return ciblem, pointPatch
@staticmethod
def __crible(x_size, y_size, x1, y1, mask):
counter = 0
cibles, ciblem = [], []
for i in range(x_size):
for j in range(y_size):
if mask[y1 + i, x1 + j] == 0:
counter += 1
cibles += [(i, j)]
else:
ciblem += [(i, j)]
return counter, cibles, ciblem, x_size, y_size
@staticmethod
def __is_patch_complete(x, y, x_size, y_size, original):
for i in range(x_size):
for j in range(y_size):
if original[x + i, y + j] == 0:
return False
return True
@staticmethod
def __update(im, gradient_x, gradient_y, confidence, source, mask, d_omega, point, list, index, size):
p = d_omega[index]
patch = ExemplarBasedInpainter.__generate_patch_coordinates(im, size, p)
x1, y1 = patch[0]
px, py = point
for (i, j) in list:
im[y1 + i, x1 + j] = im[py + i, px + j]
confidence[y1 + i, x1 + j] = confidence[py, px]
source[y1 + i, x1 + j] = 1
mask[y1 + i, x1 + j] = 0
return im, gradient_x, gradient_y, confidence, source, mask
| true
|
8d300fa432ecb3899824c184669d8b9569d1bdb4
|
Python
|
kproshakov/SudokuCV
|
/main.py
|
UTF-8
| 1,516
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
from SudokuCV import SudokuCV
import cv2
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
w,h = 400, 500
master.minsize(width=w, height=h)
master.maxsize(width=w, height=h)
master.title
self.pack()
self.file = Button(self, text='Browse', command=self.choose)
self.choose = Label(self, text="Choose file").pack()
#Replace with your image
self.image = Image.open('Default.png')
self.image = self.image.resize((350, 350))
self.image = ImageTk.PhotoImage(self.image)
self.label = Label(image=self.image)
self.s = SudokuCV()
self.file.pack()
self.label.pack()
def choose(self):
ifile = filedialog.askopenfile(parent=self,mode='rb',title='Choose a file')
path = Image.open(ifile)
path = path.resize((350, 350))
self.image2 = ImageTk.PhotoImage(path)
self.label.configure(image=self.image2)
self.label.image=self.image2
solved = self.s.solve_sudoku_pic(str(ifile.name))
solved = cv2.resize(solved, (350, 350))
solved = Image.fromarray(solved)
self.image2 = ImageTk.PhotoImage(solved)
self.label.configure(image=self.image2)
self.label.image=self.image2
root = Tk()
root.title("SudokuCV")
app = GUI(master=root)
app.mainloop()
root.destroy()
root.mainloop()
| true
|
088a0fb4c0b57af11965ad91e87af83450bd29de
|
Python
|
terencesll/AdventOfCode
|
/2020/02a.py
|
UTF-8
| 567
| 3.109375
| 3
|
[] |
no_license
|
file = open("02.txt")
numValid = 0
for line in file:
tokens = line.split(":")
policy = tokens[0].split(" ")
policyMinMax = policy[0].split("-")
policyMin = int(policyMinMax[0])
policyMax = int(policyMinMax[1])
policyLetter = policy[1]
password = tokens[1].strip()
count = { policyLetter: 0}
for char in password:
if char not in count:
count[char] = 0
count[char] += 1
#print(count)
if count[policyLetter] >= policyMin and count[policyLetter] <= policyMax:
numValid += 1
print(numValid)
| true
|
e6ffb1fdba2715f233a2c98c251f8a468a42b994
|
Python
|
cfvillalta/postdoc
|
/UID_in_HMM_out_domain.py
|
UTF-8
| 2,542
| 3.078125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
#The purpose of this script was to put in a list of IDs from a phylogenetic tree branch and pull their sequecnes from a list of sequecnes I might have. The script then aligns those sequences with Clustal Omega and builds an HMM with the alignment.
import phylo_tools
import sys
import re
#list of UIDs, like a list of UIDs I had picked from java tree view
input = sys.argv[1]
#file with fasta seqs
input_2 = sys.argv[2]
#split file name at '.' to use name later
input_s = input.split(".")
#open list of UIDs
input_open =open(input, 'rU')
#read each line of IDs
GIDs= input_open.readlines()
#create list I will put IDs into.
GID_list = []
#for loop goes through GIDs list from text file.
for GID in GIDs:
#strip /n from each GID
GID=GID.strip()
#split each GID by '/' because the GID is a number id, /, and coordinates of domain(in this case tyrosinase domains.)
GID_s=GID.split("/")
# print GID_s[0]
GID_list.append(GID_s[0])
#inputs my txt file with fasta sequences.
input_2_open = open(input_2, 'rU')
#read each line of the text file into a list called seqs.
seqs = input_2_open.readlines()
#created an empty dict I will put seqs into with the seq id as the key and the value being the seqeucne.
input_seqs ={}
#loop through list seq.
for seq in seqs:
#strip each string in list of trailign whitespace e.g. /n
seq=seq.strip()
#strings in list that begin with ">"
if seq.startswith(">"):
#within those will look for pattern of ">" followed by a number \d+ and ending with a backslash /. Search pattern is called gid
gid = re.compile(r"(>)(\d+)(/)")
#search string for pattern in gid
match= gid.search(seq)
#if match present
if match:
#grab the id
id = match.group(2)
#use the id as the key for sequence in diction input_seqs
input_seqs[id]=[]
#if no '>' then add to a list of seqs that belong to the id that superceded it.
else:
input_seqs[id].append(seq)
#make a file with the same name as the UID input file but with a .fasta file extenstion.
fasta = open('%s.fasta' %(input_s[0]),'w')
#Look through each key in the GID_list.
for seq in GID_list:
#if gid in dictionary
if input_seqs[seq]:
#write out the id and print joined seqs into new fasta file.
fasta.write('>%s\n%s\n' %(seq, ''.join(input_seqs[seq])))
#align fasta file with clustal omega, outputs a clustal alignment
phylo_tools.ClustalO(input_s[0])
#build hmm with clustal alignment using hmmbuild
phylo_tools.hmmbuild('%s_clustalo' %(input_s[0]))
| true
|
8ca6a7a0868efbd8da3e414e96191f107805b0a3
|
Python
|
dcobas/adctest
|
/PAGE/Waveform.py
|
UTF-8
| 1,250
| 2.875
| 3
|
[] |
no_license
|
__author__ = "Federico Asara"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Federico Asara", "Juan David Gonzalez Cobas"]
__license__ = "GPL2"
__version__ = "1.0.0"
__maintainer__ = "Federico Asara"
__email__ = "federico.asara@gmail.com"
__status__ = "Production"
from numpy import array
from Item import *
"""This class represent a generic waveform.
You must implement the generate and generatePeriod methods in order to subclass
this. Refer to their docstrings."""
class Waveform(Item):
def get(self, what):
"""Get an attribute value. Supports Pyro4."""
return self.__getattribute__(what)
def set(self, what, how):
"""Set an attribute value. Supports Pyro4."""
self.__setattr__(what, how)
def generate(self, nbits, frequency, samples, fsr):
"""A waveform must provide this method.
Create a numeric array which represents the wave."""
return array([])
def generatePeriod(self, nbits, samples, fsr):
"""A waveform must provide this method.
Create a numeric array which represents a period of the wave."""
return array([])
def __init__(self, *args, **kwargs):
Item.__init__(self, *args, **kwargs)
def getType(self):
return type(self)
| true
|
47f8635b536fb7ad614874d5250f29811a2f619f
|
Python
|
PolinaAlexandr/python-numeric-types-exercise
|
/main_test.py
|
UTF-8
| 1,354
| 3.421875
| 3
|
[] |
no_license
|
import unittest
import main
class MainTest(unittest.TestCase):
def test_square_area(self):
self.assertEqual(main.square_area(5), 25)
def test_rectangle_area(self):
self.assertEqual(main.rectangle_area(3, 4), 12)
def test_triangle_area(self):
self.assertEqual(main.triangle_area(2, 3, 4), 24)
def test_parallelogram_area_sin(self):
self.assertEqual(main.parallelogram_area_sin(2, 4, 60), 480)
def test_parallelogram_area_base(self):
self.assertEqual(main.parallelogram_area_base(3, 6), 18)
def test_degree_to_radians(self):
result = main.degree_to_radians(57.29577951308232)
expected = 1.0
self.assertTrue(self.is_close(result, expected))
@staticmethod
def is_close(a, b, rel_tol=1e-13, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def test_radians_to_degrees(self):
result = main.radians_to_degrees(1.0)
expected = 57.29577951308232
self.assertTrue(self.is_close(result, expected))
def test_square_equation_roots(self):
self.assertEqual(main.square_equation_roots(1, 2, -48), (6.0, -8.0))
def test_leap_year(self):
self.assertTrue(main.is_leap(2004))
if __name__ == '__main__':
unittest.main()
| true
|
bd299caada8e0c8e526eb123af0a4eaf03f4e110
|
Python
|
mlavarias/PFB2017
|
/rnaseq/countingkmers.py
|
UTF-8
| 606
| 2.78125
| 3
|
[] |
no_license
|
import re
import sys
from Bio import SeqIO
kmer_length = 8
#sys.argv[1]
filename = sys.argv[1]
top_kmers = 10
# sys.argv[3]
kmerdict = {}
def count_kmers(kmerdict, sequence):
for i in range(0,len(sequence)-kmer_length+1):
kmer = sequence[i:i+kmer_length]
if kmer in kmerdict:
kmerdict[kmer] += 1
else:
kmerdict[kmer] = 1
for record in SeqIO.parse(filename, 'fastq'):
# print(record.seq)
count_kmers(kmerdict, str(record.seq))
top_sorted = sorted(kmerdict, key= lambda x:kmerdict[x], reverse = True)[0:top_kmers+1]
for item in top_sorted:
print('{}\t{}'.format(item, kmerdict[item]))
| true
|
a284b512112268f258fbe8c390a0e5286c0f9535
|
Python
|
Natquuu/BirdClassification
|
/gmms/GMM5.py
|
UTF-8
| 3,771
| 2.796875
| 3
|
[] |
no_license
|
import numpy as np
from scipy.stats import norm
import scipy.stats as stats
import matplotlib.pyplot as plt
import matplotlib
def plot_distributions(data, data_sampled, mu, sigma, K, color="green", color_sampled="red", name='plot.png'):
matplotlib.rcParams['text.usetex'] = True
plt.rcParams.update({'font.size': 16})
data_sampled = np.clip(data_sampled, np.min(data), np.max(data))
plt.hist(data, bins=15, color=color, alpha=0.45, density=True)
plt.hist(data_sampled, bins=15, range=(np.min(data), np.max(data)),
color=color_sampled, alpha=0.45, density=True)
for k in range(K):
curve = np.linspace(mu[k] - 10 * sigma[k], mu[k] + 10 * sigma[k], 100)
color = np.random.rand(3)
plt.plot(curve, stats.norm.pdf(
curve, mu[k], sigma[k]), color=color, linestyle="--", linewidth=3)
plt.ylabel(r"$p(x)$")
plt.xlabel(r"$x$")
plt.tight_layout()
plt.xlim(20, 120)
plt.savefig(name, dpi=200)
plt.show()
def plot_likelihood(nll_list):
matplotlib.rcParams['text.usetex'] = True
plt.rcParams.update({'font.size': 16})
plt.plot(np.arange(len(nll_list)), nll_list,
color="black", linestyle="--", linewidth=3)
plt.ylabel(r"(negative) log-likelihood")
plt.xlabel(r"iteration")
plt.tight_layout()
plt.xlim(0, len(nll_list))
plt.savefig('nll.png', dpi=200)
plt.show()
def sampler(pi, mu, sigma, N):
data = list()
for n in range(N):
k = np.random.choice(len(pi), p=pi)
sample = np.random.normal(loc=mu[k], scale=sigma[k])
data.append(sample)
return data
def main():
data = np.genfromtxt('./bdims.csv', delimiter=',', skip_header=1) # [:,-2]
data = data[:, -3]
N = data.shape[0]
K = 2 # two components GMM
tot_iterations = 100 # stopping criteria
# Step-1 (Init)
mu = np.random.uniform(low=42.0, high=95.0, size=K)
sigma = np.random.uniform(low=5.0, high=10.0, size=K)
pi = np.ones(K) * (1.0 / K) # mixing coefficients
r = np.zeros([K, N]) # responsibilities
nll_list = list() # store the neg log-likelihood
for iteration in range(tot_iterations):
# Step-2 (E-Step)
for k in range(K):
r[k, :] = pi[k] * norm.pdf(x=data, loc=mu[k], scale=sigma[k])
r = r / np.sum(r, axis=0) # [K,N] -> [N]
# Step-3 (M-Step)
N_k = np.sum(r, axis=1) # [K,N] -> [K]
for k in range(K):
# update means
mu[k] = np.sum(r[k, :] * data) / N_k[k]
# update variances
numerator = r[k] * (data - mu[k]) ** 2
sigma[k] = np.sqrt(np.sum(numerator) / N_k[k])
# update weights
pi = N_k / N
likelihood = 0.0
for k in range(K):
likelihood += pi[k] * norm.pdf(x=data, loc=mu[k], scale=sigma[k])
nll_list.append(-np.sum(np.log(likelihood)))
# Check for invalid negative log-likelihood (NLL)
# The NLL is invalid if NLL_t-1 < NLL_t
# Note that this can happen for round-off errors.
if (len(nll_list) >= 2):
if (nll_list[-2] < nll_list[-1]):
raise Exception("[ERROR] invalid NLL: " + str(nll_list[-2:]))
print("Iteration: " + str(iteration) + "; NLL: " + str(nll_list[-1]))
print("Mean " + str(mu) + "\nStd " +
str(sigma) + "\nWeights " + str(pi) + "\n")
# Step-4 (Check)
if (iteration == tot_iterations - 1):
break # check iteration
plot_likelihood(nll_list)
data_gmm = sampler(pi, mu, sigma, N=1000)
plot_distributions(data, data_gmm, mu, sigma, K, color="green",
color_sampled="red", name="plot_sampler.png")
if __name__ == "__main__":
main()
| true
|
78cb19d858d9bf3bfd2e14b1583873c04fdb1abb
|
Python
|
vlbos/bos.oracle-test
|
/oracle.testenv/test/airdropburn/unionset.py
|
UTF-8
| 2,941
| 2.78125
| 3
|
[] |
no_license
|
# coding:utf-8
import csv
import re
import json
airdrop_accounts_file = './dataset/accounts_info_bos_snapshot.airdrop.normal.csv'
airdrop_msig_accounts_file = './dataset/accounts_info_bos_snapshot.airdrop.msig.json'
nonactive_accounts_file = './dataset/nonactivated_bos_accounts.txt'
nonactive_msig_accounts_file = './dataset/nonactivated_bos_accounts.msig'
nonactive_airdrop_accounts_file = "./unactive_airdrop_accounts.csv"
# txt
def loadtxt(txt):
f = open(txt, 'r')
sourceInline = f.readlines()
dataset = []
for line in sourceInline:
temp1 = line.strip('\x00')
temp1 = temp1.strip('\n')
if (temp1 == ''):
continue
dataset.append(temp1.strip())
f.close
return dataset
# csv
def loadcsv(csvFile):
f = open(csvFile, 'r')
reader = csv.reader(f)
csvset = {}
csvlist = []
for item in reader:
csvset[item[4]] = item[5]
csvlist.append(item[4])
f.close()
return csvset, csvlist
def unionset():
# 读取txt获取主网未激活账户
tacclist = loadtxt(nonactive_accounts_file)
# 读取空投账户 csv集合
caccset, cacclist = loadcsv(airdrop_accounts_file)
# 创建数值集合
tc = set(tacclist) & set(cacclist)
resCsv = []
sumBurn = 0
# 构造交集结果
for item in tc:
resCsv.append([item, caccset[item]])
sumBurn += float(caccset[item].replace('BOS', '').strip())
print('len of unactive', len(resCsv))
msig, sumBurnmsig = intersectmsigset()
resCsv += msig
sumBurn += sumBurnmsig
# 写结果
with open(nonactive_airdrop_accounts_file, 'w') as cfile:
writer = csv.writer(cfile)
for item in resCsv:
writer.writerow(item)
cfile.close()
print('unactive airdrop accounts count:', len(resCsv))
print('unactive airdrop accounts quantity:', sumBurn)
def msigfromjson():
# 由于文件中有多行,直接读取会出现错误,因此一行一行读取
file = open(airdrop_msig_accounts_file, 'r', encoding='utf-8')
csvset = {}
lst = []
for line in file.readlines():
item = json.loads(line)
csvset[item['bos_account']] = item['bos_balance']
lst.append(item['bos_account'])
file.close()
return csvset,lst
def intersectmsigset():
# 读取csv集合
msiglist = loadtxt(nonactive_msig_accounts_file)
accquan,unactive_list = msigfromjson()
# 创建数值集合
tc = set(msiglist) & set(unactive_list)
print('unactive airdrop msig accounts count:', len(tc))
resCsv = []
sumBurn = 0
# 构造交集结果
for item in tc:
resCsv.append([item, accquan[item]])
sumBurn += float(accquan[item].replace('BOS', '').strip())
print('unactive airdrop msig accounts count:', len(resCsv))
print('unactive airdrop msig accounts quantity:', sumBurn)
return resCsv, sumBurn
unionset()
| true
|
3ba0eb687948eb4db2fe69d8b1aafc9d816ccfb5
|
Python
|
goareum93/K-digital-training
|
/01_Python/07_string/string_trans.py
|
UTF-8
| 523
| 4.34375
| 4
|
[] |
no_license
|
# # replace()
#
# text = 'Java Programming'
# text = text.replace('Java', 'Python')
# print(text)
#
# # 대문자/소문자 변환
# # upper() lower() capitalize() title() swapcase()
# text = 'java programming is Fun'
# print(text.upper())
# print(text.lower())
# print(text.title())
# print(text.capitalize())
# print(text.swapcase())
# 공백문자 제거 strip(), lstrip(), rstrip()
text = ' java programming is Fun '
print(text + '---')
print(text.strip())
print(text.lstrip() )
print(text.rstrip() + '---')
| true
|
b55dbe1c09f1f37308ab23697e81fd9241f76adc
|
Python
|
robgoyal/BookSolutions
|
/PracticalProgramming/Chapter15/code_samples.py
|
UTF-8
| 450
| 3.4375
| 3
|
[] |
no_license
|
def double_preceding(values):
if values != []:
temp = values[0]
values[0] = 0
for i in range(1, len(values)):
double = 2 * temp
temp = values[i]
values[i] = double
def average(values):
count, total = 0, 0
for value in values:
if value is not None:
total += value
count += 1
if count == 0:
return total
return total / count
| true
|
493c343957b9e6ba6560ef8c8950083e77313792
|
Python
|
kitakou0313/cracking-the-code-interview
|
/cracking-the-code-interview/chap3_3.py
|
UTF-8
| 1,534
| 3.65625
| 4
|
[] |
no_license
|
import unittest
# 固定版で実装
class MultiStack():
def __init__(self, capacity):
self.stacks = [[]]
self.capacity = capacity
def push(self, val):
if len(self.stacks[-1]) == self.capacity:
self.stacks.append([])
self.stacks[-1].append(val)
def pop(self):
havingStackInd = -1
while not(havingStackInd == -len(self.stacks) or len(self.stacks[havingStackInd]) != 0):
havingStackInd -= 1
return self.stacks[havingStackInd].pop() if len(self.stacks[havingStackInd]) != 0 else None
def pop_at(self, stackAt):
return self.stacks[stackAt].pop() if len(self.stacks[stackAt]) != 0 else None
class Test(unittest.TestCase):
def test_multi_stack(self):
stack = MultiStack(3)
stack.push(11)
stack.push(22)
stack.push(33)
stack.push(44)
stack.push(55)
stack.push(66)
stack.push(77)
stack.push(88)
self.assertEqual(stack.pop(), 88)
self.assertEqual(stack.pop_at(1), 66)
self.assertEqual(stack.pop_at(0), 33)
self.assertEqual(stack.pop_at(1), 55)
self.assertEqual(stack.pop_at(1), 44)
self.assertEqual(stack.pop_at(1), None)
stack.push(99)
self.assertEqual(stack.pop(), 99)
self.assertEqual(stack.pop(), 77)
self.assertEqual(stack.pop(), 22)
self.assertEqual(stack.pop(), 11)
self.assertEqual(stack.pop(), None)
if __name__ == "__main__":
unittest.main()
| true
|
012955a73c2d0d14c1196f517ea076df37876a99
|
Python
|
mdhvkothari/Python-Program
|
/leetCode/Single Number III.py
|
UTF-8
| 348
| 3.015625
| 3
|
[] |
no_license
|
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
dict = {}
result= []
for num in nums:
if num in dict:
dict[num] +=1
else:
dict[num] = 1
for i in dict:
if dict[i] == 1:
result.append(i)
return result
| true
|
554d6649ff94bd88b17fe2a56ab6b943e374f8fe
|
Python
|
biswasalex410/Python_1st_Part_Subeen_Book
|
/list add & multiplication operation.py
|
UTF-8
| 241
| 3.6875
| 4
|
[] |
no_license
|
li1 = [1, 2, 3]
li2 = [4, 5, 6]
li = li1 + li2
print(li)
li1 = [1, 2, 3]
li2 = li1 * 3
print(li2)
li = ["a", "b", "c"]
print(li)
str = "".join(li)
print(str)
str = ",".join(li)
print(str)
str = "-".join(li)
print(str)
| true
|
d3b72b72c5387ede0d708e9dc0d157a850209558
|
Python
|
aelkikhia/portal
|
/portal/input/jsonstream.py
|
UTF-8
| 2,660
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
from portal.input.jsonep import JsonEventHandler, JsonEventParser
class JsonMessageHandler(object):
def header(self, key, value):
pass
def body(self, body):
pass
MESSAGE_ROOT = 1
class JsonMessageAssembler(JsonEventHandler):
def __init__(self, message_handler):
self.message_handler = message_handler
self.tree_depth = 0
self.object_stack = list()
self.component_name = None
self.reading_headers = True
self.current_field = None
self.current_object = None
self.string_buffer = ''
def _pop_tree(self):
finished = self.object_stack.pop()
if self.object_stack:
self.current_object = self.object_stack[-1]
if self._in_message_root():
self._hand_off(finished)
def _assign(self, tree_object):
if self.current_field is not None:
self.current_object[self.current_field] = tree_object
self.current_field = None
else:
self.current_object.append(tree_object)
def _in_message_root(self):
return len(self.object_stack) == MESSAGE_ROOT
def _hand_off(self, message):
if self.reading_headers:
self.message_handler.header(self.component_name, message)
else:
self.message_handler.body(message)
def begin_object(self):
tree_object = dict()
if self.object_stack:
self._assign(tree_object)
else:
self.reading_headers = True
self.object_stack.append(tree_object)
self.current_object = tree_object
def end_object(self):
self._pop_tree()
def begin_array(self):
tree_object = list()
if self.object_stack:
self._assign(tree_object)
else:
raise Exception('A JSON stream message may not begin with an array.')
self.object_stack.append(tree_object)
self.current_object = tree_object
def end_array(self):
self._pop_tree()
def fieldname(self, name):
if self._in_message_root():
if name == 'body':
self.reading_headers = False
self.component_name = name
self.current_field = name
def string_value_part(self, string):
self.string_buffer += string
def string_value_end(self, string):
self.string_value_part(string)
self._assign(self.string_buffer)
self.string_buffer = ''
def number_value(self, value):
self._assign(value)
def boolean_value(self, value):
self._assign(value)
def null_value(self):
self._assign(None)
| true
|
4f9635d60dcda56f2e1bad747cf280facea897e2
|
Python
|
christmo/zari
|
/functions/telegram/impl.py
|
UTF-8
| 8,223
| 2.515625
| 3
|
[] |
no_license
|
from services.sentimiento import Sentimiento
from telegram.productos import consultar_productos, menu_productos, promociones, validar_parametros_producto
from database.command import limpiar_carrito, pagar_carrito
from database.persitencia import save_shopping_car, save_tarjeta_usuario, save_usuario
from entities.df_context import get_carrito_context, get_user_context
from entities.df_request import get_name, get_parameter, get_product_from_params, get_username_telegram, get_product_from_params, user_parameters
from entities.df_response import DFResponse
from database import consultas as query
from entities.usuario import Usuario
def saludo(request):
"""
Procesa la respuesta del Intent Welcome de saludo
"""
response = DFResponse(request)
bot_response = request["queryResult"]["fulfillmentText"]
name = get_name(request)
username = get_username_telegram(request)
print(f"username: {username}")
if username != None:
usuario = query.usuario(username)
if usuario != None and len(usuario.get_nombre()) > 1:
response.text(bot_response.replace('{name}', usuario.get_nombre()))
response.context_usuario(usuario)
return response.to_json()
nombre = name if name != None else username
response.text(bot_response.replace('{name}', nombre))
return response.to_json()
def agregar_producto(request):
"""
Agregar producto al carrito de compras
"""
response = DFResponse(request)
user = get_user_context(request)
if user != None:
producto = get_product_from_params(request)
car = save_shopping_car(user, producto)
response.text(
f"Productos en el carrito {len(car.detalles)} por un total de {car.total}€")
response.context_shoppingcar(car)
response.inline_buttons("🤔 Te puedo llevar a ", [
"💶 Pagar", "🛒 Ver Carrito"])
else:
print('Enviar a registrar al cliente')
response.text(
"Necesitamos registrarte como usuario para agregar productos a tu carrito, "
"completa las preguntas para poderte dar mejores recomendaciones "
"y ajustar las búsquedas a tu información solo tardará 1 minuto."
'\n\nPara empezar tu registro dime "zari agregame como cliente"'
'\n(Si al iniciar no quieres continuar siempre me puedes decir "cancelar" y detendré las preguntas)'
)
response.inline_buttons("🤔 Te puedo llevar a ", [
"📄 Registrarte", "🛍️ Promociones"])
return response.to_json()
def eliminar_carrito(request):
"""
Proceso para desactivar el carrito de compras enviado, y generar uno nuevo
"""
response = DFResponse(request)
car = get_carrito_context(request)
result = limpiar_carrito(car.id_car)
if result:
response.text(
"Carrito de compras listo para recibir nuevos productos!")
else:
response.text(
"Tu carrito de compras no se ha podido limpiar, intenta nuevamente!")
return response.to_json()
def consultar_carrito(request):
"""
Consultar los productos del carrito y el total a pagar
"""
response = DFResponse(request)
user = get_user_context(request)
if user != None:
productos = query.shopping_cart(user)
response.shopping_cart_text(productos)
response.inline_buttons("🤔 Te puedo llevar a ",
["🛒 Limpiar Carrito", "💶 Pagar"])
else:
response.register_event()
return response.to_json()
def tarjetas(request):
"""
Consultar las tarjetas del cliente para el pago
"""
response = DFResponse(request)
user = get_user_context(request)
if user != None:
user = query.tarjetas(user)
if len(user.get_tarjetas()) > 0:
response.quick_replies(
'Con que tarjeta quieres pagar?',
user.get_tarjetas()
)
else:
response.register_card_event(user)
else:
response.register_event()
return response.to_json()
def comprar(request):
"""
Proceso para comprar todos los productos del carrito
"""
response = DFResponse(request)
user = get_user_context(request)
if user != None:
orden = pagar_carrito(user)
if orden != None:
tarjeta = get_parameter(request, 'tarjeta')
response.text(
f"Se ha procesado el pago con tú tarjeta terminada en {tarjeta}, "
f"el número de orden es {orden.carrito}, tus productos se entregarán el {orden.fecha_formateada()} "
f"en tu dirección registrada: {orden.direccion}"
)
response.inline_buttons("🤔 Si quieres puedes calificarme: ",
["⭐ Experiencia", "🛍️ Promociones"])
else:
response.text("No haz agregado nada a tu carrito, no se hizo ningún cargo a tu tarjeta.")
else:
response.register_event()
return response.to_json()
def registrar_usuario(request):
"""
Registrar Usuario en el sistema
"""
response = DFResponse(request)
user = user_parameters(request)
user = save_usuario(user)
usuario = Usuario.parse_usuario(user)
response.context_usuario(usuario)
response.text(
"Genial, ahora puedes agregar productos a tu carrito!!!"
)
response.inline_buttons("🤔 Te puedo llevar a",
["🛍️ Promociones"])
return response.to_json()
def feedback_sentimiento(request):
response = DFResponse(request)
comentario = get_parameter(request, 'comentario')
sentimiento = Sentimiento(comentario)
resultado = sentimiento.clasificar()
if resultado == 'positivo':
response.sentimiento_positivo_event()
if resultado == 'negativo':
response.sentimiento_negativo_event()
if resultado == 'neutro':
response.sentimiento_neutro_event()
print(f"sentimiento: {resultado}")
return response.to_json()
def registrar_tarjeta(request):
"""
Registrar tarjeta del usuario
"""
response = DFResponse(request)
user = get_user_context(request)
tarjeta = get_parameter(request, 'tarjeta')
save_tarjeta_usuario(user, tarjeta)
response.text(
"Genial, ahora ya puedes pagar lo que quieras con tu tarjeta!!!"
)
return response.to_json()
def gateway(request):
"""
Unifica la salida de los intents procesados con Webhook Telegram
"""
response = ""
if request["queryResult"]["intent"] != None:
intent = request["queryResult"]["intent"]["displayName"]
print(f"Intent invocado Telegram: {intent}")
if intent == "Welcome":
response = saludo(request)
if intent == "AgregarProducto":
response = agregar_producto(request)
if intent == "EliminarCarrito":
response = eliminar_carrito(request)
if intent == "VerCarrito":
response = consultar_carrito(request)
if intent == "Comprar":
response = tarjetas(request)
if intent == "Comprar-tarjeta":
response = comprar(request)
if intent == "Comprar-registrar-tarjeta":
response = registrar_tarjeta(request)
if intent == "RegistrarUsuario":
response = registrar_usuario(request)
if intent == "SolicitarProducto" or intent == "parametros-producto-talla" \
or intent == "parametros-producto-numero" or intent == "producto-root":
response = consultar_productos(request)
if intent == "parametros-producto":
response = validar_parametros_producto(request)
if intent == "Productos" or intent == "Ayuda":
response = menu_productos(request)
if intent == "Productos":
response = menu_productos(request)
if intent == "Experiencia-sentimiento":
response = feedback_sentimiento(request)
if intent == "Promociones":
response = promociones(request)
return response
| true
|
014225a5be06a12304a51d388792de2dca7a911a
|
Python
|
big0ren/MalwareInvestigationTool
|
/Services/TimerCountDown.py
|
UTF-8
| 156
| 2.921875
| 3
|
[] |
no_license
|
import time
for t in range(120,-1,-1):
minutes = t / 60
seconds = t % 60
print "%d:%2d" % (minutes,seconds) # Python v2 only
time.sleep(1.0)
| true
|
a6cb4bd1c560abaad1a0deaffc2214891c6453fa
|
Python
|
aqlaboratory/openfold
|
/openfold/model/embedders.py
|
UTF-8
| 9,577
| 2.53125
| 3
|
[
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive",
"CC-BY-NC-4.0"
] |
permissive
|
# Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch.nn as nn
from typing import Tuple, Optional
from openfold.model.primitives import Linear, LayerNorm
from openfold.utils.tensor_utils import add, one_hot
class InputEmbedder(nn.Module):
"""
Embeds a subset of the input features.
Implements Algorithms 3 (InputEmbedder) and 4 (relpos).
"""
def __init__(
self,
tf_dim: int,
msa_dim: int,
c_z: int,
c_m: int,
relpos_k: int,
**kwargs,
):
"""
Args:
tf_dim:
Final dimension of the target features
msa_dim:
Final dimension of the MSA features
c_z:
Pair embedding dimension
c_m:
MSA embedding dimension
relpos_k:
Window size used in relative positional encoding
"""
super(InputEmbedder, self).__init__()
self.tf_dim = tf_dim
self.msa_dim = msa_dim
self.c_z = c_z
self.c_m = c_m
self.linear_tf_z_i = Linear(tf_dim, c_z)
self.linear_tf_z_j = Linear(tf_dim, c_z)
self.linear_tf_m = Linear(tf_dim, c_m)
self.linear_msa_m = Linear(msa_dim, c_m)
# RPE stuff
self.relpos_k = relpos_k
self.no_bins = 2 * relpos_k + 1
self.linear_relpos = Linear(self.no_bins, c_z)
def relpos(self, ri: torch.Tensor):
"""
Computes relative positional encodings
Implements Algorithm 4.
Args:
ri:
"residue_index" features of shape [*, N]
"""
d = ri[..., None] - ri[..., None, :]
boundaries = torch.arange(
start=-self.relpos_k, end=self.relpos_k + 1, device=d.device
)
reshaped_bins = boundaries.view(((1,) * len(d.shape)) + (len(boundaries),))
d = d[..., None] - reshaped_bins
d = torch.abs(d)
d = torch.argmin(d, dim=-1)
d = nn.functional.one_hot(d, num_classes=len(boundaries)).float()
d = d.to(ri.dtype)
return self.linear_relpos(d)
def forward(
self,
tf: torch.Tensor,
ri: torch.Tensor,
msa: torch.Tensor,
inplace_safe: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
tf:
"target_feat" features of shape [*, N_res, tf_dim]
ri:
"residue_index" features of shape [*, N_res]
msa:
"msa_feat" features of shape [*, N_clust, N_res, msa_dim]
Returns:
msa_emb:
[*, N_clust, N_res, C_m] MSA embedding
pair_emb:
[*, N_res, N_res, C_z] pair embedding
"""
# [*, N_res, c_z]
tf_emb_i = self.linear_tf_z_i(tf)
tf_emb_j = self.linear_tf_z_j(tf)
# [*, N_res, N_res, c_z]
pair_emb = self.relpos(ri.type(tf_emb_i.dtype))
pair_emb = add(pair_emb,
tf_emb_i[..., None, :],
inplace=inplace_safe
)
pair_emb = add(pair_emb,
tf_emb_j[..., None, :, :],
inplace=inplace_safe
)
# [*, N_clust, N_res, c_m]
n_clust = msa.shape[-3]
tf_m = (
self.linear_tf_m(tf)
.unsqueeze(-3)
.expand(((-1,) * len(tf.shape[:-2]) + (n_clust, -1, -1)))
)
msa_emb = self.linear_msa_m(msa) + tf_m
return msa_emb, pair_emb
class RecyclingEmbedder(nn.Module):
"""
Embeds the output of an iteration of the model for recycling.
Implements Algorithm 32.
"""
def __init__(
self,
c_m: int,
c_z: int,
min_bin: float,
max_bin: float,
no_bins: int,
inf: float = 1e8,
**kwargs,
):
"""
Args:
c_m:
MSA channel dimension
c_z:
Pair embedding channel dimension
min_bin:
Smallest distogram bin (Angstroms)
max_bin:
Largest distogram bin (Angstroms)
no_bins:
Number of distogram bins
"""
super(RecyclingEmbedder, self).__init__()
self.c_m = c_m
self.c_z = c_z
self.min_bin = min_bin
self.max_bin = max_bin
self.no_bins = no_bins
self.inf = inf
self.linear = Linear(self.no_bins, self.c_z)
self.layer_norm_m = LayerNorm(self.c_m)
self.layer_norm_z = LayerNorm(self.c_z)
def forward(
self,
m: torch.Tensor,
z: torch.Tensor,
x: torch.Tensor,
inplace_safe: bool = False,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
m:
First row of the MSA embedding. [*, N_res, C_m]
z:
[*, N_res, N_res, C_z] pair embedding
x:
[*, N_res, 3] predicted C_beta coordinates
Returns:
m:
[*, N_res, C_m] MSA embedding update
z:
[*, N_res, N_res, C_z] pair embedding update
"""
# [*, N, C_m]
m_update = self.layer_norm_m(m)
if(inplace_safe):
m.copy_(m_update)
m_update = m
# [*, N, N, C_z]
z_update = self.layer_norm_z(z)
if(inplace_safe):
z.copy_(z_update)
z_update = z
# This squared method might become problematic in FP16 mode.
bins = torch.linspace(
self.min_bin,
self.max_bin,
self.no_bins,
dtype=x.dtype,
device=x.device,
requires_grad=False,
)
squared_bins = bins ** 2
upper = torch.cat(
[squared_bins[1:], squared_bins.new_tensor([self.inf])], dim=-1
)
d = torch.sum(
(x[..., None, :] - x[..., None, :, :]) ** 2, dim=-1, keepdims=True
)
# [*, N, N, no_bins]
d = ((d > squared_bins) * (d < upper)).type(x.dtype)
# [*, N, N, C_z]
d = self.linear(d)
z_update = add(z_update, d, inplace_safe)
return m_update, z_update
class TemplateAngleEmbedder(nn.Module):
"""
Embeds the "template_angle_feat" feature.
Implements Algorithm 2, line 7.
"""
def __init__(
self,
c_in: int,
c_out: int,
**kwargs,
):
"""
Args:
c_in:
Final dimension of "template_angle_feat"
c_out:
Output channel dimension
"""
super(TemplateAngleEmbedder, self).__init__()
self.c_out = c_out
self.c_in = c_in
self.linear_1 = Linear(self.c_in, self.c_out, init="relu")
self.relu = nn.ReLU()
self.linear_2 = Linear(self.c_out, self.c_out, init="relu")
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: [*, N_templ, N_res, c_in] "template_angle_feat" features
Returns:
x: [*, N_templ, N_res, C_out] embedding
"""
x = self.linear_1(x)
x = self.relu(x)
x = self.linear_2(x)
return x
class TemplatePairEmbedder(nn.Module):
"""
Embeds "template_pair_feat" features.
Implements Algorithm 2, line 9.
"""
def __init__(
self,
c_in: int,
c_out: int,
**kwargs,
):
"""
Args:
c_in:
c_out:
Output channel dimension
"""
super(TemplatePairEmbedder, self).__init__()
self.c_in = c_in
self.c_out = c_out
# Despite there being no relu nearby, the source uses that initializer
self.linear = Linear(self.c_in, self.c_out, init="relu")
def forward(
self,
x: torch.Tensor,
) -> torch.Tensor:
"""
Args:
x:
[*, C_in] input tensor
Returns:
[*, C_out] output tensor
"""
x = self.linear(x)
return x
class ExtraMSAEmbedder(nn.Module):
"""
Embeds unclustered MSA sequences.
Implements Algorithm 2, line 15
"""
def __init__(
self,
c_in: int,
c_out: int,
**kwargs,
):
"""
Args:
c_in:
Input channel dimension
c_out:
Output channel dimension
"""
super(ExtraMSAEmbedder, self).__init__()
self.c_in = c_in
self.c_out = c_out
self.linear = Linear(self.c_in, self.c_out)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x:
[*, N_extra_seq, N_res, C_in] "extra_msa_feat" features
Returns:
[*, N_extra_seq, N_res, C_out] embedding
"""
x = self.linear(x)
return x
| true
|
476ac0415ea078851ddaf5e0a1af5e9d0c794735
|
Python
|
AJaafer/1.Python-Tutorial-for-Beginners-Full-Course-2019
|
/36.Return statement.py
|
UTF-8
| 64
| 2.859375
| 3
|
[] |
no_license
|
def square(number):
return number * number
print(square(9))
| true
|
14cc623fd920cb20d689d5306a0f72ef6dc6d96b
|
Python
|
WPrendota/WordFrequencyFaster
|
/word_frequency_faster.py
|
UTF-8
| 1,771
| 3.359375
| 3
|
[] |
no_license
|
import time
from argparse import ArgumentParser
from OperationsOnLinesInDocument import OperationsOnLinesInDocument
from OperationsOnWordsInDocument import OperationsOnWordsInDocument
# Main function
def main(args):
if args.w:
if args.p:
oow = OperationsOnWordsInDocument(args.w, 'utf8')
for word in oow.file_frequency_word():
print(word)
if args.c:
oow = OperationsOnWordsInDocument(args.w, 'utf8')
print(oow.file_frequency_word())
if not args.c and not args.p:
oow = OperationsOnWordsInDocument(args.w, 'utf8')
print(oow.file_word_counter())
if args.l:
ool = OperationsOnLinesInDocument(args.l, "utf8")
print(ool.file_line_counter())
# Argument Parser:
def arg_pars():
parser = ArgumentParser(description='Text document finder.')
parser.add_argument('-w', type=str,
help='Print number of all words from a text document with utf8 encoding. Usage: [-w][file_name]')
parser.add_argument('-p', action='store_true',
help='Print all words from word searcher. Usage: [-w][file_name][-p]')
parser.add_argument('-c', action='store_true',
help='Print all words with frequency from word searcher. Usage: [-w][file_name][-c]')
parser.add_argument('-l',
help='Print number of all lines from a text document with utf8 encoding. Usage: [-l][file_name]')
return parser.parse_args()
if __name__ == "__main__":
start_time = time.time()
main(arg_pars()) #Parsed arguments are moved to main function.
elapsed_time = time.time() - start_time
print(elapsed_time) #Printing time of program running.
| true
|
e67f358d4d81278dced18c52effc9650aad3c94c
|
Python
|
Pavlmir/python-basics-geekbr
|
/Lesson_2_types_and_operations/les_2_task2.py
|
UTF-8
| 946
| 4.4375
| 4
|
[] |
no_license
|
# 2. Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
array = []
for i in range(1, 10):
array.append(int(input(f"Введите - {i}-ое значение списка: ")))
print(f"Текущий список - {array}")
if len(array) % 2 == 0:
len_array = len(array) # четное
else:
len_array = len(array) - 1 # нечетное
for i in range(0, len_array, 2):
x = array[i]
array[i] = array[i + 1]
array[i + 1] = x
print(f"Итоговый список - {array}")
| true
|
d9d381b1ecbc86e933c63274a9945fa8ba4e1914
|
Python
|
shivasitharaman/python
|
/py3.py
|
UTF-8
| 116
| 3.625
| 4
|
[] |
no_license
|
num1 = 50
num2 = 3
div = int(num1) / int(num2)
print('The div of {0} and {1} is {2}'.format(num1, num2, div))
| true
|
0e1fd7888fb2d3c6d5de7415812ab928d475006d
|
Python
|
apple/swift-lldb
|
/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py
|
UTF-8
| 2,515
| 2.546875
| 3
|
[
"NCSA",
"Apache-2.0",
"LLVM-exception"
] |
permissive
|
"""
Test SBBreakpoint APIs.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class BreakpointAPITestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = True
@add_test_categories(['pyapi'])
def test_breakpoint_is_valid(self):
"""Make sure that if an SBBreakpoint gets deleted its IsValid returns false."""
self.build()
exe = self.getBuildArtifact("a.out")
# Create a target by the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Now create a breakpoint on main.c by name 'AFunction'.
breakpoint = target.BreakpointCreateByName('AFunction', 'a.out')
#print("breakpoint:", breakpoint)
self.assertTrue(breakpoint and
breakpoint.GetNumLocations() == 1,
VALID_BREAKPOINT)
# Now delete it:
did_delete = target.BreakpointDelete(breakpoint.GetID())
self.assertTrue(
did_delete,
"Did delete the breakpoint we just created.")
# Make sure we can't find it:
del_bkpt = target.FindBreakpointByID(breakpoint.GetID())
self.assertTrue(not del_bkpt, "We did delete the breakpoint.")
# Finally make sure the original breakpoint is no longer valid.
self.assertTrue(
not breakpoint,
"Breakpoint we deleted is no longer valid.")
@add_test_categories(['pyapi'])
def test_target_delete(self):
"""Make sure that if an SBTarget gets deleted the associated
Breakpoint's IsValid returns false."""
self.build()
exe = self.getBuildArtifact("a.out")
# Create a target by the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Now create a breakpoint on main.c by name 'AFunction'.
breakpoint = target.BreakpointCreateByName('AFunction', 'a.out')
#print("breakpoint:", breakpoint)
self.assertTrue(breakpoint and
breakpoint.GetNumLocations() == 1,
VALID_BREAKPOINT)
location = breakpoint.GetLocationAtIndex(0)
self.assertTrue(location.IsValid())
self.assertTrue(self.dbg.DeleteTarget(target))
self.assertFalse(breakpoint.IsValid())
self.assertFalse(location.IsValid())
| true
|
4012b602f23e219e9757d4c121b7f60975930d95
|
Python
|
KBIbiopharma/pybleau
|
/pybleau/reporting/dash_reporter.py
|
UTF-8
| 3,034
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
""" Class to drive the generation of a data report using Dash as the backend.
"""
import logging
from uuid import uuid4
from flask import Flask
import dash
import dash_html_components as html
from traits.api import Any, Bool, Int, List, Str
from .base_reporter import BaseReporter
from .section_report_element import SectionReportElement
from .image_report_element import ImageReportElement
logger = logging.getLogger(__name__)
class DashReporter(BaseReporter):
""" Base reporter object to generate a report targeting a specific backend.
"""
#: Flask WSGI application dash builds on
flask_app = Any
#: Dash top-level application object
dash_app = Any
#: Port to serve the fask application on
port = Int(8053)
#: List of CSS style sheets to style the web app
stylesheets = List
#: Whether to require authentication to access the webapp
include_auth = Bool(False)
# BaseReport attributes ---------------------------------------------------
#: Backend for the reporter
backend = Str("dash")
#: Title of the report
report_title = Str("New Dash Report")
def generate_report(self):
""" Initialize the report and insert all elements.
"""
self.initialize_report()
self.insert_report_elements()
def initialize_report(self):
""" Initialize the report by creating a Dash app, adding logo & title.
"""
self.dash_app = dash.Dash(
__name__, external_stylesheets=self.stylesheets,
server=self.flask_app
)
children = []
if self.report_logo:
report_logo_element = ImageReportElement(self.report_logo,
align="right").to_dash()
children.extend(report_logo_element)
if self.report_title:
title_element = SectionReportElement(self.report_title,
align='center').to_dash()
children.extend(title_element)
self.dash_app.layout = html.Div(children=children)
def insert_report_elements(self):
""" Insert all report elements specified.
"""
for element in self.report_elements:
app_elements = element.to_report(self.backend)
self.dash_app.layout.children.extend(app_elements)
def open_report(self):
""" Start the Dash server, and print server info.
"""
if self.include_auth:
import dash_auth
pw = str(uuid4())
logger.warning("Password for this session: {}".format(pw))
pass_pairs = [('jrocher', pw)]
dash_auth.BasicAuth(self.dash_app, pass_pairs)
self.dash_app.run_server(debug=True, port=self.port)
# Traits initialization methods -------------------------------------------
def _stylesheets_default(self):
return ['https://codepen.io/chriddyp/pen/bWLwgP.css']
def _flask_app_default(self):
return Flask(__name__)
| true
|
0289b816d0951aa76680a287a0252c9f7c41f46a
|
Python
|
didwns7347/algotest
|
/알고리즘문제/16566 카드게임 DFS.py
|
UTF-8
| 280
| 2.625
| 3
|
[] |
no_license
|
n,m,k = map(int,input().split())
card=list(map(int,input().split()))
draw=list(map(int,input().split()))
check=[0 for _ in range(n+1)]
def find(node):
if check[node]==0:
check[node]=1
return node
return find(node+1)
for num in draw:
print(find(num+1))
| true
|
bb9aadca4fb1595eb49bd805655e004cc013d9e9
|
Python
|
Aprameyo/Competitive-Programming
|
/CodeChef/ZCO Contest/ZCO14003.py
|
UTF-8
| 378
| 2.75
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 8 22:48:10 2020
@author: Aprameyo
"""
import numpy as np
Solution = []
SolSpace = []
N = int(input())
for i in range(0,N):
temp = int(input())
Solution.append(temp)
Solution_2 = sorted(Solution)
for i in range(0,N):
Solution_2[i] = Solution_2[i]*(N-i)
ans = max(Solution_2)
print(ans)
| true
|
7da19d189ed2b9adf61011dc96d4c76adc82f347
|
Python
|
toshiakiasakura/rakutto_collect_project
|
/prj_input/pyqt5_basic/dist_gui/developing/3_exp_dist.py
|
UTF-8
| 5,882
| 2.609375
| 3
|
[] |
no_license
|
# usr/bin/python3
# coding:utf-8
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from PyQt5 import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import glob
from PIL import Image
from scipy.stats import norm
from scipy.stats import expon
def GetNDigit(v,n = 5):
v = str(v)
if len(v.replace(".","")) < n + 1:
return(v)
else:
ind = 0
s = ""
for i in range(1000):
if v[i] == "." :
s += v[i]
continue
else:
s += v[i]
ind += 1
if ind >= n:
return(s)
class Application(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.initFigure()
self.UpdateFigure()
self.initSlidebar()
# initialize UI
def initUI(self):
# For FigureWidget
self.FigureWidget = QtWidgets.QWidget(self)
# make FigureLayout. This FigureLayout will be added by vbox.
self.FigureLayout = QtWidgets.QVBoxLayout(self.FigureWidget)
# delett margin
self.FigureLayout.setContentsMargins(0,0,0,0)
self.FileList = QtWidgets.QListWidget(self)
# make ButtonsLayout
self.ButtonWidget = QtWidgets.QWidget(self)
self.SubWidget = QtWidgets.QWidget(self)
# alinment
self.setGeometry(0,0,900,600)
self.FigureWidget.setGeometry(200,0,500,500)
self.ButtonWidget.setGeometry(200,500,500,100)
self.SubWidget.setGeometry(700,0,200,600)
self.FileList.setGeometry(0,0,200,600)
def initFigure(self):
# make Figure
self.Figure = plt.figure()
# add Figure to FigureCanvas
self.FigureCanvas = FigureCanvas(self.Figure)
# add FigureCanvas to Layout
self.FigureLayout.addWidget(self.FigureCanvas)
self.axis = self.Figure.add_subplot(1,1,1)
self.axis.plot([1,2],[2,3])
self.show()
def initSlidebar(self):
self.inputLine = QtWidgets.QLineEdit()
self.outputLine = QtWidgets.QLineEdit()
self.outputLine.setReadOnly(True)
UpdateButton= QtWidgets.QPushButton("Update")
UpdateButton.clicked.connect(self.UpdateGraph)
UpdateButton.clicked.connect(self.GetResults)
lineLayout = QtWidgets.QGridLayout()
lineLayout.addWidget(QtWidgets.QLabel("tau"),0,0)
lineLayout.addWidget(self.inputLine,0,1)
lineLayout.addWidget(QtWidgets.QLabel("mean"),1,0)
lineLayout.addWidget(self.outputLine,1,1)
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(UpdateButton)
buttonsLayout = QtWidgets.QHBoxLayout(self.ButtonWidget)
buttonsLayout.addLayout(lineLayout)
buttonsLayout.addLayout(vbox)
#### for subwidget results #####
self.MeanDisplay = QtWidgets.QLineEdit()
self.VarianceDisplay = QtWidgets.QLineEdit()
self.MedianDisplay = QtWidgets.QLineEdit()
SubLineLayout = QtWidgets.QGridLayout()
SubLineLayout.addWidget(QtWidgets.QLabel("mean"),0,0)
SubLineLayout.addWidget(self.MeanDisplay,0,1)
SubLineLayout.addWidget(QtWidgets.QLabel("variance"),1,0)
SubLineLayout.addWidget(self.VarianceDisplay,1,1)
SubLineLayout.addWidget(QtWidgets.QLabel("Median"),2,0)
SubLineLayout.addWidget(self.MedianDisplay,2,1)
self.SubWidgetLayout = QtWidgets.QVBoxLayout(self.SubWidget)
self.SubWidgetLayout.addLayout(SubLineLayout)
def UpdateFigure(self):
# delete previous figure
self.FigureLayout.takeAt(0)
self.Figure = plt.figure()
self.axis = self.Figure.add_subplot(1,1,1)
self.axis.plot([1,4],[4,1])
self.show()
self.FigureCanvas = FigureCanvas(self.Figure)
self.FigureLayout.addWidget(self.FigureCanvas)
def UpdateGraph(self):
# delete previous figure
self.FigureLayout.takeAt(0)
# release memory not to be heavy,and make figure
plt.clf()
self.Figure = plt.figure()
# get random numbers from normal distribution
text = self.inputLine.text()
try:
tau = float(text)
except:
QtWidgets.QMessageBox.about(self,"Error","Error Message\nput a value to parameter")
return(0)
ex = expon(scale=tau)
x = np.linspace(ex.ppf(0.05),ex.ppf(0.95),1000)
y = ex.pdf(x)
# show the graph
self.axis = self.Figure.add_subplot(1,1,1)
self.axis.plot(x,y)
self.axis.set_title("Exponential distribution")
self.axis.set_xlabel(r"$\frac{1}{\tau}e^{-\frac{x}{tau}}$ ")
self.show()
self.FigureCanvas = FigureCanvas(self.Figure)
self.FigureLayout.addWidget(self.FigureCanvas)
def GetResults(self):
text = self.inputLine.text()
try:
tau = float(text)
except:
QtWidgets.QMessageBox.about(self,"Error","Error Message\nput a value to parameter")
return(0)
self.MeanDisplay.setText(GetNDigit( tau))
self.VarianceDisplay.setText(GetNDigit(tau**2))
self.MedianDisplay.setText(GetNDigit(tau*np.log(2)))
#this function is for reference
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
if __name__=="__main__":
app = QtWidgets.QApplication(sys.argv)
qapp = Application()
qapp.show()
sys.exit(app.exec_())
| true
|
7703031c73034b5c0389d03e78073de020a52765
|
Python
|
paiv/synasm
|
/synasm/asm.py
|
UTF-8
| 4,032
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import ast
import array
import base64
import fileinput
import re
import sys
class SynasmError(Exception): pass
token_rx = re.compile(r'^\s*((?:\s*(?:\-?\'(?:\\.|[^\'])+\'|[^\s;]+))*?)\s*(?:;.*?)?\s*$', re.M)
label_rx = re.compile(r'^\s*(\w+\:)?\s*(.*?)\s*$', re.M)
def parse(text):
for tok in token_rx.findall(text):
for label,instr in label_rx.findall(tok):
if label:
yield ':' + label[:-1]
if instr:
yield instr
instr_rx = re.compile(r'^\s*(\w+)(.*?)\s*$')
args_rx = re.compile(r'\s+(\-?\'(?:\\.|[^\'])+\'|[:-]?\w+)')
op_table = {
# name: code, nargs
'halt': (0, 0),
'set': (1, 2),
'push': (2, 1),
'pop': (3, 1),
'eq': (4, 3),
'gt': (5, 3),
'jmp': (6, 1),
'jt': (7, 2),
'jf': (8, 2),
'add': (9, 3),
'mult': (10, 3),
'mod': (11, 3),
'and': (12, 3),
'or': (13, 3),
'not': (14, 2),
'rmem': (15, 2),
'wmem': (16, 2),
'call': (17, 1),
'ret': (18, 0),
'out': (19, 1),
'in': (20, 1),
'noop': (21, 0),
}
def unescape(s):
u = ast.literal_eval(s)
return u if isinstance(u, str) else s
def emit(asm, labels=None):
def arg(x):
if x[0] == '\'':
assert x[-1] == '\''
x = unescape(x)
if len(x) == 1:
x = ord(x)
return x
elif x[0] == ':':
if labels is not None:
if x in labels:
return labels[x]
raise SynasmError('{} label not defined'.format(asm))
return x
elif x[:2] == '-\'':
assert x[3] == '\''
return -ord(x[2]) % 32768
elif x.isalpha():
return ord(x) - ord('a') + 32768
else:
return int(x, 0) % 32768
def explode_str(code, i=1):
if i >= len(code):
yield code
elif isinstance(code[i], str) and code[i][0] != ':':
for x in code[i]:
for y in explode_str(code[:i] + (ord(x),) + code[i+1:], i + 1):
yield y
else:
for y in explode_str(code, i + 1):
yield y
name, args = instr_rx.findall(asm)[0]
args = tuple(arg(x) for x in args_rx.findall(args) if x)
op, n = op_table[name]
code = (op,) + args[:n]
if len(code) != n + 1:
raise SynasmError('{} {} takes {} arguments'.format(asm, name, n))
for x in explode_str(code):
yield x
def step1(lines):
if isinstance(lines, str):
lines = lines.splitlines()
return list(x for line in lines for x in parse(line))
def step2(ast):
labels = dict()
prog = []
for x in ast:
if x[0] == ':':
labels[x] = len(prog)
else:
prog.append(x)
return (prog, labels)
def step3(ast):
lines, labels = ast
asm = list(x for line in lines for x in emit(line))
runlen = []
size = 0
for instr in asm:
runlen.append(size)
size += len(instr)
runlen.append(size)
runlen.append(size)
labels = {l:runlen[i] for l,i in labels.items()}
asm = (x for line in lines for x in emit(line, labels))
return list(filter(None, asm))
def step4(asm):
raw = array.array('H', (x for instr in asm for x in instr))
if sys.byteorder != 'little':
raw.byteswap()
return raw
def assemble(text, verbose=False):
ast = step1(text)
ast = step2(ast)
raw = step3(ast)
if verbose:
sys.stderr.write('{} instructions\n'.format(len(raw)))
raw = step4(raw)
if verbose:
sys.stderr.write('{} bytes\n'.format(len(raw) * raw.itemsize))
return raw
def assemble_files(files, outfile, encode=False, verbose=False):
raw = assemble(fileinput.input(files), verbose=verbose)
if encode:
s = base64.b64encode(raw.tobytes())
w = 76
s = b'\n'.join(s[i:i+w] for i in range(0, len(s), w))
outfile.write(s + b'\n')
else:
raw.tofile(outfile)
| true
|
bdcba38282e5767bf6adf2da937f2fe6ec1eca3c
|
Python
|
1047465356/Spider_Armies
|
/爬取高匿名代理IP/快代理+百度api检测.py
|
UTF-8
| 2,559
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
# @Author : Aiden
# @Email : aidenlen@163.com
# @Time : 2020-3-11
from logging import exception
from os import write
import requests
from lxml import etree
import time
from fake_useragent import UserAgent
# 文件名
filename='proxy.txt'
# 代理容器
proxys_list = []
# 默认 True 开启代理检测(只生成可用proxy)
check = True
# 检测超时(秒)
timeout = 0.2
# 爬取总页数
total_page = 5
def scrape_url(page):
time.sleep(1)
print('\n===========正在爬取第{}页数据============'.format(page))
url = 'https://www.kuaidaili.com/free/inha/{}'.format(page)
headers = {'User-Agent': UserAgent(path='fake_useragent.json').random}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response
except Exception as e:
print('Exception: {}, url: {}'.format(e, url))
def parse_html(response):
tree = etree.HTML(response.text)
trs = tree.xpath('//*[@id="list"]/table/tbody/tr')
for tr in trs:
ip_num = tr.xpath('./td[1]/text()')[0]
ip_port = tr.xpath('./td[2]/text()')[0]
ip_proxy = ip_num + ':' + ip_port
if tr.xpath('./td[4]/text()')[0] == 'HTTP':
proxy = {'http': 'http://' + ip_proxy}
if tr.xpath('./td[4]/text()')[0] == 'HTTPS':
proxy = {'https': 'https://' + ip_proxy}
proxys_list.append(proxy)
return proxys_list
def check_ip(proxys):
print('\n===============开启检测================')
checked_proxys = []
for proxy in proxys:
try:
response = requests.get(url = 'https://www.baidu.com', proxies = proxy, timeout = timeout)
if response.status_code == 200:
checked_proxys.append(proxy)
except Exception as e:
print('Exception: {}, 检测不合格: {}'.format(e, proxy))
else:
print('检测合格: {}'.format(proxy))
return checked_proxys
def save_ip(proxys):
with open(filename, 'a', encoding='utf-8') as file:
for proxy in proxys:
file.write(str(proxy) + '\n')
print('保存成功: ', filename)
if __name__ == '__main__':
for page in range(1, total_page + 1):
response = scrape_url(page)
proxys = parse_html(response)
#print(proxys)
if check:
checked_proxys = check_ip(proxys)
save_ip(checked_proxys)
else:
save_ip(proxys)
| true
|
f2838a80ebc23f373df1263aa4d87ac12fee5c81
|
Python
|
ripssr/Code-Combat
|
/7_Sarven_Desert/273-Operation_Killdeer/killdeer.py
|
UTF-8
| 223
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
def shouldRun():
return hero.health < hero.maxHealth / 2
while True:
if shouldRun():
hero.moveXY(75, 37)
else:
enemy = hero.findNearestEnemy()
if (enemy):
hero.attack(enemy)
| true
|
841c1374df47c586be86f24746fa5eab50298a72
|
Python
|
burck1/tnt-battlesnake
|
/battlesnake/agent.py
|
UTF-8
| 3,862
| 2.6875
| 3
|
[] |
no_license
|
import json
import logging
import os
import time
from collections import deque
import numpy as np
import tensorflow as tf
from tensorflow.python.saved_model import loader
from .constants import Direction
from .snake import Snake
from .data_to_state import data_to_state
LOGGER = logging.getLogger("Agent")
class Agent(Snake):
def __init__(self, width: int, height: int, stacked_frames: int, path: str):
self.width = width
self.height = height
self.stacked_frames = stacked_frames
self.path = path
self.observation_ph, self.q_values = self._load_graph()
def _compute_actions(self, observation):
q_values = self.sess.run(self.q_values, {self.observation_ph: [observation]})[0]
actions = np.argsort(q_values)[::-1]
return actions
def _load_graph(self):
with tf.Graph().as_default() as graph:
self.sess = tf.Session(graph=graph)
loader.load(self.sess, [tf.saved_model.tag_constants.SERVING], self.path)
observation_ph = graph.get_tensor_by_name("snake_0/Placeholder:0")
q_values = graph.get_tensor_by_name("snake_0/q_func/Sum:0")
return observation_ph, q_values
def on_reset(self):
self.head_direction = Direction.up
self.frames = deque(
np.zeros([self.stacked_frames, self.width, self.height], dtype=np.uint8),
self.stacked_frames,
)
def get_direction(self, data):
state = data_to_state(self.width, self.height, data, self.head_direction)
self.frames.appendleft(state)
observation = np.moveaxis(self.frames, 0, -1)
actions = self._compute_actions(observation)
self.head_direction = self._find_best_action(actions, data)
if self.head_direction == Direction.up:
return "up"
elif self.head_direction == Direction.left:
return "left"
elif self.head_direction == Direction.down:
return "down"
else:
return "right"
def _find_best_action(self, actions, data):
head = data["you"]["body"][0]
head = [head["x"] + 1, head["y"] + 1]
directions = [self._get_direction(i) for i in actions]
next_coords = [self._get_next_head(direction, head) for direction in directions]
low_health = data["you"]["health"] <= 75
if low_health:
for direction, next_coord in zip(directions, next_coords):
coord_is_food = any(
[
np.array_equal(next_coord, [coord["x"], coord["y"]])
for coord in data["board"]["food"]
]
)
if coord_is_food:
return direction
for direction, next_coord in zip(directions, next_coords):
if not self._check_no_collision(next_coord, data):
return direction
else:
print("Avoided collision! Trying other directions...")
continue
print("Giving up!")
return directions[0]
def _check_no_collision(self, head, data):
collision = False
for s in data["board"]["snakes"]:
for body_idx, coord in enumerate(s["body"]):
coord = [coord["x"] + 1, coord["y"] + 1]
if s["id"] == data["you"]["id"] and body_idx == 0:
continue
else:
if np.array_equal(head, coord):
collision = True
snake_head_x, snake_head_y = head[0], head[1]
hit_wall = (
snake_head_x <= 0
or snake_head_y <= 0
or snake_head_x >= self.width - 1
or snake_head_y >= self.height - 1
)
if hit_wall:
collision = True
return collision
| true
|
b1c8e56382eaac478d32f3d0e1d765cf2decbf95
|
Python
|
rockshaker/leetcodeme
|
/026_remove_duplicates_from_sorted_array.py
|
UTF-8
| 381
| 3.078125
| 3
|
[] |
no_license
|
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
n = 0
for num in nums[1:]:
if num != nums[n]:
n += 1
nums[n] = num
return n + 1
s = Solution()
print s.removeDuplicates([1, 1, 2])
| true
|
b31facace3152d307c1f708642304336be82f643
|
Python
|
Lucas-JS/PLP
|
/Estruturado/olimpiadas.py
|
UTF-8
| 4,366
| 3.375
| 3
|
[] |
no_license
|
# Lucas de Jesus Silva - 20731356 - atividade 2 PLP - Estruturado
#=================================================================================================
# método para determinar vencedor do levantamento de pesos
def levantamentoPeso (x,y):
vencedor = ""
if x["peso"] > y["peso"]:
vencedor = x["nome"]
else:
vencedor = y["nome"]
print("Vencedor do levantamento de pesos: "+vencedor)
#=================================================================================================
# Método para determinar o vencedor do Judo:
def judo (x,y):
vencedor = ""
if x["ippon"] == True :
return "Vencedor do judo: " + x["nome"]
if y["ippon"] == True :
return "Vencedor do judo: " + y["nome"]
if x["wazari"] == y["wazari"] :
if x["yuko"] > y["yuko"] :
vencedor = x["nome"]
else:
vencedor = y["nome"]
if x["wazari"] > y["wazari"]:
vencedor = judocaX["nome"]
else:
vencedor = y["nome"]
return "Vencedor do judô: " + vencedor
#=================================================================================================
# O calculo do vencedor da modalidade de arremesso de pesos foi separado nos 3 proximos metodos
# encontra maior arremesso
def maiorArremesso(a,b,c):
maior = a;
if b > maior :
maior = b
if c > maior :
maior = c
return maior
# encontra segundo maior arremesso
def segundoMaior(a,b,c):
if a > b :
if c > a :
return a
if b > c :
return b
else :
if c > b :
return b
if a > c :
return a
return c
# determina vencedor do arremesso de pesos
def arremessoPesos (x, y):
vencedor = ""
xMaior = maiorArremesso(x["arr1"],x["arr2"],x["arr3"])
yMaior = maiorArremesso(y["arr1"],y["arr2"],y["arr3"])
xSegundo = segundoMaior(x["arr1"],x["arr2"],x["arr3"])
ySegundo = segundoMaior(y["arr1"],y["arr2"],y["arr3"])
if xMaior == yMaior:
if xSegundo > ySegundo:
vencedor = x["nome"]
else:
vencedor = y["nome"]
else:
if xMaior > yMaior:
vencedor = x["nome"]
else:
vencedor = y["nome"]
return "Vencedor do arremesso de pesos: "+vencedor
#=================================================================================================
# O calculo da vencedora da modalidade de ginastica artistica foi separado nos 4 proximos metodos
# encontra menor nota da ginasta para descarte
def menorNota(a,b,c,d,e):
menor = a
if b < menor :
menor = b
if c < menor :
menor = c
if d < menor :
menor = d
if e < menor :
menor = e
return menor;
# soma notas da ginasta para calculo da media
def somaNotas(a,b,c,d,e):
return a + b + c + d + e
# calcula media de ginasta, descartando menor nota
def mediaGinasta(a,b,c,d,e):
return (somaNotas(a,b,c,d,e) - menorNota(a,b,c,d,e))/4
# determina vencedora da ginastica artistica
def ginasticaArtistica(x,y):
vencedora = ""
mediaX = mediaGinasta(x["n1"],x["n2"],x["n3"],x["n4"],x["n5"])
mediaY = mediaGinasta(y["n1"],y["n2"],y["n3"],y["n4"],y["n5"])
if mediaX > mediaY :
vencedora = x["nome"]
else:
vencedora = y["nome"]
return "Vencedora da ginástica artística: "+vencedora
#=================================================================================================
# Levantamento de pesos
levantadorX = {"nome":"João","peso":310}
levantadorY = {"nome":"Carlos","peso":320}
levantamentoPeso(levantadorX,levantadorY)
#=================================================================================================
# Judo
judocaX = {"nome":"Thiago","ippon":False,"wazari":6,"yuko":10}
judocaY = {"nome":"Lucas","ippon":False,"wazari":5,"yuko":14}
print(judo(judocaX,judocaY))
#=================================================================================================
# Arremesso de pesos
arremessadorX = {"nome":"José","arr1":20.53,"arr2":21.9,"arr3":21.5}
arremessadorY = {"nome":"Luiz","arr1":20.78,"arr2":22.6,"arr3":22.7}
print(arremessoPesos(arremessadorX,arremessadorY))
#=================================================================================================
# Ginastica artistica
ginastaX = {"nome":"Beatriz","n1":9.5,"n2":9.0,"n3":9.1,"n4":8.75,"n5":8.8}
ginastaY = {"nome":"Lilian","n1":9.3,"n2":8.5,"n3":9.2,"n4":8.9,"n5":9.4}
print(ginasticaArtistica(ginastaX,ginastaY))
| true
|
7e3b857f7a07e28425edaa3f21cac527673635fb
|
Python
|
jackiboi307/cogpy
|
/examples/doublebuffer.py
|
UTF-8
| 369
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
from cogpy import *
from math import sin, cos # circle animation
from random import choice
screen = DoubleBufferCanvas((50, 25))
i = 0
while True:
# screen.fill(" ")
coords = (int(25 * (1 + sin(i))),
int(12 * (1 + cos(i))))
screen.draw.pixel(coords, choice(misc.ascii_shade_1))
screen.render(False)
i += .01
| true
|
f1849c76d329120bc502fde629914f3b230396f6
|
Python
|
yunabe/codelab
|
/google/gflags_example_test.py
|
UTF-8
| 4,561
| 2.875
| 3
|
[] |
no_license
|
import commands
import os
import sys
import unittest
class TestGflagsCppProgram(unittest.TestCase):
def testDefault(self):
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example'))
def testHelp(self):
helpOutput = commands.getoutput('./gflags_example --help')
self.assertTrue('-name (Username. Says hello to this user.) '
'type: string default: "world"' in helpOutput)
def testFlags(self):
self.assertEqual('Hello foo.',
commands.getoutput('./gflags_example --name=foo'))
self.assertEqual('Hello foo.',
commands.getoutput('./gflags_example --name foo'))
self.assertEqual('Hello foo.',
commands.getoutput('./gflags_example -name=foo'))
self.assertEqual('Hello foo.',
commands.getoutput('./gflags_example -name foo'))
def testBoolFlag(self):
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example --overwrite_name'))
def testPositiveBoolExpressions(self):
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=true'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=yes'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=t'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=y'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=1'))
def testNegativeBoolExpressions(self):
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--overwrite_name=false'))
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--overwrite_name=no'))
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--overwrite_name=f'))
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--overwrite_name=n'))
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--overwrite_name=0'))
def testBoolFlagWithNo(self):
# --no<bool_flag> works as --<bool_flag>=false
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example --nooverwrite_name'))
# The value for --no<bool_flag> seems to be ignored,
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--nooverwrite_name=true'))
self.assertEqual('Hello world.',
commands.getoutput('./gflags_example '
'--nooverwrite_name=false'))
def testBoolFlagCaseInsensitive(self):
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=T'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=Y'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=tRue'))
self.assertEqual('Hello %s.' % os.getlogin(),
commands.getoutput('./gflags_example '
'--overwrite_name=yEs'))
def testFlagValidator(self):
self.assertEqual('Hello 0123456789.',
commands.getoutput('./gflags_example '
'--name=0123456789'))
output = commands.getoutput('./gflags_example '
'--name=01234567890')
self.assertTrue('Value for --name: 01234567890 is too long.' in output)
if __name__ == '__main__':
unittest.main()
| true
|
db0975d89962afc9b06513802c0418284677562d
|
Python
|
sainathurankar/Python-programs
|
/BubbleSort.py
|
UTF-8
| 399
| 3.953125
| 4
|
[] |
no_license
|
def BubbleSort(arr):
l=len(arr)
for i in range(l):
flag=0
for j in range(l-1-i):
if arr[j]>arr[j+1]:
temp=arr[j]
arr[j]=arr[j+1]
arr[j+1]=temp
flag=1
if flag==0:break
arr=list(map(int,input("Enter array: ").split()))
BubbleSort(arr)
print("Sorted Array:",*arr)
| true
|
51df9bf116971974955a47e292912ae67a9e8d8b
|
Python
|
lixiang007666/Algorithm_LanQiao
|
/DP/dayday_up.py
|
UTF-8
| 827
| 2.625
| 3
|
[] |
no_license
|
import math
import cmath
import string
import sys
import bisect
import heapq
from queue import Queue, LifoQueue, PriorityQueue
from itertools import permutations, combinations
from collections import deque, Counter
from functools import cmp_to_key
if __name__ == "__main__":
dp = [[0 for _ in range(2005)] for _ in range(2005)]
n = int(input())
a = list(map(int, input().strip().split()))
ans = 0
i = n - 1
while i >= 0:
dp[i][1] = 1
for j in range(i + 1, n):#比i大1
if a[j] > a[i]:
k = 2# 长度
while 1:
if dp[j][k - 1] == 0:
break
dp[i][k] = dp[i][k] + dp[j][k - 1]
k += 1
i -= 1
for i in range(n):
ans += dp[i][4]
print(ans)
| true
|
7c5bb342a98be97fdb8a3949785abdd528ebc1fc
|
Python
|
biavidalf/beatriz-vidal-poo-python-ifce-p7
|
/Presença/atvd03_presenca.py
|
UTF-8
| 787
| 3.875
| 4
|
[] |
no_license
|
"""
ATIVIDADE 03 - PRESENÇA: POO - P7 DE INFO - BEATRIZ V.
ENUNCIADO: Para ganhar o prêmio máximo na Mega Sena, é necessário
acertar todos os 6 números em seu bilhete com os 6 números entre 1 e 60
sorteados. Escreva um programa que gere uma seleção aleatória de 6 números para
uma aposta. Certifique-se de que os 6 números selecionados não contenham
duplicatas. Exibir os números em ordem crescente.
"""
from random import *
# Criando usando o type set porque já automaticamente elimina
# os números duplicados
numeros = set()
def gerar_numeros():
while len(numeros) < 6:
numeros.add(randint(1, 60))
return numeros
gerar_numeros()
numeros_ordenados = sorted(numeros)
print(f'Os números gerados foram: {numeros_ordenados}')
| true
|
e013da69e3f47ae73c0df92bfa7223e0d7a8a008
|
Python
|
CCNITSilchar/Coding-Club-Contribution-Tracker-and-Leaderboard
|
/git_repo.py
|
UTF-8
| 1,001
| 2.59375
| 3
|
[] |
no_license
|
#!/usr/bin/env python
#Learn how this works here: http://youtu.be/pxofwuWTs7c
import urllib2
import json
import pymysql
from json_connection import database
from json_connection import json_l
conn=database()
conn.connect('coding_club')
conn.cursor.execute("SELECT name_of_repos FROM git_repos ")
list_of_repos=set()
repos=conn.cursor.fetchall()
for r in repos:
list_of_repos.add(r[0])
conn.cursor.execute("SELECT scholar_id,github_h FROM student_info ")
repo_q=conn.cursor.fetchall()
for q in repo_q:
repo_scholar_id=q[0]
repo_handle=q[1]
points=0
repo_url="https://api.github.com/users/"+q[1]+"/repos"
repo_ob=json_l()
repo_data=repo_ob.fetch_data_from_api(repo_url)
for i in range(len(repo_data)):
repo_name=repo_data[i]['name']
repo_stars=int(repo_data[i]['stargazers_count'])
fork_status=repo_data[i]['fork']
print repo_name, fork_status
if fork_status==False:
if repo_name in list_of_repos or repo_stars>=100:
points+=25
print q[1],repo_name
print q[1], points
| true
|
df197b95860eb81f7d9f6460e3cee77a8a7b3830
|
Python
|
AdamZhouSE/pythonHomework
|
/Code/CodeRecords/2344/60799/235346.py
|
UTF-8
| 185
| 2.734375
| 3
|
[] |
no_license
|
T = int(input())
for hhh in range(0, T):
input()
aList = [int(i) for i in input().split()]
d = int(input())
[print(i, end=' ') for i in aList[d:]+aList[0:d]]
print()
| true
|
260f4f1f67458871d22b457cc4fe0f3bdfce5dad
|
Python
|
RastogiAbhijeet/NewsReader
|
/Scrapping.py
|
UTF-8
| 4,087
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
from bs4 import BeautifulSoup
from urllib import request
# from pymongo import
from newspaper import Article
import newspaper
from textblob import TextBlob
from datetime import date
import json
from databaseHandling import InterfaceClass
class ScrapNews(object):
def __init__(self):
self.listTitleLink = []
self.obj = InterfaceClass()
self.listTitleLink = self.obj.validation()
self.url = request.urlopen("https://news.google.com/news/?ned=us&hl=en")
def fetchLinks(self):
soup = BeautifulSoup(self.url,'html.parser')
for link in soup.find_all("a"):
x = str(link.get('href'))
# print(x)
if x[0] == 'h' or x[0] == '/':
if '/section' in x:
print(x)
def fetch_news(self):
'''
1. linkAppend : This list is used to avoid the redundancy in fetching the topic links
2. linkAppendNews : This list is used to avoid the redundancy in fetching the links on individual topic page
'''
linkAppend = []
listAppendNews = []
soup = BeautifulSoup(self.url,'html.parser')
# link is an iterable for all the links present on the main Link
for link in soup.find_all("a"):
linkLayer_1 = str(link.get('href'))
if linkLayer_1[0] == 'h':
# if '/news' in linkLayer_1 and '/topic' in linkLayer_1 and '/section' in linkLayer_1:
if '/section' in linkLayer_1:
linkLayer_1 = 'https://news.google.com/news/' + linkLayer_1
if ('topic/BUSINESS' in linkLayer_1 or 'topic/NATION' in linkLayer_1 or 'topic/WORLD' in linkLayer_1 or 'topic/TECHNOLOGY' in linkLayer_1) and linkLayer_1 not in linkAppend:
print(linkLayer_1)
try:
urlLinkLayer_1 = request.urlopen(linkLayer_1)
soupLayer_1 = BeautifulSoup(urlLinkLayer_1,'html.parser')
count = 0
linkAppend.append(linkLayer_1)
for targetLink in soupLayer_1.find_all('a'):
if count < 20:
tempLink = str(targetLink.get('href'))
# print(tempLink)
if (tempLink[0] == 'h' and ('google' not in tempLink) and ('youtube' not in tempLink) and ('headlines/section/topic/' not in tempLink)) and tempLink not in listAppendNews :
# print("Hello")
print(tempLink)
count+=1
listAppendNews.append(tempLink)
self.process_item(tempLink)
except :
pass
def process_item(self,url_link):
# obj = InterfaceClass()
news = Article(url = url_link)
news.download()
news.parse()
x = news.text
y = news.title
if y not in self.listTitleLink:
self.listTitleLink.append(y)
print("hello")
sentVal, classValue = self.sentiValue(x)
jsonObj = {}
list = []
list.append(date.today())
jsonObj['Date'] = str(list[0])
jsonObj['NewsData'] = x
jsonObj['NewsTitle'] = y
jsonObj['Sentiment'] = sentVal
jsonObj['Classification'] = classValue
self.obj.insertData(jsonObj)
def sentiValue(self,x):
blob = TextBlob(x)
sentVal = blob.sentiment.polarity
classificationValue = None#blob.classify()
return sentVal, classificationValue
scrapObj = ScrapNews()
scrapObj.fetch_news()
'''
Program Control
1. Fetch News()
2. ProcessItem()
3. SentiValue()
'''
| true
|
79073d8e675248cb7a0f870c6830f70466538803
|
Python
|
mahendraphd/Python_LD
|
/AutoDictonary.py
|
UTF-8
| 1,783
| 2.515625
| 3
|
[] |
no_license
|
import time
import sys
import os
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from time import strftime
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=chrome_options)
sys.path.append(os.path.abspath("SO_site-packages"))
import pyperclip
recent_value = ""
D = time.strftime("%D")
r = time.strftime("%r")
while True:
tmp_value = pyperclip.paste()
if tmp_value != recent_value:
recent_value = tmp_value
word=recent_value.strip('')
print(word)
driver.get("https://dictionary.cambridge.org/dictionary/english/"+word)
content=driver.page_source
soup=BeautifulSoup(content,"lxml")
for row in soup.find_all('div',attrs={"class" : "def ddef_d db"}):
print("...................................................................")
string=row.text
print(string.strip(' :'))
#print("Value changed: %s" % str(recent_value)[:20])
#with open('out_clipboard.txt', '+a') as output:
#try:
#output.write("[Start]----------------"+D+" "+r+"----------------\n")
#output.write("%s\n\n" % str(tmp_value))
#output.write("[End]-----------------------------------------------------------------\n\n\n")
#except:
#output.write("[Start]----------------" + D + " " + r+"----------------\n")
#output.write("%s\n\n" % str(tmp_value.encode('UTF-8')))
#output.write("[End]-----------------------------------------------------------------\n\n\n")
time.sleep(0.1)
| true
|
de1721c82366d88c0e358926352ecb8da54bcb2f
|
Python
|
guillox/Practica_python
|
/2013/tp3/tp3part1ej1.py
|
UTF-8
| 795
| 3.3125
| 3
|
[] |
no_license
|
"""Manejo de archivos
Parte I
1.- Dado un conjunto de números (que se tomarán de la entrada estándar), generar dos archivos:
uno con los números pares y otro con los impares."""
L = [1,2,3,4,5,5]
conjuntoL = set(L)
def creacion():
archimp=open("archivo.txt","w")
archimp.close()
archpar=open("archivo txt","w")
archpar.close()
def escpar(listapar):
archpar=open("archivopar.txt","a")
for p in range(1,len(listapar)):
archpar.write(listapar[p])
archpar.close
def escimp(listapar):
archimp=open("archivoimp.txt","a")
for i in range(1,len(listaimpar)):
archimp.write(listaimpar[p])
archimp.close
creacion()
Listapar=[]
listaimp=[]
for x in range(1,len(L)):
if L[x]%2==0:
Listapar.append(L[x])
else:
listaimp.append(l[x])
escpar(listapar)
escimp(listimp)
| true
|
a7874461612ea64782c02c6195def6351edcbb6b
|
Python
|
skaidan/burger
|
/tests/integration/orders/test_order_data_access.py
|
UTF-8
| 1,924
| 2.609375
| 3
|
[] |
no_license
|
from django.test import testcases
from inventory.models import Inventory
from orders.data_access.order_data_access import OrderDataAccess
from orders.models import Order, OrderElement, OrderStatus
from organizations.models import Restaurant
class OrderDataAccessIntegrationTestCase(testcases.TestCase):
order = None
elements = None
def setUp(self):
self.order = self._initialize_order()
def test_when_data_access_is_called_then_order_is_retrieved_from_origin_of_data(self):
order_data_access = OrderDataAccess()
order_data_access.get_order(self.order.id)
self.assertTrue(order_data_access.order.paid,
'Error, paid status should be True. Check connection to SourceData')
def test_when_data_access_is_called_then_order_elements_are_retrieved_from_origin_of_data(self):
self.elements = self._initialize_elements()
order_data_access = OrderDataAccess()
order_data_access.get_order(self.order.id)
expected_number_of_elements_in_order = 1
self.assertEqual(expected_number_of_elements_in_order, len(order_data_access.order_items),
'Error, items number should be {expected}'.format(
expected=expected_number_of_elements_in_order))
def _initialize_order(self):
order = Order()
order.paid = True
order.status = OrderStatus[0][0]
order.save()
return order
def _initialize_elements(self):
restaurant = Restaurant()
restaurant.save()
inventory = Inventory()
inventory.restaurant = restaurant
inventory.save()
element = OrderElement()
element.order_id = self.order.id
element.final_price = 5
element.offer_number_in_order = 0
element.price = 5
element.inventory = inventory
element.save()
return [element, ]
| true
|
f831a0e794ab6bbbe7b5d4bb5c0693505d53ffb0
|
Python
|
JenTus/pyalgorithm
|
/788_rotated_digits.py
|
UTF-8
| 705
| 3.375
| 3
|
[] |
no_license
|
range(1, -2, -1)
aa = "abdgw"
len(aa)
[aa[i] for i in range(len(aa)-1, -1, -1)]
range(1, 3+1, 1)
def reverse(s):
if s == "2":
return "5"
elif s == "5":
return "2"
elif s == "6":
return "9"
elif s == "9":
return "6"
elif (s == "0") or (s == "1") or (s == "8"):
return s
else:
return "00"
def rotatedDigits(N):
goodlist = []
for n in range(1, N + 1, 1):
sn = str(n)
newlist = [reverse(i) for i in sn]
new = ''.join(newlist)
if (len(new) == len(sn)) & (sn != new):
goodlist.append(n)
return goodlist
[reverse(i) for i in "3333"]
rotatedDigits(857)
len(rotatedDigits(857))
| true
|
c42e1804d4a295eff0fe5006d9c7355d02a3353a
|
Python
|
rfelts/wsgi-calculator
|
/calculator.py
|
UTF-8
| 5,314
| 3.96875
| 4
|
[] |
no_license
|
#!/usr/bin/env python3
# Russell Felts
# Assignment 04 WSGI Calculator
import traceback
"""
For your homework this week, you'll be creating a wsgi application of
your own.
You'll create an online calculator that can perform several operations.
You'll need to support:
* Addition
* Subtractions
* Multiplication
* Division
Your users should be able to send appropriate requests and get back
proper responses. For example, if I open a browser to your wsgi
application at `http://localhost:8080/multiple/3/5' then the response
body in my browser should be `15`.
Consider the following URL/Response body pairs as tests:
```
http://localhost:8080/multiply/3/5 => 15
http://localhost:8080/add/23/42 => 65
http://localhost:8080/subtract/23/42 => -19
http://localhost:8080/divide/22/11 => 2
http://localhost:8080/ => <html>Here's how to use this page...</html>
```
To submit your homework:
* Fork this repository (Session03).
* Edit this file to meet the homework requirements.
* Your script should be runnable using `$ python calculator.py`
* When the script is running, I should be able to view your
application in my browser.
* I should also be able to see a home page (http://localhost:8080/)
that explains how to perform calculations.
* Commit and push your changes to your fork.
* Submit a link to your Session03 fork repository!
"""
def info(*args):
"""
Produces a string that describes the site and how to use it
:param args: unused as nothing is being calculated
:return: String containing html describing the site
"""
page = """
<h1>Calculator</h1>
<p>This site is a simple calculator that will add, substract, multiply, and divide two numbers.</p>
<p>Simply enter a url similar to http://localhost:8080/add/23/42 and the answer will be returned.</p>
<p> The possible paths are /add/#/#, /substract/#/#, /multiply/#/#, /divide/#/#</p>
"""
return page
def add(*args):
"""
Adds to ints in a list
:param args: to numbers to add
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = sum(temp_list)
return str(total)
def subtract(*args):
"""
Subtract two ints
:param args: to numbers to subtract
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = temp_list[0] - temp_list[1]
return str(total)
def multiply(*args):
"""
Multiply two ints
:param args: to numbers to multiply
:return: a STRING with the sum of the arguments
"""
# Convert the args to ints
temp_list = contert_to_int(*args)
total = temp_list[0] * temp_list[1]
return str(total)
def divide(*args):
"""
Divides two ints
:param args: to numbers to divide
:return: a STRING with the sum of the arguments
"""
temp_list = contert_to_int(*args)
try:
total = temp_list[0] / temp_list[1]
except ZeroDivisionError:
raise ZeroDivisionError
return str(total)
def contert_to_int(*args):
"""
Converts the string args to a list of ints
:param args: Two strings
:return: A list of ints
"""
return [int(arg) for arg in args]
def resolve_path(path):
"""
Take the request and determine the function to call
:param path: string representing the requested page
:return: func - the name of the requested function,
args - iterable of arguments required for the requested function
"""
funcs = {
'': info,
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# Split the path to determine what the function and arguments
path = path.strip('/').split('/')
func_name = path[0]
args = path[1:]
# Get the requested function from the dictionary or raise an error
try:
func = funcs[func_name]
except KeyError:
raise NameError
return func, args
def application(environ, start_response):
"""
Handle incoming requests and route them to the appropriate function
:param environ: dictionary that contains all of the variables from the WSGI server's environment
:param start_response: the start response method
:return: the response body
"""
headers = [('Content-type', 'text/html')]
try:
path = environ.get('PATH_INFO', None)
if path is None:
raise NameError
func, args = resolve_path(path)
body = func(*args)
status = "200 OK"
except NameError:
status = "404 Not Found"
body = "<h1>Not Found</h1>"
except ZeroDivisionError:
status = "400 Bad Request"
body = "<h1>Bad Request</h1>"
except Exception:
status = "500 Internal Server Error"
body = "<h1>Internal Server Error</h1>"
print(traceback.format_exc())
finally:
headers.append(('Content-length', str(len(body))))
start_response(status, headers)
return [body.encode('utf8')]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
srv = make_server('localhost', 8080, application)
srv.serve_forever()
| true
|
0bbadf9fcefc08b37ffe747886efd5da16288bda
|
Python
|
ThQuirino/api-em-flask-com-python
|
/server.py
|
UTF-8
| 2,144
| 2.546875
| 3
|
[] |
no_license
|
from flask import Flask, render_template,request
import index
import re
from src import procurarDados
from src import inserir
app=Flask("PDF")
@app.route('/',methods=["GET","POST"])
def index():
#if __name__=='__main__':
if(request.method =='POST'):
valor=request.form.get("name")
comparar=re.match(r'\s',valor)
if(comparar != None or valor ==''):
return "o campo nao deve ser nulo"
else:
ProdutoBanco=procurarDados.bancoDados(valor)
if(ProdutoBanco.procurarProduto()=='erro'):
return 'produto em falta no estoque'
return render_template('dados.html')
return render_template('index.html')
@app.route('/enviar',methods=['GET','POST'])
def enviar_dados():
if(request.method=='POST'):
nome=request.form.get("nome")
email=request.form.get("email")
cpf=request.form.get("cpf")
data=request.form.get("data")
comparar=re.match(r'[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}',cpf)
if(comparar == None or cpf ==''):
print('cpf invalido')
return render_template('dados.html')
else:
lista={"nome":nome,"email":email,"cpf":cpf,"data":data}
ClienteBanco=inserir.inserirBanco().inserCliente(lista)
if(ClienteBanco=='Boleto'):
return render_template('final.html')
else:
return render_template('cadastro.html')
return render_template('dados.html')
@app.route('/cadastrado',methods=['GET','POST'])
def enviar_dados_cadastrados():
if(request.method=='POST'):
cpf=request.form.get("cpf")
comparar=re.match(r'\s',cpf)
if(comparar != None or comparar ==''):
return "o campo nao deve ser nulo"
else:
ProdutoBanco=procurarDados.bancoDados(cpf)
if(ProdutoBanco.procurarCpf()=='erro'):
print('Nome errado. Por favor, digite novamente')
return render_template('cadastro.html')
return render_template('final.html')
return render_template('cadastro.html')
app.run()
| true
|
aa087af80234b36325b573274c8bb5e0a76af51b
|
Python
|
Heminyildiz/Python-SansOyunlari.py
|
/SansOyunlari/SansOyunlari.py
|
UTF-8
| 1,479
| 3.8125
| 4
|
[] |
no_license
|
import random
print("Şanslı Sayı'ya Hoşgeldiniz")
input("*****Başlamak için ENTER'a basınız*****")
print("-"*30)
print("Şans Oyunu Kod")
print("-"*15)
print("Sayısal Loto: 1")
print("Super Loto: 2")
print("On Numara: 3")
print("Sans Topu: 4")
print("-"*30)
name = input("Adınız: ")
cevap = input("Lütfen oynamak istediğiniz şans oyununun kodunu giriniz: ")
listeSay = range(1,49)
listeSup = range(1,54)
listeOn = range(1,80)
listeSans1 = range(1,34)
listeSans2 = range(1,14)
if cevap == "1":
sayi1 = random.sample(listeSay, 6)
sayi1.sort(reverse=False)
print(f"Sayın {name}, şanslı sayılarınız: {sayi1}")
elif cevap == "2":
sayi2 = random.sample(listeSay, 6)
sayi2.sort(reverse=False)
print(f"Sayın {name}, şanlı sayılarınız: {sayi2}")
elif cevap == "3":
sayi3 = random.sample(listeOn, 10)
sayi3.sort(reverse=False)
print(f"Sayın {name}, şanslı sayılarınız: {sayi3}")
elif cevap == "4":
sayi4 = random.sample(listeSans1, 5)
sayi4.sort(reverse=False)
sayi5 = random.sample(listeSans2, 1)
sayi5.sort(reverse=False)
print(f"Sayın {name}, şanslı sayılarınız {sayi4} + {sayi5} " )
else:
print("Lütfen oynamak istediğiniz oyunun kodunu giriniz!")
print("İyi Şanslar!!")
input("*****Çıkmak için ENTER'a basınız*****")
# Kullanıcıdan farklı kolon seçenekleriyle ilgili veri alınabilir!!
| true
|
721c3cb91d6f94a8f69b49a5e5a74150cd00388f
|
Python
|
likeaeike/tts
|
/tts.py
|
UTF-8
| 659
| 2.765625
| 3
|
[] |
no_license
|
#!/usr/bin/python
import pyttsx, sys, getopt
def main(argv):
inputstring = ""
try:
opts, arg = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputstring> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'tts -i <inputstring>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputstring = arg
return inputstring
print 'Input file is "', inputstring
if __name__ =="__main__":
input = main(sys.argv[1:])
engine = pyttsx.init()
engine.say(input)
engine.runAndWait()
| true
|
d4f37a0268aac0e28339ee980c5f68fc8e9a336f
|
Python
|
davidsongoap/yper
|
/word.py
|
UTF-8
| 2,117
| 3.046875
| 3
|
[] |
no_license
|
# __ __ ____ ______ ____
# \ \/ // __ \ / ____// __ \
# \ // /_/ // __/ / /_/ /
# / // ____// /___ / _, _/
# /_//_/ /_____//_/ |_|
#
# By Davidson Gonçalves
# github.com/davidsongoap/yper
import pygame
from screens.palette import Colors
class Word:
def __init__(self, text, x, y, font, win):
self.text = text
self.x = x
self.y = y
self.win = win
self.active = False
self.has_error = False
self.font = pygame.font.Font(font, 35)
self.text_render = self.font.render(self.text, True, Colors.DARK_BLUE1)
self.textRect = self.text_render.get_rect()
self.textRect.topleft = (self.x, self.y)
self.current_char_idx = 0
def toggle_active(self):
self.active = not self.active
def get_topright(self):
return self.textRect.topright
def change_pos(self, x, y):
self.textRect.topleft = (x, y)
def draw(self):
background_color = Colors.WHITE1 if self.active else Colors.DARK_BLUE2
if self.has_error and self.active:
background_color = Colors.RED
horizontal_padding = 5
button_width = (self.textRect.topright[0]-self.textRect.topleft[0]) + horizontal_padding*2
button_height = self.textRect.bottomright[1] - self.textRect.topright[1]
button_background_pos = (self.textRect.topleft[0]-horizontal_padding,
self.textRect.topleft[1],
button_width,
button_height)
radius = 8
pygame.draw.rect(self.win, background_color,
button_background_pos, border_radius=radius)
self.win.blit(self.text_render, self.textRect)
def process_char(self, char):
valid_char = False
if char == self.text[self.current_char_idx]:
self.current_char_idx += 1
self.has_error = False
valid_char = True
else:
self.has_error = True
is_finished = self.current_char_idx == len(self.text)
return is_finished, valid_char
| true
|
ee49750e435e8befc0dc1de188039c8268849aed
|
Python
|
burakkose/HackerRank
|
/Challenges/AlternatingCharacters/solve.py
|
UTF-8
| 262
| 3.515625
| 4
|
[
"Unlicense"
] |
permissive
|
strings = []
for i in range(int(input(""))):
strings.append(input(""))
index = 0
deletion = 0
for j in range(1,len(strings[i])):
if strings[i][index] == strings[i][j]:
deletion += 1
else: index = j
print(deletion)
| true
|
89756535f320c86257b886e95823f452f9d82da4
|
Python
|
skriser/pythonlearn
|
/Day24/矩阵的行列式.py
|
UTF-8
| 255
| 3.0625
| 3
|
[] |
no_license
|
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@time: 2018/05/29 16:39
@author: 柴顺进
@file: 矩阵的行列式.py
@software:rongda
@note:
"""
import numpy as np
vector = np.mat("3 4;5 6")
# 求行列式
det = np.linalg.det(vector)
print(det)
| true
|
396d534e8bf1b47d3c33edcade28686b58983b1d
|
Python
|
lforet/astroid
|
/wifi/wifi_graph.py
|
UTF-8
| 3,693
| 2.65625
| 3
|
[] |
no_license
|
import matplotlib.pyplot as plt
import numpy as np
import time
import thread
import math
import random
from wifi_consume import *
from matplotlib import mpl
import sys
import matplotlib.colors as mcolors
class wifi_graph():
def __init__(self, wifi_to_graph):
self.wifi_to_graph = wifi_to_graph
self.fig = None
self.ax = None
self.win = None
self.run()
def drange(self, start, stop, step):
r = start
while r < stop:
yield r
r += step
def closest(self, target, collection):
return min((abs(target - i), i) for i in collection)[1]
def calculate_color(self, val):
#R=(255*val)/100
R=(255*(100-val))/100;
#G=(255*(100-val))/100;
G=(255*val)/100
B=0
#print R,G,B
to_return = [self.normalize_val(R, 0, 255),self.normalize_val(G, 0, 255),B]
return to_return
def normalize_val(self, val, floor, ceiling):
return float (int(((float(val) - floor) / ceiling) * 100)) / 100
def calculate_color2(self, val):
if val > 99: val = 99
temp = int(self.translate(val, 0, 80, 0, 4))
color = []
n = 5
R = (1.0 - (0.25 * temp))
G = (0.25 * temp)
B = 0
color = [R,G,B]
#print 'val:', val, ' temp:', temp, ' color:', color
return color
def translate(self, sensor_val, in_from, in_to, out_from, out_to):
out_range = out_to - out_from
in_range = in_to - in_from
in_val = sensor_val - in_from
val=(float(in_val)/in_range)*out_range
out_val = out_from+val
return out_val
def animate(self):
n= 100
# http://www.scipy.org/Cookbook/Matplotlib/Animations
x = []
y = [0] * 100
for i in range(n):
x.append(i)
cdict = {'red': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 1.0, 1.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))
}
cmap = mcolors.LinearSegmentedColormap('my_colormap', cdict, 5)
#cmap = mpl.cm.cool
#norm = mpl.colors.Normalize(vmin=100, vmax=0)
#bounds = [0, 25, 50, 75, 100]
#norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cax = self.ax.imshow((x,y), cmap=cmap)
cbar = self.fig.colorbar(cax, orientation='vertical')
#wifi = consume_wifi('wifi.1', '192.168.1.190')
while True:
time.sleep(.2)
y = y[1:]
signal_value = self.wifi_to_graph.signal_strength
#print signal_value
try:
val = int(self.wifi_to_graph.signal_strength)
if val < 0: val = 0
#print val
except:
val = 0
#val = random.randint(0,100)
pass
y.append(val)
plt.cla()
plt.xticks(xrange(0,110,10))#, endpoint=True))
plt.yticks(xrange(0,110,10))#, endpoint=True))
plt.xlabel('10 seconds')
plt.ylabel('Strength')
plt.grid(True)
plt.ylim([0,110])
plt.xlim([0,110])
plt.grid(True)
#from mpl_toolkits.axes_grid1 import make_axes_locatable
#divider = make_axes_locatable(plt.gca())
#cax = plt.append_axes("right", "5%", pad="3%")
#cbar = plt.colorbar(fig, orientation='vertical')
#plt.tight_layout()
colors = []
for i in range(len(x)):
#colors.append(calculate_color(y[i]))
colors.append(self.calculate_color2(y[i]))
#print val , colors[99]
plt.bar(x , y, 1, color=colors)
self.fig.canvas.draw()
def graph(self):
self.fig, self.ax = plt.subplots(dpi=60)
self.win = self.fig.canvas.manager.window
self.win.after(10, self.animate)
plt.show ()
def run(self):
self.th = thread.start_new_thread(self.graph, ())
if __name__ == "__main__":
IP = 'localhost'
if len(sys.argv) > 1:
#if sys.argv[1] == 'testmode':
IP = str(sys.argv[1])
wifi = consume_wifi('wifi.1', IP)
graph_wifi = wifi_graph(wifi)
i = 0
while True:
time.sleep(1)
print 'signal strength:', wifi.signal_strength, i
i += 1
| true
|
8e6fece1119c52ecfc8c412d51e067a61d023fac
|
Python
|
DenisRang/GradingSystem
|
/generator_random_works.py
|
UTF-8
| 1,157
| 2.890625
| 3
|
[] |
no_license
|
import os
import random
from mimesis import Person
STUDENTS_COUNT = 50
new_directory = os.getcwd() + r'\New works'
person = Person('en')
for i in range(STUDENTS_COUNT):
name_letter = person.name()[0]
surname = person.surname()
file_name = new_directory + '//' + name_letter + '.' + surname + '.'
file_a1 = open(file_name + 'a1', 'w')
random_grade = random.randint(30, 100)
file_a1.write(str(random_grade))
file_a1.close()
file_a2 = open(file_name + 'a2', 'w')
random_grade = random.randint(30, 100)
file_a2.write(str(random_grade))
file_a2.close()
file_a3 = open(file_name + 'a3', 'w')
random_grade = random.randint(30, 100)
file_a3.write(str(random_grade))
file_a3.close()
file_p = open(file_name + 'p', 'w')
random_grade = random.randint(30, 100)
file_p.write(str(random_grade))
file_p.close()
file_m = open(file_name + 'm', 'w')
random_grade = random.randint(30, 100)
file_m.write(str(random_grade))
file_m.close()
file_f = open(file_name + 'f', 'w')
random_grade = random.randint(30, 100)
file_f.write(str(random_grade))
file_f.close()
| true
|
f3f1d5dae7c58701848798634b105f201374dcd1
|
Python
|
crunchiness/rss
|
/robot/vision/vision.py
|
UTF-8
| 2,582
| 2.578125
| 3
|
[] |
no_license
|
"""Main vision class"""
from robot.vision.localisation import detect_pieces
import numpy as np
import cv2
from robot.vision.resource_finder import DetectionConfirmer, CubeDetector, get_mean
class Vision:
def __init__(self, io):
self.io = io
self.io.cameraSetResolution('high')
self.belief = []
self.model_names = [
'zoidberg',
'mario',
'wario',
'watching'
]
self.detection_confirmers = {
'zoidberg': DetectionConfirmer(),
'mario': DetectionConfirmer(),
'wario': DetectionConfirmer(),
'watching': DetectionConfirmer()
}
self.cube_detectors = {
'zoidberg': CubeDetector('zoidberg'),
'mario': CubeDetector('mario'),
'wario': CubeDetector('wario'),
'watching': CubeDetector('watching')
}
def do_image(self):
# Pieces identification
for i in range(0, 1):
self.io.cameraGrab()
img = self.io.cameraRead()
assert img is not None, 'failed to read image'
# self.belief = detect_pieces(img, save=True, display=False)
print self.belief
def see_resources(self, model_name):
self.model_names = [
model_name
]
resources = {}
# img = None
for i in range(0, 5):
self.io.cameraGrab()
img = self.io.cameraRead()
for model_name in self.model_names:
# print 'Checking', model_name
detection = self.cube_detectors[model_name].detect_cube(img)
if detection:
# print len(detection['p1'])
for (x, y) in np.int32(detection['p1']):
cv2.circle(img, (x, y), 2, (0, 255, 255))
cv2.circle(img, get_mean(detection), 2, (255, 0, 0), 10)
# self.io.imshow('Window', img)
resources[model_name] = {'mean': get_mean(detection), 'found': True}
# for model_name in self.model_names:
# resources[model_name] = self.detection_confirmers[model_name].get_result()
# if detection_temp:
# # print resources
# for (x, y) in np.int32(detection_temp['p1']):
# cv2.circle(img, (x, y), 2, (0, 255, 255))
# if 'mario' in resources and resources['mario']:
# cv2.circle(img, get_mean(detection_temp), 2, (255, 0, 0), 10)
# cv2.imshow('Window', img)
# cv2.waitKey(10)
return resources, img
| true
|
eb2ed11302e45fef97339559445b32dedd79e1c2
|
Python
|
friendnj/pythonautotest
|
/unittest1/baidu_unittest.py
|
UTF-8
| 1,006
| 2.796875
| 3
|
[] |
no_license
|
from selenium import webdriver
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
class Baidu(unittest.TestCase):
'''百度搜索测试'''
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(10)
self.base_url = "https://www.baidu.com/"
def test_baidu_search(self):
'''搜索关键字:HTMLTestRunner'''
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_id("kw").send_keys("HTMLTestRunner")
driver.find_element_by_id("su").click()
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
testunit=unittest.TestSuite()
testunit.addTest(Baidu("test_baidu_search"))
now=time.strftime("%Y-%m-%d %H-%M-%S")
filename='./'+now+'result.html'
fp=open(filename, 'wb')
runner=HTMLTestRunner(stream=fp, title='百度搜索测试报告', description='用例执行情况:')
runner.run(testunit)
fp.close()
| true
|