repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flywheel-apps/bids_hcp | 249,108,138,464 | d4542dc227b2b0f6736ef358d1d42e1479c7f68c | 15e365acf4d528922ddafafa1dff83d883090a36 | /fw_gear_hcp_func/hcpfunc_qc_mosaic.py | 4aeaf947d4bcd2641aa9499df584189a0735cf0f | []
| no_license | https://github.com/flywheel-apps/bids_hcp | 5aebb508c4342f400ad9c7803cb80dcbf679124a | 6c5fd56d215561098672231245cf825028dce04d | refs/heads/master | 2023-07-05T01:23:24.365332 | 2021-08-04T18:04:59 | 2021-08-04T18:04:59 | 391,175,719 | 0 | 0 | null | false | 2021-08-04T18:05:01 | 2021-07-30T19:57:04 | 2021-08-02T22:04:26 | 2021-08-04T18:05:00 | 266 | 0 | 0 | 0 | Python | false | false | """
Builds, validates, and excecutes parameters for the HCP helper script
/tmp/scripts/hcpfunc_qc_mosaic.sh
part of the hcp-func gear
"""
import logging
import os
import os.path as op
from collections import OrderedDict
from flywheel.GearToolkitContext.interfaces.command_line import (
build_command_list,
exec_command,
)
log = logging.getLogger(__name__)
def build(context):
config = context.config
params = OrderedDict()
params["qc_scene_root"] = op.join(context.work_dir, config["Subject"])
params["fMRIName"] = config["fMRIName"]
# qc_image_root indicates where the images are going
params["qc_image_root"] = op.join(
context.work_dir,
config["Subject"] + "_{}.hcp_func_QC.".format(config["fMRIName"]),
)
context.gear_dict["QC-Params"] = params
def execute(context):
SCRIPT_DIR = context.gear_dict["SCRIPT_DIR"]
command = [op.join(SCRIPT_DIR, "hcpfunc_qc_mosaic.sh")]
command = build_command_list(
command, context.gear_dict["QC-Params"], include_keys=False
)
command.append(">")
command.append(op.join(context.work_dir, "logs", "functionalqc.log"))
stdout_msg = (
"Pipeline logs (stdout, stderr) will be available "
+ 'in the file "pipeline_logs.zip" upon completion.'
)
log.info("Functional QC Image Generation command: \n")
exec_command(context, command, shell=True, stdout_msg=stdout_msg)
| UTF-8 | Python | false | false | 1,428 | py | 18 | hcpfunc_qc_mosaic.py | 14 | 0.67437 | 0.67437 | 0 | 49 | 28.142857 | 74 |
J3ff-Mathew/python_small | 10,273,561,808,957 | d0acf54c52520a8f9a0b4ce3178c2dd6b8254242 | e3dda4d14224d7f61ad7f63867b1e458d090fe26 | /coinflipbimboo.py | 8521b471dcdab0ed07e4f6e155a79fd8321265fe | []
| no_license | https://github.com/J3ff-Mathew/python_small | 515e70a5baae64d6243b61f84f46a0ec4f85dd03 | 3a1b7f789723c3c5b7c55a3b187f68cf46e8f70a | refs/heads/master | 2023-08-11T03:30:47.618386 | 2021-09-15T04:48:23 | 2021-09-15T04:48:23 | 406,616,469 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import random
face=["h","t"]
def coin_flip():
"""flips the coin to find if you win or lose"""
call=input("Press 'h' for heads and 't' for tails: ").lower()
flip=random.choice(face)
if call==flip:
return "Win"
else:
return "Lose"
while quit!='q':
print(f"You {coin_flip()}")
quit=input("To quit press q or else press any other key: ")
# def square(num):
# """Finds the squares of the no passed"""
# return num**2
# n=int(input("Enter a no to square:"))
# print(square(n))
| UTF-8 | Python | false | false | 489 | py | 16 | coinflipbimboo.py | 16 | 0.635992 | 0.633947 | 0 | 21 | 22.238095 | 62 |
Andesha/ViewClust | 5,540,507,848,227 | 7c691afec98f96db37d26124cf4235e7410481a0 | 3088cf3726e9dd92ac26d6cb09f4f745e0c3dd25 | /viewclust/to_terminal.py | 49f4923de4ced2fdde0102824fc169a558e7bc7a | [
"MIT"
]
| permissive | https://github.com/Andesha/ViewClust | 3a158ad38afdd8576fbac848e561ed7c6736f562 | 9310be5f82a1439d5c18cf588622de742a1997da | refs/heads/master | 2023-03-09T08:38:07.816284 | 2023-02-02T16:21:57 | 2023-02-02T16:21:57 | 244,706,846 | 4 | 5 | MIT | false | 2023-02-08T01:25:58 | 2020-03-03T18:06:12 | 2022-06-22T13:05:26 | 2023-02-08T01:25:57 | 95 | 3 | 4 | 4 | Python | false | false | from typing import Union, Optional, List
import pandas as pd
import plotille
import os
def to_terminal(series: Union[pd.Series, List[pd.Series]],
title: str = 'resource usage',
pu: str = 'cpu', labels: Optional[list] = None):
"""
Plot a datetime series (or a list of them) to terminal
Parameters
-------
series:
A datetime series or a list of series to be plot
title:
Title for the plot
pu:
Processing using (GPU or CPU) for y axis
labels:
If multiple series, the labels of each ome
"""
size = os.get_terminal_size()
colors = ['blue', 'yellow', 'magenta', 'cyan', 'white', 'green']
if not isinstance(series, list):
series = [series]
if labels is None:
labels = [None for _ in range(len(series))]
else:
if len(labels) != len(series):
raise Exception('Labels do not match inputs')
print(title.center(size.columns))
fig = plotille.Figure()
fig.color_mode = 'names'
fig.x_label = 'Dates'
fig.y_label = f'{pu} count'
for idx, s in enumerate(series):
s = s.map('{:.2f}'.format).astype(float)
x = s.index
y = s.values
q1 = s.quantile(0.1)
fig.set_x_limits(min_=min(x), max_=max(x))
fig.set_y_limits(min_=min(y) - q1, max_=max(y) + q1)
fig.plot(x, y, lc=colors[idx], label=labels[idx])
print(fig.show(legend=True))
| UTF-8 | Python | false | false | 1,451 | py | 23 | to_terminal.py | 14 | 0.575465 | 0.57133 | 0 | 47 | 29.87234 | 68 |
RomanKoshkin/human-robot-interaction | 10,531,259,817,435 | 84c77f0bba2a1246601b5c0ad174ff5efae9c775 | 9c35a997fd07179bd0ccc85a9f7b1f22c4b3b9d4 | /src/Prior-generation.py | 573c96a49dfbff61c6f56da440b43292b9c8d1c5 | [
"Apache-2.0"
]
| permissive | https://github.com/RomanKoshkin/human-robot-interaction | 8fb939030bea2efc75cd3d0abfc7e17d9fbe75a4 | f27d59f85ec0c97c8cfe562402cabf71e66857f1 | refs/heads/master | 2023-07-28T23:43:19.332810 | 2021-10-06T03:15:31 | 2021-10-06T03:15:31 | 288,921,904 | 0 | 0 | null | false | 2021-10-05T07:43:51 | 2020-08-20T06:11:29 | 2021-10-05T07:37:00 | 2021-10-05T07:43:50 | 35,475 | 0 | 0 | 0 | Jupyter Notebook | false | false | #!/usr/bin/python2.7
import sys
sys.path.insert(0, '/home/torobo/catkin_ws/src/torobo_robot/torobo_rnn/scripts')
from torobo_rnn_utils import *
import os
import numpy as np
import rospy
import math
import matplotlib.pyplot as plt
from sensor_msgs.msg import Image
import ctypes
from utils2 import Utils
import utils2
from NRL import NRL
from collections import deque
import time
from torobo_operator import ToroboOperator
torobo = ToroboOperator()
# ROS Image message -> OpenCV2 image converter
#from cv_bridge import CvBridge, CvBridgeError
# OpenCV2 for saving an image
#print gravity_compensation_effort
time.sleep(2)
#bridge = CvBridge()
la_min = [70.0, 80.0, -30.0, 0.0]
la_max = [100.0, 90.0, 30.0, 15.0]
DATA_DIR_0='/home/torobo/catkin_ws/src/tutorial/src/data/Joints_9_right_arm/0_1_0_1_0_0_1_1/primitive_0_0.csv'
DATA_DIR_1='/home/torobo/catkin_ws/src/tutorial/src/data/Training_data_2/primitive_1_0.csv'
DATA_DIR_2='/home/torobo/catkin_ws/src/tutorial/src/data/Training_data_3/primitive_2_0.csv'
ra_min = la_min
ra_max = la_max
# Define the minimum and maximum of the head angles
head_min = [-20.0, -10.0]
head_max = [20.0, 20.0]
ARM_JNTS_FIXED = 0.0
TORSO_FIXED = 0.0
def to_radians(input_data):
data=input_data
for i in range(data.shape[0]):
#pos_list=data[i]
for j in range(len(data[i])):
data[i][j]=math.radians(data[i][j])
return data
def model_to_radians(input_data):
for i in range(len(input_data)):
input_data[i]=math.radians(input_data[i])
return input_data
# The movement will be generated for 4 seconds
PLAY_DURATION = 10
# We'll capture 10 data points per second
CAPTURE_RATE = 10
#NUM_TRIALS = 5
# Set velocity override here (0-100[%])
#set_velocity_override(torobo, 50.0)
# Set softness override here (0-100[%])
set_softness_override(torobo, 50.0)
servo_on(torobo)
class Trial(object):
def __init__(self):
self.nrl=NRL()
self.cwd=os.getcwd()
self.ut=Utils(self.cwd)
self.nZ = '4,1'
self.nD = '40,10'
#nZ = '4,2,1'
#nD = '40,20,10'
prop_path = "/home/torobo/catkin_ws/src/tutorial/src/data/config/model_2_seq_2.d"
self.nrl.newModel(prop_path.encode('ascii'))
self.nrl.load()
self.nDof = self.nrl.getNDof()
self.stateBufferSize = self.nrl.getStateBufferSize(self.nD, self.nZ, self.ut.delimiter)
if self.nDof > 0:
winSize = 15
winBufferSize = winSize * self.nDof
winBuffdata = deque(maxlen=winSize) # circular buffer
primId = 2
# The e_w parameters set bellow assume the network has two layers
# as in the original distribution of the sources
# in case more layers are set by changing the properties.d file,
# the same dimension for e_w must be considered
e_w = [0.025,0.025]
self.start=False
expTimeSteps = 30
postdiction_epochs = 15
alpha = 0.1
beta1 = 0.9
beta2 = 0.999
storeStates = False
storeER = False
showERLog = False
self.nrl.e_enable(primId,\
winSize,
(ctypes.c_float * len(e_w))(*e_w),
expTimeSteps,
postdiction_epochs,
(ctypes.c_float)(alpha),
(ctypes.c_float)(beta1),
(ctypes.c_float)(beta2),
storeStates,
storeER)
def generate_pos(self):
self.tgt_pos_buffer = np.zeros((self.nDof,), dtype=float)
dataOut = (ctypes.c_float * self.nDof)(*self.tgt_pos_buffer)
self.stateBufferSize = self.nrl.getStateBufferSize(self.nD, self.nZ, self.ut.delimiter)
self.nrl.e_generate(dataOut)
self.tgt_pos = np.frombuffer(dataOut, np.float32)
return self.tgt_pos
model=Trial()
servo_on(torobo)
time.sleep(1)
move_homepos(torobo)
torobo.set_control_mode(ToroboOperator.TORSO_HEAD, 'all', 'position')
torobo.set_control_mode(ToroboOperator.LEFT_ARM, 'all', 'position')
torobo.set_control_mode(ToroboOperator.RIGHT_ARM, 'all', 'position')
time.sleep(1)
move_startpos(torobo)
Demonstration=True
if Demonstration==True:
print "Demonstrating Recorded Trajectory"
print"PRIMITIVE_0"
cor_saved=np.loadtxt(DATA_DIR_0, delimiter=",")
cor_saved_1=np.loadtxt(DATA_DIR_1, delimiter=",")
cor_saved_2=np.loadtxt(DATA_DIR_2, delimiter="," )
for i in xrange(cor_saved.shape[0]):
#left_cor=list(cor_saved[i][:6])
right_cor=list(array_radians(cor_saved[i]))
#torobo.move(ToroboOperator.LEFT_ARM, positions=left_cor)
#time.sleep(1)
torobo.move(ToroboOperator.RIGHT_ARM, positions=right_cor)
time.sleep(1)
print 'PRIMITIVE_1'
move_startpos(torobo)
for i in xrange(cor_saved_1.shape[0]):
#
#
#left_cor=list(cor_saved_1[i][:6])
right_cor=list(array_radians(cor_saved_1[i]))
#torobo.move(ToroboOperator.LEFT_ARM, positions=left_cor)
torobo.move(ToroboOperator.RIGHT_ARM, positions=right_cor)
time.sleep(1)
print "PRIMITIVE_2"
move_startpos(torobo)
for i in xrange(cor_saved_2.shape[0]):
#left_cor=list(cor_saved_2[i][:6])
#right_cor=list(cor_saved_2[i][6:12])
# torobo.move(ToroboOperator.LEFT_ARM, positions=left_cor)
right_cor=list(array_radians(cor_saved_2[i]))
torobo.move(ToroboOperator.RIGHT_ARM, positions=right_cor)
time.sleep(1)
move_startpos(torobo)
time.sleep(1)
servo_off(torobo)
PRIOR_GENERATION=False
if PRIOR_GENERATION==True:
print "Demontrating prior generation"
servo_on(torobo)
time.sleep(1)
model_list=[]
model_data=np.array(model.generate_pos())
for i in xrange(300):
full_cor=np.array(model.generate_pos())
#model_data=np.vstack((model_data, full_cor))
right_cor=list(array_radians(full_cor))
#left_cor=full_cor[:6]
#print left_cor
#model_list.append(left_cor[0])
#right_cor=full_cor[6:]
#right_cor=full_cor
#torobo.move(ToroboOperator.LEFT_ARM, positions=left_cor)
torobo.move(ToroboOperator.RIGHT_ARM, positions=right_cor)
time.sleep(1)
#time.sleep(1)
#np.savetxt('/home/shpurov/catkin_ws/src/reaching_task/scripts/data/model_data.csv', model_data, delimiter=",")
move_startpos(torobo)
time.sleep(1)
servo_off(torobo)
| UTF-8 | Python | false | false | 6,605 | py | 652 | Prior-generation.py | 25 | 0.624375 | 0.597275 | 0 | 206 | 31.063107 | 115 |
gabriellaec/desoft-analise-exercicios | 10,393,820,865,861 | b27e162efe39802255fe08ff611cb2f0839eb4b3 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_367/ch21_2020_04_20_17_53_12_892023.py | ffe197e9ac39aa68922c0ede91bfc0835f18d3e7 | []
| no_license | https://github.com/gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | y=float(input('Dias: '))
x=float(input('horas: '))
p=float(input('minutos: '))
o=float(input('segundos: '))
soma= (y* 86400) + (x * 3600) + (p*60) + o
print('soma é {0}' .format(soma)) | UTF-8 | Python | false | false | 186 | py | 35,359 | ch21_2020_04_20_17_53_12_892023.py | 35,352 | 0.583784 | 0.518919 | 0 | 7 | 25.571429 | 42 |
nikhilobili/senti | 9,113,920,641,563 | eae6890cd0078d029a8e8042b76ef640b4bc945b | b13fc9cdfa0467639b4c7398796ded68620566c5 | /main.py | 6687316fcd976734973f41555b59cc857b32fada | []
| no_license | https://github.com/nikhilobili/senti | c61aefeb24573f44e43b0156c82d8fa6b8a8b1b5 | a69c96f64abe4466fb6fdcb8c36f82a2d19e241e | refs/heads/main | 2023-08-21T05:35:28.150449 | 2021-10-09T00:25:17 | 2021-10-09T00:25:17 | 415,159,337 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Created by C Bharath Sai Reddy
import paralleldots
import matplotlib.pyplot as plt
import numpy as np
import time
# Create a parellel dots account and place the key in the below function
paralleldots.set_api_key( "4YJoR9RToT1Oki3s79ejR8ZBs0trCyZcYNrYHpHp59M" )
f = open("rtest.txt", encoding='cp437')
#f = open("test2.txt", "r")
a=f.read().split("-")
a=a[4:]
x=[]
for i in a:
z=i.split("\n")
z=z[0]
x.append(z)
p=x[0].split(":")
p1=len(p[0])+1
q=x[1].split(":")
q1=len(q[0])+1
#print(p1)
u1=0
u2=0
u1s=[]
u2s=[]
def senti(text):
dic={}
time.sleep(1)
dic=paralleldots.emotion( text )
dic=dic["emotion"]
c=[]
for i in dic.keys():
c.append(dic[i])
x=max(c)
#print(x)
x=c.index(x)
#print(x)
k=0
for i in dic.keys():
if(k==x):
return str(i)
k=k+1
for i in range(len(x)):
t=x[i]
t1=t.split(":")
if(len(t1[0])==p1-1):
print(t[p1:])
u1=u1+1
ss=senti(str(t[p1:]))
print("Sentiment: ",ss)
u1s.append(ss)
else:
u2=u2+1
print(t[q1:])
ss2=senti(str(t[q1:]))
print("Sentiment: ",ss2)
u2s.append(ss2)
#fig = plt.figure()
def piee(awe):
labels = list(set(awe))
sizes=[]
for i in labels:
sizes.append(awe.count(i))
qw=len(sizes)
colors = ['gold', 'cyan','yellowgreen', 'lightcoral', 'lightskyblue','red']
colors=colors[:qw]
#explode = (0.1, 0, 0) # explode 1st slice
# Plot
plt.pie(sizes,labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
#plt.subplot(1,2,1)
plt.show()
#piee(u1s)
#piee(u2s)
#ax = fig.add_axes([0,0,1,1])
users = [p[0],q[0]]
feq = [u1,u2]
y_pos = np.arange(len(users))
plt.bar(y_pos, feq)
# Create names on the x-axis
plt.xticks(y_pos, users)
# Show graphic
#plt.subplot(1,2,2)
plt.show()
print(u1s,u2s)
| UTF-8 | Python | false | false | 2,032 | py | 10 | main.py | 4 | 0.533465 | 0.49311 | 0 | 98 | 18.734694 | 79 |
brainysmurf/asw | 18,708,877,573,433 | a8519733fcd92467acd4f4af999046779ea4298d | 4f6f3c9fc04a7d1a02173d23c86d241c71458af6 | /AppleScriptWrapper/Firefox.py | a665a7fcdb6ba03416c6e5a361104f55ddc7fd85 | [
"LicenseRef-scancode-public-domain"
]
| permissive | https://github.com/brainysmurf/asw | d4a11a3c1c95b1910019357788379248ab2f0a94 | 14ff7c3a83c38afbeca1c254a847366238beeca6 | refs/heads/master | 2020-06-02T19:29:45.008556 | 2011-08-24T13:41:59 | 2011-08-24T13:41:59 | 2,038,528 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from AppleScriptWrapper.Basic import AppleScriptWrapper
import re
class Klass(AppleScriptWrapper):
def __init__(self):
AppleScriptWrapper.__init__(self, "Firefox")
def current_document(self):
self.application.windows[0]
def name_of_current_document(self):
name = AppleScriptWrapper.name_of_current_document(self)
if name:
s = re.search(r'(.*)\.\w{3,} \(.*?\)', name)
if s:
return s.group(1)
else:
return name
def extention_of_current_document(self):
name = AppleScriptWrapper.name_of_current_document(self)
if name:
s = re.search(r'.*\.\w{3,4} \((\w{3,4}).*?\)', name)
if s:
return s.group(1)
else:
return self.default_extension
def save(self):
""" Nature of web browsing and Firefox makes this very tricky to solve """
raise NotImplementedError
def save_as(self, path):
""" See save above """
#self.save_gui(path)
raise NotImplementedError
if __name__ == "__main__":
f = Klass()
print(f.save('/Users/brainysmurf/Desktop'))
| UTF-8 | Python | false | false | 1,189 | py | 21 | Firefox.py | 20 | 0.55677 | 0.550042 | 0 | 42 | 27.309524 | 82 |
KolesnikovaAnna/EpamPython2019 | 3,023,657,009,828 | bd973436dcc4f82c290bbcbf11c9c4ed31000996 | 4042e4526c093c98b380312be5d936aa0177f989 | /02-Functions/hw3.py | 1e99342ac4fb8109dad4cd25b2a3fcd587bd03d6 | []
| no_license | https://github.com/KolesnikovaAnna/EpamPython2019 | d5e332a677fc2029bab7cc29aadd1318bbcf1717 | 98191de362d55a253eef8ff4891b85089a04f3c4 | refs/heads/master | 2020-05-24T17:41:06.462686 | 2019-06-08T20:00:52 | 2019-06-08T20:00:52 | 187,391,485 | 0 | 0 | null | true | 2019-05-18T18:19:23 | 2019-05-18T18:19:23 | 2019-05-11T16:56:39 | 2019-05-11T16:56:38 | 3 | 0 | 0 | 0 | null | false | false | '''Напишите реализацию функции make_it_count, которая принимает в качестве
аргументов некую функцию (обозначим ее func) и имя глобальной переменной
(обозначим её counter_name), возвращая новую функцию, которая ведет себя
в точности как функция func, за тем исключением, что всякий раз при вызове
инкрементирует значение глобальной переменной с именем counter_name.
'''
counter_name = 1
global_variable = 5
def func():
return "Bla bla bla"
def make_it_count(func, counter_name):
def new_func():
func()
nonlocal counter_name
counter_name += global_variable
print(counter_name)
return counter_name
return new_func
new_func = make_it_count(func,counter_name)
new_func() | UTF-8 | Python | false | false | 981 | py | 11 | hw3.py | 9 | 0.725381 | 0.722607 | 0 | 24 | 29.083333 | 74 |
314casso/estate-agent | 15,290,083,601,921 | e3d23ed84e1e83e3a70fae5206e517db9e6ddb17 | 432a8d6bc8ad5af9cb5585c2184b05f58e842285 | /realestate/exportdata/migrations/0008_auto_20200608_0019.py | 5b7ac9fb92c09fb4dd387b9180b2da4d201839c9 | []
| no_license | https://github.com/314casso/estate-agent | 963e2a909ac9b190253d8ee40a69947cf19b1261 | ccd07bd599dc51251523cf5e4ea6991b1d0d529d | refs/heads/master | 2022-03-21T04:37:44.946548 | 2022-03-15T19:29:06 | 2022-03-15T19:29:06 | 4,037,752 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exportdata', '0007_auto_20170611_2125'),
]
operations = [
migrations.AddField(
model_name='basefeed',
name='foto_choice',
field=models.PositiveIntegerField(default=3, verbose_name='EstatePhoto', choices=[(3, '\u0412\u0441\u0435'), (0, '\u041d\u0435\u0442 \u0444\u043e\u0442\u043e'), (1, '\u0415\u0441\u0442\u044c \u0444\u043e\u0442\u043e')]),
),
migrations.AlterField(
model_name='feedengine',
name='engine',
field=models.CharField(default=b'AVITO', max_length=15, choices=[(b'AVITO', b'Avito'), (b'YANDEX', b'Yandex'), (b'WORDPRESS', b'Wordpress'), (b'SITEBILL', b'Sitebill')]),
),
]
| UTF-8 | Python | false | false | 881 | py | 361 | 0008_auto_20200608_0019.py | 174 | 0.606129 | 0.505108 | 0 | 24 | 35.708333 | 232 |
diazchg/NpsSDK | 8,014,408,986,029 | dfe7969fc315ff3f14a724b92291e08e508eb64f | 9acca2f5337e5bcec40c8d8b29c5e116b205eecb | /nps/nps_sdk.py | 357785677a87aafa20c8437b72a6bf9ccc53c480 | [
"MIT"
]
| permissive | https://github.com/diazchg/NpsSDK | 4563695ad4735446a27f32c9f7c7e33276b53610 | 0fe02d4818abc3eeda49c29e7102b440a4b5b37d | refs/heads/master | 2018-01-05T06:40:16.087603 | 2016-10-12T18:54:15 | 2016-10-12T18:54:15 | 70,725,744 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from suds import client, MethodNotFound
from suds.cache import ObjectCache
from nps import settings
import logging
from nps import utils
from nps.utils import RequestsTransport
import hashlib, collections
from nps.errors import RejectedException, DeclinedException, ApiException
logging.basicConfig(level=logging.INFO)
class NpsSDK:
def __init__(self, url=None, cert_abspath= None, key_abspath = None):
self._url = url
self._cert_path = cert_abspath
self._key_path = key_abspath
self._setup()
def _pprint_response(func):
def inner(*args, **kwargs):
resp = func(*args, **kwargs)
if settings.debug:
print (resp)
return resp
return inner
def _setup(self):
oc = ObjectCache()
oc.setduration(days=utils.cache_ttl)
if not self._url:
self._url = settings.WSDL_URL
if settings.cert_path is not None:
t = RequestsTransport(cert=(settings.cert_path, settings.cert_key_path))
self._client = client.Client(self._url, transport=t, timeout=utils.TIMEOUT, cache=oc)
else:
self._client = client.Client(self._url, timeout=utils.TIMEOUT, cache=oc)
if settings.debug:
logging.getLogger('suds.client').setLevel(logging.DEBUG)
def __getattr__(self, name):
client = self._client
def add_secure_hash(func):
def inner(*args, **kwargs):
m = hashlib.md5()
od = collections.OrderedDict(sorted(args[0].items()))
concatenated_data = "".join([str(x).strip() for x in od.values() if type(x) is not dict]) + settings.KEY
concatenated_data = concatenated_data.encode('utf-8')
m.update(concatenated_data)
coded = m.hexdigest()
args[0].update({"psp_SecureHash": coded})
return func(*args, **kwargs)
return inner
def add_extra_info(func):
def inner(*args, **kwargs):
info = {"SdkInfo": utils.sdk.get('language') + ' ' + utils.sdk.get('version')}
args[0].update({"psp_MerchantAdditionalDetails": info})
return func(*args, **kwargs)
return inner
def _check_errors(func):
def inner(*args, **kwargs):
resp = func(*args, **kwargs)
if resp.psp_ResponseCod in ("3", "4", "5", "6", "7", "22"):
raise DeclinedException(resp)
if resp.psp_ResponseCod in ("8", "9", "10", "11", "12", "15", "21", "23"):
raise RejectedException(resp)
return inner
@add_extra_info
@add_secure_hash
#@_check_errors
def _soap_call(*args):
try:
response = getattr(client.service, name)(args[0])
return response
except MethodNotFound as e:
raise ApiException(name)
return _soap_call
| UTF-8 | Python | false | false | 3,146 | py | 8 | nps_sdk.py | 8 | 0.541004 | 0.532104 | 0 | 89 | 33.348315 | 120 |
leonardoquesquen/Proyecto3_302 | 7,584,912,266,763 | fe091696b924e3d862b8067722eef5eb07a9e249 | 76f5d63b77dd4369f3cf66709fef32383e24c89f | /proyecto3.py | c27a7069846707be7c7b18fb3b83bcb95123ace0 | []
| no_license | https://github.com/leonardoquesquen/Proyecto3_302 | 42e734e8f532ebde9d05a6e17bbc954300b4e4ba | 469a54c367553e0d07dfd27047a074bfa07e91fa | refs/heads/master | 2020-12-03T06:40:35.956487 | 2017-06-28T22:21:31 | 2017-06-28T22:21:31 | 95,715,899 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
from tkinter.colorchooser import askcolor
class Paint(object):
anchoPincel = 1.0
DEFAULT_COLOR = 'black'
def __init__(self):
self.ventana = Tk()
self.ventana.title("Proyecto de Introducción a la ciencia de la computación")
self.normal = Button(self.ventana, text='Normal', command=self.usoNormal)
self.normal.grid(row=0, column=0)
self.redondo = Button(self.ventana, text='Redondo', command=self.usoRedondo)
self.redondo.grid(row=0, column=1)
self.cuadrado = Button(self.ventana, text='Cuadrado', command=self.usoCuadrado)
self.cuadrado.grid(row=0, column=2)
self.colorSeleccion = Button(self.ventana, text='Color', command=self.eligeColor)
self.colorSeleccion.grid(row=0, column=3)
self.borrar = Button(self.ventana, text='Borrar', command=self.borrador)
self.borrar.grid(row=0, column=4)
self.tamanoBoton = Scale(self.ventana, from_=1, to=50, orient=HORIZONTAL)
self.tamanoBoton.grid(row=1, column=2)
self.areaDibujo = Canvas(self.ventana, bg='white', width=600, height=600)
self.areaDibujo.grid(row=2, columnspan=5)
self.old_x = None
self.old_y = None
self.ancho = self.tamanoBoton.get()
self.color = self.DEFAULT_COLOR
self.eraser_on = False
self.botonActivo = self.normal
self.botonActivo.config(relief=SUNKEN)
self.areaDibujo.bind('<B1-Motion>', self.paint)
self.tipo="normal"
self.ventana.mainloop()
def usoNormal(self):
self.tipo="normal"
self.activarBoton(self.normal)
def usoRedondo(self):
self.tipo="redondo"
self.activarBoton(self.redondo)
def usoCuadrado(self):
self.tipo="cuadrado"
self.activarBoton(self.cuadrado)
def eligeColor(self):
self.color = askcolor(color=self.color)[1]
def borrador(self):
self.tipo = "borrar"
self.activarBoton(self.borrar , eraser_mode=True)
def activarBoton(self, boton, eraser_mode=False):
self.botonActivo.config(relief=RAISED)
boton.config(relief=SUNKEN)
self.botonActivo = boton
self.eraser_on = eraser_mode
def paint(self, event):
self.ancho = self.tamanoBoton.get()
colorPintar = 'white' if self.eraser_on else self.color
x=event.x
y=event.y
if self.old_x and self.old_y:
if self.tipo=="normal":
self.areaDibujo.create_line(self.old_x, self.old_y, x, y,
width=self.ancho, fill=colorPintar,
capstyle=ROUND, smooth=TRUE, splinesteps=36)
elif self.tipo=="redondo":
r= self.ancho
self.areaDibujo.create_oval(x-r, y-r, x+r,y+r,outline=colorPintar , fill=colorPintar)
elif self.tipo=="cuadrado":
self.areaDibujo.create_rectangle(x, y,x+self.ancho , y+self.ancho, outline=colorPintar, fill=colorPintar, width=2)
else:
self.areaDibujo.create_line(self.old_x, self.old_y, x, y, width=self.ancho, fill=colorPintar, capstyle=ROUND, smooth=TRUE, splinesteps=36)
self.old_x = x
self.old_y = y
if __name__ == '__main__':
Paint()
| UTF-8 | Python | false | false | 2,864 | py | 1 | proyecto3.py | 1 | 0.713487 | 0.702306 | 0 | 94 | 29.446809 | 142 |
n-winspear/Stataflow-CS235-Flix | 6,347,961,693,400 | abddd4306ca1e87f3d90c49f8b2501e81143d998 | 08a715820056636d1c45d6bf285189d1219cbb32 | /backendflask/api/genre.py | b76f92028547519af51b6ee7bddc83637575262a | []
| no_license | https://github.com/n-winspear/Stataflow-CS235-Flix | 8bfeedef7c0c0ead11beb5dea62e957ac860f5f6 | fe56c0f68047e624bffbd605981f823e2f9194fa | refs/heads/master | 2023-01-02T04:50:07.550146 | 2022-04-11T09:17:28 | 2022-04-11T09:17:28 | 293,440,004 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from flask import make_response, jsonify
from flask_restful import Resource, reqparse
from backendflask.adapters.memoryrepository import MemoryRepository
from backendflask.adapters.gcloudrepository import GCloudRepository
from backendflask.domain_models.genre import Genre
import json
# DB Connection
db = MemoryRepository()
#db = GCloudRepository()
# Request Parser
parser = reqparse.RequestParser()
parser.add_argument('genreName', type=str,
help="Name of the genre")
class Genre(Resource):
def get(self, genreID: str) -> str:
genre = db.get_genre(genreID=genreID)
response = {
"successful": True if genre else False,
"genre": genre.toJSON(),
}
if response['successful']:
return make_response(jsonify(response), 200)
else:
return make_response(jsonify(response), 404)
def put(self, genreID: str) -> str:
args = parser.parse_args()
response = {
"successful": False,
"genreName": args['genreName'],
}
response['successful'] = True if db.update_genre(
Genre(
genreID=genreID,
genre_name=args['genreName'],
)
) else False
if response['successful']:
return make_response(jsonify(response), 201)
else:
return make_response(jsonify(response), 400)
def delete(self, genreID: str) -> str:
response = {
"successful": False,
}
response['successful'] = True if db.delete_genre(
genreID=genreID) else False
if response['successful']:
return make_response(jsonify(response), 200)
else:
return make_response(jsonify(response), 404)
| UTF-8 | Python | false | false | 1,794 | py | 43 | genre.py | 39 | 0.604236 | 0.594203 | 0 | 57 | 30.473684 | 67 |
Sun1Plus/SA-homework | 85,899,383,111 | d9cf361d93691177d440ce443c0923128d50d0fc | 93e1e500c336e3bd7c44d3ba521f77c570158ce5 | /project (py3)/ClientDemo2.py | 05ecd4fcea94b3b7ed1f866833afa16dee70f2e4 | []
| no_license | https://github.com/Sun1Plus/SA-homework | e7731ba13b00c294bb3c8e11d29dbe8a10657586 | e3afb3eb7e4288cda1a2dc6a8bb2ea3c8ef9fd83 | refs/heads/master | 2020-04-09T22:07:53.849072 | 2018-12-06T04:54:33 | 2018-12-06T04:54:33 | 160,620,737 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 51423))
data = s.recv(1024)
print(data)
# send the ID and key
str_Id = "admin"
s.send(str_Id.encode('utf-8'))
s.recv(1024)
str_key = "admin"
s.send(str_key.encode('utf-8'))
if ((s.recv(1024)).decode() == "login"):
myname = socket.getfqdn(socket.gethostname())
print(myname)
myaddr = socket.gethostbyname(myname)
print(myaddr)
while 1:
data = s.recv(1024).decode()
time.sleep(1)
print(data)
print(data=='alive?')
if data =='alive?':
str_yes = "yes"
s.send(str_yes.encode('utf-8'))
else:
break | UTF-8 | Python | false | false | 708 | py | 7 | ClientDemo2.py | 7 | 0.577684 | 0.532486 | 0 | 36 | 18.694444 | 53 |
atmark-techno/ThingsCloud-samples | 25,769,838,823 | c227b95b159522261c97024247c0fd2818383900 | e2074e71c0ed7d12afc850e10489dafba022cebe | /Armadillo-IoT_GW/modules/lib/active_reporter.py | 32ac3ffe5292042ea8f10b0901c69690d1b175e1 | [
"MIT"
]
| permissive | https://github.com/atmark-techno/ThingsCloud-samples | abe2ca81be9d8b6c352418dc2e86ea23c65f15d6 | 0f272283b0fb57f305b2f228ea1e3e787ddf80cf | refs/heads/main | 2023-06-10T00:46:45.658640 | 2021-07-05T04:18:25 | 2021-07-05T04:18:25 | 381,943,731 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import asyncio
from abc import ABC, abstractmethod
class ActiveReporter(ABC):
def __init__(self, report_queue, report_repository):
self._quit_requested = False
self._report_queue = report_queue
self._report_repository = report_repository
self._curr_state = None
def start_loop(self, timeout=None):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self._async_loop(timeout))
def request_stop(self):
self._quit_requested = True
async def _async_loop(self, timeout=None):
if timeout is not None:
started_at = int(time())
self._before_loop()
while not self._quit_requested:
self._handle_state()
if timeout is not None:
now = int(time())
if (now - started_at) >= timeout:
break
self._after_loop()
def _transit_state(self, next_state):
self._do_transit_action(next_state)
self._curr_state = next_state
@abstractmethod
def _before_loop(self):
pass
@abstractmethod
def _after_loop(self):
pass
@abstractmethod
def _handle_state(self):
pass
@abstractmethod
def _do_transit_action(self, next_state):
pass
#
# End of File
#
| UTF-8 | Python | false | false | 1,362 | py | 38 | active_reporter.py | 32 | 0.575624 | 0.575624 | 0 | 56 | 23.303571 | 58 |
ARWongQ/artificialntelligence_FinalProject | 12,463,995,098,067 | 90204f9a9952211924de6566e0333a5e85bd340d | 45c398a04ac78f9485b0e4cecd0cda23152e1472 | /rolloutAgent.py | 221142d52c7bb796abc005ceeba13fe7848f653a | []
| no_license | https://github.com/ARWongQ/artificialntelligence_FinalProject | fe23f03aa9d3bf95b32e2081cae63478d0d5762c | 681135f207b88e853b705d5e71b3a0149725d4a4 | refs/heads/master | 2021-04-15T08:05:41.563142 | 2018-05-01T15:42:22 | 2018-05-01T15:42:22 | 126,395,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import random
import UltimateTTT
import copy
from randomAgent import randomAgent
#This class holds the information of an agent that uses rollout
class rolloutAgent:
def __init__(self):
self.name = "Rollout Agent"
self.firstMove = None
#Uses rollout to pick a next move
def getMove(self, world, possibleMoves, currentPlayer):
rolloutMultiplier = 500
printInfo = 1000
#print(possibleMoves)
#500 rollouts per move
rolloutNum = len(possibleMoves) * rolloutMultiplier
wins = [0] * len(possibleMoves)
#Do everything randomly after the first move
randAgent = randomAgent()
randAgent2 = randomAgent()
for i in xrange(rolloutNum):
#Keep track on which move to update
moveIdx = i%len(possibleMoves)
firstMove = possibleMoves[moveIdx]
randAgent.firstMove = firstMove
#Perform a random game on this UTTT board
worldCopy = copy.deepcopy(world)
worldCopy.setVerbose(0)
winner = worldCopy.playThree(randAgent, randAgent2)
# print('Finished one rollout\n')
if winner == currentPlayer:
wins[moveIdx] += 1
chosenMove = wins.index(max(wins))
# self.firstMove = None
# #After the game ended check who was the winner!
# winner = worldCopy.playThree(randAgent, randAgent2)
#
# #print every 250 moves
# # if(i % printInfo == 0 and i != 0):
# # print("Finished #" + str(i) + " rollout\n")
#
# #Utility function
# if(worldCopy.wonBy == currentPlayer):
# wins[moveIdx] += 20
#
# for i in xrange(3):
# for j in xrange(3):
# TTTBoard =worldCopy.mainGrid[i][j]
# if(TTTBoard.wonBy == currentPlayer):
# wins[moveIdx] += 1
# elif(TTTBoard.wonBy == 'O'):
# wins[moveIdx] -= 0.5
#
# chosenMove = wins.index(max(wins))
#self.firstMove = None
return possibleMoves[chosenMove]
#Returns a wanting boards
def getBoardMove(self, possibleBoards):
#pick a board
if len(possibleBoards) == 1:
return possibleBoards[0]
else:
i =random.randint(0,len(possibleBoards)-1)
return possibleBoards[i]
| UTF-8 | Python | false | false | 2,490 | py | 8 | rolloutAgent.py | 7 | 0.553815 | 0.540964 | 0 | 79 | 30.506329 | 65 |
web-2u/cmsplugin-aea-video | 4,011,499,501,591 | 9b162388026bc486f100807cbbad72898a9fcd68 | 0a2e38bd2a3bb7b829aa507efe009e245b8491c4 | /cms_plugins.py | 361bd968237fea0b98d0bd672a8cfe3761214b09 | [
"MIT"
]
| permissive | https://github.com/web-2u/cmsplugin-aea-video | 9c0de335089f70abe2bde5ae265a8fd1cba82060 | 0d12a9d12b4dc56206c0b665247d9207db355f12 | refs/heads/master | 2020-12-24T14:01:37.197374 | 2015-06-13T22:57:36 | 2015-06-13T22:57:36 | 37,389,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
import os
from django.utils.translation import ugettext_lazy as _
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from filer.settings import FILER_STATICMEDIA_PREFIX
from plugin.models import ALN_Video
class ALN_VideoPlugin(CMSPluginBase):
model = ALN_Video
name = _("ALN_Video Video (Filer)")
render_template = "cmsplugin_filer_alnvideo/video.html"
text_enabled = True
general_fields = [
'title',
'movie_url',
('movie_ratio', 'width', 'height'),
('auto_play', 'auto_hide'),
('fullscreen', 'loop'),
]
fieldsets = [
(None, {
'fields': general_fields,
}),
(_('formats'), {
'fields': ('video_mp4', 'video_webm', 'video_ogv', 'image')
})
]
def render(self, context, instance, placeholder):
formats = {}
for format in ('video_mp4', 'video_webm', 'video_ogv'):
if getattr(instance, format + '_id'):
formats[format.replace('_', '/')] = getattr(instance, format).url
context.update({
'object': instance,
'placeholder': placeholder,
'formats': formats
})
return context
def icon_src(self, instance):
return os.path.normpath(u"%s/icons/video_%sx%s.png" % (FILER_STATICMEDIA_PREFIX, 32, 32,))
plugin_pool.register_plugin(ALN_VideoPlugin) | UTF-8 | Python | false | false | 1,447 | py | 8 | cms_plugins.py | 5 | 0.579129 | 0.574292 | 0 | 52 | 26.846154 | 98 |
tefra/xsdata-w3c-tests | 17,265,768,534,045 | ea5a91e6795e5d82ba2136a5b7c774ee4b991cae | ad13583673551857615498b9605d9dcab63bb2c3 | /output/instances/nistData/atomic/token/Schema+Instance/NISTXML-SV-IV-atomic-token-pattern-3-2.py | 36ed7a888f35127d17b34cc2374176608efdf807 | [
"MIT"
]
| permissive | https://github.com/tefra/xsdata-w3c-tests | 397180205a735b06170aa188f1f39451d2089815 | 081d0908382a0e0b29c8ee9caca6f1c0e36dd6db | refs/heads/main | 2023-08-03T04:25:37.841917 | 2023-07-29T17:10:13 | 2023-07-30T12:11:13 | 239,622,251 | 2 | 0 | MIT | false | 2023-07-25T14:19:04 | 2020-02-10T21:59:47 | 2023-01-18T19:44:58 | 2023-07-25T14:19:02 | 36,096 | 2 | 0 | 0 | Python | false | false | from output.models.nist_data.atomic.token.schema_instance.nistschema_sv_iv_atomic_token_pattern_3_xsd.nistschema_sv_iv_atomic_token_pattern_3 import NistschemaSvIvAtomicTokenPattern3
obj = NistschemaSvIvAtomicTokenPattern3(
value="59353 And Work Product Tools Street Is Well Base , NC 13653"
)
| UTF-8 | Python | false | false | 300 | py | 18,966 | NISTXML-SV-IV-atomic-token-pattern-3-2.py | 14,569 | 0.816667 | 0.77 | 0 | 6 | 49 | 182 |
dagege1993/codeformyself | 10,368,051,089,374 | e1fa91558553b2112e261de431a82345fd68302d | 1787eb394653a963377f977980125e0d05a2ddbb | /IDGdemo/Downloads/mysql/360sql语句/5.查询下载量前100app的每个月的下载量变化.py | eb0aa952182b9ca82a668581da643d0501c3416a | []
| no_license | https://github.com/dagege1993/codeformyself | 51283169b819309e63c135ebca501f87d37a1651 | 0b32c6e1b224f543d23e284104d311f2a5c41475 | refs/heads/master | 2021-10-25T01:23:59.036132 | 2019-06-06T06:23:37 | 2019-06-06T06:23:37 | 146,266,239 | 7 | 8 | null | false | 2021-10-06T23:16:41 | 2018-08-27T08:03:11 | 2021-07-14T12:44:14 | 2021-10-06T23:16:40 | 40,736 | 7 | 9 | 14 | HTML | false | false | import csv
import pymysql
db = pymysql.connect("192.168.103.31", "root", "adminadmin", "downloads")
cursor = db.cursor()
month_list = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
data_list = []
for i, month in enumerate(month_list):
if i < len(month_list) - 1:
sql = """select max(stat_dt),min(stat_dt) from ANDROID_SAFE_APP_DAILY where dt_type='周' and stat_dt>='2018-%s-01' and stat_dt<'2018-%s-01'""" % (
month, month_list[i + 1])
cursor.execute(sql)
data_set = cursor.fetchone()
start_time = data_set[1]
end_time = data_set[0]
if start_time:
change_sql = """
select b.app_name,b.category,a.* from (select a.*,chg/datediff('%s','%s')*30 as chg_month from ( select *,(downs-f_downs) as chg from (select app_keys,downs,(select downs from ANDROID_SAFE_APP_DAILY where dt_type='周' and stat_dt='%s' and app_keys=a.app_keys) as f_downs
from ANDROID_SAFE_APP_DAILY a where dt_type='周' and stat_dt='%s' and app_keys in (select t.app_keys from (select app_keys from (select app_keys,avg(downs) downs from ANDROID_SAFE_APP_TOP WHERE stat_dt = '2018-12-23' GROUP BY app_id) a ORDER BY downs desc limit 100 ) as t) and stat_dt>='2018-01-01' and stat_dt<'2018-12-31' ) a )a )a left join ANDROID_SAFE_APP b on (a.app_keys=b.app_keys)
""" % (end_time, start_time, start_time, end_time)
print(change_sql)
cursor.execute(change_sql)
# 提交到数据库执行
serch_data = cursor.fetchall()
for serch in serch_data:
serch = list(serch)
serch.append(start_time)
data_list.append(serch)
filename = '100app' + '.csv'
with open(filename, 'a+', newline='') as f:
writer = csv.writer(f)
# head_list = ['app名字', '一级类','app_keys','']
# writer.writerow(head_list)
for row in data_list:
writer.writerow(row)
print(data_list)
| UTF-8 | Python | false | false | 1,983 | py | 715 | 5.查询下载量前100app的每个月的下载量变化.py | 617 | 0.594567 | 0.552025 | 0 | 38 | 50.342105 | 393 |
gdefias/StudyPython | 9,208,409,890,371 | a7d3ba47a52691508fdbdc75d44db233e07b58f7 | 0c2b9d1dd4e92b623394f3915bfcb95b49953441 | /Python/test_base/test_random.py | 0e810eb31775d9a0460caab81dc2975d7ddd03a7 | [
"Apache-2.0"
]
| permissive | https://github.com/gdefias/StudyPython | ea49e00c2e4bc7768c93da5753a1230af29e0153 | c0a3273b7d5f95803a56c5481865e38145923556 | refs/heads/master | 2017-02-24T21:25:18.924402 | 2017-02-11T15:56:53 | 2017-02-11T15:56:53 | 47,770,013 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding=utf8
import os
import string
import random
# print ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(16)))
print ''.join([(string.ascii_letters+string.digits)[x] for x in random.sample(range(0,62),11)])
#随机电话号码
print '158' + ''.join([str(random.randint(0, 9)) for x in range(0,8)])
| UTF-8 | Python | false | false | 309 | py | 745 | test_random.py | 642 | 0.670034 | 0.616162 | 0 | 13 | 21.846154 | 95 |
dailylifes/rClock | 2,010,044,708,246 | 0e33742f95ea739325bf7a419c1f5b7510e2b663 | cd5d251fb710f834ac1f7d388da1e4eff36fbecb | /GUI.py | 1c6de164d715f284a3149ff3f56b49062ef230a7 | []
| no_license | https://github.com/dailylifes/rClock | 1c73864afbf5d5cccd9d51326ba889ac6de78266 | 2d5d45b7765df1a8ed8b327882eb806e2df68317 | refs/heads/master | 2023-03-26T04:23:29.307995 | 2021-03-24T10:31:23 | 2021-03-24T10:31:23 | 246,729,815 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pygame
from datetime import datetime
import math,time
pygame.init()
clock = pygame.time.Clock()
surface = pygame.display.set_mode((1440, 720))
surfrect = surface.get_rect()
if surfrect.h>surfrect.w:
q = surfrect.w // 2
center2=q,q*3
else :
q = surfrect.h // 2
center2=q*3,q
center1=q,q
RADIUS = q - 50
radius_list = {'sec': RADIUS +10, 'min': RADIUS - 55, 'hour': RADIUS - 100, 'digit': RADIUS - 30}
arc = RADIUS + 8
clock60 = dict(zip(range(0,60,1), range(0, 360, 6))) # for hours, minutes and seconds
font = pygame.font.SysFont('Verdana', 60)
#img = pygame.image.load('img/2.png').convert_alpha()
#bg = pygame.image.load('img/bg4.jpg').convert()
#bg_rect = bg.get_rect()
#bg_rect.center = WIDTH, HEIGHT
#dx, dy = 1, 1
# x = H_WIDTH + radius_list[key] * math.cos(math.radians(clock_dict[clock_hand]) - math.pi / 2)
# y = H_HEIGHT + radius_list[key] * math.sin(math.radians(clock_dict[clock_hand]) - math.pi / 2)
def clock_pos(center, clock_hand, key):
x = center[0] + radius_list[key] * math.cos(math.radians(clock_hand*6) - math.pi / 2)
y = center[1] + radius_list[key] * math.sin(math.radians(clock_hand*6) - math.pi / 2)
return x, y
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# dx *= -1 if bg_rect.left > 0 or bg_rect.right < WIDTH else 1
# dy *= -1 if bg_rect.top > 0 or bg_rect.bottom < HEIGHT else 1
# bg_rect.centerx += dx
# bg_rect.centery += dy
# surface.blit(bg, bg_rect)
# surface.blit(img, (0, 0))
surface.fill((0,0,0))
t = datetime.now()
hour, minute, second = ((t.hour % 12) * 5 + t.minute // 12) % 60, t.minute, int(t.strftime("%S"))+time.time()%1 # t.second
time_render = font.render(f'{t:%H:%M:%S}', True, pygame.Color('#00FF00'), pygame.Color('#555555'))
surface.blit(time_render, (q-117, q+100))
for digit, pos in clock60.items():
radius = 20 if not digit % 3 and not digit % 5 else 8 if not digit % 5 else 2
pygame.draw.circle(surface, pygame.Color('gainsboro'), clock_pos(center1,digit, 'digit'), radius, 7)
pygame.draw.line(surface, pygame.Color('orange'), center1, clock_pos(center1,hour, 'hour'), 15)
pygame.draw.line(surface, pygame.Color('green'), center1, clock_pos(center1,minute, 'min'), 7)
pygame.draw.line(surface, pygame.Color('magenta'), center1, clock_pos(center1,second, 'sec'), 4)
pygame.draw.circle(surface, pygame.Color('#FFFFFF'), center1, 8)
sec_angle = -math.radians(second*6) + math.pi / 2
pygame.draw.arc(surface, pygame.Color('#00FFFF'),
(q - arc, q - arc, 2 * arc, 2 * arc),
math.pi / 2, sec_angle, 8)
h =int(datetime.now().strftime("%H")) # hours
m = int(datetime.now().strftime("%M")) # minutes
s = int(datetime.now().strftime("%S"))+time.time()%1 # seconds upto nano seconds
rh = h+22 if h<2 else h-2 # r hours
rnow = rh*4.1666666667+m*0.06944444+s*0.001157 # 100/24/60/60
rr=str(rnow*10**10)[:6]
rrm=(rnow%1)*60
rrs=(rnow%0.01)*6000
time_render = font.render(f'{rr[:2]}:{rr[2:4]}:{rr[4:6]}', True, pygame.Color('#00FF00'), pygame.Color('#555555'))
surface.blit(time_render, (center2[0]-117, center2[1]+100))
for digit in range(100):
radius = 20 if not digit % 100 and not digit % 5 else 8 if not digit % 10 else 2
pygame.draw.circle(surface, pygame.Color('gainsboro'), clock_pos(center2, digit*0.6, 'digit'), radius, 7)
pygame.draw.line(surface, pygame.Color('#FF0000'), center2, clock_pos(center2,rnow*0.6, 'hour'), 15)
pygame.draw.line(surface, pygame.Color('green'), center2, clock_pos(center2,rrm, 'min'), 7)
pygame.draw.line(surface, pygame.Color('magenta'), center2, clock_pos(center2,rrs, 'sec'), 4)
pygame.draw.circle(surface, pygame.Color('#FFFFFF'), center2, 8)
sec_angle = -math.radians(rrs*6) + math.pi / 2
pygame.draw.arc(surface, pygame.Color('#00FFFF'),
(center2[0] - arc, center2[1]- arc, 2 * arc, 2 * arc),
math.pi / 2, sec_angle, 8)
pygame.display.flip()
clock.tick(60)
| UTF-8 | Python | false | false | 4,114 | py | 4 | GUI.py | 3 | 0.619105 | 0.559067 | 0 | 87 | 46.287356 | 129 |
nabw/InternetControl | 5,849,745,504,852 | 049ea7a64c8cea1946ce72e01814ac410aef2e5b | dee8613a99dc5fcb076f34a14726d28d6df20e59 | /InternetControl.py | a0621ef9dea6baeb5621a43468702ed680cbed1d | [
"Apache-2.0"
]
| permissive | https://github.com/nabw/InternetControl | 6cbae5471de377bacf7a782c30fda5010c1f11f9 | fbc9040c8a1f6bbe2064b781087c808e02a097dc | refs/heads/master | 2021-01-10T07:00:26.752715 | 2016-02-21T06:23:56 | 2016-02-21T06:23:56 | 51,488,072 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 14:12:48 2016
@author: Nico Barnafi
"""
#import threading
import sys
ideal_down = 80.
ideal_up = 40.
def listen_write(T):
from time import time, ctime, sleep
from speedtest_cli import speedtest
from Twitter import Twitter
def mean(l):
return float(sum(l))/len(l)
def write_to_log(m):
f = open('log', 'r')
texto = f.read()
f.close()
f = open('log','w')
texto = texto + '%s' % m
f.write(texto)
f.close()
# Twt = Twitter()
data = []
unit = 1000000
print 'Simulate for %.2f hours' % T
current_T = time()
start_T = time()
mins_5, dia = 300, 86400
diff_update = 0
diff_tweet = 86400
speeds_down, speeds_up = [], []
while current_T - start_T <= T*3600:
if current_T - start_T >= diff_update:
print '%.2f/%.2f hours to go' % (current_T/3600.-start_T/3600., T)
try:
down, up = speedtest()
except:
print 'Connection error, restarting...'
continue
speeds_down.append(down)
speeds_up.append(up)
line = '%s;%.2f;%.2f\n' % (ctime(),down/unit, up/unit)
write_to_log(line)
#data.append('%s;%.2f;%.2f\n' % (ctime(),down/unit, up/unit))
current_T = time()
diff_update += mins_5 # Update every 5 minutes
else:
sleep(30)
current_T = time()
if current_T - start_T >= diff_tweet and mean(speeds_down)/unit < ideal_down and mean(speeds_up)/unit < ideal_up:
msge = '%.2f Down y %.2f Up (avg diario) es menos de lo acordado o no? #VTR #ParenDeCagarme' % (mean(speeds_down)/unit, mean(speeds_up)/unit)
# Twt.tweet(msge)
diff_tweet += dia
current_T = time()
def monitor(T):
print "InternetSpeed monitor started. Monitoring for %.2f hours (%.0f days) " % (T, T/24.)
f = open('log','w')
f.close()
D = listen_write(T)
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-t', type = float, dest='sim_time', help='Time to control in hours.', required = True)
args = parser.parse_args()
T = args.sim_time
monitor(T)
print 'Done... profit.'
| UTF-8 | Python | false | false | 2,455 | py | 3 | InternetControl.py | 2 | 0.517719 | 0.49002 | 0 | 78 | 29.371795 | 153 |
cassandra-server/PrintCodeBot | 3,006,477,110,596 | fa4181ee6788a1840de6ed41dd4a7036ab88591a | f62a606aff0524006463cf0643e217c0b2810803 | /printcodebot.py | 126d35302de77130c295cc22bd2fa89b53b57b56 | [
"MIT"
]
| permissive | https://github.com/cassandra-server/PrintCodeBot | bfc29aa5c90e7d714058250ca50c0d7dd15e7299 | 58d8d3db44a514b0e6d25bd38bbc3d805202cb5c | refs/heads/master | 2023-02-20T05:52:00.404525 | 2021-01-24T11:51:44 | 2021-01-24T11:51:44 | 299,023,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
import subprocess
import sys
def get_data (raw, value): #value: 0 --> default / 1 --> usernames / 2 --> groups
ug_data = raw.split(',')
if value == 0:
path = 'config/defaults.txt'
elif value == 1:
path = 'config/users.txt'
elif value == 2:
path = 'config/groups.txt'
f = open(path, 'r')
lines = []
for line in f:
lines.append(line)
f.close()
addressees = []
if value == 2 or value == 0:
for group in ug_data:
for line in lines:
if (group == line.split(' ')[0]):
if (group == 'token'):
return line.split(' ')[1].replace('\n','')
addressees.extend(get_data(line.split(' ')[1].replace('\n',''), 1))
break
elif value == 1:
for username in ug_data:
if username.isnumeric():
addressees.append(username)
else:
for line in lines:
if username == line.split(' ')[0]:
addressees.append(line.split(' ')[1])
break
return addressees
def new_configuration ():
print ("WELCOME TO THE CONFIGURATION OF PRINT CODE BOT")
print ("----------------------------------------------")
print ("\nTOKEN:")
token = input("Paste here your token: ")
print ("\nUSERNAMES:")
answer = 'y'
usernames = []
while (answer == 'y'):
usernames.append(input("Write a default username for the machine [alias/id]? ").replace('\n',''))
answer = input ("Do you wish to add another username [Y/N]? ").lower()
f = open ('config/defaults.txt', 'w+')
f.write ("token " + token + '\n')
f.write ("addressees ")
for username in usernames:
f.write(username + ',')
f.close()
print ("CONFIGURATION ENDED! THANKS :)")
exit()
def add(value): #value: 0 --> defaults / 1 --> usernames / 2 --> groups
entries = []
if value == 0:
path = 'config/defaults.txt'
print ("WELCOME TO THE ADD DEFAULT USER DIALOG")
print ("--------------------------------------")
elif value == 1:
path = 'config/users.txt'
print ("WELCOME TO THE ADD USER DIALOG")
print ("---------------------------------")
elif value == 2:
path = 'config/groups.txt'
print ("WELCOME TO THE ADD GROUP DIALOG")
print ("-------------------------------")
f = open (path, 'a')
answer = 'y'
while (answer == 'y'):
if value == 0:
print ("\nNEW DEFAULT USER:")
id = input("Alias/Id: ")
entries.append(id + ',')
answer = input("Do you wish to add another username [Y/N]? ").lower()
elif value == 1:
print ("\nNEW USER:")
alias = input("Alias: ")
id = input("Id: ")
entries.append(alias + " " + id + "\n")
answer = input("Do you wish to add another username [Y/N]? ").lower()
elif value == 2:
print ("\nNEW GROUP:")
alias = input("Group alias: ")
id = ""
answer2 = 'y'
while (answer2 == 'y'):
print ('\nNEW USER IN "' + alias + '" GROUP')
id = id + input ("Alias/Id: ").replace('\n','') + ","
answer2 = input("Do you wish to add another username to group [Y/N]? ")
entries.append(alias + " " + id + "\n")
answer = input ("Do you wish to add another group [Y/N]? ").lower()
for entry in entries:
f.write(entry)
f.close()
print ("DIALOG ENDED! THANKS :)")
exit()
arguments = sys.argv
if (len(arguments) == 2):
if (arguments[1] == "-c"):
new_configuration()
if (arguments[1] == "--add-default-user"):
add(0)
if (arguments[1] == "--add-user"):
add(1)
if (arguments[1] == "--add-group"):
add(2)
bot = telegram.Bot(str(get_data("token", 0)))
code = ""
usernames_raw = ""
groups_raw = ""
addressees = []
specifiedUsers = False
specifiedGroups = False
for i in range (1, len(arguments)):
if (arguments [i] == "-u"):
specifiedUsers = True
addressees.extend(get_data(arguments[i+1], 1))
if (arguments [i] == "-g"):
specifiedGroups = True
addressees.extend(get_data(arguments[i+1], 2))
if (arguments [i] == "-f"):
code += arguments[i+1] + " "
if (specifiedUsers==False and specifiedGroups==False):
addressees.extend(get_data("addressees", 0))
code += "> .stuff.txt"
subprocess.call(code, shell=True)
f = open(".stuff.txt", 'r')
text2 = ""
for line in f:
text2 += line
f.close()
for addressee in list(dict.fromkeys(addressees)):
bot.send_message(chat_id=addressee, text=text2)
| UTF-8 | Python | false | false | 4,199 | py | 3 | printcodebot.py | 1 | 0.585377 | 0.574422 | 0 | 160 | 25.24375 | 99 |
V-Sekai/BlenderSynth | 12,541,304,551,339 | d4570e5ed00455decbf157cadc226c154db35620 | 5dbabad0e2ee092619cab8f8c46f7cc606671837 | /blendersynth/blender/armature.py | dbcac5d8775fe5e02f01e0dd08102f6bb2db2e71 | [
"MIT"
]
| permissive | https://github.com/V-Sekai/BlenderSynth | 5b4249d64db7013e0c3d97801aac6d35b4bb6eb6 | 800518d448e6153c1fd6f08fa89d63e57634aed3 | refs/heads/main | 2023-09-04T00:50:58.990026 | 2023-09-04T00:18:30 | 2023-09-04T00:18:30 | 686,787,856 | 0 | 0 | null | true | 2023-09-03T23:48:27 | 2023-09-03T23:48:26 | 2023-09-03T23:48:27 | 2023-08-31T13:41:53 | 23,887 | 0 | 0 | 0 | null | false | false | """Armature object for managing pose"""
from .bsyn_object import BsynObject, animatable_property
from .other_objects import Empty
from .utils import SelectObjects, SetMode
from typing import Union
from ..utils import types
import bpy
import mathutils
class PoseBone(BsynObject):
def __init__(self, object: bpy.types.PoseBone):
self._object = object
@property
def name(self) -> str:
return self.obj.name
@property
def constraints(self):
return self.obj.constraints
@property
def armature(self):
return self.obj.id_data
@property
def matrix_world(self):
return self.armature.matrix_world @ self.obj.matrix
@property
def location(self) -> mathutils.Vector:
"""
Gets the world location of the head (start) of the bone.
"""
return self.obj.head
@property
def head_location(self) -> mathutils.Vector:
"""
Gets the world location of the head (start) of the bone.
"""
return self.armature.matrix_world @ self.obj.head
@property
def tail_location(self) -> mathutils.Vector:
"""
Gets the world location of the tail (or end) of the bone.
"""
return self.armature.matrix_world @ self.obj.tail
@property
def rotation_euler(self) -> mathutils.Euler:
return self.matrix_world.to_euler()
@animatable_property('scale')
def set_scale(self, scale: types.VectorLikeOrScalar):
"""Set scale of pose bone.
:param scale: Scale to set. Either single value or 3 long vector"""
if isinstance(scale, (int, float)):
scale = (scale, scale, scale)
self.obj.scale = scale
class BoneConstraint(BsynObject):
"""Generic pose bone constraint object"""
def __init__(self, pose_bone: PoseBone, constraint: bpy.types.Constraint, empty: Empty):
self.pose_bone = pose_bone
self.constraint = constraint
self.empty = empty
self._object = empty.obj
@property
def name(self):
return f"{self.constraint.name}: {self.pose_bone.name} -> {self.empty.name}"
@property
def bone(self):
return self.pose_bone
def remove(self):
"""Remove this constraint."""
self.bone.constraints.remove(self.constraint)
if self.empty is not None:
self.empty.remove()
@property
def armature(self):
return self.bone.id_data
class Armature(BsynObject):
"""This class manages armatures - a collection of posable bones."""
def __init__(self, object: bpy.types.Armature):
self._object = object
self.ik_constraints = {} # for IK constraints
self.constraints = {} # for generic constraints
self.pose_bones = {n: PoseBone(b) for n, b in object.pose.bones.items()}
@property
def name(self) -> str:
return self.obj.name
@property
def pose(self) -> bpy.types.Pose:
return self.obj.pose
def get_bone(self, bone: Union[str, PoseBone, bpy.types.PoseBone]) -> PoseBone:
"""
Get bone from armature.
:param bone_name: Name of bone to get (or PoseBone object)
:return: PoseBone object
"""
if isinstance(bone, PoseBone):
return bone
if isinstance(bone, bpy.types.PoseBone):
return self.pose_bones[bone.name]
if isinstance(bone, str):
return self.pose_bones[bone]
raise TypeError(f"Expected bone to be PoseBone, str, or PoseBone, got {type(bone)}")
def pose_bone(self, bone: Union[str, bpy.types.PoseBone], rotation: types.VectorLike = None,
location: types.VectorLike = None, scale: types.VectorLike = None,
frame: int = None):
"""Set the pose of a bone by giving a Euler XYZ rotation and/or location.
:param bone: Name of bone to pose, or PoseBone object
:param rotation: Euler XYZ rotation in radians
:param location: Location of bone
:param scale: Scale of bone
:param frame: Frame to set pose on. If given, will insert keyframe here.
"""
with SetMode('POSE', object=self.obj):
if isinstance(bone, str):
bone = self.get_bone(bone)
bone.rotation_mode = 'XYZ'
if rotation is not None:
bone.set_rotation_euler(rotation, frame=frame)
if location is not None:
bone.set_location(location, frame=frame)
if scale is not None:
bone.set_scale(scale, frame=frame)
def clear_pose(self, rot=True, location=True, scale=True, bones=None):
"""Clear the pose of the armature.
For the target bones, sets poses to zero, and removes any IK constraints.
:param rot: Clear rotation
:param location: Clear location
:param scale: Clear scale
:param bones: List of bones to clear. If not given, will clear all bones.
"""
with SetMode('POSE', object=self.obj):
for bone in self.pose.bones:
if bones is None or bone.name in bones:
if rot:
bone.rotation_euler = (0, 0, 0)
if location:
bone.location = (0, 0, 0)
if scale:
bone.scale = (1, 1, 1)
for bone_name in self.ik_constraints.keys():
if bone_name == bone.name:
self.ik_constraints[bone_name].remove() # remove the constraint
self.ik_constraints.pop(bone_name) # remove reference to it
for cname in [*self.constraints.keys()]:
constraint = self.constraints[cname]
if constraint.pose_bone.name == bone.name:
self.constraints[cname].remove()
self.constraints.pop(cname)
def add_constraint(self, bone: Union[str, PoseBone], constraint_name: str, target:Empty=None, **kwargs) -> BoneConstraint:
"""
Applies a generic bone constraint. Returns BoneConstraint object
:param bone: Bone to apply constraint to
:param constraint_name:
:param target: Empty target. If none given, will create one.
Any other constraint specific keyword arguments given as well will be fed into the new constraint
"""
bone = self.get_bone(bone)
# Add IK constraint to the specified bone
constraint = bone.constraints.new(constraint_name)
for k, v in kwargs.items():
setattr(constraint, k, v)
# Create an empty to serve as the IK target
if target is None:
target = Empty(name="Target_For_" + bone.name)
constraint.target = target.object
bpy.context.view_layer.update()
constraint = BoneConstraint(bone, constraint, target)
self.constraints[constraint.name] = constraint
return constraint
| UTF-8 | Python | false | false | 6,004 | py | 82 | armature.py | 66 | 0.701033 | 0.699367 | 0 | 219 | 26.415525 | 123 |
mayfield/aionanomsg | 2,765,958,983,045 | f57419ffb6e7a8e96469e81db9e8a71d129a67ce | d39725442cce65ffa069b544a95f2d18c3e0637d | /aionanomsg/pubsub.py | 84f3b6b1a340c7cb99a2d52a26d09f285716e936 | [
"MIT"
]
| permissive | https://github.com/mayfield/aionanomsg | 47bde1e9c8741fb080e984fbfb529c138c45fb9c | eae4d56b97031f130dce1a4097592e79c30d9364 | refs/heads/master | 2020-12-26T07:03:32.656364 | 2016-12-01T05:38:34 | 2016-12-01T05:38:34 | 68,728,648 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
aionanomsg pubsub high-level wrapper for NNSocket.
While possible to use aionanomsg.NNSocket directly for pubsub this module
provides a higher level interface for doing pubsub that allows more natural
interaction from a python type program.
"""
import asyncio
from . import socket, symbols
class Subscriber(socket.NNSocket):
""" An NN_SUB based NNSocket with extra sauce for easy living. """
def __init__(self, **kwargs):
self._listeners = {}
self._stopping = False
self._router_task = None
super().__init__(symbols.NN_SUB, **kwargs)
self._stopped = asyncio.Event(loop=self._loop)
def subscribe(self, topic:str, listener):
""" Bind this socket to a topic and hook the listener func/coro to
that topic so it will run on any published data addressed to it. """
topic = topic.encode()
if topic not in self._listeners:
self.setsockopt(symbols.NN_SUB, symbols.NN_SUB_SUBSCRIBE, topic)
self._listeners[topic] = []
self._listeners[topic].append(listener)
def unsubscribe(self, topic:str, listener):
topic = topic.encode()
self._listeners[topic].remove(listener)
def start(self):
""" Start handling published data to our topics. """
assert not self._stopping
self._router_task = self._loop.create_task(self._router())
def stop(self):
if self._stopping:
return
self._stopping = True
async def wait_stopped(self):
""" Block until the subscriber is completely shutdown. """
if self._router_task is None:
return
await self._stopped.wait()
async def _router(self):
""" Route messages to the correct listeners. """
try:
while not self._stopping:
data = await self.recv()
topic, msg = data.split(b'|', 1)
listeners = self._listeners[topic]
for x in listeners:
asyncio.ensure_future(x(msg), loop=self._loop)
finally:
self._stopped.set()
class Publisher(socket.NNSocket):
""" An NN_PUB based NNSocket with extra sauce for easy living. """
def __init__(self, **kwargs):
super().__init__(symbols.NN_PUB, **kwargs)
async def publish(self, topic:str, msg:bytes):
""" Publish a pre-encoded (bytes) message to a topic. """
await self.send(b'%s|%s' % (topic.encode(), msg))
| UTF-8 | Python | false | false | 2,477 | py | 8 | pubsub.py | 6 | 0.607186 | 0.606782 | 0 | 73 | 32.931507 | 76 |
kateapl/python_hw | 2,413,771,649,989 | 4ad0f37c8261bed40aec22f4a45a1abb5717db92 | 67ec8ed9811c4651726f8df7225408a0c3366fb0 | /homework6/counter.py | 9cb504ca5838e80d9f22c1e2991c68185193055b | []
| no_license | https://github.com/kateapl/python_hw | ca87266fb315f61e59415dad1f860717c0d58422 | 8d684698a36e29aedc9c9aea5c9ff4e1b0059010 | refs/heads/main | 2023-04-17T10:21:49.095849 | 2021-05-07T09:55:28 | 2021-05-07T09:55:28 | 343,718,071 | 0 | 0 | null | false | 2021-05-07T09:55:29 | 2021-03-02T09:32:29 | 2021-05-05T19:25:58 | 2021-05-07T09:55:28 | 181 | 0 | 0 | 0 | Python | false | false | """
Написать декоратор instances_counter, который применяется к любому классу
и добавляет ему 2 метода:
get_created_instances - возвращает количество созданых экземпляров класса
reset_instances_counter - сбросить счетчик экземпляров,
возвращает значение до сброса
Имя декоратора и методов не менять
Ниже пример использования
"""
def instances_counter(cls):
"""Some code"""
class AClass(cls):
__instance = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
AClass.__instance += 1
@classmethod
def get_created_instances(cls) -> int:
return cls.__instance
@classmethod
def reset_instances_counter(cls) -> int:
count = cls.__instance
AClass.__instance = 0
return count
return AClass
@instances_counter
class User:
pass
if __name__ == '__main__':
User.get_created_instances() # 0
user, _, _ = User(), User(), User()
user.get_created_instances() # 3
user.reset_instances_counter() # 3
| UTF-8 | Python | false | false | 1,282 | py | 55 | counter.py | 49 | 0.620075 | 0.613508 | 0 | 44 | 23.227273 | 73 |
Modupeolawuraola/python_examples | 17,798,344,501,745 | 4992c4124c274fe3a20f1fabfbfcb54acf5b6b36 | 87a0303aa883ab4ea21d993846c3fcc14dad94a1 | /smaller_number.py | 859e1145ef2a796c9ec127b297b0f86ecaf6a853 | []
| no_license | https://github.com/Modupeolawuraola/python_examples | 60737252afca8cdca281be1cacab2274803d3764 | 6cd1d83b025d7afa354f2b918b05fd0d4a02fd1b | refs/heads/master | 2023-01-04T14:53:54.806612 | 2020-10-27T15:20:38 | 2020-10-27T15:20:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # You are provided with two numbers. Find and print the smaller number.
a=int(input("Enter the number1:"))
b=int(input("Enter the number2:"))
if b>a:
print(b)
# else:
# exit | UTF-8 | Python | false | false | 197 | py | 167 | smaller_number.py | 166 | 0.619289 | 0.609137 | 0 | 10 | 17.9 | 71 |
OpenSCAP/OVAL-visualization-as-graph | 15,874,199,127,890 | f24eb3222924d0ebcfd9ca947929822d0cc776d4 | 33d5c2dcea16adcfc516b09a2929a478610d806f | /oval_graph/_xml_parser_oval_scan_definitions.py | dad3e34c4e8edfb01c2fa5128d8103923e9d9013 | [
"Apache-2.0"
]
| permissive | https://github.com/OpenSCAP/OVAL-visualization-as-graph | b0a56e0aa802a64f25193729e6feeadbe3b4e138 | 9119cf413d0a0d2d79795848eb04fb3d919ab3be | refs/heads/master | 2020-06-27T18:21:43.482464 | 2020-04-17T21:53:18 | 2020-04-17T21:53:18 | 200,017,125 | 21 | 11 | null | null | null | null | null | null | null | null | null | null | null | null | null | from ._xml_parser_comments import _XmlParserComments
from ._xml_parser_test_info import _XmlParserTestInfo
class _XmlParserScanDefinitions:
def __init__(self, definitions, oval_definitions, report_data):
self.definitions = definitions
self.comments_parser = _XmlParserComments(oval_definitions)
self.test_info_parser = _XmlParserTestInfo(report_data)
def get_scan(self):
dict_of_definitions = {}
for definition in self.definitions:
id_definition = definition.get('definition_id')
dict_of_definitions[id_definition] = dict(
commnet=None, node=self._build_node(
definition[0], "Definition", id_definition))
self.comments_parser.insert_comments(dict_of_definitions)
return self._fill_extend_definition(dict_of_definitions)
def _get_negate_status(self, node):
str_to_bool = {
'true': True,
'false': False,
}
negate_status = False
if node.get('negate') is not None:
negate_status = str_to_bool[node.get('negate')]
return negate_status
def _get_result(self, negate_status, tree):
"""
This method removes the negation of
the result. Because negation is already
included in the result in ARF file.
"""
result = tree.get('result')
reverse_negate_value = {
'true': 'false',
'false': 'true',
}
if negate_status and result in ('true', 'false'):
result = reverse_negate_value[result]
return result
def _build_node(self, tree, tag, id_definition=None):
negate_status = self._get_negate_status(tree)
node = dict(
id=id_definition,
operator=tree.get('operator'),
negate=negate_status,
result=self._get_result(negate_status, tree),
comment=None,
tag=tag,
node=[],
)
for child in tree:
if child.get('operator') is not None:
node['node'].append(self._build_node(child, "Criteria"))
else:
negate_status = self._get_negate_status(child)
result_of_node = self._get_result(negate_status, child)
if child.get('definition_ref') is not None:
node['node'].append(
dict(
extend_definition=child.get('definition_ref'),
result=result_of_node,
negate=negate_status,
comment=None,
tag="Extend definition",
))
else:
node['node'].append(
dict(
value_id=child.get('test_ref'),
value=result_of_node,
negate=negate_status,
comment=None,
tag="Test",
test_result_details=self.test_info_parser.get_info_about_test(
child.get('test_ref')),
))
return node
def _fill_extend_definition(self, dict_of_definitions):
out = {}
for id_definition, definition in dict_of_definitions.items():
out[id_definition] = dict(
comment=definition['comment'],
node=self._fill_extend_definition_help(
definition['node'],
dict_of_definitions))
return out
def _fill_extend_definition_help(self, value, dict_of_definitions):
out = dict(
operator=value['operator'],
negate=value['negate'],
result=value['result'],
comment=value['comment'],
tag=value['tag'],
node=[],
)
for child in value['node']:
if 'operator' in child:
out['node'].append(
self._fill_extend_definition_help(
child, dict_of_definitions))
elif 'extend_definition' in child:
out['node'].append(
self._find_definition_by_id(
dict_of_definitions,
child['extend_definition'],
child['negate'],
child['comment'],
child['tag'],
))
else:
out['node'].append(child)
return out
def _find_definition_by_id(
self,
dict_of_definitions,
id_,
negate_status,
comment,
tag):
if id_ in dict_of_definitions:
dict_of_definitions[id_]['node']['negate'] = negate_status
dict_of_definitions[id_]['node']['comment'] = comment
dict_of_definitions[id_]['node']['tag'] = tag
return self._fill_extend_definition_help(
dict_of_definitions[id_]['node'], dict_of_definitions)
| UTF-8 | Python | false | false | 5,157 | py | 38 | _xml_parser_oval_scan_definitions.py | 29 | 0.493698 | 0.493504 | 0 | 134 | 37.485075 | 90 |
marciopocebon/chipwhisperer-lint | 12,902,081,761,732 | b6bdd4c42e030ce6b2ffaf3ed8b95ba0eadea877 | da5709febd35f567ae8561848a2cb531313dbd52 | /server-backend/server/aes_helper.py | f0cf8aee646a94e57346bccebf929b31eadea205 | []
| no_license | https://github.com/marciopocebon/chipwhisperer-lint | 48c0a83067309f40f275c977eba30a58abe89ca8 | 492f0189e98980e4e6517a50177eb6d3d2db83d4 | refs/heads/master | 2020-07-02T22:40:56.865512 | 2018-08-08T17:58:30 | 2018-08-08T17:58:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | _sbox=(
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16)
_gal1=tuple(range(256))
_gal2=(
0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e,0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e,
0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e,0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e,
0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e,0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e,
0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e,0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e,
0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e,0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e,
0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae,0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe,
0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce,0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde,
0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee,0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe,
0x1b,0x19,0x1f,0x1d,0x13,0x11,0x17,0x15,0x0b,0x09,0x0f,0x0d,0x03,0x01,0x07,0x05,
0x3b,0x39,0x3f,0x3d,0x33,0x31,0x37,0x35,0x2b,0x29,0x2f,0x2d,0x23,0x21,0x27,0x25,
0x5b,0x59,0x5f,0x5d,0x53,0x51,0x57,0x55,0x4b,0x49,0x4f,0x4d,0x43,0x41,0x47,0x45,
0x7b,0x79,0x7f,0x7d,0x73,0x71,0x77,0x75,0x6b,0x69,0x6f,0x6d,0x63,0x61,0x67,0x65,
0x9b,0x99,0x9f,0x9d,0x93,0x91,0x97,0x95,0x8b,0x89,0x8f,0x8d,0x83,0x81,0x87,0x85,
0xbb,0xb9,0xbf,0xbd,0xb3,0xb1,0xb7,0xb5,0xab,0xa9,0xaf,0xad,0xa3,0xa1,0xa7,0xa5,
0xdb,0xd9,0xdf,0xdd,0xd3,0xd1,0xd7,0xd5,0xcb,0xc9,0xcf,0xcd,0xc3,0xc1,0xc7,0xc5,
0xfb,0xf9,0xff,0xfd,0xf3,0xf1,0xf7,0xf5,0xeb,0xe9,0xef,0xed,0xe3,0xe1,0xe7,0xe5)
_gal3=(
0x00,0x03,0x06,0x05,0x0c,0x0f,0x0a,0x09,0x18,0x1b,0x1e,0x1d,0x14,0x17,0x12,0x11,
0x30,0x33,0x36,0x35,0x3c,0x3f,0x3a,0x39,0x28,0x2b,0x2e,0x2d,0x24,0x27,0x22,0x21,
0x60,0x63,0x66,0x65,0x6c,0x6f,0x6a,0x69,0x78,0x7b,0x7e,0x7d,0x74,0x77,0x72,0x71,
0x50,0x53,0x56,0x55,0x5c,0x5f,0x5a,0x59,0x48,0x4b,0x4e,0x4d,0x44,0x47,0x42,0x41,
0xc0,0xc3,0xc6,0xc5,0xcc,0xcf,0xca,0xc9,0xd8,0xdb,0xde,0xdd,0xd4,0xd7,0xd2,0xd1,
0xf0,0xf3,0xf6,0xf5,0xfc,0xff,0xfa,0xf9,0xe8,0xeb,0xee,0xed,0xe4,0xe7,0xe2,0xe1,
0xa0,0xa3,0xa6,0xa5,0xac,0xaf,0xaa,0xa9,0xb8,0xbb,0xbe,0xbd,0xb4,0xb7,0xb2,0xb1,
0x90,0x93,0x96,0x95,0x9c,0x9f,0x9a,0x99,0x88,0x8b,0x8e,0x8d,0x84,0x87,0x82,0x81,
0x9b,0x98,0x9d,0x9e,0x97,0x94,0x91,0x92,0x83,0x80,0x85,0x86,0x8f,0x8c,0x89,0x8a,
0xab,0xa8,0xad,0xae,0xa7,0xa4,0xa1,0xa2,0xb3,0xb0,0xb5,0xb6,0xbf,0xbc,0xb9,0xba,
0xfb,0xf8,0xfd,0xfe,0xf7,0xf4,0xf1,0xf2,0xe3,0xe0,0xe5,0xe6,0xef,0xec,0xe9,0xea,
0xcb,0xc8,0xcd,0xce,0xc7,0xc4,0xc1,0xc2,0xd3,0xd0,0xd5,0xd6,0xdf,0xdc,0xd9,0xda,
0x5b,0x58,0x5d,0x5e,0x57,0x54,0x51,0x52,0x43,0x40,0x45,0x46,0x4f,0x4c,0x49,0x4a,
0x6b,0x68,0x6d,0x6e,0x67,0x64,0x61,0x62,0x73,0x70,0x75,0x76,0x7f,0x7c,0x79,0x7a,
0x3b,0x38,0x3d,0x3e,0x37,0x34,0x31,0x32,0x23,0x20,0x25,0x26,0x2f,0x2c,0x29,0x2a,
0x0b,0x08,0x0d,0x0e,0x07,0x04,0x01,0x02,0x13,0x10,0x15,0x16,0x1f,0x1c,0x19,0x1a)
_gal9=(
0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f,0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77,
0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf,0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7,
0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04,0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c,
0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94,0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc,
0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49,0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01,
0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9,0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91,
0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72,0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a,
0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2,0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa,
0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3,0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b,
0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43,0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b,
0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8,0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0,
0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78,0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30,
0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5,0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed,
0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35,0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d,
0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e,0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6,
0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e,0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46)
_gal11=(
0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31,0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69,
0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81,0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9,
0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a,0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12,
0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa,0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2,
0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7,0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f,
0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77,0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f,
0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc,0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4,
0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c,0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54,
0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6,0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e,
0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76,0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e,
0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd,0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5,
0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d,0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55,
0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30,0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68,
0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80,0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8,
0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b,0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13,
0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb,0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3)
_gal13=(
0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23,0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b,
0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3,0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b,
0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98,0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0,
0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48,0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20,
0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e,0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26,
0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e,0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6,
0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5,0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d,
0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25,0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d,
0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9,0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91,
0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29,0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41,
0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42,0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a,
0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92,0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa,
0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94,0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc,
0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44,0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c,
0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f,0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47,
0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff,0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97)
_gal14=(
0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a,0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a,
0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca,0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba,
0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1,0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81,
0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11,0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61,
0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87,0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7,
0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67,0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17,
0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c,0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c,
0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc,0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc,
0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b,0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b,
0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b,0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb,
0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0,0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0,
0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50,0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20,
0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6,0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6,
0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26,0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56,
0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d,0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d,
0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd,0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d)
_galI=_gal14,_gal11,_gal13,_gal9
_galNI=_gal2,_gal3,_gal1,_gal1
def _mixcolumn (column, inverse):
#Use galois lookup tables instead of performing complicated operations
#If inverse, use matrix with inverse values
g0,g1,g2,g3=_galI if inverse else _galNI
c0,c1,c2,c3=column
return (
g0[c0]^g1[c1]^g2[c2]^g3[c3],
g3[c0]^g0[c1]^g1[c2]^g2[c3],
g2[c0]^g3[c1]^g0[c2]^g1[c3],
g1[c0]^g2[c1]^g3[c2]^g0[c3])
def _mixcolumns (state, inverse):
# Perform mix_column for each column in the state
for i, j in (0, 4), (4, 8), (8, 12), (12, 16):
state[i:j] = _mixcolumn(state[i:j], inverse)
return state
def _shiftrow (row, shift):
#Circular shift row left by shift amount
row+=row[:shift]
del row[:shift]
return row
def subbytes(inp):
return [sbox(i) for i in inp]
def mixcolumns(state):
return _mixcolumns(state, False)
def shiftrows (state):
#Extract rows as every 4th item starting at [1..3]
#Replace row with shift_row operation
for i in 1,2,3:
state[i::4] = _shiftrow(state[i::4],i)
return state
def sbox(inp):
s = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
0x54, 0xbb, 0x16]
return s[inp]
def invsbox(inp):
s = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
0x21, 0x0c, 0x7d]
return s[inp]
rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
0xe8, 0xcb ]
def g_func(inp, rcon):
#Step 1: change order
newlist = [inp[1], inp[2], inp[3], inp[0]]
#Step 2: s-box
newlist = [sbox(t) for t in newlist]
#Step 3: apply rcon
newlist[0] ^= rcon
return newlist
def h_func(inp):
#Step 1: s-box
newlist = [sbox(t) for t in inp]
return newlist
def xor(l1, l2):
return [l1[i] ^ l2[i] for i in range(0, len(l1))]
def keyScheduleRounds(inputkey, inputround, desiredround):
"""
inputkey = starting key, 16/32 bytes
inputround = starting round number (i.e. 0 = first)
desiredround = desired round number (i.e. 10 = last for 16-byte)
returns desired round number. Can go forward or backwards.
When dealing with AES-256, inputkey is 16 bytes and inputround
indicates round that bytes 0...15 are from.
"""
#Some constants
n = len(inputkey)
if n == 16:
pass
elif n == 32:
desiredfull = desiredround
desiredround = int(desiredround / 2)
#Special case for inputround of 13, needed for 'final' round...
if inputround != 13:
if inputround % 2 == 1:
raise ValueError("Input round must be divisible by 2")
inputround = int(inputround / 2)
else:
if inputround <= desiredfull:
if desiredfull < 13:
raise ValueError("Round = 13 only permissible for reverse")
if desiredfull == 13:
return inputkey[0:16]
else:
return inputkey[16:32]
else:
raise ValueError("Invalid keylength: %d"%n)
rnd = inputround
state = list(inputkey)
#Check if we are going forward or backwards
while rnd < desiredround:
rnd += 1
#Forward algorithm, thus need at least one round
state[0:4] = xor(state[0:4], g_func(state[(n-4):n], rcon[rnd]))
for i in range(4, n, 4):
if n == 32 and i == 16:
inp = h_func(state[(i-4):i])
else:
inp = state[(i - 4):i]
state[i:(i+4)] = xor(state[i:(i+4)], inp)
while rnd > desiredround:
#For AES-256 final-round is 13 as that includes 32 bytes
#of key. Convert to round 12 then continue as usual...
if n == 32 and rnd == 13:
inputrnd = int(12/2)
rnd = inputrnd
oldstate = list(state[16:32])
state[16:32] = state[0:16]
for i in range(12, 0, -4):
state[i:(i+4)] = xor(oldstate[i:(i+4)], oldstate[(i-4):i])
state[0:4] = xor(oldstate[0:4], g_func(state[(n - 4):n], rcon[7]))
if rnd == desiredround:
break
# Reverse algorithm, thus need at least one round
for i in range(n-4, 0, -4):
if n == 32 and i == 16:
inp = h_func(state[(i-4):i])
else:
inp = state[(i - 4):i]
state[i:(i+4)] = xor(state[i:(i+4)], inp)
state[0:4] = xor(state[0:4], g_func(state[(n - 4):n], rcon[rnd]))
rnd -= 1
#For AES-256, we use half the generated key at once...
if n == 32:
if desiredfull % 2:
state = state[16:32]
else:
state = state[0:16]
#Return answer
return state | UTF-8 | Python | false | false | 19,148 | py | 39 | aes_helper.py | 12 | 0.666075 | 0.352935 | 0 | 357 | 52.638655 | 80 |
prayswear/ICN | 9,191,230,058,362 | c5379cf8501df5e528ff95e697b640204eff966f | 5b96b6bf5ae357deab937ea66bda5f0f8d6b4df3 | /test/test.py | 16e7c94af79010325bda355ec7ef484da6e47f9b | []
| no_license | https://github.com/prayswear/ICN | 1154ea6d25e4ce0878f2055ebf2f82a9644e97d4 | 760caae64e8a79c8c31ca60af3e6a8095578da8b | refs/heads/master | 2021-08-18T23:35:25.843931 | 2017-11-24T06:44:55 | 2017-11-24T06:44:55 | 103,603,049 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pickle
a=[1,2,3]
b='asb'
try:
with open('mytest.txt','wb') as myfile:
pickle.dump(a,myfile)
pickle.dump(b,myfile)
except IOError as e:
print(e)
try:
with open('mytest.txt','rb') as readfile:
c=pickle.load(readfile)
d=pickle.load(readfile)
print(c)
print(d)
except IOError as e:
print(e)
| UTF-8 | Python | false | false | 360 | py | 33 | test.py | 31 | 0.583333 | 0.575 | 0 | 19 | 17.947368 | 45 |
the-krafty-koder/pay-3 | 17,635,135,739,063 | c3d26843a773c45f0254643ff3b1ba2cc04cee52 | 10da28522dfaff6a17bf1a94f1d3af7dad662f04 | /payroll/employee_management/migrations/0007_auto_20200214_1858.py | 4556c5469233ba3a9d9a4a6630827b8818389627 | [
"MIT"
]
| permissive | https://github.com/the-krafty-koder/pay-3 | 5c4981c99ff8386deac45953a7f12bfa99bb9198 | 7ebaade8536d8635983cdfbd44ef308b93563ed3 | refs/heads/master | 2023-02-23T10:59:18.211147 | 2022-07-15T11:56:19 | 2022-07-15T11:56:19 | 281,345,660 | 1 | 1 | null | false | 2023-02-15T18:53:45 | 2020-07-21T08:51:54 | 2022-07-15T11:57:18 | 2023-02-15T18:53:41 | 25,069 | 1 | 0 | 4 | Python | false | false | # Generated by Django 3.0.3 on 2020-02-14 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('employee_management', '0006_contract_employee_name'),
]
operations = [
migrations.AddField(
model_name='employee',
name='gender',
field=models.CharField(default=None, max_length=5, null=True),
),
migrations.AddField(
model_name='employee',
name='identification_number',
field=models.CharField(default=None, max_length=40, null=True),
),
]
| UTF-8 | Python | false | false | 642 | py | 113 | 0007_auto_20200214_1858.py | 85 | 0.573209 | 0.538941 | 0 | 23 | 25.913043 | 75 |
Mismael/AITechs | 6,090,263,653,127 | 4ad7695bb46643b7bc0a830fbc715e460cf1d9db | c436b76d983424c4424b51a09b972ccda26a3a85 | /libs/id.py | 282ec24dca4a719cacd9868d2cc906d1862d4b98 | []
| no_license | https://github.com/Mismael/AITechs | c9039698e46611e649ee286a35543e6fec61c38f | a56563c46f98094b005be3011a9c23e6519f6b1e | refs/heads/master | 2018-12-24T20:45:06.094429 | 2018-12-02T10:03:30 | 2018-12-02T10:03:30 | 134,665,415 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 01:46:15 2018
@author: mohammed-PC
"""
'''
Modules Imports
'''
import os
import csv
import cv2
import sys
import dlib
import time
import keras
import imutils
import platform
import numpy as np
import tensorflow as tf
from keras.models import load_model
from matplotlib import pyplot as plt
class ID:
def __init__(self, frontSide, backSide):
try:
'''Display Environment Elements'''
print("## Environment")
print("OS: "+platform.system()+" "+platform.release()+" x"+platform.architecture()[0])
print("Keras Version:",keras.__version__)
print("TensorFlow Version:",tf.__version__)
print("Opencv Version:",cv2.__version__)
'''Variables and Instances'''
self.side = ''
self.file_name = 'data_store.csv'
self.classifier = load_model('./assets/ar_numbers_v6.h5')
self.classifier.compile(loss= 'categorical_crossentropy', optimizer='adam')
self.detector = dlib.get_frontal_face_detector()
'''Assets'''
self.assets = './assets/images/'
self.temp_egy_logo = cv2.imread(self.assets+'logo_0.jpg')
self.temp_nesr = cv2.imread(self.assets+'logo_1.jpg')
self.temp_pharaonic = cv2.imread(self.assets+'logo_2.jpg')
'''Load both sides of ID card and display their resolution'''
dataset ='./dataset/'
self.back_img = cv2.imread(dataset+ backSide )
self.face_img = cv2.imread(dataset+ frontSide )
print("Front Side Resolution: ", self.face_img.shape )
print("Back Side Resolution: ", self.back_img.shape )
'''Classifier Input Shape'''
self.NIDimage = (64,64)
self.clsfInputWidth = self.NIDimage[0]
self.clsfInputHeight = self.NIDimage[1]
print("\nProject Variables and Instances are Loaded successfully")
except:
'''If any of the System variables or
instances didn't load, the system
terminates
'''
print("Some Instances Can't Load !")
sys.exit()
def crop_points(self, image):
"""
This Function displays an Interactive UI enables user
to select four corner points, then return new rectangular
prespective
Args:
image (3D Array): RGB Image
Returns:
image (3D Array): RGB Image with new prespectives
"""
new_image = image.copy()
drawing=False
mode=True
points_presp = []
def setPrespectives(image_file , arr ):
def order_points(pts):
"""
This Function orders four points to shape a rectangle
Args:
pts (2D List): 4 points
Returns:
rect (2D List): recatnge ordered 4 corner points
"""
rect = np.zeros((4, 2), dtype = "float32")
s = pts.sum(axis = 1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
def four_point_transform(image, pts):
rect = order_points(pts)
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype = "float32")
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
return warped
img = image_file
arr = arr
arr = np.array(arr, dtype = "float32")
warped = four_point_transform(img, arr)
h , w , l = warped.shape
h = int( w/1.5 )
warped = cv2.resize(warped , (w , h))
return warped
def interactive_drawing(event,x,y,flags,param):
global ix,iy,drawing, mode, current_Image
if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
ix,iy=x,y
if len(points_presp) < 4 :
cv2.line(image,(x,y), (x,y) , (0,0,255) , 8 )
points_presp.append([x,y])
else:
print("You Can't Select More Than 4 Points ! \n")
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
return x,y
#image = imutils.resize(image, width=500)
cv2.namedWindow('Photo',cv2.WINDOW_NORMAL)
cv2.setMouseCallback('Photo',interactive_drawing)
while(1):
cv2.imshow('Photo',image)
k=cv2.waitKey(1)&0xFF
if k==27: #esc --> exit
cv2.destroyAllWindows()
break
elif k==110: #n --> new
image = new_image.copy()
h , w , _ = image.shape
points_presp = []
elif k==99: #c --> crop
if len(points_presp) == 4:
image = setPrespectives(image,points_presp)
cv2.destroyAllWindows()
return image
def crop_front(self, front, scale):
global side
# // must removed after test
side = 'face'
#Scale
scale_factor = scale
#Real Card width and height
w = 8.6
h = 5.5
#init. card area parameters
scaled_h = int(h*scale_factor)
scaled_w = int(w*scale_factor)
print("New Front Side Scaled Resolution: " + str(scaled_h) + ", " + str(scaled_w) + "\n")
##Front
#X
face_xi , face_xf = int(0.3*scale_factor) , int((0.3+2.2)*scale_factor)
birthdate_xi , birthdate_xf = int(0.3*scale_factor) , int((0.3+3)*scale_factor)
pin_xi , pin_xf = int(0.3*scale_factor) , int((0.3+3)*scale_factor)
logo_xi , logo_xf = int((0.3+3)*scale_factor) , int(7.5*scale_factor)
name_xi , name_xf = int((0.3+3)*scale_factor) , int(w*scale_factor)
add_xi , add_xf = int((0.3+3)*scale_factor) , int(w*scale_factor)
idno_xi , idno_xf = int((0.3+3+0.3)*scale_factor) , int(w*scale_factor)
#Y
face_yi , face_yf = int(0.4*scale_factor) , int(3.2*scale_factor)
birthdate_yi , birthdate_yf = int(3.7*scale_factor) , int(4.8*scale_factor)
pin_yi , pin_yf = int(4.8*scale_factor) , int(h*scale_factor)
logo_yi , logo_yf = int(0*scale_factor) , int(1.2*scale_factor)
name_yi , name_yf = int(1.3*scale_factor) , int(2.5*scale_factor)
add_yi , add_yf = int(2.5*scale_factor) , int(3.8*scale_factor)
idno_yi , idno_yf = int((4.1+0.15)*scale_factor) , int(4.9*scale_factor)
card = cv2.bitwise_not(np.zeros((scaled_h,scaled_w,3), np.uint8))
card_f = front
card_f = cv2.resize(card_f, (scaled_w , scaled_h))
thick = 2
#front
face = card_f[face_yi:face_yf , face_xi:face_xf]
birthdate = card_f[birthdate_yi:birthdate_yf , birthdate_xi:birthdate_xf]
pin = card_f[pin_yi:pin_yf , pin_xi:pin_xf]
logo = card_f[logo_yi:logo_yf , logo_xi:logo_xf]
name = card_f[name_yi:name_yf , name_xi:name_xf]
add = card_f[add_yi:add_yf , add_xi:add_xf]
idno = card_f[idno_yi:idno_yf , idno_xi:idno_xf]
front = {'face':face,'birthdate': birthdate, 'pin': pin, 'logo': logo,'name': name, 'add': add, 'idno': idno}
return front
def is_face_card(self, card):
#ADD AKAZE ->Edit
is_logo = self.Matcher(self.temp_egy_logo, card['logo'])
return (is_logo and self.is_face(card['face']))
##AKAZE Feature matching
def Matcher (self, originalImage, tempelateImage):
###Load Original Image and Tempelate Image
originalImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
originalImage_H, originalImage_W = originalImage.shape
#Original Croped Area to Compare to the matching area
originalImage_Area = originalImage_H * originalImage_W
tempelateImage = cv2.cvtColor(tempelateImage, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
tempelateImage = clahe.apply(tempelateImage)
tempelateImage_H, tempelateImage_W = tempelateImage.shape
###Create AKAZE
akaze = cv2.AKAZE_create()
originalImage_kp, originalImage_des = akaze.detectAndCompute (originalImage,None)
tempelateImage_kp, tempelateImage_des = akaze.detectAndCompute(tempelateImage, None)
###Find Matches
matcher = cv2.BFMatcher()
knnMatches = matcher.knnMatch(tempelateImage_des,originalImage_des, k=2)
good = []
for m,n in knnMatches:
if m.distance < 0.9*n.distance:
good.append(m)
src_pts = np.float32([ tempelateImage_kp[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ originalImage_kp[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
pts = np.float32([ [0,0],[0,tempelateImage_H-1],[tempelateImage_W-1,tempelateImage_H-1],[tempelateImage_W-1,0] ]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts,M)
#Edit Polylines point to get perfect squared points
if(dst[0][0][0] > dst[1][0][0]): dst[0][0][0] = dst[1][0][0]
if(dst[0][0][0] < dst[1][0][0]): dst[1][0][0] = dst[0][0][0]
if(dst[3][0][0] > dst[2][0][0]): dst[2][0][0] = dst[3][0][0]
if(dst[3][0][0] < dst[2][0][0]): dst[3][0][0] = dst[2][0][0]
if(dst[0][0][1] > dst[3][0][1]): dst[0][0][1] = dst[3][0][1]
if(dst[0][0][1] < dst[3][0][1]): dst[3][0][1] = dst[0][0][1]
if(dst[1][0][1] > dst[2][0][1]): dst[2][0][1] = dst[1][0][1]
if(dst[1][0][1] < dst[2][0][1]): dst[1][0][1] = dst[2][0][1]
matchingContour_H = dst[1][0][1] - dst[0][0][1]
matchingContour_W = dst[3][0][0] - dst[0][0][0]
matchingContour_Area = matchingContour_H * matchingContour_W
matchingAreaPercentage = matchingContour_Area/originalImage_Area
if (matchingAreaPercentage > 0.75):
return True
else:
return False
def extract_front_data(self, front_img_parts):
id_num = self.extract(front_img_parts['idno'], 14)
birthdate = [2] #extract(front_img_parts['birthdate'], 10)
return {'id': id_num, 'birthdate': birthdate}
def show_face_result(self, face_card):
# will be best if next static data added in config file
print("===================Front=====================")
# print("IS IT REAL CARD?: " ,face_card['is_id_card'])
# print("BirthDate:" , face_card['birthdate'])
print("ID NUMBER: " ,face_card['id'])
def crop_back(self, back, scale):
global side
# // must removed after test
side = 'back'
#Scale
scale_factor = scale
#Real Card width and height
w = 8.6
h = 5.5
#init. card area parameters
scaled_h = int(h*scale_factor)
scaled_w = int(w*scale_factor)
print("New Back Side Scaled Resolution: " + str(scaled_h) + ", " + str(scaled_w) + "\n")
##Back
#X
nesr_xi , nesr_xf = int(7*scale_factor) , int(8.3*scale_factor)
pharaonic_xi , pharaonic_xf = int(0.3*scale_factor) , int(2*scale_factor)
info_xi , info_xf = int(2.4*scale_factor) , int(7*scale_factor)
expiry_xi , expiry_xf = int(2.5*scale_factor) , int(7*scale_factor)
code_xi , code_xf = int(0*scale_factor) , int(w*scale_factor)
#Y
nesr_yi , nesr_yf = int(0*scale_factor) , int(2.2*scale_factor)
pharaonic_yi , pharaonic_yf = int(0*scale_factor) , int(2.2*scale_factor)
info_yi , info_yf = int(0.3*scale_factor) , int(2.2*scale_factor)
expiry_yi , expiry_yf = int(2.4*scale_factor) , int(3*scale_factor)
code_yi , code_yf = int(3*scale_factor) , int(h*scale_factor)
card = cv2.bitwise_not(np.zeros((scaled_h,scaled_w,3), np.uint8))
card_b = back
card_b = cv2.resize(card_b, (scaled_w , scaled_h))
#back - cut process
nesr = card_b[nesr_yi:nesr_yf , nesr_xi:nesr_xf]
pharaonic = card_b[pharaonic_yi:pharaonic_yf , pharaonic_xi:pharaonic_xf ]
info = card_b[info_yi:info_yf , info_xi:info_xf]
code = card_b[code_yi:code_yf , code_xi:code_xf]
expiry = card_b[expiry_yi:expiry_yf , expiry_xi:expiry_xf]
sliced_image = self.horizontal_split(info)
plt.imshow(info)
plt.figure()
first_line = sliced_image[0]
card_id = self.vertical_split(first_line)[0]
# expiry = vertical_split(expiry)[1]
# rename this dict
back = {'nesr':nesr,'pharaonic': pharaonic, 'info': info, 'code': code,'expiry': expiry, 'id': card_id }
return back
def is_back_card(self, card):
# here will add Hog code ISA to chek back card
is_nesr = self.Matcher(self.temp_nesr, card['nesr'])
is_pharaonic = self.Matcher(self.temp_pharaonic, card['pharaonic'])
return (is_nesr and is_pharaonic)
def extract_back_data(self, back_img):
id_num = self.extract(back_img['id'], 14)
# expiry = extract(back_img['expiry'], '*') # Expiry Date
# plt.imshow(back_img['id'])
# plt.figure()
return {'id_num': id_num}
def show_back_result(self, back_data):
print("===================Back======================")
if back_data is not None:
print("ID NUMBER: ", back_data['id_num'])
# print("Expiry Date: ", back_data['expiry'])
else:
print("there is no data to extract")
def is_face(self, face):
plt.imshow(face)
plt.figure()
plt.show()
gray = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
# faces.
faces = self.detector(gray, 1)
print("Number of faces detected: {}".format(len(faces)))
return len(faces) is 1
def horizontal_split(self, image):
h , w, l = image.shape
image_resized = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(image_resized,140,200)
kernel = np.ones((3,3), np.uint8)
edges = cv2.dilate(edges, kernel, iterations=1)
rowSum = []
for r in range(0,h):
row = edges[r:r+1 , 0:w-1 ]
x = np.count_nonzero (row)
rowSum.append(x)
cuts_pos = []
cnt = 0
for i in range (0 , len(rowSum)):
if rowSum[i] == 0 and cnt == 0:
cuts_pos.append(i)
cnt = 1
elif rowSum[i] != 0 :
cnt = 0
if cuts_pos[0] != 0:
cuts_pos.insert(0, 0)
statments = []
for i in range (0 , len(cuts_pos)-1):
statments.append(image[cuts_pos[i]:cuts_pos[i+1] , 0:w])
return statments
def vertical_split(self, image):
grayIamge = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
thresh_image = self.threshold(grayIamge)
kernel = np.ones((12,12), np.uint8)
dilated_image = cv2.dilate(thresh_image, kernel, iterations=1)
edges, contours, hierarchy = cv2.findContours(dilated_image,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
lst = []
slices = []
for i in range(0,len(contours)):
arr = [x,y,w,h] = cv2.boundingRect(contours[i])
x,y,w,h = cv2.boundingRect(contours[i])
lst.append(arr)
y0 = lst[i][1] - 3
if y0 < 0:
y0 = lst[i][1]
x0 = lst[i][0]
yf0 = (y0 + lst[i][3] )
xf0 = (x0 + lst[i][2] )
slices.append(image[y0:yf0, x0:xf0 ])
# cv2.imshow('card_id', image[y0:yf0, x0:xf0 ])
# cv2.waitKey(0)
return slices
def threshold(self, image):
gray = cv2.GaussianBlur(image, (3, 3), 2)
light_less_img = 225 - self.remove_bad_lighting(gray)
light_less_img *= light_less_img
segmanted_image = self.segmantation(light_less_img)
(thresh, thresh_image) = cv2.threshold(segmanted_image, 12, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
return thresh_image
def predict_num(self, image, thresh_image,expected_length):
# plt.imshow(thresh_image)
# plt.figure()
clsfInputWidth = self.NIDimage[0]
clsfInputHeight = self.NIDimage[1]
space = 0
nums = []
_, contours, hierarchy = cv2.findContours(thresh_image,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# next line sort contours as perarea size to give me biggest realnumber first
# then small noise at last indexes
contours.sort(key=lambda x:-cv2.contourArea(x))
# next line trancat just our desigered numbers length after sorting them by sizes
contours = contours[:expected_length] if expected_length is not '*' else contours
# next line sorts the numbers as per ther position from left to right
contours.sort(key=lambda x:cv2.boundingRect(x))
print(len(contours))
for indx, contour in enumerate(contours) :
boundRect = cv2.boundingRect(contour)
# if any dimision of countor is biger than desired input for the classifier
# we will adjust currant box to contain new dimension of countor then will resize it
# this helps us to prevent any bad scaling
# if biger than box
if (boundRect[2] > clsfInputWidth) | (boundRect[3] > clsfInputHeight) :
# select max then adjust classifier box
clsfInputWidth = max(boundRect[2] , boundRect[3])
clsfInputHeight = clsfInputWidth
else:
clsfInputWidth = self.NIDimage[0]
clsfInputHeight = self.NIDimage[1]
# find the center of the contour
centerPointX = (boundRect[0] + ( boundRect[2] // 2))
centerPointY = (boundRect[1] + ( boundRect[3] // 2))
# pointer to the start of the box relative to center of the object
x0= centerPointX-(clsfInputWidth//2) - space
y0= centerPointY-(clsfInputHeight//2)- space
# to prevent negative value for each number near to image boundary
x0 = x0 if x0 > -1 else 0
y0 = y0 if y0 > -1 else 0
# the end point to the box that contains the object from start point to box size
xf0 = (x0+ clsfInputWidth + space)
yf0 = (y0 + clsfInputHeight + space)
# p= (w/2)+s
# x = p(b/2)
slice_img = image[y0:yf0 , x0:xf0 ]
#slice_img = self.heatMapFilter(slice_img)
imresize = cv2.resize(slice_img, (self.NIDimage[0] , self.NIDimage[1]))
# channel last
imreshaped = imresize.reshape(self.NIDimage[0] , self.NIDimage[1], 1)
classes = self.classifier.predict_classes(np.array([imreshaped]))
nums.append(classes[0])
cv2.imwrite('./test/'+str(classes[0])+'-'+side+'-'+str(time.time())+'.jpg' , imreshaped)
return nums
def extract(self, image, expected_length):
plt.imshow(image)
plt.figure()
grayIamge = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
# next line to be tested
grayIamge = imutils.resize(grayIamge, height=100)
plt.imshow(grayIamge)
plt.figure()
thresh_image = self.threshold(grayIamge)
plt.imshow(thresh_image)
plt.figure()
arr = self.predict_num(grayIamge, thresh_image, expected_length)
print(arr)
return arr
def remove_bad_lighting(self, input_img):
median = cv2.medianBlur(input_img, 41)
return (input_img / median)
def segmantation(self, input_img):
K = 2
channels = 3 if len(input_img.shape)> 2 else 1
Z = input_img.reshape((-1,channels))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10, cv2.KMEANS_PP_CENTERS )
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
thresh_segmanted_image = res.reshape((input_img.shape))
return thresh_segmanted_image
def dodge(self, image, mask):
"""
"""
return cv2.divide(image, 255-mask, scale=256)
def error_handling(self, value):
"""
"""
if value is not None:
return value
else:
return False
def heatMapFilter(self, number_image):
"""
This Function maps gray scale input image into HeatMap (COLORMAP_JET)
Args:
number_image (2D Array): gray scale image
Returns:
whiteBkgNumber (2D Array):Binary Image, white background and black number
"""
contourAreas = []
solidBlk = np.zeros(number_image.shape, np.int8)
heatmapImage = cv2.applyColorMap(number_image, cv2.COLORMAP_JET)
filtered = cv2.inRange(heatmapImage,(254,0,0),(255,255,0))
_, contours, hierarchy = cv2.findContours(filtered,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
contourAreas.append(cv2.contourArea(c))
cv2.drawContours(solidBlk, contours, contourAreas.index(max(contourAreas)), 255, -1)
whiteBkgNumber = cv2.inRange(solidBlk,0,100)
return whiteBkgNumber
def store_csv(self, data):
"""
This Function Stores front and back side data in CSV file
Args:
data (dic): front and back side extracted data
"""
is_file_exist = os.path.exists(self.file_name)
with open(self.file_name ,'a') as csvfile:
field_names = list(data.keys())
writer = csv.DictWriter(csvfile, fieldnames=field_names)
if not is_file_exist:
writer.writeheader()
writer.writerow(data)
| UTF-8 | Python | false | false | 23,703 | py | 84 | id.py | 36 | 0.537822 | 0.512171 | 0 | 585 | 39.488889 | 137 |
curious95/projektCORM | 4,561,255,299,071 | f17687138daed5ed7a5f3195efc0a650500a7a4a | adef79334cd1d7d0ba1f03470812a54d362c744e | /src/operations/send_mail.py | 533c8bad36299c23a36e57ff11011dabadd14792 | [
"Apache-2.0"
]
| permissive | https://github.com/curious95/projektCORM | 877f71e8c4f6f26c35354c98688cd866eff697bf | df03028d9ea6ae30ac29eaaceeea5541536b7754 | refs/heads/main | 2023-03-30T20:18:21.999023 | 2021-04-08T04:40:16 | 2021-04-08T04:40:16 | 355,651,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from mailjet_rest import Client
import os
def send_mail(data_dict):
api_key = 'a250fe782d77b72c1d56e61dba45b90d'
api_secret = '469d131a28910a535146932dbb9353f3'
mailjet = Client(auth=(api_key, api_secret), version='v3.1')
data = {
'Messages': [
{
"From": {
"Email": "kamal.flyhigh@gmail.com",
"Name": "Zoneomics Metrics"
},
"To": [
{
"Email": "kamalpradhan95@outlook.com",
"Name": "Kamal Pradhan"
}
],
"Subject": "Zoneomics Daily Metrics",
"TextPart": "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
"HTMLPart": "<h3>Dear passenger 1, welcome to <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3><br />May the delivery force be with you!"
}
]
}
result = mailjet.send.create(data=data)
print(result.status_code)
print(result.json())
| UTF-8 | Python | false | false | 897 | py | 3 | send_mail.py | 2 | 0.602007 | 0.544036 | 0 | 30 | 28.9 | 149 |
bomb1e/gotgit | 6,846,177,903,246 | a6fd6bcaceb9201ce0baa5c84d9b9ceb8d951ce4 | 7192da38b6afd3c60f80ccbecb3040cf34369ce3 | /fc025e2e-894c-4240-b938-94fc394d319a.py | a1357bfcd49bdd25805dd2e9705dbf9e9a44cf48 | []
| no_license | https://github.com/bomb1e/gotgit | 6699fa9e6adb0a79f22441df41a102b09b78c2ce | 3c14cb6d1d0c4cba6a1e24a9899462d2e4bee2ce | refs/heads/master | 2020-06-12T06:00:34.695425 | 2018-08-01T02:00:02 | 2018-08-01T02:00:02 | 75,600,461 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | from __future__ import print_function
def func48(arg312, arg313):
var318 = func49(arg313, arg312)
var329 = func50(arg313, var318)
var334 = func53(var318, arg312)
var335 = arg313 | -20 & arg313
if var335 < var334:
var336 = ((arg313 - (var335 + ((-779 ^ (var334 + arg312) | var335 & (var329 ^ (562 & (arg312 ^ -25966020 + arg313 & -60 - -255896887) - (var335 + -1185075195)))) + (var329 + (1924005650 + arg312))) | -814)) - arg313 | var318) - arg313
else:
var336 = (1419980636 - (var329 & (253 - ((-982 & (arg312 | -823 & (var329 + -758) ^ var318 + var334)) ^ var334))) + 667344137 & (((1338891816 + var318) ^ var329) ^ var335 | var329 & arg312 & var335) - var318) | arg313 & arg313
result = (var318 - ((arg313 | var334) & ((var329 + 339 | arg312) ^ var318 + var318 | var334) & arg312)) ^ var329 + var329
return result
def func53(arg330, arg331):
var332 = 0
for var333 in range(24):
var332 += arg330 | var333
return var332
def func52(arg321, arg322):
var323 = arg321 & -1555868972 & arg322
var324 = -430 - var323
var325 = arg322 ^ var323
var326 = (1901005547 - ((((arg322 & var325) & var325) ^ (arg321 ^ arg322)) & 190) - arg321 & 739) & arg321
var327 = -1081611249 | arg322
result = 873 & ((var326 ^ arg322 | arg322 ^ (308 - (var326 - var326 + arg321 | arg321 ^ var325))) - var324) - 1739123470
return result
def func49(arg314, arg315):
var316 = 0
for var317 in range(18):
var316 += arg315 + var317 + arg314
return var316
def func47(arg299, arg300):
var301 = arg300 | arg299 ^ (-618 & 777)
var302 = ((arg300 & 349) + var301) - var301
var303 = (arg300 & var301) - arg299 - arg300
var304 = (-786 + var302 + var301) ^ 288987919
var305 = -1630436276 + (arg299 - (var302 & var302))
var306 = (var303 | 1960358616 & var301) + 1944741573
if var303 < var305:
var307 = -55277389 + arg299 | (var306 - var305)
else:
var307 = arg299 & (var301 ^ (var303 + arg300))
var308 = arg299 + arg299 + var305
var309 = var306 & var304 - arg299 + var301
var310 = (var308 | var306) - 200741036
var311 = (var302 | var310) & -410052250
result = ((var301 - (var303 ^ var308) ^ var304 | var305 ^ arg300 + var308) + arg300 + var308 | var309 - var306) + var305
return result
def func35(arg251, arg252):
var282 = func36(arg252, arg251)
var293 = var285(arg252, var282)
var294 = (955 + 356) | -326
var295 = var282 + (var293 + (var282 | var293) ^ var293 | arg251 - var282 - (arg251 ^ ((((var282 & (arg251 & -728 - var294)) ^ arg251) | -913 | var282) ^ var293)) ^ var293 & var282 + -585558755 - var293) - arg252 - -279
if var295 < arg252:
var296 = arg251 ^ (var295 - 554 & var294)
else:
var296 = (var295 ^ var294) - 720675579
var297 = 169 - ((var282 + ((var294 ^ (arg251 + arg252)) + arg252)) ^ arg251)
var298 = var282 | ((var293 & 522) - var282 | arg251)
result = var295 & ((var294 | (844 + (var295 - var298))) - (arg251 & ((var297 & 98) & (arg251 + 401324285 + -120164832) & 297819300)))
return result
def func46(arg286, arg287):
var288 = -748784831 + (1588557795 ^ -1031143482 | 1075303597 | -899)
var289 = (183387913 ^ (((arg286 - arg286) + arg287) - var288) + -363 + -978) & (775 & arg287)
var290 = -1492053323 + arg287
var291 = ((var290 - arg286) - -937 + (var290 + -1924253049) & (arg286 + (var289 & var290 ^ var289 & 79 | var289) - var290) | var289 | var289 | -867 + var290) ^ var289 ^ ((var289 ^ 931) & var289) | var290 & var289
var292 = var289 + ((arg287 | ((-75 + var291 + ((var291 & arg286 | (var289 + ((var290 | (-549 ^ 1923850215)) + var289 | var288 + arg287 - var291) ^ -1632223953) & 426514076) - arg287) & var290) & -1082748422 & arg286) & arg286) | var288)
result = arg286 | (var292 & var290)
return result
def func45():
closure = [7]
def func44(arg283, arg284):
closure[0] += func46(arg283, arg284)
return closure[0]
func = func44
return func
var285 = func45()
def func38(arg255, arg256):
var257 = func41()
def func42(arg258, arg259):
var260 = (961585716 | var257 & arg259) & arg259
var261 = (708 - var260) & arg258 + arg259
var262 = (679547014 + (var257 | var261)) & arg259
if arg255 < arg258:
var263 = var262 ^ -1834786611
else:
var263 = var261 ^ var262 + 319 + var260
var264 = 539 | (var257 | var260) & var261
var265 = ((var261 & var264) | 258) & arg259
var266 = ((arg255 - arg256) - var257) + arg255
var267 = ((var264 & var261) & var264) - arg258
var268 = var262 & var264
var269 = (var267 & arg255) ^ (var262 - arg255)
var270 = arg256 + var266 + var257 ^ var264
result = (var261 ^ 1055713145 - var257 ^ var262) + (var262 & var261) ^ var268
return result
var271 = func42(arg256, var257)
var276 = func43(var271, arg256)
var277 = var257 | 362 | var276 - ((var257 - var271) - (var257 & var271)) & ((arg255 + (arg255 - 198392299)) & var276 | var271) ^ var257 & arg256 + (((1217028904 | arg255) | arg255) & arg256 | var271 - var271 | var257 | -1309486940)
var278 = (237 + var277) - 1584577489
var279 = -110868654 ^ 1024325291
var280 = var276 + var279 | ((var277 - var279 | 747 | (((var257 - var271) - var257) - arg255 - var279) ^ var257 & -1334022039) - arg256) + var276 ^ ((var278 ^ ((var277 ^ var278) | var278 - 737) - var279) ^ 798 ^ var279)
result = 145407433 | (var278 & arg255) ^ var257 | ((arg255 & (var277 - var280 ^ (var278 & -472 + var276))) | arg255) + var276
return result
def func43(arg272, arg273):
var274 = 0
for var275 in range(36):
if var275 < arg272:
var274 += -8 - var275
else:
var274 += arg272 + arg273 + var275
return var274
def func41():
func39()
result = len(range(8))
func40()
return result
def func40():
global len
del len
def func39():
global len
len = lambda x : -9
def func27(arg161, arg162):
var221 = func28(arg162, arg161)
var231 = var224(var221, arg162)
var232 = var221 ^ arg162 + 1078066353 + var221
var233 = arg162 + 1462458408
var234 = var231 & var233
var235 = var234 - (arg161 & arg161) + var233
if var231 < var234:
var236 = (var232 & 921) & var235 & var232
else:
var236 = 416 | 842486270 & var221 + var234
if var231 < var231:
var237 = arg161 + var221 & 696786693
else:
var237 = var235 & var234 - var233
if arg161 < arg162:
var238 = var233 - var233
else:
var238 = var231 - var231 + var234 & arg162
var239 = (-86684342 + var231 + arg162) - var232
var240 = arg162 | ((var239 & var233) | 1099598909)
var241 = -374 | arg161 - (var235 + -873)
if arg162 < var235:
var242 = (arg161 - (var240 + var235)) & arg161
else:
var242 = (var241 | (var239 - var221)) | var232
var243 = 824 & var231 - -264 + arg162
var244 = arg162 ^ arg162 + arg162 & var239
var245 = arg162 + -525
var246 = (var240 ^ var240 & -485) | var235
var247 = var241 - (var244 + var243) & var233
var248 = var245 | var247 & var245 + var244
if var232 < var240:
var249 = (var244 | var243) ^ var246
else:
var249 = (183086889 & var221) & (var248 - arg162)
var250 = var233 ^ var235
result = var221 & var234 & 24
return result
def func34(arg225, arg226):
var227 = 174 + -2140735701
var228 = arg225 | (((arg226 - (arg226 & var227)) ^ arg225) & (var227 - arg226 + (301 & -837 & -879)) | (var227 + arg225) | var227 ^ -551 - arg226 - -712)
var229 = ((var228 ^ (var228 + -73 & ((var227 | arg226 + (arg226 ^ var227)) | arg226 & var228 + 1279504050 | (arg226 | (426 & var227))))) + ((-918 ^ (var227 + ((249816495 - -699055311) + 1434831398))) - arg225 & arg225) & -839) | arg225
var230 = (var228 & (((((var229 | var228 ^ var227) + ((arg226 & var228) ^ var227 - var229 + 1916762389 ^ arg226 ^ (var228 ^ 1141600833 & 22) - var229 ^ 1894927515)) + arg226) - -802987847) & var229)) & var228 - var228 ^ 402 & -1710770120
result = (-1233689324 ^ (var227 ^ (var227 & var228 & arg226)) ^ var227 | (((arg225 ^ var227) ^ arg225) - arg225 - arg226)) ^ var230
return result
def func33():
closure = [-6]
def func32(arg222, arg223):
closure[0] += func34(arg222, arg223)
return closure[0]
func = func32
return func
var224 = func33()
def func28(arg163, arg164):
var185 = func29(arg164, arg163)
var210 = func30(arg164, arg163)
var215 = func31(arg164, var185)
var216 = arg164 & -1571806916
var217 = var216 - ((var185 + (((1752131379 ^ (var210 | arg164)) - var210) + (arg164 - (arg163 + -634105100)))) | (var215 & ((457688034 + (arg164 | (((arg164 - (arg164 | var216 & 945)) + arg163) - var210))) + 1437850267) - var215)) ^ var185 + 285
var218 = var210 - var210 + ((var216 + -35) - 1618199305) + (var216 ^ var216) ^ var210 + (1433918455 & arg163 | var215 + 337933236) ^ (var217 | (arg163 + (var210 - -135) & (var215 | arg163 - var216)) & var210 - arg163) ^ 930
var219 = (arg164 | var217) & var210 & (var217 | var218) + arg163
var220 = ((var219 ^ (var215 | arg163) - var217 + var210) | 15543178 & (var217 - arg164 + (var210 & var218)) ^ 2145746781 ^ (var185 ^ 627 + var216) | (var210 | var210 | arg163) ^ var215 - var215 + var216) - var217 ^ 509
result = 152 ^ (var217 | var219) | var219 & ((arg164 & -1375761531) | 1087605967)
return result
def func31(arg211, arg212):
var213 = 0
for var214 in range(42):
var213 += var214 + 8
return var213
def func30(arg186, arg187):
var188 = 1522434967 - ((397 | 1252872636) - arg186)
var189 = arg187 + var188
var190 = 48 + arg186
var191 = (-315 & (arg186 | var188)) + var189
var192 = var189 | arg186 ^ arg187 + arg186
var193 = 2020233601 + var189 - -2046647921 ^ var189
var194 = 1287087356 ^ -697 + var193 | var193
var195 = var190 - arg186
if var192 < var189:
var196 = -162 + var194 | -300 | var191
else:
var196 = (73 - 1329783647) + var194
var197 = arg187 & arg187
var198 = var193 ^ (var194 | var194) + var191
var199 = (var190 & -589) - var194
var200 = (-443 & var188) ^ var194 | var189
if arg187 < var191:
var201 = var199 ^ var194
else:
var201 = arg187 | (var192 & var198) - var199
var202 = (var190 - arg186) | var198 - var199
var203 = var193 ^ var202
var204 = (75 - (var195 & var189)) | var193
var205 = ((-647 | var199) & var197) ^ var193
var206 = arg186 ^ var188 - var202 - var195
var207 = (var195 - var202 & var195) | var197
var208 = var192 - (var189 + var202)
var209 = (var189 ^ var206 ^ -1886208592) & var206
result = (var209 ^ var194) + var202 & var200
return result
def func29(arg165, arg166):
var167 = (arg166 ^ 1308338392) | 1419869103 + arg166
var168 = var167 | 517
var169 = (arg165 - arg165) - -605 + var167
var170 = (var168 ^ var168 - arg166) | -1819197082
var171 = var167 | ((arg165 + var168) & var168)
if arg166 < arg166:
var172 = arg166 | var169 & var170 - -1462898913
else:
var172 = (var167 & var168 ^ var167) - var167
var173 = var171 ^ arg165 - arg165 ^ var168
var174 = (1389095435 + arg165 | var168) - var169
var175 = 888 | var170
var176 = var169 | (var171 ^ arg166 + 454)
var177 = 1771807874 ^ var168
var178 = arg166 + (arg166 - var176)
var179 = -925 | (var178 + var168) & arg166
var180 = -1080802602 | ((var176 | 1458735841) + var179)
var181 = var173 + (arg165 + arg165) | var180
var182 = (-634 & arg166) & arg166
var183 = ((var179 - var174) ^ var177) & arg166
var184 = var174 + var171 + var175 | var175
result = var177 & var178 + var167 - var184 & ((((arg165 - var168 ^ arg165 + var170) | -224) ^ var170 | var170) + var171)
return result
def func26(arg142, arg143):
var144 = 445 ^ 1874695115
var145 = (-61 - (-743 | -408)) ^ arg143
var146 = (var145 + -197 + -1627487742) & -1276935751
var147 = -1631052927 + -1451981140
var148 = var144 & arg142
var149 = var148 & var146
var150 = var144 | var147
var151 = (var149 - var150 ^ arg143) & var150
var152 = var150 | ((arg143 - -994) + var148)
var153 = (var150 - var147 & 145473449) ^ var151
var154 = (var148 ^ arg143) ^ (var147 ^ var146)
var155 = arg143 ^ var146
var156 = (var153 + var154) + var155 ^ var154
var157 = var150 & (var147 | var148) + var150
var158 = var145 | ((var155 ^ var146) ^ var145)
var159 = var154 ^ var151 + (var149 - var152)
var160 = var144 | var149
result = (var145 & ((var154 - var152) + var150 | var151 | var147) | var155 & var154) ^ var157 - var144
return result
def func25(arg136, arg137):
var138 = ((-1984019403 - -740 | (190 - arg137)) + (-1158433911 + ((arg136 | -1848548023) - arg136 & 75165947))) | arg137
var139 = 1649581660 & arg136
var140 = (arg137 | var139 ^ var139 & arg136) + arg136
var141 = var139 + var140
result = var139 & (600095084 ^ var140 - (var139 | ((var139 & 882266350) | var139))) & arg136 & arg136 ^ arg136 + 791 - var140
return result
def func21(arg101, arg102):
var117 = func22(arg101, arg102)
var121 = func23(var117, arg102)
var122 = (775 + var117) & 480 + var117
var123 = 1638474128 + var117
var124 = (arg102 & (var121 & var121)) | arg101
var125 = (arg101 | var123 + -290108677) - var124
var126 = (var123 ^ (var125 + var121)) | var117
if var122 < var126:
var127 = arg102 & arg102
else:
var127 = var124 ^ var125 - var121 | arg101
var128 = (arg102 + var122 & -738) & var126
var129 = (var117 & var121) + var126 | var117
if arg101 < var117:
var130 = ((-101456569 & arg102) | var126) + var117
else:
var130 = var122 + -940
var131 = 236 - var126
var132 = ((arg101 ^ arg101) | var124) | var131
var133 = (var129 - var131 + var123) + var121
var134 = ((-808390448 | arg102) + var133) | var126
var135 = var125 | var117 ^ var133 - var123
result = var129 - var135 - var133
return result
def func22(arg103, arg104):
var105 = ((-989 ^ -188) + arg104) | arg104
if arg104 < arg104:
var106 = arg103 | arg104 | -764
else:
var106 = 707 & ((114 | arg103) - -93219914)
var107 = var105 - 1283331100
var108 = arg103 & (-655277439 & -752) & var107
var109 = var108 & 83 & 951
if arg104 < var109:
var110 = var105 & var108 + arg103
else:
var110 = ((arg103 ^ var105) | var107) - var107
var111 = (var107 ^ var108 + var105) - arg103
var112 = ((483 & arg103) - var105) | var111
var113 = ((arg104 | arg103) & -1501423467) | 789
var114 = var113 - (-82426940 + var112) ^ var113
var115 = (var111 + var107) | arg104 | var114
var116 = arg104 - var105 ^ -428 + var114
result = var109 ^ var112 | arg103
return result
def func11(arg72, arg73):
var76 = class12()
for var77 in range(17):
var76.func13(var77, var77)
var82 = func14(arg72, arg73)
var87 = func15(var82, arg72)
if var82 < var82:
var92 = class16()
else:
var92 = class18()
for var93 in range(13):
var94 = var92.func17
var94(var93, arg72)
var99 = func20(arg72, var82)
var100 = (-1517872346 ^ (-515 + var87) | var82) ^ (arg73 & 539161067)
result = arg72 | (((arg73 & var100 | (var82 & (var100 ^ var87) | var82) ^ -1843984994) - 552549200) + var100 + -448)
return result
def func20(arg95, arg96):
var97 = 0
for var98 in range(17):
var97 += -4 - var98 ^ arg95
return var97
class class18(object):
def func17(self, arg90, arg91):
result = arg90 - (0 - (arg90 - (1566510561 - 0)) - arg91)
return result
class class16(object):
def func17(self, arg88, arg89):
return 0
def func15(arg83, arg84):
var85 = 0
for var86 in range(19):
var85 += var86 + 3 + -8
return var85
def func14(arg78, arg79):
var80 = 0
for var81 in range(46):
if var81 < var81:
var80 += var81 | -5 | arg79
else:
var80 += var81 ^ 8 ^ arg79
return var80
class class12(object):
def func13(self, arg74, arg75):
result = -1 | 0
return result
def func1(arg1, arg2):
var69 = var5(arg2, arg1)
var70 = (((695 + (-592 | var69 | arg2 - ((-905 | 79) ^ var69 - arg1 & var69 | (-510 - 779485725 + 289))) + arg2) ^ (arg1 + -112 | var69) | var69 & var69) | (arg2 ^ 1422755361) - arg1) & 615
var71 = arg2 - 1487153155 & (-794 | (var69 - arg1)) | arg2 | (-1125430633 | (-834891158 ^ var69)) + arg1
result = var70 & var71
return result
def func4(arg6, arg7):
var32 = func5(arg7, arg6)
def func6(arg33, arg34):
var35 = (arg6 - arg7) | (var32 & arg6)
var36 = (var35 | arg6 | arg6) - arg7
var37 = arg6 + (var35 ^ (arg7 - arg7))
var38 = -1071490825 & (var32 & -741)
var39 = ((var38 | var35) | arg6) & arg33
var40 = var39 & (var35 - 1768366662) & var36
var41 = var35 & ((var40 + arg33) + var38)
var42 = (arg33 + (var40 - arg6)) & arg34
var43 = arg34 ^ var36 | arg34
var44 = arg7 ^ var35 + arg7 ^ arg6
var45 = 9 ^ var38
var46 = var39 + var37
var47 = var43 - var36
if var47 < arg33:
var48 = (var41 & -1921099137 + var38) + var45
else:
var48 = var32 + arg6 ^ var44 | var41
if arg7 < var45:
var49 = ((arg6 - 1165599194) - var46) | var44
else:
var49 = var32 ^ -2115477322
var50 = var46 + ((arg33 ^ arg33) | var38)
var51 = (var45 + arg34) ^ var37 - arg6
result = var42 ^ (-91 - var32 & (987617346 - arg33) ^ (var37 ^ var42 + var32 | var44)) | var36 ^ var51 ^ arg34
return result
var52 = func6(arg7, var32)
var53 = func9()
var58 = func10(arg7, arg6)
var59 = -679 - var52 & var52 | arg6
var60 = -1248563863 | 1741999837
var61 = arg7 & -696635801
var62 = var60 - var32
var63 = ((arg7 & var32) + var59) ^ var61
if var53 < var60:
var64 = (var60 ^ -323) ^ var60 | var32
else:
var64 = var60 & var62
var65 = var61 + arg6 ^ var59 - var59
var66 = var62 | var58 - arg7
var67 = ((var60 & 357326936) & var32) - arg6
if var32 < var60:
var68 = var67 - var53
else:
var68 = var58 & var65 | var63 + arg6
result = var63 - (var59 & -872)
return result
def func10(arg54, arg55):
var56 = 0
for var57 in range(16):
var56 += var56 ^ arg54 - 8
return var56
def func9():
func7()
result = len(range(20))
func8()
return result
def func8():
global len
del len
def func7():
global len
len = lambda x : 3
def func5(arg8, arg9):
var10 = arg9 - 493 + arg8
var11 = (var10 & (-660 & -1763024830)) | arg8
var12 = 353667263 & (var10 ^ 34)
var13 = arg8 & -1893188160
if var10 < var13:
var14 = (var11 & var13) & (var10 | arg8)
else:
var14 = arg8 & arg8 ^ -798 | arg8
var15 = (-87 ^ arg9) | var11
var16 = 996620829 - var15 | 292751100
if arg9 < var15:
var17 = 178398287 | var15
else:
var17 = var11 - var15 ^ arg9 + var11
if var12 < var10:
var18 = var10 ^ var10 ^ -514
else:
var18 = arg8 ^ (var12 + arg9) | var12
var19 = var10 ^ -383
var20 = arg9 & arg9 | -194
var21 = (var13 | arg9) & 155 + var15
var22 = var13 | var10 ^ var19 + arg8
var23 = var10 - var19 + var19 ^ arg8
var24 = var21 | var23
var25 = var15 + var22 + (854618713 + var10)
var26 = var10 & var22 + var20 ^ var19
var27 = (var16 + -778) - arg9 & var25
var28 = (var13 & var22) & (var27 + arg9)
var29 = arg8 ^ var11
var30 = ((var15 ^ var19) & var20) + var25
var31 = var29 - (var29 ^ var16)
result = ((146 + var26) & var16 + var26) + var11
return result
def func3():
closure = [3]
def func2(arg3, arg4):
closure[0] += func4(arg3, arg4)
return closure[0]
func = func2
return func
var5 = func3()
def func23(arg118, arg119):
closure = [0]
def func24(acc, rest):
var120 = 8 | (((8 ^ ((acc | 2) & 2)) | acc) - 8)
closure[0] += var120
if acc == 0:
return var120
else:
result = func24(acc - 1, var120)
return result
result = func24(10, 0)
return result
def func36(arg253, arg254):
def func37(acc, rest):
var281 = func38(8, rest)
if acc == 0:
return var281
else:
result = func37(acc - 1, var281)
return result
result = func37(10, 0)
return result
def func50(arg319, arg320):
def func51(acc, rest):
var328 = func52(6, 1)
if acc == 0:
return var328
else:
result = func51(acc - 1, var328)
return result
result = func51(10, 0)
return result
if __name__ == "__main__":
print('prog_size: 5')
print('func_number: 11')
print('arg_number: 72')
for i in range(25000):
x = 5
x = func1(x, i)
print(x, end='')
print('prog_size: 5')
print('func_number: 21')
print('arg_number: 101')
for i in range(25000):
x = 5
x = func11(x, i)
print(x, end='')
print('prog_size: 2')
print('func_number: 25')
print('arg_number: 136')
for i in range(25000):
x = 5
x = func21(x, i)
print(x, end='')
print('prog_size: 0')
print('func_number: 26')
print('arg_number: 142')
for i in range(25000):
x = 5
x = func25(x, i)
print(x, end='')
print('prog_size: 0')
print('func_number: 27')
print('arg_number: 161')
for i in range(25000):
x = 5
x = func26(x, i)
print(x, end='')
print('prog_size: 5')
print('func_number: 35')
print('arg_number: 251')
for i in range(25000):
x = 5
x = func27(x, i)
print(x, end='')
print('prog_size: 5')
print('func_number: 47')
print('arg_number: 299')
for i in range(25000):
x = 5
x = func35(x, i)
print(x, end='')
print('prog_size: 2')
print('func_number: 48')
print('arg_number: 312')
for i in range(25000):
x = 5
x = func47(x, i)
print(x, end='')
print('prog_size: 5')
print('func_number: 54')
print('arg_number: 337')
for i in range(25000):
x = 5
x = func48(x, i)
print(x, end='') | UTF-8 | Python | false | false | 22,632 | py | 25,849 | fc025e2e-894c-4240-b938-94fc394d319a.py | 25,848 | 0.574938 | 0.303597 | 0 | 575 | 38.361739 | 249 |
Anand-S23/Instagram-Clone | 8,151,847,936,541 | 21b65aa58f8248efedc89d8f49cdb80f778ea907 | 516f243bd1827ec01e5f946cb07183350c989f26 | /post/migrations/0020_auto_20191020_1820.py | b2a309dcad73d891638bd10843af7364d188ad2f | []
| no_license | https://github.com/Anand-S23/Instagram-Clone | e383bfdcb8770112e9bec0c67f01abd410db5984 | dc4b6cdd31689e2fa2354851cbcb3447f61b5661 | refs/heads/master | 2020-08-07T15:25:30.671288 | 2019-11-25T20:09:06 | 2019-11-25T20:09:06 | 213,504,868 | 1 | 0 | null | false | 2019-10-23T23:11:26 | 2019-10-07T23:21:38 | 2019-10-23T23:03:07 | 2019-10-23T23:11:26 | 965 | 0 | 0 | 0 | JavaScript | false | false | # Generated by Django 2.1 on 2019-10-20 18:20
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0019_auto_20191020_1812'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='comment_date',
field=models.DateTimeField(default=datetime.datetime(2019, 10, 20, 18, 20, 2, 493897)),
),
migrations.AlterField(
model_name='post',
name='post_date',
field=models.DateTimeField(default=datetime.datetime(2019, 10, 20, 18, 20, 2, 490898)),
),
]
| UTF-8 | Python | false | false | 656 | py | 57 | 0020_auto_20191020_1820.py | 40 | 0.591463 | 0.487805 | 0 | 24 | 26.333333 | 99 |
keolis-metropole-orleans/ITxPT | 9,586,367,009,203 | a58ebcf474eb0fb0130160323432d934fbb810b3 | 6f2fd86fdcff8e96e11245a17f74fa645e9583a3 | /AVMS/ServerAVMS.py | fc488b036a115a7b1ea74df3c55dac5d39150b15 | [
"MIT"
]
| permissive | https://github.com/keolis-metropole-orleans/ITxPT | 48f78957c16a7d159f1936fe76b129eb1baf30dc | 1fdf6768be3415e6193d32d87194bfcd3574a889 | refs/heads/main | 2023-07-15T12:39:25.470637 | 2021-08-25T14:08:56 | 2021-08-25T14:08:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from http.server import HTTPServer, BaseHTTPRequestHandler
import xml.etree.ElementTree as ET
# Création de l'objet Server
class Server(BaseHTTPRequestHandler):
# Setup du headers
def _set_headers(self):
""" Fonction qui permet de setup le headers
Nom fonction : _set_headers
Paramètre : self
Return : rien"""
# Répondre avec le code 200 OK pour signaler la réussite de la requête
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.end_headers()
# Fonction do_POST
def do_POST(self):
""" Fonction qui permet de récupérer les stream xml envoyer en POST et de les traiter
Nom fonction : do_POST
Paramètre : self
Return : rien mais peut print la data après avoir été traiter dans les différentes fonctions
(driver_id, destination_name, line_name, last_stop_point_ref et time_next_stop)"""
# Récupération de la taille des données
content_length = int(self.headers['Content-Length'])
# Récupération des données
post_data = self.rfile.read(content_length)
# Création du tree et récupération de la root
tree = ET.ElementTree(ET.fromstring(post_data))
root = tree.getroot()
# Parcours le plus haut node
for tag in root.findall("."):
# Vérification si il s'agit d'un packet provenant du module "PlannedPattern"
if tag.tag == "PlannedPatternDelivery":
print("DriverID : ")
# Execution de la fonction driver_id sur la data récupéré
print(driver_id(post_data))
print("\n")
print("Destination : ")
# Execution de la fonction destination_name sur la data récupéré
print(destination_name(post_data))
print("\n")
print("Nom de ligne : ")
# Execution de la fonction line_name sur la data récupéré
print(line_name(post_data))
print("\n")
# Vérification si il s'agit d'un packet provenant du module "VehicleMonitoring"
if tag.tag == "VehicleMonitoringDelivery":
print("Dernier Arrêt : ")
# Execution de la fonction last_stop_point_ref sur la data récupéré
print(last_stop_point_ref(post_data))
print("\n")
# Vérification si il s'agit d'un packet provenant du module "JourneyMonitoring"
if tag.tag == "JourneyMonitoringDelivery":
# Execution de la fonction time_next_stop sur la data récupéré
res = time_next_stop(post_data)
# Si la longueur de res est supérieur à deux cela veut dire que time_next_stop retourne un message d'erreur
if len(res) > 2:
print("Heure d'arrivée : ")
print(res)
else:
print("Heure d'arrivée prévue : ")
# Affichage sur la console de l'heure d'arrivée prévue
print(res[0])
print("Heure d'arrivée éstimé : ")
# Affichage sur la console de l'heure d'arrivée éstimé
print(res[1])
print("\n")
def driver_id(data):
""" Fonction qui permet de récupérer l'identifiant du conducteur en fonction de data passé en paramètre
Nom fonction : driver_id
Paramètre : data, un flux xml
Return : un string qui a comme valeur le DriverID"""
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()
for tag in root.findall("."):
if tag.tag == "PlannedPatternDelivery":
if tag.find("PlannedPattern") is None:
return "Error, 'PlannedPattern' tag not exists"
else:
if tag.find("PlannedPattern/DriverID") is None:
return "Error, 'DriverID' tag not exists"
else:
for elem in root.findall("./PlannedPattern/DriverID"):
if elem.text is None:
return "Error, 'DriverID' tag is empty"
else:
return elem.text
def destination_name(data):
""" Fonction qui permet de récupérer le nom du terminus en fonction de data passé en paramètre
Nom fonction : destination_name
Paramètre : data, un flux xml
Return : un string qui a comme valeur le libellé de la destination final"""
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()
for tag in root.findall("."):
if tag.tag == "PlannedPatternDelivery":
if tag.find("PlannedPattern") is None:
return "Error, 'PlannedPattern' tag not exists"
else:
if tag.find("PlannedPattern/DestinationName") is None:
return "Error, 'DestinationName' tag not exists"
else:
for elem in root.findall("./PlannedPattern/DestinationName"):
if elem.text is None:
return "Error, 'DestinationName' tag is empty"
else:
return elem.text
def line_name(data):
""" Fonction qui permet de récupérer le nom de la ligne en fonction de data passé en paramètre
Nom fonction : line_name
Paramètre : data, un flux xml
Return : un string qui a comme valeur le mnémonique commercial de ligne"""
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()
for tag in root.findall("."):
if tag.tag == "PlannedPatternDelivery":
if tag.find("PlannedPattern") is None:
return "Error, 'PlannedPattern' tag not exists"
else:
if tag.find("PlannedPattern/ExternalLineRef") is None:
return "Error, 'ExternalLineRef' tag not exists"
else:
for elem in root.findall("./PlannedPattern/ExternalLineRef"):
if elem.text is None:
return "Error, 'ExternalLineRef' tag is empty"
else:
return elem.text
def last_stop_point_ref(data):
""" Fonction qui permet de récupérer le nom du dernier arrêt auquel le bus s'est arrêté
Nom fonction : last_stop_point_ref
Paramètre : data, un flux xml
Return : un string qui a comme valeur le numéro du point (NLP de l'objet arrêt du fichier neutre des points)"""
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()
for tag in root.findall("."):
if tag.tag == "VehicleMonitoringDelivery":
if tag.find("VehicleActivity") is None:
return "Error, 'VehicleActivity' tag not exists"
else:
if tag.find("VehicleActivity/ProgressBetweenStops") is None:
return "Error, 'ProgressBetweenStops' tag not exists"
else:
if tag.find("VehicleActivity/ProgressBetweenStops/PreviousCallRef") is None:
return "Error, 'PreviousCallRef' tag not exists"
else:
if tag.find("VehicleActivity/ProgressBetweenStops/PreviousCallRef/StopPointRef") is None:
return "Error, 'StopPointRef' tag not exists"
else:
for elem in root.findall(
"./VehicleActivity/ProgressBetweenStops/PreviousCallRef/StopPointRef"):
if elem.text is None:
return "Error, 'StopPointRef' tag is empty"
else:
return elem.text
def time_next_stop(data):
""" Fonction qui permet de récupérer à la fois, l'heure d'arrivée prévue et celle éstimé, du prochain arrêt, en fonction de data passé en paramètre
Nom fonction : time_next_stop
Paramètre : data, un flux xml
Return : un tuple qui a comme valeur en indice 0, l'heure théorique d’arrivée au prochaine arrêt (YYYY-MMDDThh:mm:ss+hh:mm)
et en indice 1, l'heure applicable d’arrivée au prochaine arrêt (YYYY-MMDDThh:mm:ss+hh:mm) (théorique +avance/retard)"""
tree = ET.ElementTree(ET.fromstring(data))
root = tree.getroot()
for tag in root.findall("."):
if tag.tag == "JourneyMonitoringDelivery":
if tag.find("MonitoredJourney") is None:
return "Error, 'MonitoredJourney' tag not exists"
else:
if tag.find("MonitoredJourney/MonitoredCall") is None:
return "Error, 'MonitoredCall' tag not exists"
else:
if tag.find("MonitoredJourney/MonitoredCall/Order") is None:
return "Error, 'Order' tag not exists"
else:
# Récupération du numéro Order du MonitoredCall
for orders in root.findall("./MonitoredJourney/MonitoredCall/Order"):
if orders.text is None:
return "Error, 'Order' tag is empty"
else:
order = orders.text
if tag.find("MonitoredJourney/OnwardCalls") is None:
return "Error, 'OnwardCalls' tag not exists"
else:
if tag.find("MonitoredJourney/OnwardCalls/OnwardCall") is None:
return "Error, 'OnwardCall' not exists"
else:
# Recherche du numéro Order +1 (qui correspond donc au prochain arrêt)
for elem in root.findall("./MonitoredJourney/OnwardCalls/OnwardCall"):
if elem[1].text is None:
return "Error, 'Order' tag is empty"
else:
if int(elem[1].text) == int(order) + 1:
if tag.find("MonitoredJourney/OnwardCalls/OnwardCall/PlannedArrivalTime") is None:
return "Error, 'PlannedArrivalTime' not exists"
else:
if tag.find("MonitoredJourney/OnwardCalls/OnwardCall/ExpectedArrivalTime") is None:
return "Error, 'ExpectedArrivalTime' tag not exists"
else:
# elem[2].text correspond au contenue de la balise PlannedArrivalTime
if elem[2].text is None:
return "Error, 'PlannedArrivalTime' tag is empty"
else:
# elem[3].text correspond au contenue de la balise ExpectedArrivalTime
if elem[3].text is None:
return "Error, 'ExpectedArrivalTime' tag is empty"
else:
return elem[2].text, elem[3].text
def run(server_class=HTTPServer, handler_class=Server, addr="localhost", port=8000):
""" Fonction qui permet de run le serveur
Paramètres: server_class: , handler_class: la class Server par défaut, addr: localhost par défaut, port: 8000 par défaut
Return: Ne retourne rien, permet de faire tourner le serveur"""
# Initialisation du server_address via les paramètre addr et port de la fonction
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
run(addr='127.0.0.1', port=8000)
| UTF-8 | Python | false | false | 12,636 | py | 38 | ServerAVMS.py | 17 | 0.525265 | 0.522152 | 0 | 294 | 41.608844 | 151 |
tanyabonilla/webproject | 17,454,747,113,120 | c8eff9d122e0a4cc59a6c69c81b6b0dd4bf15423 | 051a832fe8e657641b08688200d09ab34cb5a10d | /myCalsite/myCalapp/urls.py | 4ecc6663b0e02bfacab147b9b32880612ce7d800 | [
"MIT"
]
| permissive | https://github.com/tanyabonilla/webproject | 0d8417b5de4eb58a819714506e4e491c645d0f58 | 8c194faf68129a090a0309e601f92f4269c870ca | refs/heads/master | 2022-11-15T10:10:47.346420 | 2019-12-24T07:20:58 | 2019-12-24T07:20:58 | 215,208,836 | 2 | 0 | MIT | false | 2022-11-04T19:31:03 | 2019-10-15T04:46:27 | 2019-12-24T07:21:02 | 2022-11-04T19:31:00 | 430 | 0 | 0 | 4 | JavaScript | false | false | from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.CalendarView.as_view(), name='calendar'),
path('logout/', views.logout_view),
path('login/', auth_views.LoginView.as_view()),
path('register/', views.register),
path('myfriends/', views.add_remove_friend),
path('myfriends/friends/', views.friends_view), #json
path('friends/', views.friends_view), #json
path('chat/', views.chatindex, name='chat'),
path('chat/chatrooms/', views.chatrooms_view), #json
path('chat/<str:room_name>/', views.room, name='room'),
path('chat/events/', views.room, name='room'),
path('chat/tasks/', views.room, name='room'),
path('chat/friends/', views.room, name='room'),
path('events/', views.events_view), #json
path('tasks/', views.tasks_view), #json
path('chatrooms/', views.chatrooms_view), #json
path('new_events_tasks/', views.new_events_tasks), #new_event
path('new_events_tasks/events/', views.events_view), #json
path('new_events_tasks/tasks/', views.tasks_view), #json
path('new_events_tasks/friends/', views.friends_view), #json
path('new_events_tasks/chatrooms/', views.chatrooms_view), #json
path('mytasks/', views.mytask_view),
path('mytasks/tasks/', views.tasks_view), #json
path('mytasks/events/', views.events_view), #json
path('mytasks/friends/', views.friends_view), #json
path('mytasks/chatrooms/', views.chatrooms_view), #json
] | UTF-8 | Python | false | false | 1,531 | py | 22 | urls.py | 10 | 0.662312 | 0.662312 | 0 | 33 | 45.424242 | 68 |
d3fin3d/mercycogs | 15,040,975,471,991 | f3ad9f234ff73ddd1848d96123647e94dfc25fdc | 8fa8701de63b33e327b915cb01c73ca533de58f3 | /wikipedia.py | ba75645ef071522d4b7d3ba7c47447bebe02793d | []
| no_license | https://github.com/d3fin3d/mercycogs | fa51a07216cedee39e55446570fb850f07069f31 | e2f1e9edf698d86000016d8dcf680ad49cf958ca | refs/heads/master | 2021-01-15T15:31:05.366774 | 2016-08-31T22:39:20 | 2016-08-31T22:39:20 | 64,248,940 | 0 | 1 | null | false | 2016-08-31T22:39:21 | 2016-07-26T19:35:19 | 2016-07-26T20:16:26 | 2016-08-31T22:39:20 | 357 | 0 | 0 | 4 | Python | null | null | from .utils.dataIO import fileIO
from discord.ext import commands
import aiohttp
import html
import os
import re
class Wikipedia:
"""
Le Wikipedia Cog
"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, name='wikipedia', aliases=['wiki', 'w'])
async def _wikipedia(self, context, *query: str):
"""
Get information from Wikipedia
"""
try:
url = 'https://en.wikipedia.org/w/api.php?'
payload = {}
payload['action'] = 'query'
payload['format'] = 'json'
payload['prop'] = 'extracts'
payload['titles'] = " ".join(query).replace(' ', '_')
payload['exsentences'] = '3'
payload['redirects'] = '1'
payload['explaintext'] = '1'
headers = {'user-agent': 'Red-cog/1.0'}
conn = aiohttp.TCPConnector(verify_ssl=False)
session = aiohttp.ClientSession(connector=conn)
async with session.get(url, params=payload, headers=headers) as r:
result = await r.json()
session.close()
if '-1' not in result['query']['pages']:
for page in result['query']['pages']:
title = result['query']['pages'][page]['title']
description = result['query']['pages'][page]['extract']
message = '\n{}\n\n{}'.format(title, description)
else:
message = 'I\'m sorry, I can\'t find {}'.format(" ".join(query))
except Exception as e:
message = 'Something went terribly wrong! [{}]'.format(e)
await self.bot.say('```{}```'.format(message))
def setup(bot):
n = Wikipedia(bot)
bot.add_cog(n)
| UTF-8 | Python | false | false | 1,475 | py | 6 | wikipedia.py | 5 | 0.632542 | 0.628475 | 0 | 52 | 27.365385 | 78 |
alecraso/spackl | 11,373,073,401,202 | d61c8e8d5eb5358f5d2b5124bbc4e1772c2facc2 | 15f0a82506d2c049df0285e5948b97b80d58a40b | /tests/test_util.py | 7d926245cd84e2c4e08c2ff4909607af2e294695 | [
"MIT"
]
| permissive | https://github.com/alecraso/spackl | c71475e565ab487439ef6492151a19da19033361 | 71906a3da6470f67bff19c42bd0f1f8748c5056f | refs/heads/master | 2023-08-09T16:02:35.164229 | 2019-03-09T07:28:26 | 2019-03-09T07:28:26 | 174,647,506 | 0 | 0 | MIT | false | 2023-07-21T16:09:08 | 2019-03-09T04:22:08 | 2019-03-09T07:28:31 | 2023-07-21T16:09:08 | 32 | 0 | 0 | 3 | Python | false | false | import datetime
import decimal
import json
import pytest
from collections import OrderedDict
from spackl.util import DtDecEncoder
results = [OrderedDict([('a', 1), ('b', decimal.Decimal(2.0)), ('c', datetime.date(2018, 8, 1))]),
OrderedDict([('a', 4), ('b', decimal.Decimal(5.0)), ('c', datetime.date(2018, 9, 1))]),
OrderedDict([('a', 7), ('b', decimal.Decimal(8.0)), ('c', datetime.datetime(2018, 10, 1))])]
def test_dtdecencoder():
with pytest.raises(TypeError):
json.dumps(results)
expected_json = (
'[{"a": 1, "b": 2.0, "c": "2018-08-01"}, '
'{"a": 4, "b": 5.0, "c": "2018-09-01"}, '
'{"a": 7, "b": 8.0, "c": "2018-10-01T00:00:00"}]')
data = json.dumps(results, cls=DtDecEncoder, sort_keys=True)
assert data == expected_json
bad_json = {'a': 7, 'b': decimal.Decimal(8.0), 'c': datetime.datetime(2018, 10, 1), 'd': OrderedDict}
with pytest.raises(TypeError):
json.dumps(bad_json, cls=DtDecEncoder, sort_keys=True)
| UTF-8 | Python | false | false | 1,011 | py | 40 | test_util.py | 29 | 0.585559 | 0.509397 | 0 | 28 | 35.107143 | 105 |
NeoNeuron/bmtk | 10,204,842,321,681 | 8281ef3e96c9ed06adc100477e3ff876b6b36df1 | fd47dc01b2e31a61e208867893216656f3bdc5ec | /bmtk/tests/builder/test_id_generator.py | ba9dc5ecb451623fe544fbd58a44ce2f2f0ea15b | [
"BSD-3-Clause"
]
| permissive | https://github.com/NeoNeuron/bmtk | e67390b16ee9d88295cc64de60abf3f3faa25045 | 257a2041d0b936efeae60c1f37d0542624fd88ea | refs/heads/develop | 2023-01-23T22:54:09.267010 | 2020-12-11T12:46:43 | 2020-12-11T12:46:43 | 303,979,929 | 1 | 0 | BSD-3-Clause | true | 2020-12-11T12:46:44 | 2020-10-14T10:27:51 | 2020-10-14T12:16:28 | 2020-12-11T12:46:43 | 142,475 | 0 | 0 | 0 | Python | false | false | import pytest
from bmtk.builder.id_generator import IDGenerator
def test_generator():
generator = IDGenerator()
assert(generator.next() == 0)
assert(generator.next() == 1)
assert(generator.next() == 2)
def test_generator_initval():
generator = IDGenerator(101)
assert(generator.next() == 101)
assert(generator.next() == 102)
assert(generator.next() == 103)
def test_contains():
generator = IDGenerator(init_val=10)
gids = [generator.next() for _ in range(10)]
assert(len(gids) == 10)
assert(10 in generator)
assert(19 in generator)
assert(20 not in generator)
def test_remove():
generator = IDGenerator(init_val=101)
assert(generator.next() == 101)
generator.remove_id(102)
generator.remove_id(104)
generator.remove_id(106)
assert(generator.next() == 103)
assert(generator.next() == 105)
assert(generator.next() == 107)
| UTF-8 | Python | false | false | 916 | py | 117 | test_id_generator.py | 51 | 0.657205 | 0.601528 | 0 | 36 | 24.444444 | 49 |
NYPL-Simplified/circulation | 15,109,694,986,989 | 25fada0191dfaf5c3d124431eddb7a373a23c67a | d5b1aeec9c21c9a258e66aed7aa3dcdbec37b376 | /core/tests/models/test_appeal.py | d0c317b00b03a1afc784749b1a31c96eade8152f | [
"Apache-2.0"
]
| permissive | https://github.com/NYPL-Simplified/circulation | 5a13d5c43e12da154dcd864709bce0578ec05a30 | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | refs/heads/develop | 2023-08-16T19:24:25.376510 | 2023-08-15T11:38:49 | 2023-08-15T11:38:49 | 27,605,405 | 20 | 19 | NOASSERTION | false | 2023-08-16T13:15:11 | 2014-12-05T18:53:04 | 2022-12-14T22:30:15 | 2023-08-16T13:15:10 | 99,864 | 18 | 17 | 83 | Python | false | false | from ...model import Work
class TestAppealsAssignment:
def test__assign_appeals(self, db_session, create_work):
"""
GIVEN: A Work item
WHEN: Assigning appeals
THEN: Verify that the correct appeals have been assigned
"""
work = create_work(db_session)
work.assign_appeals(0.50, 0.25, 0.20, 0.05)
assert 0.50 == work.appeal_character
assert 0.25 == work.appeal_language
assert 0.20 == work.appeal_setting
assert 0.05 == work.appeal_story
assert Work.CHARACTER_APPEAL == work.primary_appeal
assert Work.LANGUAGE_APPEAL == work.secondary_appeal
# WHEN: Increasing the cutoff point
# THEN: There is no secondary appeal.
work.assign_appeals(0.50, 0.25, 0.20, 0.05, cutoff=0.30)
assert 0.50 == work.appeal_character
assert 0.25 == work.appeal_language
assert 0.20 == work.appeal_setting
assert 0.05 == work.appeal_story
assert Work.CHARACTER_APPEAL == work.primary_appeal
assert Work.NO_APPEAL == work.secondary_appeal
| UTF-8 | Python | false | false | 1,098 | py | 903 | test_appeal.py | 713 | 0.627505 | 0.581056 | 0 | 29 | 36.862069 | 65 |
jgv7/Isotuple | 6,923,487,314,306 | 97f3563bc5d9fa0fef531005082dd59978029c9f | c8d443f0728fe86740ab8cfb645d47b970f3f59e | /workarea_ntupleIso/makeHisto.py | 2d189274643cd4f369a7bfcd3e2a533f503e2a08 | []
| no_license | https://github.com/jgv7/Isotuple | 58968f1eaba54c98b036064f4f07b1da6be33cc2 | 67b949a97e2912f9c939183e4528b75a203484e9 | refs/heads/master | 2016-08-08T00:44:42.479626 | 2015-04-24T21:25:09 | 2015-04-24T21:25:09 | 34,356,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from ROOT import *
from math import sqrt
dict = {}
def makeTH1F( name, title, nbins, xmin, xmax ):
if (name in dict):
print " -- Error: TH1F histogram %s already declared." % name
return
dict[name] = TH1F(name, title, nbins, xmin, xmax)
dict[name].Sumw2()
def makeTH2F( name, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax ):
if (name in dict):
print " -- Error: TH2F histogram %s already declared." % name
return
dict[name] = TH2F(name, title, nbinsx, xmin, xmax, nbinsy, ymin, ymax)
dict[name].Sumw2()
def makeTProfile( name, title, nbins, xmin, xmax ):
if (name in dict):
print " -- Error: TProfile %s already declared." % name
return
dict[name] = TProfile(name, title, nbins, xmin, xmax)
#dict[name].Sumw2()
def dPhi_mPi_Pi( x ):
kPi = 3.14159265359
while ( x >= kPi ):
x -= 2*kPi
while ( x < -kPi ):
x += 2*kPi
return x
def DeltaR( e1, p1, e2, p2 ):
dEta = (e1 - e2)
dPhi = dPhi_mPi_Pi(p1-p2)
return sqrt( dEta*dEta + dPhi*dPhi )
| UTF-8 | Python | false | false | 1,007 | py | 70 | makeHisto.py | 32 | 0.618669 | 0.587885 | 0 | 40 | 24.15 | 72 |
googoles/Python_Algorithm | 10,514,079,987,674 | e18777f81c295dd1f2eaf1ca810f14688824a052 | 76e7e5b21d064bdb4c3f1a8e18216197db3c3c6e | /Algorithm_basic/recursion_practice/search.py | f05a5c506835dc07406bd0f6816aea45166ea6cc | []
| no_license | https://github.com/googoles/Python_Algorithm | f594314aa51deed31008945843f28192916f1577 | 80c2c8ef4c4b617e2adea1fdcc6901109d546781 | refs/heads/master | 2022-12-26T16:30:19.579556 | 2020-09-11T14:34:31 | 2020-09-11T14:34:31 | 240,672,932 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def search(li, begin, end, target):
if begin>end:
return -1
elif target == li[begin]:
return begin
else:
return search(li,begin+1, end, target)
li = [1,6,10,7,2,5]
target = 10
search(li,0,5,10) | UTF-8 | Python | false | false | 230 | py | 152 | search.py | 150 | 0.573913 | 0.508696 | 0 | 11 | 20 | 46 |
hahyuning/coding_test | 15,092,515,105,063 | dfd5b49f445abec253b301c82bb36407087d6848 | f7b721dd39c5d0b6a2a409280db1517e9e590295 | /problem_solving/2021/211225/211225_5.py | 9629fa33fa228311ea0438583463a4af2c7e07b9 | []
| no_license | https://github.com/hahyuning/coding_test | 9ac5c1424ef7637affe8167374ff832b0e7c03ee | 70cae3bd40ff4ef0c5a29a22acd8304d7d0bbee3 | refs/heads/master | 2023-07-05T01:17:06.650554 | 2022-08-04T06:39:27 | 2022-08-04T06:39:27 | 353,721,441 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import heapq
def dijkstra(i, start):
q = []
heapq.heappush(q, (0, start))
dist[i][start] = 0
while q:
cost, now = heapq.heappop(q)
if dist[i][now] != -1 and dist[i][now] < cost:
continue
for nxt, nxt_cost in graph[now]:
nxt_cost += cost
if nxt_cost < dist[i][nxt] or dist[i][nxt] == -1:
dist[i][nxt] = nxt_cost
heapq.heappush(q, (nxt_cost, nxt))
n = int(input())
friends = list(map(int, input().split()))
m = int(input())
graph = [[] for _ in range(n + 1)]
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
graph[b].append((a, c))
dist = [[-1] * (n + 1) for _ in range(3)]
for i in range(3):
dijkstra(i, friends[i])
max_val = -1
ans = 0
for i in range(1, n + 1):
min_val = -1
for j in range(3):
if min_val == -1 or dist[j][i] < min_val:
min_val = dist[j][i]
if max_val == -1 or min_val > max_val:
max_val = min_val
ans = i
print(ans) | UTF-8 | Python | false | false | 1,043 | py | 1,091 | 211225_5.py | 1,090 | 0.492809 | 0.47651 | 0 | 45 | 22.2 | 61 |
chauvm/massp-mentees-exercises | 4,604,204,969,667 | 09d47092f481428f6be598cb4589b57033072ea2 | 9a854ac51cb5f6d75f0915de39358d02f42c1f4d | /python/algorithm/easy_reshape_matrix.py | 9fdbfb03cba651cbd0b0a14928866148d667d5ed | [
"MIT"
]
| permissive | https://github.com/chauvm/massp-mentees-exercises | f07533614bbc8ddd650dc133afd91140a66b80e4 | 741a890c6beeeb623ee7598f62a78167de5a68d7 | refs/heads/master | 2020-04-01T07:53:23.399626 | 2018-10-28T03:30:42 | 2018-10-28T03:30:42 | 153,008,489 | 1 | 1 | MIT | false | 2018-10-28T03:40:52 | 2018-10-14T19:02:44 | 2018-10-28T03:30:50 | 2018-10-28T03:40:26 | 3 | 0 | 1 | 1 | Python | false | null | '''
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
'''
def matrix_reshape(nums, r, c):
pass
| UTF-8 | Python | false | false | 1,071 | py | 5 | easy_reshape_matrix.py | 3 | 0.720822 | 0.690943 | 0 | 34 | 30.5 | 186 |
regulusweb/django-oscar-api | 13,769,665,157,503 | eb7ac3c10068b12d5310614f70fa278acf466272 | f0e4cd636a70864a51dfe8f836ed8a5da4775f07 | /oscarapi/tests/test_apps/apps/oscarapi/serializers/__init__.py | 7f493b8edaa2b8397acbaed29c4525094cd22d2e | [
"BSD-2-Clause"
]
| permissive | https://github.com/regulusweb/django-oscar-api | 4a276337dfaa684aaa55f1ce09877be6c808e81d | 54b90aa27daf3ba22fcb0f2c9f03b3a6402c82c7 | refs/heads/master | 2020-04-05T09:26:16.880534 | 2017-02-10T14:00:12 | 2017-02-10T14:00:12 | 40,957,350 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | from .basket import * | UTF-8 | Python | false | false | 21 | py | 18 | __init__.py | 10 | 0.761905 | 0.761905 | 0 | 1 | 21 | 21 |
bchuey/valet | 16,080,357,582,300 | 1de641c85fadc97dd1dfc03777ccb7bcf62380b3 | 5959a8f6170fb2ad412944255b4a761362d97a08 | /src/locations/models.py | 5cbcec75d6c56b022e966abb7e628fd24213c620 | []
| no_license | https://github.com/bchuey/valet | 7bd59e93023c5eaa915ed1fcca76a588202c5063 | 2aae705c718a5b10cc9fbe4b2e93ad819e1328c2 | refs/heads/master | 2016-08-11T22:14:58.720776 | 2016-04-26T17:49:51 | 2016-04-26T17:49:51 | 54,831,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from __future__ import unicode_literals
from django.db import models
from accounts.models import PARKING_ZONES
# Create your models here.
class Location(models.Model):
lat = models.CharField(verbose_name='latitude', max_length=255, null=True, blank=True)
lng = models.CharField(verbose_name='longitude', max_length=255, null=True, blank=True)
full_address = models.CharField(verbose_name='full address', max_length=255, null=True, blank=True)
class Meta:
db_table = 'gps_locations'
def __unicode__(self):
return unicode(self.id) or u''
def __str__(self):
return str(self.id)
class IntersectionLatLng(models.Model):
lat = models.FloatField(verbose_name='latitude', max_length=255, null=True, blank=True)
lng = models.FloatField(verbose_name='longitude', max_length=255, null=True, blank=True)
parking_section = models.ForeignKey('ParkingSection', related_name='coordinates')
class Meta:
db_table = 'intersections'
def __unicode__(self):
return unicode(self.id)
def __str__(self):
return str(self.id)
class ParkingSection(models.Model):
label = models.CharField(max_length=2, choices=PARKING_ZONES)
time_limit = models.IntegerField()
# accepted_permit = models.ForeignKey(ParkingPermit)
class Meta:
db_table = 'parking_sections'
def __unicode__(self):
return unicode(self.label)
def __str__(self):
return self.label
# class ParkingPermit(models.Model):
| UTF-8 | Python | false | false | 1,426 | py | 60 | models.py | 48 | 0.719495 | 0.708275 | 0 | 66 | 20.5 | 100 |
Mengqiao2020/Challenge-of-Leetcode2020 | 8,203,387,539,837 | 9384c1ac9eee75db9e65a5a2195943e5cb0b8675 | efbf6249d6f59bf80cb1a04c115bad65913e2192 | /39xdgy/q16.py | 3f7cf0ede1ce70a661d24034f34f6413a1a1b38f | []
| no_license | https://github.com/Mengqiao2020/Challenge-of-Leetcode2020 | 122719626aff14232f9a8dc4bd94ea4988325f88 | c2c880dd9185a1d10e01e870ad85174bf6955ad3 | refs/heads/main | 2023-02-18T20:04:59.314256 | 2021-01-17T04:06:00 | 2021-01-17T04:06:00 | 325,318,479 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
!!!!!
3sum closest
56ms, 99.24%, 10.10%
'''
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
return self.KSumClosest(nums, 3, target)
def KSumClosest(self, nums: List[int], k: int, target: int) -> int:
N = len(nums)
if N == k:
return sum(nums[:k])
# target too small
current = sum(nums[:k])
if current >= target:
return current
# target too big
current = sum(nums[-k:])
if current <= target:
return current
if k == 1:
return min([(x, abs(target - x)) for x in nums], key = lambda x: x[1])[0]
closest = sum(nums[:k])
for i, x in enumerate(nums[:-k+1]):
if i>0 and x == nums[i-1]:
continue
current = self.KSumClosest(nums[i+1:], k-1, target - x) + x
if abs(target - current) < abs(target - closest):
if current == target:
return target
else:
closest = current
return closest | UTF-8 | Python | false | false | 1,125 | py | 25 | q16.py | 23 | 0.48 | 0.462222 | 0 | 40 | 27.15 | 85 |
calvinchankf/AlgoDaily | 6,098,853,601,480 | e794c29fd8af3b0ba36b8fb77d57f1c2e16eac4c | e00f0f6a6f605532b1123d3e985a5902609eb30a | /leetcode/2751/main.py | f0f726110db8521407a1d948385cbb36630e544f | []
| no_license | https://github.com/calvinchankf/AlgoDaily | b53c5ea5896e9b8662f4f97bce3eb41b480eb8e0 | 8ee5006e42442043816881ee88ccc485a3a56ec5 | refs/heads/master | 2023-08-25T11:48:47.415388 | 2023-08-25T08:55:22 | 2023-08-25T08:55:22 | 146,955,627 | 154 | 48 | null | false | 2023-09-09T09:02:43 | 2018-09-01T00:56:43 | 2023-09-03T17:36:52 | 2023-09-09T09:02:42 | 63,478 | 2 | 1 | 11 | Python | false | false | """
stack + hashtable
- very similar to lc135, additionally:
- sort the original posstions for displaying the result in the later stage
- sort the robots by positions
- just added some logic to decrement the health upon collision
Time O(NlogN)
Space O(N)
"""
class Solution:
def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]:
n = len(positions)
position_map = {}
A = []
for i in range(n):
p = positions[i]
h = healths[i]
d = directions[i]
A.append([p, h, d])
position_map[p] = i
A.sort(key=lambda x: x[0])
# print(A)
S = []
for i in range(n):
x = A[i]
if x[2] == 'R':
S.append(x)
else:
while len(S) > 0 and S[-1][2] == 'R' and S[-1][1] < x[1]:
S.pop()
x[1] -= 1
if len(S) > 0 and S[-1][2] == 'R' and S[-1][1] == x[1]:
S.pop()
elif len(S) == 0:
S.append(x)
elif S[-1][2] == 'L':
S.append(x)
elif S[-1][2] == 'R' and S[-1][1] > x[1]:
S[-1][1] -= 1
# print(S)
S.sort(key=lambda x: position_map[x[0]])
return [h for _p, h, _d in S]
| UTF-8 | Python | false | false | 1,435 | py | 3,428 | main.py | 3,404 | 0.416028 | 0.394425 | 0 | 46 | 30.195652 | 108 |
YaminiHP/SimilitudeApp | 14,611,478,743,768 | f96876ccee1d5e491f5a67d67aaee71aca261844 | 8acffb8c4ddca5bfef910e58d3faa0e4de83fce8 | /ml-flask/Lib/site-packages/nltk/corpus/reader/nps_chat.py | e685b2d0bc4729ed5bb215418cd66d3d3f628919 | [
"MIT"
]
| permissive | https://github.com/YaminiHP/SimilitudeApp | 8cbde52caec3c19d5fa73508fc005f38f79b8418 | 005c59894d8788c97be16ec420c0a43aaec99b80 | refs/heads/master | 2023-06-27T00:03:00.404080 | 2021-07-25T17:51:27 | 2021-07-25T17:51:27 | 389,390,951 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:f0679235f8a9752d007fe639fcc52cac3aaed31c94f815cddf0381f63bc625da
size 2846
| UTF-8 | Python | false | false | 129 | py | 3,552 | nps_chat.py | 3,523 | 0.883721 | 0.534884 | 0 | 3 | 42 | 75 |
Cyberwatch/httpie-cbw-api-auth | 13,778,255,087,741 | 4665827af84ff9b8f0d94f14700a262a674c6445 | 888ccd2fb03e7a6d02036394cb26022066015b91 | /setup.py | 3973f4a65b0477f20600ef7bd862934fbef6d520 | [
"BSD-3-Clause"
]
| permissive | https://github.com/Cyberwatch/httpie-cbw-api-auth | e5b19d8d88fbf33903dbfa4c76f599771755556b | 7393ad002d12cc3399b9ac497002f0504517d1e1 | refs/heads/master | 2021-08-22T11:59:21.199078 | 2020-08-28T13:38:09 | 2020-08-28T14:00:01 | 217,558,787 | 0 | 1 | BSD-3-Clause | false | 2020-08-28T14:00:03 | 2019-10-25T15:05:38 | 2019-12-20T16:43:18 | 2020-08-28T14:00:02 | 6 | 0 | 1 | 0 | Python | false | false | from setuptools import setup
try:
import multiprocessing
except ImportError:
pass
setup(
name='httpie-cbw-api-auth',
description='CyberWatch ApiAuth plugin for HTTPie.',
long_description=open('README.md').read().strip(),
version='0.1.0',
author='CyberWatch SAS',
author_email='contact@cyberwatch.fr',
license='MIT',
url='https://gitlab.cbw.io/CyberwatchTeam/httpie-cbw-api-auth',
py_modules=['httpie_cbw_api_auth'],
zip_safe=False,
entry_points={
'httpie.plugins.auth.v1': [
'httpie_cbw_api_auth = httpie_cbw_api_auth:CbwApiAuthPlugin'
]
},
install_requires=[
"httpie>=0.9.9"
]
)
| UTF-8 | Python | false | false | 681 | py | 3 | setup.py | 2 | 0.632893 | 0.622614 | 0 | 26 | 25.192308 | 72 |
SinghMPManas/PythonAutomationFramework1 | 13,460,427,507,950 | cb87b398983beb0cca12f4174925d5165ee57ee9 | e3befe74919cb3fb9677a11e8070fca10f0c98a3 | /pages/LoginPage.py | caf868985e403bc74ab42634e5d1b5513a4a5907 | []
| no_license | https://github.com/SinghMPManas/PythonAutomationFramework1 | fb31959a274b3c422fbaecce443ef631c834f27c | 5798ce49074f801d674bf30eefb4fb489c7867cf | refs/heads/master | 2020-09-26T04:01:29.914723 | 2019-12-05T17:56:44 | 2019-12-05T17:56:44 | 226,160,557 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class loginPage():
def __init__(self, driver):
self.driver = driver
self.username_textbox_id = "identifierId"
self.username_button_xpath = "//span[@class='RveJvd snByac']"
self.password_textbox_name = "password"
self.password_button_xpath = "//span[contains(text(),'Next')]"
def enter_username(self, username):
self.driver.find_element_by_id(self.username_textbox_id).clear()
self.driver.find_element_by_id(self.username_textbox_id).send_keys(username)
def click_username_button(self):
self.driver.find_element_by_xpath(self.username_button_xpath).click()
def enter_password(self, password):
self.driver.find_element_by_name(self.password_textbox_name).clear()
self.driver.find_element_by_name(self.password_textbox_name).send_keys(password)
def click_password_button(self):
self.driver.find_element_by_xpath(self.password_button_xpath).click() | UTF-8 | Python | false | false | 958 | py | 4 | LoginPage.py | 4 | 0.680585 | 0.680585 | 0 | 23 | 40.695652 | 88 |
bumps/bumps | 4,904,852,698,065 | 393d2481ddb01d8773b6d5bab76af5f08b795ced | ce60f76c6ad4c48fd6182240b302ee057809cc66 | /bumps/gui/log_view.py | 377fc4a856406f29e4dc2df28bc02cf31251f5e1 | [
"MIT",
"LicenseRef-scancode-public-domain"
]
| permissive | https://github.com/bumps/bumps | 8ae10e8d15c0aa64e0bab6e00e7fabb2ca1b0860 | 2594e69567d534b434dc0eae727b77fdeff411d4 | refs/heads/master | 2023-08-22T17:56:49.987181 | 2023-07-26T14:22:23 | 2023-07-26T14:22:23 | 2,799,064 | 48 | 28 | NOASSERTION | false | 2023-07-26T14:22:24 | 2011-11-17T22:22:02 | 2023-06-02T16:18:40 | 2023-07-26T14:22:23 | 13,245 | 51 | 27 | 63 | Python | false | false | import wx
IS_MAC = (wx.Platform == '__WXMAC__')
class LogView(wx.Panel):
title = 'Log'
default_size = (600,200)
def __init__(self, *args, **kw):
wx.Panel.__init__(self, *args, **kw)
self.log_info = []
vsizer = wx.BoxSizer(wx.VERTICAL)
self.progress = wx.TextCtrl(self,-1,style=wx.TE_MULTILINE|wx.HSCROLL)
self._redraw()
vsizer.Add(self.progress, 1, wx.EXPAND)
self.SetSizer(vsizer)
vsizer.Fit(self)
self.SetAutoLayout(True)
#self.SetupScrolling()
self.Bind(wx.EVT_SHOW, self.OnShow)
def OnShow(self, event):
if not event.Show: return
#print "showing log"
if self._need_redraw:
#print "-redraw"
self._redraw()
def get_state(self):
return self.log_info
def set_state(self, state):
self.log_info = state
self._redraw()
def log_message(self, message):
if len(self.log_info) > 1000:
del self.log_info[:-1000]
self.log_info.append(message)
self._redraw()
def _redraw(self):
if not IS_MAC and not self.IsShown():
self._need_redraw = True
else:
self._need_redraw = False
self.progress.Clear()
self.progress.AppendText("\n".join(self.log_info))
| UTF-8 | Python | false | false | 1,339 | py | 211 | log_view.py | 177 | 0.551158 | 0.539208 | 0 | 51 | 25.254902 | 77 |
coderZsq/coderZsq.practice.data | 5,050,881,587,290 | b84a4a55824f15712d80e9adbfa02ee63f9be3c3 | c010875f491833eb1219e848c2553c25c3b20371 | /study-notes/py-collection/03_常见数据类型/04_练习.py | a3175fa5b5ca5bd03b45ad0e6588aab97acfd8b6 | [
"MIT"
]
| permissive | https://github.com/coderZsq/coderZsq.practice.data | 98cd8607706a4bc13e2b36874e0a8292a7e48eba | 67065db6ed8abc912d941bcb0acca16f122a053f | refs/heads/master | 2023-08-16T11:51:05.572689 | 2023-08-10T08:19:43 | 2023-08-10T08:19:43 | 141,536,622 | 3 | 1 | MIT | false | 2023-08-10T08:19:45 | 2018-07-19T06:51:09 | 2023-08-09T05:14:37 | 2023-08-10T08:19:43 | 109,162 | 3 | 0 | 2 | Jupyter Notebook | false | false | import turtle as t
# 设置画笔的大小
t.pensize(20)
# 隐藏方向箭头
t.hideturtle()
# 第1条边
t.pencolor('red')
t.forward(100)
# 第2条边
t.pencolor('green')
t.right(90)
t.forward(100)
# 第3条边
t.pencolor('blue')
t.right(90)
t.forward(100)
# 第4条边
t.pencolor('orange')
t.right(90)
t.forward(100)
t.mainloop() | UTF-8 | Python | false | false | 365 | py | 184 | 04_练习.py | 179 | 0.622222 | 0.546032 | 0 | 28 | 9.321429 | 20 |
utikeev/bio-normalizers | 2,310,692,430,418 | eab8aa6280e2d129c840c941e795a05f4ea91897 | e986dbfe9ef74926ebbca9979bfa811db85e625e | /bionorm/normalizers/species/DictNormalizer/data/build_dict.py | c9ae02e495554499432bf1a8bece6d601c24b4cc | [
"MIT"
]
| permissive | https://github.com/utikeev/bio-normalizers | 3b81a7d75cdbd868ba6680a3f49510e8183b0765 | d7234d8ce01687d24f0f5bbba63a59eb87474bbb | refs/heads/master | 2023-04-27T05:05:50.085331 | 2021-04-20T20:30:08 | 2021-04-21T08:16:13 | 261,192,144 | 0 | 0 | MIT | false | 2023-04-21T20:43:33 | 2020-05-04T13:49:10 | 2021-04-21T08:16:17 | 2023-04-21T20:43:33 | 134 | 0 | 0 | 1 | Python | false | false | import argparse
from collections import defaultdict
from pathlib import Path
from typing import NamedTuple, Optional, Dict, List
from tqdm import tqdm
def setup_argparser():
parser = argparse.ArgumentParser()
parser.add_argument("--dump", type=lambda x: Path(x), required=True)
parser.add_argument("--out", type=lambda x: Path(x), required=True)
return parser
class SpeciesEntry(NamedTuple):
id: str
name: str
unique_name: Optional[str]
s_type: str
def main(dump: Path, out: Path):
same_name: Dict[str, List[SpeciesEntry]] = defaultdict(list)
with dump.open('r') as f:
lines = f.readlines()
for line in tqdm(lines, 'Processing lines'): # type: str
parts = line.split('|')
s_id = parts[0].strip()
s_name = parts[1].strip()
unique_name: Optional[str] = parts[2].strip()
unique_name = None if unique_name == '' else unique_name
s_type = parts[3].strip()
entry = SpeciesEntry(s_id, s_name, unique_name, s_type)
if entry.unique_name:
same_name[entry.name].append(entry)
same_name = {k: v for k, v in same_name.items() if len(v) > 1}
number = 0
with out.open('w') as f:
for name, items in same_name.items(): # type: str, List[SpeciesEntry]
f.write(name + '\n')
for item in items:
number += 1
f.write(f'\t{item}\n')
f.write('\n')
print(f'Total {len(lines)} names processed.')
print(f'Found {number} conflicting names grouped into {len(same_name)} chunks.')
if __name__ == '__main__':
argparser = setup_argparser()
args_ = argparser.parse_args()
main(args_.dump, args_.out)
| UTF-8 | Python | false | false | 1,760 | py | 87 | build_dict.py | 61 | 0.5875 | 0.583523 | 0 | 56 | 30.428571 | 84 |
niyoufa/tnd_server | 10,093,173,195,860 | 95dd1efb5eaeb83f57b83808712413aeff1f917f | 4c2a391f2f4d7361f2c7111b6d63edf67056f327 | /model_autoload.py | 1755fa320cc81b5f3c24c3d992064118086c7d2f | []
| no_license | https://github.com/niyoufa/tnd_server | 6d69db32ceb5a6a14417b3e8b0f021fdc0e7e79c | 59c9ac6769773573685be215b4674d77545fe127 | refs/heads/master | 2020-06-23T15:43:28.891619 | 2016-08-26T03:44:01 | 2016-08-26T03:44:01 | 66,613,944 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding=utf-8
import pdb
import os
import importlib
_model_file_list = os.listdir(os.path.dirname(__file__)+"/model")
model_module_names = [name.split(".")[0] for name in _model_file_list \
if not name.endswith(".pyc") and name not in ["__init__.py","mongo.py","Redis.py"]]
def _generate_collections(root_module,model_module_names):
for name in model_module_names:
model_module = importlib.import_module(".%s" % name, root_module)
model_name = getattr(model_module, "", None)
collections = _generate_collections("renren.model",model_module_names) | UTF-8 | Python | false | false | 591 | py | 30 | model_autoload.py | 24 | 0.666667 | 0.663283 | 0 | 15 | 38.466667 | 105 |
alexmerser/flask-xxl | 10,685,878,664,542 | 57bb6c76928eaf1e639f758a62b1e3a0c18824e2 | 2669bcd2f409a3cd7227017bc74c8a1e22359eda | /flask_xxl/hooks.py | dc908a6341731895e23783bfb8c91ba9c47357ab | []
| no_license | https://github.com/alexmerser/flask-xxl | ebdc7162bdd247659159a4e2deaca3537a618972 | 530f08eed38cc07f9776520108a3eb0f0efa31f3 | refs/heads/master | 2020-12-30T18:58:11.584791 | 2015-02-01T05:16:46 | 2015-02-01T05:16:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from mrbob import bobexceptions as mbe
# post question hooks - takes (configurator,question,answer)
# pre question hooks - takes (configurator,question)
def add_apps(c,q):
if not c.variables['project.add_apps']:
raise mbe.SkipQuestion
def check_for_captcha(c,q):
if not c.variables['local_settings.use_captcha']:
raise mbe.SkipQuestion
def db_related_skip(c,q):
if not c.variables['project.use_database']:
raise mbe.SkipQuestion
# pre render hooks - takes nothing - maybe configurator
def make_db_uri(c):
if c.variables['project.use_database']:
fmt = '%s://%s:%s@%s:%d/%s'
c.variables['project.db_uri'] = fmt % (c.variables['project.db-driver'],
c.variables['project.db-username'],
c.variables['project.db-password'],
c.variables['project.db-host'],
c.variables['project.db-port'],
c.variables['project.db-name'])
# post render hooks - takes (configurator)
| UTF-8 | Python | false | false | 1,164 | py | 7 | hooks.py | 6 | 0.542955 | 0.542955 | 0 | 35 | 32.171429 | 82 |
nikolauspschuetz/sbr | 17,575,006,181,481 | d14d862ca4d498d026f2023c685b0e33695849d5 | 773a17f7466dcf0dfeb581d8202f82672d444e3c | /sbr/ui/info.py | dee0417e74eacb4c22edd67e3c8bba5a2dc26f6f | []
| no_license | https://github.com/nikolauspschuetz/sbr | 7f6bc2e9276c03cc63ded9fe5bd9cd48cb0742bb | 75f24820731e43e25d011694c99172979360e939 | refs/heads/master | 2020-09-02T06:12:56.984614 | 2020-08-12T03:02:19 | 2020-08-12T03:02:19 | 219,152,230 | 1 | 0 | null | false | 2020-10-18T17:21:49 | 2019-11-02T12:43:02 | 2020-10-18T16:42:16 | 2020-10-18T17:21:48 | 392 | 1 | 0 | 1 | Python | false | false | """
# Created by nik at 12/2/19
"""
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from webelem import WebElem
class InfoBox(WebElem):
"""info box element of ui-dialog pop-up
Methods:
columns: list(str), text of each element in the table head, i.e. column names
has_scroll: bool, info-box has scrollbar
header: str, a compact element with all-caps text
info_lines: list(InfoLine), get the list of info-line in the tbody
tbody: WebElement, contains all info-line elements
thead: WebElement, element containing column elements for the info-lines
values: list(list), extract the values from each info-line via the InfoLine.values() method
"""
selector = dict(by=By.CLASS_NAME, value='info-box')
def __init__(self, elem):
super().__init__(elem=elem, name='info-box')
def columns(self):
"""text of each element in the table head, i.e. column names
:return: list(str)
"""
return [x.text for x in self.thead().find_elements_by_class_name('header-grid')]
def has_scroll(self):
"""in case of many info-line elements, info-box will have a scroll-bar
:return: bool
"""
try:
self.elem.find_element_by_class_name('jspVerticalBar')
return True
except NoSuchElementException:
return False
def header(self):
"""info-box header: a compact element with all-caps text
:return: str
"""
return self.elem.find_element_by_class_name('header').text
def info_lines(self):
"""get each info-line in the table body. tr elems' attribute 'class' should equal 'info_line_alternate1'
:return: list(InfoLine)
"""
return [InfoLine(x) for x in self.tbody().find_elements(**InfoLine.selector)]
def tbody(self):
"""element containing all info-lines
:return: WebElement
"""
return self.elem.find_element_by_class_name('info-grid').find_element_by_tag_name('tbody')
def thead(self):
"""element containing column elements for the info-lines
:return: WebElem
"""
return self.elem.find_element_by_tag_name('thead')
def values(self, driver=None):
"""extract the values from each info-line
note that the info-box may have a scroll-bar, which then requires the driver to be passed. the values() method
of each InfoLine is used for extraction.
:param driver: selenium driver
:return: list
"""
values = []
if self.has_scroll():
assert driver is not None
for il in self.info_lines():
if not any(il.values()) and self.has_scroll():
driver.execute_script("arguments[0].scrollIntoView(true);", il.elem)
values.append(il.values())
return values
class InfoLine(WebElem):
"""info-line in tbody.
each info-line contains three values: the timestamp, and the pair of spread values. see values()
Methods:
values: list(str), values in the info-line
"""
selector = dict(by=By.TAG_NAME, value='tr')
def __init__(self, elem):
super().__init__(elem=elem, name='info-line')
def values(self):
"""extract the text of each td tag in the info-line.
the first value should be a 'year-less' timestamp, e.g. '09/12 01:01 PM'
the second and third values should be the pair of spread values
:return: list(str)
"""
return [td.text for td in self.elem.find_elements_by_tag_name('td')]
| UTF-8 | Python | false | false | 3,674 | py | 45 | info.py | 43 | 0.620033 | 0.61595 | 0 | 118 | 30.135593 | 118 |
cappuccino213/IMCISDB_Migration | 6,090,263,633,707 | b307bdf3caceae1e7881177ac8a37bfa5a731b9a | 0b9ce477019979bae8d40646e9eb9a6bf3f09136 | /test1.py | 4de24d245a01fe60d589dcdefc5853bcda788a29 | []
| no_license | https://github.com/cappuccino213/IMCISDB_Migration | c4938d9f360c34abb33aded1ac6285111c5501b2 | 9306e4aa9d07e96cef292cfd4c1954ebcb68c9a3 | refs/heads/master | 2020-04-13T07:12:24.119495 | 2018-12-25T03:52:04 | 2018-12-25T03:52:04 | 163,043,970 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # l = [i for i in range(33)]
# n = 7
# # print([l[i:i+n] for i in range(0,len(l),n)])
#
# for i in range(0,len(l),n):
# print(l[i:i+n])
from read_ini import *
from ReadSql import view_sql,select_sql,insert_sql
from mssql import MSSQL
import datetime
import decimal
import re
DB1 = MSSQL(host1,user1,password1,datebase1)
DB2 = MSSQL(host2,user2,password2,datebase2)
view = view_sql()
SQL1 = select_sql()
SQL2 = insert_sql()
def get_name(sql):
table_l = []
try:
sql_ = sql.replace('\n',' ').replace('\t','')
sqllist = sql_.lower().split(';')
for i in sqllist:
l = i.split(' ')
table_l.append(l[l.index('into')+1])
print('获取到待迁移的表名列表:',table_l)
return table_l
except Exception as e:
print('获取表名失败,异常:',str(e))
# print(get_name(SQL2)[1])
def get_sql(sql):
try:
return sql.split(';')
except Exception as e:
print('提取sql语句失败,原因:',str(e))
# l=get_name(SQL2)
# print(get_sql(SQL1)[1])
# print(get_sql(SQL2)[1])
#检查sql脚本是否匹配
def check_script():
"""匹配成功返回True"""
if len(get_sql(SQL1)) == len(get_sql(SQL2)):
return True
else:
print("查询与插入的sql语句数目不匹配")
# print(tname)
#获取待迁移表的索引
def get_index(table_name):
l = get_name(SQL2) #获取脚本中的表名
indexL = []
try:
nameL = table_name.lower().split(',')
print('获取到配置文件中的表名列表:',nameL)
for i in nameL:
indexL.append(l.index(i))
print('配置文件中的表名在sql脚本中的索引列表:',indexL)
return indexL
except Exception as e:
print('获取表名Index,异常:',str(e))
# get_index(tname)
def migration(get_sql,insert_sql,tn):
"""db1为源数据库,db2目标数据库"""
num = DB1.ExecQuery("select count(*) from "+tn)[0][0]
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'表%s需迁移数据:'%tn,num)
Data1 = DB1.ExecQuery(get_sql)
start = datetime.datetime.now()
print(start.strftime("%Y-%m-%d %H:%M:%S"),"开始迁移数据,每组迁移%d"%set_size)
j = 0
for i in range(0,len(Data1),set_size):
j = j+1
set = Data1[i:i+set_size]
DB2.ExecMany(insert_sql, set)
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'第%d组数据%d条完成迁移'%(j,len(set)))
DB2.conn.close()
end = datetime.datetime.now()
print(end.strftime("%Y-%m-%d %H:%M:%S"),"完成数据迁移")
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),'执行耗时:', end - start)
def transfer():
'''根据配置文件mt的值,决定迁移方式'''
if m_type == 1:#进行批量迁移
if check_script():
lenth = len(get_sql(select_sql()))
try:
for i in range(lenth):
migration(get_sql(SQL1)[i], get_sql(SQL2)[i], get_name(SQL2)[i])
print('-------------')
except IndexError as e:
print(str(e))
elif m_type == 2:#指定表迁移
try:
for i in get_index(tname):
print('配置表名',i)
print(get_sql(SQL1)[i])
print(get_sql(SQL2)[i])
print(get_name(SQL2)[i])
# migration(get_sql(SQL1)[i], get_sql(SQL2)[i], get_name(SQL2)[i])
print('-------------')
except IndexError as e:
print(str(e))
else:
print('参数mt值配置有误')
# transfer()
# migration(get_sql(SQL1)[1], get_sql(SQL2)[1], get_name(SQL2)[1])
def query_conditon(sql):
"""根据脚本找到where查询条件"""
regex = "where.*"
table_l = []
try:
sql_ = sql.replace('\n', ' ').replace('\t', '')
sqllist = sql_.lower().split(';')
for i in sqllist:
table_l.append(''.join(re.findall(regex,i)))
print('获取到查询条件:', table_l)
return table_l
except Exception as e:
print('获取到查询条件,异常:', str(e))
return table_l
l = "PatientIndex where PIDAssigningAuthority LIKE 'local.RIS.%';"
# print(query_conditon(l))
t = select_sql()
query_conditon(t)
# print(query_conditon(t))
# print(type(t),t) | UTF-8 | Python | false | false | 3,889 | py | 12 | test1.py | 9 | 0.624019 | 0.606862 | 0 | 150 | 21.933333 | 91 |
IBMDataScience/NorthwesternAI | 18,571,438,630,066 | 1601e46350a7bbb53d6a735de6c7eedfde464422 | 5dfb74965d5cd9a7840157104d0d6bee9b8072fc | /additional-resources/MachineLearning/DeepLearning/NeuralNetworkModeler/Deep_learning_demo-keras.py | 122fd32ac63215ebb16eef5cc45565b695e22d0f | []
| no_license | https://github.com/IBMDataScience/NorthwesternAI | 9bbb954e80cd27cd29143ee22083f0d5e7f8ace6 | f034f7b78868b8637087e40327fd2424c55a0bdf | refs/heads/master | 2020-04-01T11:45:50.197592 | 2018-12-04T22:05:46 | 2018-12-04T22:05:46 | 153,176,669 | 5 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
IBM Deep Learning (IDE) Generated Code.
Compatible Keras Version : 2.1
Tested on Python Version : 3.6.3
'''
# Choose the underlying compiler - tensorflow or theano
import json
import os
with open(os.path.expanduser('~') + "/.keras/keras.json","r") as f:
compiler_data = json.load(f)
compiler_data["backend"] = "tensorflow"
compiler_data["image_data_format"] = "channels_last"
with open(os.path.expanduser('~') + '/.keras/keras.json', 'w') as outfile:
json.dump(compiler_data, outfile)
# Global variable intilization
defined_metrics = []
defined_loss = ""
# import all the required packages
import numpy as np
import keras
from keras.models import Model
import keras.backend as K
import keras.regularizers as R
import keras.constraints as C
from keras.layers import Activation, AveragePooling2D, BatchNormalization, Convolution2D, Dense, Flatten, GlobalAveragePooling2D, GlobalMaxPooling2D, Input, MaxPooling2D
from keras.optimizers import Adam
# Load data from pickle object
import pickle
class_labels_count = 1
with open('fashion_mnist-train.pkl', 'rb') as f:
(train_data, train_label) = pickle.load(f)
if (len(train_data.shape) == 3):
if('tensorflow' == 'tensorflow'):
train_data = train_data.reshape(train_data.shape[0], train_data.shape[1], train_data.shape[2], 1).astype('float32') / 255
else:
train_data = train_data.reshape(train_data.shape[0], 1, train_data.shape[1], train_data.shape[2]).astype('float32') / 255
if (len(train_label.shape) == 1) or (len(train_label.shape) == 2 and train_label.shape[1] == 1):
from keras.utils import np_utils
class_labels_count = len(set(train_label.flatten()))
train_label = np_utils.to_categorical(train_label, class_labels_count)
else:
class_labels_count = train_label.shape[1]
val_data = []
if('fashion_mnist-valid.pkl'):
with open('fashion_mnist-valid.pkl', 'rb') as f:
(val_data, val_label) = pickle.load(f)
if (len(val_data.shape) == 3):
if('tensorflow' == 'tensorflow'):
val_data = val_data.reshape(val_data.shape[0], val_data.shape[1], val_data.shape[2], 1).astype('float32') / 255
else:
val_data = val_data.reshape(val_data.shape[0], 1, val_data.shape[1], val_data.shape[2]).astype('float32') / 255
if (len(val_label.shape) == 1) or (len(val_label.shape) == 2 and val_label.shape[1] == 1):
from keras.utils import np_utils
val_label = np_utils.to_categorical(val_label, class_labels_count)
else:
print('Validation set details not provided')
test_data = []
if('fashion_mnist-test.pkl'):
with open('fashion_mnist-test.pkl', 'rb') as f:
(test_data, test_label) = pickle.load(f)
if (len(test_data.shape) == 3):
if('tensorflow' == 'tensorflow'):
test_data = test_data.reshape(test_data.shape[0], test_data.shape[1], test_data.shape[2], 1).astype('float32') / 255
else:
test_data = test_data.reshape(test_data.shape[0], test_data.shape[1], test_data.shape[2]).astype('float32') / 255
if (len(test_label.shape) == 1) or (len(test_label.shape) == 2 and test_label.shape[1] == 1):
from keras.utils import np_utils
test_label = np_utils.to_categorical(test_label, class_labels_count)
else:
print('Test set details not provided')
print(train_data.shape)
batch_input_shape_ImageData_a7d74d30 = train_data.shape[1:]
train_batch_size = 256
if True:
#Input Layer
ImageData_a7d74d30 = Input(shape=batch_input_shape_ImageData_a7d74d30)
#Convolution2D Layer
Convolution2D_1 = Convolution2D(32, (3, 3), kernel_initializer = 'glorot_normal', bias_initializer = 'glorot_normal', padding = 'valid', strides = (1, 1), data_format = 'channels_last', use_bias = False, name = 'Convolution2D_2a2dd828')(ImageData_a7d74d30)
#Batch Normalization Layer
Convolution2D_1 = BatchNormalization(axis=3,name='bn_Convolution2D_2a2dd828')(Convolution2D_1)
#Rectification Linear Unit (ReLU) Activation Layer
ReLU_2 = Activation('relu', name = 'ReLU_08ca424c')(Convolution2D_1)
#Pooling2D Layer
Pooling2D_3 = MaxPooling2D(pool_size = (2, 2), padding = 'valid', data_format = 'channels_last', strides = (2, 2), name = 'Pooling2D_2fad9093')(ReLU_2)
#Convolution2D Layer
Convolution2D_4 = Convolution2D(64, (3, 3), kernel_initializer = 'glorot_normal', bias_initializer = 'glorot_normal', padding = 'valid', strides = (1, 1), data_format = 'channels_last', use_bias = False, name = 'Convolution2D_416ca4b2')(Pooling2D_3)
#Batch Normalization Layer
Convolution2D_4 = BatchNormalization(axis=3,name='bn_Convolution2D_416ca4b2')(Convolution2D_4)
#Rectification Linear Unit (ReLU) Activation Layer
ReLU_5 = Activation('relu', name = 'ReLU_09f975fd')(Convolution2D_4)
#Pooling2D Layer
Pooling2D_6 = MaxPooling2D(pool_size = (2, 2), padding = 'valid', data_format = 'channels_last', strides = (2, 2), name = 'Pooling2D_1f8b9f47')(ReLU_5)
#Convolution2D Layer
Convolution2D_7 = Convolution2D(64, (3, 3), kernel_initializer = 'glorot_normal', bias_initializer = 'glorot_normal', padding = 'valid', strides = (1, 1), data_format = 'channels_last', use_bias = False, name = 'Convolution2D_e2139fa8')(Pooling2D_6)
#Batch Normalization Layer
Convolution2D_7 = BatchNormalization(axis=3,name='bn_Convolution2D_e2139fa8')(Convolution2D_7)
#Rectification Linear Unit (ReLU) Activation Layer
ReLU_8 = Activation('relu', name = 'ReLU_f11d50bd')(Convolution2D_7)
#Pooling2D Layer
Pooling2D_9 = MaxPooling2D(pool_size = (2, 2), padding = 'valid', data_format = 'channels_last', strides = (2, 2), name = 'Pooling2D_4d87411b')(ReLU_8)
#Flatten Layer
Flatten_10 = Flatten(name = 'Flatten_8ed4f9b7')(Pooling2D_9)
#Dense or Fully Connected (FC) Layer
Dense_11 = Dense(10, kernel_initializer = 'glorot_normal', bias_initializer = 'glorot_normal', use_bias = False, name = 'Dense_59d0b43b')(Flatten_10)
#Softmax Activation Layer
Softmax_12 = Activation('softmax', name = 'Softmax_4bcd8d04')(Dense_11)
#Accuracy Metric
defined_metrics = ['accuracy']
#SigmoidCrossEntropy Loss
defined_loss = 'categorical_crossentropy'
# Define a keras model
model_inputs = [ImageData_a7d74d30]
model_outputs = [Softmax_12]
model = Model(inputs=model_inputs, outputs=model_outputs)
# Set the required hyperparameters
num_epochs = 20
# Defining the optimizer function
adam_learning_rate = 0.1
adam_decay = 0.1
adam_beta_1 = 0.9
adam_beta_2 = 0.999
optimizer_fn = Adam(lr=adam_learning_rate, beta_1=adam_beta_1, beta_2=adam_beta_2, decay=adam_decay)
# performing final checks
if not defined_metrics:
defined_metrics=None
if not defined_loss:
defined_loss = 'categorical_crossentropy'
if "ImageData" == "TextData" and "" == "Lang_Model":
# adding a final Dense layer which has (vocab_length+1) units
layers = [l for l in model.layers]
for i in range(len(layers)):
if isinstance(layers[i], keras.layers.core.Dense) and isinstance(layers[i+1], keras.layers.core.Activation):
d = Dense(vocab_length+1, name = 'Dense_for_LM_' + str(i+1))(layers[i].output)
layers[i+1].inbound_nodes = [] # assumption: there are no merges here
d = layers[i+1](d)
model = Model(inputs=layers[0].input, outputs=layers[len(layers)-1].output)
# Compile and train the model
model.compile(loss=defined_loss, optimizer=optimizer_fn, metrics=defined_metrics)
if len(model_outputs) > 1:
train_label = [train_label] * len(model_outputs)
if len(val_data) > 0: val_label = [val_label] * len(model_outputs)
if len(test_data) > 0: test_label = [test_label] * len(model_outputs)
# validate the model
if (len(val_data) > 0):
model.fit(train_data, train_label, batch_size=train_batch_size, epochs=num_epochs, verbose=1, validation_data=(val_data, val_label), shuffle=True)
else:
model.fit(train_data, train_label, batch_size=train_batch_size, epochs=num_epochs, verbose=1, shuffle=True)
# test the model
if (len(test_data) > 0):
test_scores = model.evaluate(test_data, test_label, verbose=1)
print(test_scores)
# saving the model
print('Saving the model...')
if 'model_result_path' not in locals() and 'model_result_path' not in globals():
model_result_path = "./keras_model.hdf5"
model.save(model_result_path)
print("Model saved in file: %s" % model_result_path)
| UTF-8 | Python | false | false | 8,722 | py | 25 | Deep_learning_demo-keras.py | 4 | 0.66166 | 0.624169 | 0 | 180 | 47.45 | 260 |
naamara/blink | 6,021,544,157,929 | 5705eb593a25ee07504b6f6a5f21447497b7b556 | 05c08e8a1440122d0b798e28b5c822eed31fdac0 | /seo/forms.py | ccd19ac6a8992404e5270701a3859796e32144b1 | [
"MIT"
]
| permissive | https://github.com/naamara/blink | 01add499370658394f27f029812762580d5f593c | 326c035b2f0ef0feae4cd7aa2d4e73fa4a40171a | refs/heads/master | 2022-12-14T00:12:00.877583 | 2019-06-21T13:29:08 | 2019-06-21T13:29:08 | 93,284,655 | 0 | 0 | null | false | 2022-11-22T03:15:06 | 2017-06-04T02:11:05 | 2019-06-21T14:16:39 | 2022-11-22T03:15:03 | 91,744 | 0 | 0 | 12 | Python | false | false | '''seo forms'''
from django import forms
from seo.models import Metadata
class AddSeoForm(forms.ModelForm):
"""
Form for saving seo
"""
class Meta:
model = Metadata
fields = '__all__'
#fields = ['keywords', 'title', 'description', 'lastname', 'ext'] | UTF-8 | Python | false | false | 261 | py | 248 | forms.py | 101 | 0.662835 | 0.662835 | 0 | 13 | 19.153846 | 67 |
gklb/gklb | 19,490,561,624,197 | b8d4c3e5fab0c92e69b04fff298a84c4a0c812d5 | 2a878e3d5c9df683882ab5d500ee8dc539406c5a | /ML/proc_train/DNN_Softmax.py | 771c920bfc65beafde40cb42dd28f3e7051e2371 | []
| no_license | https://github.com/gklb/gklb | d41c308c138ee9091aa205a6d9607377b0e6e83f | e1c9d44ac075271522d771f58c568f724fde595d | refs/heads/master | 2023-02-11T13:34:12.111283 | 2023-01-30T04:32:38 | 2023-01-30T04:32:38 | 208,537,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''참고
https://tykimos.github.io/2017/01/27/Keras_Talk/ about keras , myth
https://rfriend.tistory.com/553 construction DNN model
출처: https://3months.tistory.com/424 [Deep Play]
'''
import numpy as np
import pickle
import tensorflow as tf
import random
from tqdm import tqdm
import os
from sklearn.preprocessing import StandardScaler
import torch
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import ModelCheckpoint
from tqdm.keras import TqdmCallback
scaler = StandardScaler()
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
def labeling(arr):
gain = arr[-1] - arr[0]
if gain>0:
return 1
else:
return 0
def flattenSeries(arr, hist):
flattedArray = []
for idx in range(hist, len(arr)):
falttedPiece = []
arrPiece = arr[idx-hist:idx]
flattedPiece = np.ravel(arrPiece)
flattedArray.append(flattedPiece)
return flattedArray
def get_variables(train_size,direct):
with open(direct, 'rb') as f:
arr = pickle.load(f)
arr = arr[:train_size]
return arr.values.tolist()
def preprocFeatures(arr):
gainArr = arr.iloc[:,0].copy()
scaled_arr = scaler.transform(arr)
return gainArr, scaled_arr
def step(a, arr, arr_idx, fwd_idx):
gain = arr[arr_idx+fwd_idx][0] - arr[arr_idx][0]
if a == 2: # Bull
r = gain
elif a == 1: # Neutral
r = 0
else: # Bear
r = -gain
return r
def DNN_Classify(train_data,
train_size,
#model_load,
#learning_period,
hist, # time length of input data
iterations
#update_period, # gradient will be updated for every 10 iterations
#save_direct # location of saving weights
):
variables = train_data.iloc[:train_size].copy()
labels = torch.as_tensor(variables.Label.iloc[hist:].copy().values)
labels = torch.nn.functional.one_hot(labels.long())
variables = variables.drop('Label', axis=1).copy()
scaler.fit(variables)
_, features = preprocFeatures(variables)
#gainArr = gainArr.values.tolist()[hist:]
features = flattenSeries(features,hist)
inputdim = len(features[-1])
#model_load = False
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(128, input_dim=inputdim, activation='relu'))
model.add(tf.keras.layers.Dense(52, activation='relu'))
model.add(tf.keras.layers.Dense(2, activation='softmax'))
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy')
early_stopping = EarlyStopping(monitor='loss', mode='min', verbose=0, patience=50)
mc = ModelCheckpoint(save_direct + '/test_historic_' + str(train_size) + '.h5', monitor='loss', mode='min',
save_best_only=True)
if model_load == False:
pass
else:
model.load_weights(save_direct+'/test_historic_'+str(train_size - learning_period)+'.h5')
model.fit(np.array(features), np.array(labels), epochs=iterations, verbose=0, callbacks=[TqdmCallback(verbose=0), early_stopping, mc])
model.save_weights(save_direct+'/test_historic_'+str(train_size)+'.h5')
if __name__ == '__main__':
basedir = 'C:/Users/admin/PycharmProjects/pythonProject_tf_2'
inputdata_direct = basedir + '/pickle_var/variables1.pkl'
hist = 63
learning_period = 21
fwd_idx = 5
iterations = 1024
update_period = 32
save_direct = basedir + '/weights/dnn/weights1'
with open(inputdata_direct, 'rb') as f:
arr = pickle.load(f)
arr['Label'] = arr['KospiDeT'].rolling(fwd_idx).apply(labeling).shift(-4)
arr = arr.dropna()
firsttime = True
for idx in range(756, len(arr), learning_period):
if firsttime == True:
model_load = False
firsttime = False
else:
model_load = True
DNN_Classify(train_data=arr, train_size=idx, hist=hist, iterations=iterations)
| UTF-8 | Python | false | false | 4,205 | py | 34 | DNN_Softmax.py | 23 | 0.613533 | 0.59757 | 0 | 128 | 30.789063 | 138 |
xindongzhuaizhuai/hound | 13,357,348,320,496 | a67f7fd55fc5502b16a8406ff257c2f31ea64c84 | 9c2cf6f55b5b8abdb92efb38d780aee35f30dbdb | /table/setup.py | 0d7a2ae28448eda720d99f5298e452c6f9b0ea82 | [
"MIT"
]
| permissive | https://github.com/xindongzhuaizhuai/hound | 760b731424319e23770849085591460606059990 | 2f9e4ee97fc31c3425a1a45b712923e948dc1871 | refs/heads/master | 2020-12-21T03:06:54.281460 | 2020-04-15T04:29:14 | 2020-04-15T04:29:14 | 72,496,229 | 96 | 36 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from platform import python_version_tuple
import os
import re
LICENSE = open("LICENSE").read()
# strip links from the descripton on the PyPI
if python_version_tuple()[0] >= '3':
LONG_DESCRIPTION = open("README.rst", "r", encoding="utf-8").read().replace("`_", "`")
else:
LONG_DESCRIPTION = open("README.rst", "r").read().replace("`_", "`")
# strip Build Status from the PyPI package
if python_version_tuple()[:2] >= ('2', '7'):
LONG_DESCRIPTION = re.sub("^Build status\n(.*\n){7}", "", LONG_DESCRIPTION, flags=re.M)
install_options = os.environ.get("TABULATE_INSTALL","").split(",")
libonly_flags = set(["lib-only", "libonly", "no-cli", "without-cli"])
if libonly_flags.intersection(install_options):
console_scripts = []
else:
console_scripts = ['tabulate = tabulate:_main']
setup(name='tabulate',
version='0.7.5',
description='Pretty-print tabular data',
long_description=LONG_DESCRIPTION,
author='Sergey Astanin',
author_email='s.astanin@gmail.com',
url='https://bitbucket.org/astanin/python-tabulate',
license=LICENSE,
classifiers= [ "Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries" ],
py_modules = ['tabulate'],
entry_points = {'console_scripts': console_scripts},
test_suite = 'nose.collector')
| UTF-8 | Python | false | false | 1,899 | py | 14 | setup.py | 12 | 0.599263 | 0.588204 | 0 | 55 | 33.527273 | 91 |
zandaoguang/English | 5,145,370,840,417 | ac4b54c7d6877e9732824e8176fd0aed7d519479 | b19055f6058490ba1da346f3531dc863a2d15d5e | /basicwords.py | 41b86ece45dbe5468fc0205041ca30aeb4834b01 | []
| no_license | https://github.com/zandaoguang/English | 90a1f51d17a1e70dd5394b55f49fc7c04eedcd8d | 7aaf40103fe7de126217c0b7f962fd4c9f425c6a | refs/heads/master | 2020-04-12T04:55:31.103965 | 2018-12-18T15:44:51 | 2018-12-18T15:44:51 | 162,310,518 | 2 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | #coding=utf-8
import simplify_word as sw
import re
bw = open('data/basic_words.txt')
basicwords = []
for eachLine in bw:
basicwords.append(sw.simplify_word(re.split("[^A-Za-z]", eachLine)[0].lower()))
#print re.split("[^A-Za-z]", eachLine)[0]
print(len(list(set(basicwords))))
basicwords = list(set(basicwords))
| UTF-8 | Python | false | false | 321 | py | 11 | basicwords.py | 10 | 0.685358 | 0.676012 | 0 | 11 | 28.181818 | 83 |
kotbaton/project_euler | 2,894,807,959,329 | 0812c7a782acfe883cbeb4850f6d9d2f81d58a57 | 3195de19a4f0ccad78dd08bfafb93423b08b98e2 | /p1-50/p15/p15.const.py | 949b5eefce50aaf31363b819302407c3dad8a3df | []
| no_license | https://github.com/kotbaton/project_euler | 6e0f62033191a866576d831e0f7864a04424d966 | 9fd06607d7c367eaf900a9eae5fdc1a8ce734ca9 | refs/heads/master | 2020-06-22T03:03:04.679939 | 2019-12-30T11:37:05 | 2019-12-30T11:37:05 | 197,616,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python3
import sys
import math as m
n = 3
if len(sys.argv):
n = int(sys.argv[1])
res = m.factorial(2*n) // (m.factorial(n) * m.factorial(n))
print(res)
| UTF-8 | Python | false | false | 170 | py | 51 | p15.const.py | 47 | 0.623529 | 0.6 | 0 | 11 | 14.454545 | 59 |
57066698/npNet | 5,214,090,334,541 | cc9923f679bf686d9d3cbf370597ac50d890b94a | b52fc3c5268ce63be3ef880cdfa31a2a2ac875fb | /examples/mnist_autoencoder.py | c13492ec5495901009601113ca943995c7fe8983 | []
| no_license | https://github.com/57066698/npNet | 53ff6d97315901dd984395c4a67a80e196612e2c | edb087a86f9a559fade550692e4003b25d823294 | refs/heads/master | 2021-05-29T00:24:44.746318 | 2021-04-30T09:06:26 | 2021-04-30T09:06:26 | 254,293,830 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
from simpleNet import layers, Moduel, optims, losses
from examples.datasets.mnist_loader import load_train, load_test
import matplotlib.pyplot as plt
from PIL import Image
# net
class Encoder(Moduel):
def __init__(self):
super().__init__()
self.conv1 = layers.Conv2D(1, 16, 3, stride=2, padding="same")
self.relu1 = layers.Relu()
self.conv2 = layers.Conv2D(16, 32, 3, stride=2, padding="same")
self.relu2 = layers.Relu()
self.flatten = layers.Flatten()
self.dense = layers.Dense(32*7*7, 16)
def forwards(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.flatten(x)
x = self.dense(x)
return x
class Decoder(Moduel):
def __init__(self):
super().__init__()
self.dense = layers.Dense(16, 32 * 7 * 7)
self.reshape = layers.Reshape((-1, 32, 7, 7))
self.deconv1 = layers.Conv2DTranspose(32, 32, 3, stride=2)
self.relu1 = layers.Relu()
self.deconv2 = layers.Conv2DTranspose(32, 16, 3, stride=2)
self.relu2 = layers.Relu()
self.deconv3 = layers.Conv2DTranspose(16, 1, 3, stride=1)
self.sigmoid = layers.Sigmoid()
def forwards(self, x):
x = self.dense(x)
x = self.reshape(x)
x = self.deconv1(x)
x = self.relu1(x)
x = self.deconv2(x)
x = self.relu2(x)
x = self.deconv3(x)
x = self.sigmoid(x)
return x
class AutoEncoder(Moduel):
def __init__(self):
super().__init__()
self.encoder = Encoder()
self.decoder = Decoder()
def forwards(self, x):
latent = self.encoder(x)
y = self.decoder(latent)
return y
# dataset and gen
X_train, Y_train = load_train()
X_test, Y_test = load_test()
print(X_train.shape, Y_train.shape)
# 数据gen
class Gen:
def __init__(self, X, batch_size:int = 32):
self.batch_size = batch_size
X = np.transpose(X, (0, 3, 1, 2))
X = X / 255.0
self.X = X
self.inds = np.arange(X.shape[0])
self.end_epoch()
def next_batch(self, ind:int):
left = ind * self.batch_size
right = (ind+1) * self.batch_size
right = min(right, self.inds.shape[0])
batch_inds = self.inds[left:right]
X = self.X[batch_inds]
noise = np.random.normal(loc=0.5, scale=0.5, size=X.shape)
noise_X = noise + X
noise_X = np.clip(noise_X, 0, 1.)
return noise_X, X
def __len__(self):
import math
return math.ceil(self.inds.shape[0] / self.batch_size)
def end_epoch(self):
np.random.shuffle(self.inds)
def totol_num(self):
return self.inds.shape[0]
# printer
def show_img(imgs, epochs, rows=10, cols=10, image_size=28):
imgs = imgs.reshape((rows*3, cols, image_size, image_size))
imgs = np.vstack(np.split(imgs, rows, axis=1))
imgs = imgs.reshape((rows * 3, -1, image_size, image_size))
imgs = np.vstack([np.hstack(i) for i in imgs])
imgs = (imgs * 255).astype(np.uint8)
plt.figure()
plt.axis('off')
plt.title('Original images: top rows, '
'Corrupted Input: middle rows, '
'Denoised Input: third rows')
plt.imshow(imgs, interpolation='none', cmap='gray')
Image.fromarray(imgs).save('corrupted_and_denoised_%d.png' %epochs)
# train
autoencoder = AutoEncoder()
autoencoder.summary()
optim = optims.Adam(autoencoder)
loss = losses.MeanSquaredError()
gen_train = Gen(X_train, batch_size=32)
gen_test = Gen(X_test, batch_size=100)
autoencoder.load_weights("111.npz")
for i in range(30):
print("-------------- epochs %d --------------------" % i)
for j in range(len(gen_train)):
X, Y = gen_train.next_batch(j)
pred_Y = autoencoder(X)
l = loss(pred_Y, Y)
da = loss.backwards()
autoencoder.backwards(da)
optim.step()
if j % 10 == 0:
print("train batch %d losses:" % j, l)
gen_train.end_epoch()
autoencoder.save_weights("111.npz")
# show test imgs
rows, cols = 10, 10
noise_img, img = gen_test.next_batch(0)
netout = autoencoder(img, run=True)
imgs = np.concatenate([img[:rows*cols], noise_img[:rows*cols], netout[:rows*cols]])
show_img(imgs, i)
| UTF-8 | Python | false | false | 4,367 | py | 68 | mnist_autoencoder.py | 67 | 0.575521 | 0.547101 | 0 | 152 | 27.703947 | 87 |
p208p2002/torch-swiss | 4,922,032,532,490 | bbb697968b5109187a19d47dd28b2540cac2bdf3 | f3eb1d9312bd4fae752d819b566e4e02de0dc2dd | /torch_swiss/logger.py | 5733218511321ed2530b5d5471eb69e17afa2230 | []
| no_license | https://github.com/p208p2002/torch-swiss | 6bcd84f56e8399640c4308b6aa3feca3cbac45a8 | 2e222bc6b1d5c70925db19e53f768dc9211fce62 | refs/heads/main | 2023-02-10T15:48:55.124647 | 2020-12-31T02:35:11 | 2020-12-31T02:35:11 | 307,584,565 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import torch
def running_logger(log_dict,title=None,end='\r'):
"""
Usage Example:
`running_logger({"batch":i+1, "loss":"%3.5f"%test_log_recorder.loss, "acc":"%3.5f"%test_log_recorder.acc},'test')`
"""
if title is not None:
print(title,end=' ')
for key in log_dict.keys():
print("%s:"%key,log_dict[key],end=' ')
print(end=end)
class LogRecorder():
def __init__(self):
self.i = 0
self.running_acc = 0.0
self.running_loss = 0.0
self._y_trues = []
self._y_predicts = []
def reset(self):
self.__init__()
def add_log(self,batch_acc=0.0,batch_loss=0.0):
self.running_acc += (batch_acc - self.running_acc)/(self.i+1)
self.running_loss += (batch_loss - self.running_loss)/(self.i+1)
self.i += 1
def save_predicts_and_trues(self,logits,label):
label = label.to('cpu')
y_predicts = torch.argmax(logits,dim=1).to('cpu')
assert y_predicts.size(0) == label.size(0)
for y_p,y_t in zip(y_predicts,label):
self._y_predicts.append(y_p.item())
self._y_trues.append(y_t.item())
@property
def acc(self):
return self.running_acc
@property
def loss(self):
return self.running_loss
| UTF-8 | Python | false | false | 1,302 | py | 15 | logger.py | 8 | 0.552227 | 0.536866 | 0 | 45 | 27.933333 | 122 |
zonyzhao/pyvi | 10,849,087,420,060 | 02a5e5abd3db75efbd283fbec14a83568bfafe47 | ac1f104737ad278c98089fc69843a5fed14cb48a | /tests/utilities/test_mathbox.py | 35d524d6c13bd890917fd377ddde4f943027d038 | [
"BSD-3-Clause"
]
| permissive | https://github.com/zonyzhao/pyvi | 38c327871e085d03ccf51fc2b5b108c451d24a81 | 6b38bfaed75f84f6bf2ef43b11535510ee1c0490 | refs/heads/master | 2023-03-19T02:28:22.478749 | 2018-06-28T13:53:47 | 2018-06-28T13:53:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Test script for pyvi/utilities/mathbox.py
Notes
-----
Developed for Python 3.6
@author: Damien Bouvier (Damien.Bouvier@ircam.fr)
"""
#==============================================================================
# Importations
#==============================================================================
import unittest
import numpy as np
import pyvi.utilities.mathbox as mathbox
#==============================================================================
# Test Class
#==============================================================================
class RmsTestCase(unittest.TestCase):
def test_computation(self):
for i in range(3):
with self.subTest(i=i):
array = i * np.ones((10, 1))
self.assertEqual(mathbox.rms(array), i)
def test_shape(self):
array = (2 * np.ones((24, 1))).reshape(2, 3, 4)
shape = {0: (3, 4), 1: (2, 4), 2: (2, 3)}
for i in [0, 1, 2]:
with self.subTest(i=i):
self.assertEqual(mathbox.rms(array, axis=i).shape, shape[i],
'wrong output shape')
class DbTestCase(unittest.TestCase):
def test_computation(self):
for i in range(-5, 6):
with self.subTest(i=i):
self.assertEqual(mathbox.db(10**i), 20*i)
def test_shape(self):
array = np.array([1, 2, 3])
with self.subTest(i=0):
self.assertEqual(mathbox.db(array, array).shape, array.shape,
'wrong output shape')
with self.subTest(i=1):
self.assertEqual(mathbox.db(array, 1).shape, array.shape,
'wrong output shape')
def test_ref(self):
for i in range(-5, 6):
with self.subTest(i=i):
self.assertEqual(mathbox.db(1., ref=10**i), -20*i)
class SafedbTestCase(unittest.TestCase):
def test_computation(self):
for i in range(-5, 6):
with self.subTest(i=i):
self.assertEqual(mathbox.safe_db(10**i, 1.), 20*i)
def test_den_null(self):
self.assertEqual(mathbox.safe_db(1, 0), np.Inf)
def test_num_null(self):
self.assertEqual(mathbox.safe_db(0, 1), - np.Inf)
def test_den_and_num_null(self):
self.assertEqual(mathbox.safe_db(0, 0), - np.Inf)
def test_output_type(self):
array = np.ones((2))
tests_map = {'int_int': (1, 1, float),
'float_float': (1., 1., float),
'float_int': (1., 1, float),
'int_float': (1, 1., float),
'list_list': ([1, 1], [1, 1], np.ndarray),
'list_array': ([1, 1], array, np.ndarray),
'array_list': (array, [1, 1], np.ndarray),
'array_array': (array, array, np.ndarray)}
for name, (num, den, out_type) in tests_map.items():
with self.subTest(name=name):
self.assertIsInstance(mathbox.safe_db(num, den), out_type)
def test_wrong_shape_error(self):
tests_map = {'list3_list2': ([1, 1, 1], [1, 1]),
'num3_num2': (np.ones((3, 1)), np.ones((2, 1)))}
for name, (num, den) in tests_map.items():
with self.subTest(name=name):
self.assertRaises(ValueError, mathbox.safe_db, num, den)
class BinomialTestCase(unittest.TestCase):
def test_n_choose_0(self):
for n in range(1, 10):
with self.subTest(i=n):
self.assertEqual(mathbox.binomial(n, 0), 1)
def test_n_choose_1(self):
for n in range(1, 10):
with self.subTest(i=n):
self.assertEqual(mathbox.binomial(n, 1), n)
def test_n_choose_n(self):
for n in range(1, 10):
with self.subTest(i=n):
self.assertEqual(mathbox.binomial(n, n), 1)
def test_symmetry(self):
for n in range(1, 10):
for k in range(1, n):
with self.subTest(name='({}, {})'.format(n, k)):
self.assertEqual(mathbox.binomial(n, k),
mathbox.binomial(n, n-k))
def test_recursivity(self):
for n in range(2, 10):
for k in range(1, n):
with self.subTest(name='({}, {})'.format(n, k)):
self.assertEqual(mathbox.binomial(n, k),
mathbox.binomial(n-1, k-1) +
mathbox.binomial(n-1, k))
class ArraySymmetrizationTestCase(unittest.TestCase):
def test_symmetrization(self):
array = np.array([[1, 2, 4],
[0, 3, 6],
[0, 0, 8]])
array_sym = np.array([[1, 1, 2],
[1, 3, 3],
[2, 3, 8]])
array_sym_est = mathbox.array_symmetrization(array)
self.assertTrue(np.all(array_sym == array_sym_est))
#==============================================================================
# Main script
#==============================================================================
if __name__ == '__main__':
"""
Main script for testing.
"""
unittest.main()
| UTF-8 | Python | false | false | 5,269 | py | 27 | test_mathbox.py | 26 | 0.457962 | 0.432909 | 0 | 156 | 32.775641 | 79 |
aporlowski/cloudmesh-mpi | 18,030,272,720,606 | d94e1a1375fdb7e4c5683806c8af5c576e267b98 | 50f3550a3fefd2d5ba8237bad4e0bc66981ae967 | /examples/spawn/manager.py | cfa2fc13b37100d176c4287ceb9023d19025c48a | [
"Apache-2.0",
"Python-2.0"
]
| permissive | https://github.com/aporlowski/cloudmesh-mpi | d20fcaee78179f1db535c4a76b589c4832441527 | afd46b8b04b3744b56d53af6861f0832cd69fd8d | refs/heads/main | 2023-07-21T14:05:50.950055 | 2021-08-29T13:27:35 | 2021-08-29T13:27:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
from mpi4py import MPI
import numpy
import sys
import time
print("Hello")
comm = MPI.COMM_SELF.Spawn(sys.executable,
args=['worker.py'],
maxprocs=5)
rank = comm.Get_rank()
print(f"b and rank: {rank}")
N = numpy.array(100, 'i')
comm.Bcast([N, MPI.INT], root=MPI.ROOT)
#print(f"ROOT: {MPI.ROOT}")
print('c')
PI = numpy.array(0.0, 'd')
print('d')
comm.Reduce(None, [PI, MPI.DOUBLE],
op=MPI.SUM, root=MPI.ROOT)
print(PI)
comm.Disconnect()
| UTF-8 | Python | false | false | 526 | py | 99 | manager.py | 29 | 0.593156 | 0.579848 | 0 | 24 | 20.916667 | 46 |
Asunqingwen/Django_rapid_program | 14,061,722,936,697 | be43f45a49d6d5a1f6d39d11c58fffec9640cb25 | 15786724459b2d75e1cf12f68a71f1c532415e9e | /recruitment/settings/local.py | 7c0c2039535a838cad8df24234997d945c91c654 | []
| no_license | https://github.com/Asunqingwen/Django_rapid_program | b31b3ed6723335c7bee8bc6431aac76734986e1b | 6cdfa64a728173d8374f9915fcdc9cb2e9c008f3 | refs/heads/master | 2023-02-18T02:20:27.916814 | 2021-01-19T06:50:22 | 2021-01-19T06:50:22 | 327,861,395 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from .base import *
DEBUG = True
ALLOWED_HOSTS = []
## 务必修改以下值,确保运行时系统安全:
SECRET_KEY = "w$46bks+b3-7f(13#i%v@jwejrnxc$^^#@#@^t@fofizy1^mo9r8(-939243423300"
# # AliCloud access key ID
# OSS_ACCESS_KEY_ID = os.environ.get('OSS_ACCESS_KEY_ID','')
# # AliCloud access key secret
# OSS_ACCESS_KEY_SECRET = os.environ.get('OSS_ACCESS_KEY_SECRET','')
# # The name of the bucket to store files in
# OSS_BUCKET_NAME = 'djangorecruit'
#
# # The URL of AliCloud OSS endpoint
# # Refer https://www.alibabacloud.com/help/zh/doc-detail/31837.htm for OSS Region & Endpoint
# OSS_ENDPOINT = 'oss-cn-beijing.aliyuncs.com'
DINGTALK_WEB_HOOK = 'https://oapi.dingtalk.com/robot/send?access_token=f51af59c165a1f1ab08f3d9e5f04098c424a346e25f50efd57cbfe97b10b2dcd'
## 如果仅使用数据库中的账号,以下 LDAP 配置可忽略
## 替换这里的配置为正确的域服务器配置,同时可能需要修改 base.py 中的 LDAP 服务器相关配置:
LDAP_AUTH_URL = "ldap://47.103.86.8:389"
LDAP_AUTH_CONNECTION_USERNAME = "admin"
LDAP_AUTH_CONNECTION_PASSWORD = "admin"
INSTALLED_APPS += (
# 'debug_toolbar' # other apps for production site
)
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
'TIMEOUT': 300,
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# "PASSWORD":"mysecret",
"SOCKET_CONNECT_TIMEOUT": 5, # 连接
"SOCKET_TIMEOUT": 5, # 读写
}
}
}
# Celery application definition
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/1'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERYD_MAX_TASKS_PER_CHILD = 10
CELERYD_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_work.log")
CELERYBEAT_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_beat.log")
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
# sentry配置
sentry_sdk.init(
dsn="http://1a12d66d68df409997c149f3e8554d49@47.103.86.8:9000/7",
integrations=[DjangoIntegration()],
# 采样率,生产环境访问量过大时,建议调小(不用没一个url请求都记录性能)
traces_sample_rate=1.0,
# If you wish to associate users to errors (assuming you are using
# django.contrib.auth) you may enable sending PII data.
send_default_pii=True
)
| UTF-8 | Python | false | false | 2,535 | py | 14 | local.py | 10 | 0.692607 | 0.632512 | 0 | 72 | 31.125 | 136 |
DaHuO/Supergraph | 13,786,845,029,543 | af2dc8b2f2f5bff627180ed0cf967b691ae90000 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/CJ_16_2/16_2_1_Suski_phone.py | d778f1a3c19e83c90b6e7c943862bded7f6d1fe0 | []
| no_license | https://github.com/DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | false | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | 2019-02-21T15:42:08 | 2021-03-19T21:55:45 | 38,414 | 0 | 0 | 2 | Python | false | false | import sys
def remove0(numbers):
numbers.remove('Z');
numbers.remove('E');
numbers.remove('R');
numbers.remove('O');
def remove1(numbers):
numbers.remove('O');
numbers.remove('N');
numbers.remove('E');
def remove2(numbers):
numbers.remove('T');
numbers.remove('W');
numbers.remove('O');
def remove3(numbers):
numbers.remove('T');
numbers.remove('H');
numbers.remove('R');
numbers.remove('E');
numbers.remove('E');
def remove4(numbers):
numbers.remove('F');
numbers.remove('O');
numbers.remove('U');
numbers.remove('R');
def remove5(numbers):
numbers.remove('F');
numbers.remove('I');
numbers.remove('V');
numbers.remove('E');
def remove6(numbers):
numbers.remove('S');
numbers.remove('I');
numbers.remove('X');
def remove7(numbers):
numbers.remove('S');
numbers.remove('E');
numbers.remove('V');
numbers.remove('E');
numbers.remove('N');
def remove8(numbers):
numbers.remove('E');
numbers.remove('I');
numbers.remove('G');
numbers.remove('H');
numbers.remove('T');
def remove9(numbers):
numbers.remove('N');
numbers.remove('I');
numbers.remove('N');
numbers.remove('E');
def process(fin):
nums = list(fin.readline().strip())
result = []
while(nums):
if 'Z' in nums:
result.append(0)
remove0(nums)
elif 'W' in nums:
result.append(2)
remove2(nums)
elif 'X' in nums:
result.append(6)
remove6(nums)
elif 'G' in nums:
result.append(8)
remove8(nums)
elif 'H' in nums:
result.append(3)
remove3(nums)
elif 'S' in nums:
result.append(7)
remove7(nums)
elif 'V' in nums:
result.append(5)
remove5(nums)
elif 'U' in nums:
result.append(4)
remove4(nums)
elif 'I' in nums:
result.append(9)
remove9(nums)
elif 'O' in nums:
result.append(1)
remove1(nums)
result.sort()
return result
def main():
input_name = sys.argv[1]
fin = open(input_name, 'r')
num_cases = int (fin.readline())
for i in range(num_cases):
result = process(fin)
print("Case #{}: {}".format((i+1), ''.join(map(str, result))))
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 2,195 | py | 30,073 | 16_2_1_Suski_phone.py | 16,513 | 0.594989 | 0.58041 | 0 | 111 | 17.792793 | 70 |
Kelv1nYu/UMich_Py4E | 1,176,821,070,695 | c36ea26783211fe2553d32c1d8f71d25b5b69fb8 | 11f8e96912a5e04731163c373a207e299b26b5e0 | /Using Python to Access Web Data/ex11/ex_11_01_using_sum_function.py | 2a44f5c0127f9f7e3477771c580be551cc081c0c | []
| no_license | https://github.com/Kelv1nYu/UMich_Py4E | a7a32a42ceecf1b98e0d35a16313768654089bad | 5430002c21c5780bbe68287e33bb566cd1f49c2f | refs/heads/master | 2021-10-19T13:13:44.143335 | 2019-02-21T08:32:52 | 2019-02-21T08:32:52 | 113,317,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # using the fucntion sum() to get the sum of the list
import re
filename = input("File name:")
if len(filename) < 1: filename = "regex_sum_55433.txt"
nums = list()
counts = dict()
with open(filename) as f:
for line in f:
line = line.rstrip()
tmpnums = re.findall('[0-9]+', line)
for tmpnum in tmpnums:
nums.append(tmpnum)
# change the list of strings into list of integer, because the sum function cannot sum up the strings
for i in range(len(nums)):
nums[i] = int(nums[i])
tot = sum(nums)
print(tot)
| UTF-8 | Python | false | false | 520 | py | 17 | ex_11_01_using_sum_function.py | 16 | 0.678846 | 0.663462 | 0 | 25 | 19.8 | 101 |
FluteXu/ms-project | 4,724,464,045,436 | f09603d0e9e8c73f4055a98f2a071f3bab910bee | bf7756f40cd5487bdaf9fde3baacaedb12d17972 | /npz_to_nrrd.py | 41cdb2a2912a3d0dc7cc73679ae45c850a01622e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | https://github.com/FluteXu/ms-project | 976e525ee47069fa3f74b7d4ebf82baf032036eb | 108b1346a32dd5aea2078fc20852029342e2365f | refs/heads/main | 2023-02-22T18:10:02.940998 | 2021-01-21T01:26:01 | 2021-01-21T01:26:01 | 331,479,592 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
import os.path as osp
import numpy as np
import nrrd
import glob
"""
organ mask is flipped, npz image is zyx, mask is yxz
image npz zyx -> xyz
organ mask 1. flip 2. yxz -> xyz (trans102)
"""
if __name__ == '__main__':
pid = '0818353'
root_dir = '/data/ms_data/npz/test'
pid_dir = osp.join(root_dir, pid)
# retrieve the first ss
ss_dir = glob.glob(pid_dir + '/*/*')[0]
file_path = osp.join(ss_dir, 'image.npz')
save_path = osp.join(ss_dir, 'image.nrrd')
# for itk-snap [x, y, z]
# head is slice 0, at the bottom
img = np.load(file_path) # [z, y, x]
print('npz shape: ', img['data'].shape)
print('flip flag in npz: ', img['flip'])
# slice 0 is head
# flip flag in npz is false
img_data = np.transpose(img['data'], (2, 1, 0))
nrrd.write(save_path, img_data)
| UTF-8 | Python | false | false | 840 | py | 25 | npz_to_nrrd.py | 25 | 0.589286 | 0.567857 | 0 | 36 | 22.333333 | 52 |
ehabarman/Hackerrank-Solution-python_proficiency | 5,643,587,033,527 | df465d540b58b04ed66ff31ce0485a4166832f04 | 09fbbb55683838b962b9403f71075fa6665caa00 | /Solutions/Math/Mod Divmod.py | a999318970eeb9de5f58ebf43d985e6f1fe03cd0 | []
| no_license | https://github.com/ehabarman/Hackerrank-Solution-python_proficiency | 8362fad8c943beb084cc99a12e3c68dd78121f2b | 2d2816b597cffdc02033baefda80c0761314569d | refs/heads/master | 2020-04-21T23:56:43.563145 | 2019-02-10T09:39:16 | 2019-02-10T09:39:16 | 169,962,294 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | ''' Date 29-8-2018 '''
if __name__ == '__main__':
a,b= int(raw_input()),int(raw_input())
result = divmod(a,b)
print '{0}\n{1}\n{2}'.format(result[0],result[1],result) | UTF-8 | Python | false | false | 179 | py | 82 | Mod Divmod.py | 82 | 0.530726 | 0.463687 | 0 | 6 | 29 | 60 |
assissh/Landing-Page | 120,259,113,917 | cb053b32687d3badc023bfc52d5e7e1658612a25 | 387721add1f00b836f8b62b348ebcd02e4cb40c0 | /help_Qna/migrations/0001_initial.py | 78faf91b45a72609cb4b0dc658f266ec2bf31b74 | []
| no_license | https://github.com/assissh/Landing-Page | 9d3f35b141ab4980782d90288c16cca9ca50569a | a96119324b2fcf9d5e4eda5dd9b2681368b9c113 | refs/heads/master | 2020-03-08T10:16:15.518352 | 2018-04-04T13:51:36 | 2018-04-04T13:51:36 | 128,068,636 | 0 | 0 | null | true | 2018-04-04T13:48:11 | 2018-04-04T13:48:10 | 2018-04-04T13:43:30 | 2018-04-04T13:43:28 | 2,466 | 0 | 0 | 0 | null | false | null | # Generated by Django 2.0.3 on 2018-04-04 07:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Help_Qna_Comment', models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name='HelpQna',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Help_Qna_Answer', models.CharField(max_length=100)),
('Help_Qna_Article_Id', models.IntegerField()),
('Help_Qna_Question', models.CharField(max_length=100)),
('Help_Qna_Modified_Date', models.DateField(auto_now_add=True)),
('Help_Qna_Created_Date', models.DateField(auto_now_add=True)),
],
),
]
| UTF-8 | Python | false | false | 1,090 | py | 51 | 0001_initial.py | 47 | 0.557798 | 0.53578 | 0 | 32 | 33.0625 | 114 |
sehooh5/TIL | 16,303,695,862,662 | 8015ecc49bf0a69197af62c89b5f643d357e4f7c | 9f298cc352ed60341ccf9f43b38e59a97b934635 | /Project/PythonProject/ihub/statuses/admin.py | fd32c7955ba476808a611c27d5d7a4a4e865dd6d | []
| no_license | https://github.com/sehooh5/TIL | 90d4ed5f6f6ac962f266425a5f30dd1d2e4234d3 | b102ef61faeba5cfef4ffb26756e7f241dbe28f5 | refs/heads/master | 2021-09-16T01:56:47.832448 | 2021-08-17T03:34:52 | 2021-08-17T03:34:52 | 226,476,859 | 0 | 1 | null | false | 2021-08-17T03:49:53 | 2019-12-07T08:03:38 | 2021-08-17T03:34:58 | 2021-08-17T03:49:53 | 30,330 | 0 | 0 | 4 | CSS | false | false | from django.contrib import admin
from .models import Status
class StatusAdmin(admin.ModelAdmin):
list_display = ['api', 'updated_time', 'status']
list_editable = ['status']
# Register your models here.
admin.site.register(Status, StatusAdmin)
| UTF-8 | Python | false | false | 270 | py | 603 | admin.py | 256 | 0.688889 | 0.688889 | 0 | 13 | 18.769231 | 52 |
ahmermalik/classWork | 9,483,287,794,355 | f22586909a814a60fc0e72a9993606fe1ea172e4 | 0f27b8257e81f7cfb3a9a91bfe2e292f1f7e9459 | /Week1/exercises.py | 0e6e30a9d7f9cdf25e4400a931da0be349611de9 | []
| no_license | https://github.com/ahmermalik/classWork | 56fa3edf45ba9341876a859e33887ca799837278 | febd6790ca98f08c15ab90e970a67bf2ffc51e6e | refs/heads/master | 2021-09-10T05:26:12.367053 | 2018-03-21T04:33:09 | 2018-03-21T04:33:09 | 103,564,622 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# def exercise2():
# name = input(('What is your name?').upper())
# print(("Hello, " + name + "!").upper())
# print(("Your name has ").upper(), len(name), (" letters in it! awesome!").upper() )
# exercise2()
# def exercise3():
# print('Please fill in the blanks below:')
#
# print("____(name)____'s favorite subject in school is ____(subject)____.")
#
# name = input("What is name?")
# subject = input("What is subject?")
#
# print(name + "'s favorite subject in school is " +subject+".")
#
#
# exercise3()
# def exercise4():
#
# day = int(input("Day (0-6)? "))
#
#
# def Sun():
# print("Sunday")
# def Mon():
# print("Monday")
# def Tue():
# print("Tuesday")
# def Wed():
# print("Wednesday")
# def Thu():
# print("Thursday")
# def Fri():
# print("Friday")
# def Sat():
# print("Saturday")
#
# weekday = {
# 0 : Sun,
# 1 : Mon,
# 2 : Tue,
# 3 : Wed,
# 4 : Thu,
# 5 : Fri,
# 6 : Sat
# }
# print (weekday[day]())
# exercise4()
# def exercise5():
#
# day = int(input("Day (0-6)? "))
#
# def Mon():
# print("Work")
# def Tue():
# print("Work")
# def Wed():
# print("Work")
# def Thu():
# print("Work")
# def Fri():
# print("Sleep in")
# def Sat():
# print("Work")
# def Sun():
# print("Sleep in")
#
# weekday = {
# 0: Sun,
# 1: Mon,
# 2: Tue,
# 3: Wed,
# 4: Thu,
# 5: Fri,
# 6: Sat
# }
# print(weekday[day]())
# exercise5()
#
# def exercise6():
# cel = int(input("Please enter the temperature in Celsius: "))
# def celToFah(user):
# Fah= user * (1.8) +32
# if user < -273:
# print("This temperature is unattainable on this planet.")
# else:
# print(Fah)
#
# celToFah(cel)
# # exercise6()
#
#
# def exercise7():
#
#
#
# bill = float(input("What was the total bill?"))
# service = input("How was the service?")
#
# tipAmount = {
# "good": .2,
# "fair": .15,
# "bad": .1
# }
#
# if service == "good":
# tip = tipAmount[service] * bill
#
# if service == "fair":
# tip = tipAmount[service] * bill
#
# if service == "bad":
# tip = tipAmount[service] * bill
#
# print("\nYour bill was ${bill:.2f}, and your service was {service}.\n\nYou should tip ${tip:.2f}\n".format(bill=bill,service=service,tip=tip))
#
#
# exercise7()
#
# def exercise8():
# # (("Hello, " + name + "!").upper())
#
#
# bill = float(input("What was the total bill?"))
# service = input("How was the service?").lower()
# split = float(input("How many people will this bill be split between?"))
#
#
# tipAmount = {
# "good": .2,
# "fair": .15,
# "bad": .1
# }
#
# if service == "good":
# tip = tipAmount[service] * bill
#
# if service == "fair":
# tip = tipAmount[service] * bill
#
# if service == "bad":
# tip = tipAmount[service] * bill
#
# print("\nYour bill was ${bill:.2f}, and your service was {service}.\n\nYou should tip ${tip:.2f}\n".format(bill=bill,service=service,tip=tip))
#
# newTotal = bill + tip
# splitTotal = newTotal/split
# #print("Your total bill is: $"+ float(newTotal))
# print ("\nYour total of ${newTotal:.2f} split between {split:.0f} people will be ${splitTotal:.02f} per person. \n".format(newTotal=newTotal,service=service,splitTotal= splitTotal, split=split))
# exercise8()
#
#
# def exercise9():
# number = 0
#
# while number < 10:
# number += 1
#
# print(number)
#
#
#
#
# exercise9()
#
# def exercise10():
#
# coins = 0
# more_coins = True
#
# while more_coins:
# print("You have {0} coins.".format(coins))
# answer = input("Do you want another? Yes or no: ").lower()
# if answer == "yes":
# coins += 1
# elif answer == "no":
# print("Okay, bye!")
# want_coins = False
# else:
# print("That answer makes no sense. Try again.")
#
#
# exercise10()
| UTF-8 | Python | false | false | 4,246 | py | 83 | exercises.py | 60 | 0.489166 | 0.473151 | 0 | 188 | 21.579787 | 200 |
fbaroni/algorithmic-toolbox | 11,544,872,125,739 | 17f3cf3665960c021d2f9536836527157de86c60 | 0d1d78a1c268dba99ea5a7ff1b06825b9b16d93b | /week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 0efdaae28ff62c2d599ce72b606663ba8249ca6c | [
"Apache-2.0"
]
| permissive | https://github.com/fbaroni/algorithmic-toolbox | c6ecd54747c10307fd3c3fb7da266c9b5cc7973c | 1f433ed0d16c702105352ee3ffb4645e0bdc6d3f | refs/heads/main | 2023-07-19T07:31:09.924735 | 2021-09-01T19:10:48 | 2021-09-01T19:10:48 | 394,714,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Uses python3
from random import randint
def naive_fib(n):
if (n <= 1):
return n
return naive_fib(n - 1) + naive_fib(n - 2)
def efficient_fib(n):
if 0 == n:
return 0
if 1 == n:
return 1
fibonacci_numbers = [None] * n
fibonacci_numbers[0] = 0
fibonacci_numbers[1] = 1
for i in range(2, n):
fibonacci_numbers[i] = fibonacci_numbers[i-1] + fibonacci_numbers[i-2]
return fibonacci_numbers[n-1] + fibonacci_numbers[n-2]
n = int(input())
print(efficient_fib(n)) | UTF-8 | Python | false | false | 530 | py | 6 | fibonacci.py | 5 | 0.590566 | 0.558491 | 0 | 23 | 22.086957 | 78 |
hekpomaht92/dark_scnn | 13,125,420,065,408 | a807c374139d562481ebbce942c0251199b3f4cf | becfbd6b5b629b0a17ee421a2807ccea0fb29754 | /model.py | 3d781c816e94e139bb60fe746981e3ccca4336d8 | []
| no_license | https://github.com/hekpomaht92/dark_scnn | 72d8ace614bddea96efc6ce31c9879d6ecf6bf3e | 5cdb0f04080a53a90fa00ae942c6ceffbf2978fb | refs/heads/master | 2022-03-23T19:09:04.773115 | 2019-12-21T13:47:05 | 2019-12-21T13:47:05 | 110,541,833 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import torch
import torch.nn as nn
from parts import conv, deconv, slicing
from config import Config
import multiprocessing
from collections import OrderedDict
multiprocessing.set_start_method('spawn', True)
cfg = Config()
def generate_model(pretrained_weights=None):
model = DarkSCNN(pretrained_weights)
if pretrained_weights != None:
model.load_state_dict(torch.load(pretrained_weights))
return model
class DarkSCNN(nn.Module):
def __init__(self, pretrained_weights):
super().__init__()
self.conv1 = nn.Sequential(OrderedDict([('conv1_1', conv(3, 16, 3, 1, 1, 1, cfg.drop_rate, True, True)),\
('conv1_2', conv(16, 32, 3, 1, 1, 1, cfg.drop_rate, True, True))]))
self.conv3 = nn.Sequential(OrderedDict([('conv3_1', conv(32, 64, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('conv3_2', conv(64, 32, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv3_3', conv(32, 64, 3, 1, 1, 1, cfg.drop_rate, True, True))]))
self.conv4 = nn.Sequential(OrderedDict([('conv4_1', conv(64, 128, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('conv4_2', conv(128, 64, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv4_3', conv(64, 128, 3, 1, 1, 1, cfg.drop_rate, True, True))]))
self.conv5 = nn.Sequential(OrderedDict([('conv5_1', conv(128, 256, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('conv5_2', conv(256, 128, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv5_3', conv(128, 256, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('conv5_4', conv(256, 128, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv5_5', conv(128, 256, 3, 1, 1, 1, cfg.drop_rate, True, True))]))
self.conv6 = nn.Sequential(OrderedDict([('conv6_1', conv(256, 512, 3, 1, 2, 2, cfg.drop_rate, False, True)),\
('conv6_2', conv(512, 256, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv6_3', conv(256, 512, 3, 1, 2, 2, cfg.drop_rate, False, True)),\
('conv6_4', conv(512, 256, 1, 1, 0, 1, cfg.drop_rate, False, True)),\
('conv6_5', conv(256, 512, 3, 1, 1, 1, cfg.drop_rate, False, True))]))
self.conv7 = nn.Sequential(OrderedDict([('conv7_1', conv(512, 512, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('conv7_2', conv(512, 512, 3, 1, 1, 1, cfg.drop_rate, False, True))]))
self.upsample1 = nn.Sequential(OrderedDict([('reduce1', conv(768, 128, 3, 1, 1, 1, cfg.drop_rate, False, True)),\
('deconv1', deconv(128, 64, 3, 2, 1, 1, cfg.drop_rate, True))]))
self.reorg4 = conv(128, 64, 3, 1, 1, 1, cfg.drop_rate, False, False)
self.reduse2 = conv(128, 64, 3, 1, 1, 1, cfg.drop_rate, False, False)
self.slice = slicing(64, (9, 1), 1, (4, 0))
self.deconv_out = nn.Sequential(nn.Conv2d(64, 64, 1, 1, bias=False),\
nn.ConvTranspose2d(64, 32, 16, 8, 4),\
nn.ConvTranspose2d(32, 16, 6, 2, 2),\
nn.Conv2d(16, cfg.n_classes, 3, 1, 1, bias=False))
if pretrained_weights == None:
self.conv1.apply(self.init_weights)
self.conv3.apply(self.init_weights)
self.conv4.apply(self.init_weights)
self.conv5.apply(self.init_weights)
self.conv6.apply(self.init_weights)
self.conv7.apply(self.init_weights)
self.upsample1.apply(self.init_weights)
self.reorg4.apply(self.init_weights)
self.reduse2.apply(self.init_weights)
self.slice.apply(self.init_weights)
self.deconv_out.apply(self.init_weights)
def forward(self, x):
x = self.conv1(x)
x = self.conv3(x)
x_4 = self.conv4(x)
x_5 = self.conv5(x_4)
x = self.conv6(x_5)
x_7 = self.conv7(x)
cat_8 = torch.cat((x_5, x_7), dim=1)
del x_5
del x_7
up1 = self.upsample1(cat_8)
del cat_8
reorg4 = self.reorg4(x_4)
del x_4
cat_4 = torch.cat((reorg4, up1), dim=1)
del reorg4
del up1
x = self.reduse2(cat_4)
del cat_4
x = self.slice(x)
x = self.deconv_out(x)
return x
def init_weights(self, m):
if (type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d) and m.bias is not None:
torch.nn.init.xavier_normal_(m.weight)
m.bias.data.fill_(0.)
elif (type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d) and m.bias is None:
torch.nn.init.xavier_normal_(m.weight)
if __name__ == '__main__':
test_value = torch.ones((1, 3, 384, 960), dtype=torch.float)
model = generate_model()
ans = model(test_value)
print(ans.size()) | UTF-8 | Python | false | false | 5,386 | py | 2 | model.py | 2 | 0.488489 | 0.420349 | 0 | 102 | 51.813725 | 155 |
sabbirahm3d/misc | 13,469,017,453,264 | a65fb95c8cdd505dd7228bb93356e8e15b0a4262 | 5c2c14fdcaa86211611e341ac33230d8242d3ea1 | /kattis/yoda/run.py | 069a15ea9cf520e0f9f8c413affd406b0b7ee289 | []
| no_license | https://github.com/sabbirahm3d/misc | 9f5e59945cae53e7e17a2bc565a5fb36280b93a1 | 0df3e8499c825431d609ba072b0b2180f8860fcb | refs/heads/master | 2018-02-08T03:32:54.173692 | 2017-09-11T15:33:20 | 2017-09-11T15:33:20 | 96,362,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
first = list(next(sys.stdin)[:-1])
second = list(next(sys.stdin)[:-1])
dif = abs(len(first) - len(second))
smaller = min((first, second), key=len)
while dif:
smaller.insert(0, '0')
dif -= 1
for i in range(len(first)):
if int(first[i]) > int(second[i]):
second[i] = ''
elif int(first[i]) < int(second[i]):
first[i] = ''
first = ''.join(first)
second = ''.join(second)
print int(first) if first else "YODA"
print int(second) if second else "YODA"
| UTF-8 | Python | false | false | 493 | py | 66 | run.py | 53 | 0.598377 | 0.588235 | 0 | 22 | 21.409091 | 40 |
boulware/heat-conduction | 18,502,719,134,993 | a39f7ef634e2dd2e10525f7610c7938c3696f225 | 03f37253626967c2bd441f68eb4de30ae2c6f72b | /main.py | 2236337d17d0dff2a9383e0ffe9c69bb3729a955 | []
| no_license | https://github.com/boulware/heat-conduction | 48f380ec4795127c8a0bd5eb3d96416a72234a36 | 9197a5c0cebe70102c0e30d0d50302c41b0593f8 | refs/heads/master | 2020-03-19T08:34:07.971974 | 2018-06-05T18:33:27 | 2018-06-05T18:33:27 | 136,215,495 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import pyglet
import random
import colorsys
from color import *
random.seed()
red = Color(rgb=(1,0,0))
green = Color(rgb=(0,1,0))
#def TemperatureToColor(temperature):
# return InterpolateColors([green, red], temperature)
def UpdateTemperatures(dt, cells, grid_width, grid_height):
k = 0.1
if len(cells) != grid_width * grid_height:
print("Invalid cells info given. Exiting.")
return
# print(cells)
rows = [cells[y,:] for y in range(cells.shape[0])]
# print(rows)
# print("---")
#[zip(row[:], row[1:]) for row in ]
#cell_pairs = [zip(row[:], row[1:]) for row in [cells[i:i+grid_width] for i in ]
# NOTE: 1D cells
# cell_pairs = zip(cells[:], cells[1:])
# temperature_changes = [0.0] * len(cells)
# for i, cell_pair in enumerate(cell_pairs):
# i_left = i
# i_right = i+1
# left_cell = cell_pair[0]
# right_cell = cell_pair[1]
#
# dT = left_cell - right_cell
# dq = -k * (left_cell - right_cell) * dt
#
# # TODO: Need a way to deal with too large step sizes causing temperatures to just swap rapidly
# #if abs(dq) > abs(dT / 2):
# #temperature_changes[i_left]
#
# temperature_changes[i_left] += dq
# temperature_changes[i_right] -= dq
#
# cells += temperature_changes
def GetCellColors(cells):
n = len(cells)
colors = np.array([[green, red]]*n)
return InterpolateColors(colors, cells.flatten())
window = pyglet.window.Window(width = 500, height = 500)
grid_width, grid_height = 4, 1
cell_count = grid_width * grid_height
cell_size = min(window.width // grid_width, window.height // grid_height)
cells = np.random.rand(grid_width, grid_height)
#cells = np.array([random.random() for i in range(cell_count)])
grid_vertices = np.array([[x,y, x,y+cell_size, x+cell_size,y+cell_size, x+cell_size,y] for x in np.linspace(0, window.width-cell_size, grid_width) for y in np.linspace(0, window.height-cell_size, grid_height)]).flatten()
#cell_colors = GetCellColors(cells)
@window.event
def on_draw():
window.clear()
v_count = len(grid_vertices) // 2
vertex_colors = np.concatenate(np.repeat(GetCellColors(cells), 4))
print(vertex_colors)
pyglet.graphics.draw(v_count, pyglet.gl.GL_QUADS, ('v2f', grid_vertices), ('c3f', vertex_colors))
@window.event
def update(dt):
UpdateTemperatures(dt, cells, grid_width, grid_height)
pyglet.clock.schedule_interval(update, 1/60.0)
pyglet.app.run() | UTF-8 | Python | false | false | 2,349 | py | 2 | main.py | 2 | 0.681141 | 0.66539 | 0 | 86 | 26.325581 | 220 |
Marvingms7/IFPI-POO | 12,352,325,984,753 | 5eccf8ec5228a2c7681b61e2ecc9e675c5a584be | 68c74c87c51d5abdf5f6061b6df2b09a84b11c41 | /POOSem05Atividade02/Sem05Atv02.py | 85d68e85f271913cc95cfa93e6d1b04e4e2419c3 | [
"MIT"
]
| permissive | https://github.com/Marvingms7/IFPI-POO | 2d6f6e2c29d37ee1d47fe267148fa1217c52455c | b00d3a381812df9a1c3f3a8121f07a1c1a0cda80 | refs/heads/main | 2023-03-15T10:23:37.430380 | 2021-03-13T20:04:38 | 2021-03-13T20:04:38 | 337,423,110 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | Fatura = []
class bomba_de_combustivel:
def __init__(self, Numero, ValorLitro, CapacidadeDaBomba, QuantidadeDeCombustivel, ValorFaturado = 0, QuantidadeVendida = 0, TipoDeCombustivel = 'Gasolina Comum'):
self.__Numero = Numero
self.__ValorLitro = ValorLitro
self.__CapacidadeDaBomba = CapacidadeDaBomba
self.__QuantidadeDeCombustivel = QuantidadeDeCombustivel
if self.__QuantidadeDeCombustivel > self.__CapacidadeDaBomba:
self.__QuantidadeDeCombustivel = self.__CapacidadeDaBomba
self.__ValorFaturado = ValorFaturado
self.__QuantidadeVendida = QuantidadeVendida
self.__TipoDeCombustivel = TipoDeCombustivel
def abastecerBomba(self, Valor):
if self.__CapacidadeDaBomba >= self.__QuantidadeDeCombustivel + Valor:
self.__QuantidadeDeCombustivel += Valor
else:
self.__QuantidadeDeCombustivel = self.__CapacidadeDaBomba
return self.__QuantidadeDeCombustivel
def abastecerVeiculoPorValor(self, Valor):
Litro = Valor / self.__ValorLitro
if self.__QuantidadeDeCombustivel >= Litro:
self.__QuantidadeVendida += Litro
self.__ValorFaturado += Valor
if self.__QuantidadeDeCombustivel >= self.__QuantidadeVendida:
self.__QuantidadeDeCombustivel -= self.__QuantidadeVendida
return self.__QuantidadeVendida
def abastecerVeiculoPorLitro(self, Valor):
Valor_Litro = Valor * self.__ValorLitro
if self.__QuantidadeDeCombustivel >= Valor:
self.__QuantidadeVendida += Valor
self.__ValorFaturado += Valor_Litro
Fatura.append(self.__ValorFaturado)
if self.__QuantidadeDeCombustivel >= self.__QuantidadeVendida:
self.__QuantidadeDeCombustivel -= Valor
return self.__QuantidadeVendida
@property
def ValorLitro(self):
return self.__ValorLitro
@ValorLitro.setter
def ValorLitro(self, Valor):
self.__ValorLitro = Valor
return self.__ValorLitro
def __str__(self):
return f'Tipo de Combustivel: {self.__TipoDeCombustivel}\nValor do Litro: {self.__ValorLitro}\nQuantidade de litros: {self.__QuantidadeDeCombustivel:.2f}\nQuantidade de litros vendidos: {self.__QuantidadeVendida:.2f}\nValor total da fatura: {self.__ValorFaturado:.2f}'
Bomba01 = bomba_de_combustivel(Numero=1, ValorLitro=4.5, CapacidadeDaBomba= 5000, QuantidadeDeCombustivel=2000)
Bomba01.abastecerBomba(2999)
Bomba01.abastecerVeiculoPorValor(16)
Bomba01.abastecerVeiculoPorLitro(2)
print(Bomba01)
print(f'#='* 50)
Bomba02 = bomba_de_combustivel(Numero=2, ValorLitro=5, CapacidadeDaBomba= 10000, QuantidadeDeCombustivel=4000, TipoDeCombustivel='Gasolina Aditivada')
Bomba02.abastecerBomba(5000)
Bomba02.abastecerVeiculoPorValor(30)
Bomba02.abastecerVeiculoPorLitro(5)
print(Bomba02)
print(f'#='* 50)
Bomba03 = bomba_de_combustivel(Numero=3, ValorLitro=3, CapacidadeDaBomba= 7000, QuantidadeDeCombustivel=500, TipoDeCombustivel='Etanol')
Bomba03.abastecerBomba(4000)
Bomba03.abastecerVeiculoPorValor(20)
Bomba03.abastecerVeiculoPorLitro(5)
print(Bomba03)
print(f'#='* 50)
Bomba04 = bomba_de_combustivel(Numero=4, ValorLitro=4, CapacidadeDaBomba= 40000, QuantidadeDeCombustivel=22000, TipoDeCombustivel='Diesel')
Bomba04.abastecerBomba(13000)
Bomba04.abastecerVeiculoPorValor(300)
Bomba04.abastecerVeiculoPorLitro(8)
print(Bomba04)
print(f'#='* 50)
print(f'Valor total faturado de todas as bombas {sum(Fatura)}')
| UTF-8 | Python | false | false | 3,508 | py | 30 | Sem05Atv02.py | 29 | 0.718928 | 0.68301 | 0 | 75 | 45.773333 | 276 |
yusheng615/zcpz | 28,545 | d30077e114a57dabe2db705b996dad74353273e8 | 95738ce8239ef6f407ac9d94b6d03a6d1faa3d95 | /test.py | 18e4ebacf3f043706ac1217a205c988d8d73f59f | []
| no_license | https://github.com/yusheng615/zcpz | 67ca568b851ffdc66b5f21fcfeb6286c6b8eb4b7 | af5cfef2a75f923c21bad0cf00c867b38ecd652d | refs/heads/master | 2020-03-22T23:44:11.303262 | 2018-07-14T01:06:07 | 2018-07-14T01:11:16 | 140,825,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import unittest
import xmlrunner
from code import *
from _math import *
from random_mpt import resampleportfolio
import numpy as np
class OperationFuncsTest(unittest.TestCase):
def setUp(self):
n_assets = 5
n_obs = 252
np.random.seed(1)
self.returns = np.random.randn(n_obs, n_assets)
def tearDown(self):
print('代码测试结束')
def test_add(self):
self.assertEqual(add(4, 2), 6)
self.assertTrue(add(1, 1), 1)
def test_case(self):
self.assertTrue(is_barcode('126112611262'), 'it is not Barcode')
def test_init(self):
d = Dictcase(a=1, b='test')
self.assertTrue(isinstance(d, dict))
def test_num(self):
self.assertEqual(three_num(), 36)
def test_sqrt(self):
self.assertEqual(find_sqrt(), (11, 17))
def test_custom_range(self):
self.assertTrue(isinstance(custom_range(0, -5), list))
def test_random(self):
self.assertTrue(resampleportfolio(self.returns), 10)
if __name__ == '__main__':
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='./mk_xml'))
| UTF-8 | Python | false | false | 1,124 | py | 5 | test.py | 5 | 0.626799 | 0.596223 | 0 | 46 | 23.152174 | 72 |
fox998/Telegram-Bot | 3,865,470,608,798 | 360be97498b99f69a7fb5971b336720b553ed520 | c7ae051c56602c96832487e776e75dccae6616d0 | /timetable.py | 59033e7177764ed6d54c0810be2f98db39445e4e | []
| no_license | https://github.com/fox998/Telegram-Bot | dc2685605bb57080a2f58587947102b462582b1c | 2bb3c484a60a43022a4885a2f884980a431fdbec | refs/heads/master | 2022-12-10T15:49:10.743034 | 2019-05-30T08:32:20 | 2019-05-30T08:32:20 | 186,974,803 | 0 | 0 | null | false | 2022-12-08T05:11:21 | 2019-05-16T07:26:17 | 2019-09-24T16:52:12 | 2022-12-08T05:11:20 | 25 | 0 | 0 | 3 | Python | false | false |
import requests
from urllib import parse
from bs4 import BeautifulSoup
from markdownify import markdownify as md
identifier_of_time_section = {'style': 'font-size: 12px; text-align: center'}
identifier_of_current_day_section = {'class': 'yellow'}
def formating_lesson_data(lesson_data):
md_data = md(lesson_data)
return md_data[0:md_data.find('(')]
def parse_timetable(html_page):
soup = BeautifulSoup(html_page, 'html.parser')
lesson_data = [formating_lesson_data(val) for val in soup.find_all('td', identifier_of_current_day_section)]
time_set = {md(val) for val in soup.find_all('div', identifier_of_time_section)}
return [f'\t\n{time} {data}\n' for (time, data) in zip([*sorted(time_set)][0::2], lesson_data)]
def today_timetable(groupe):
http_response = requests.get('https://rozklad.org.ua/timetable/group/' + parse.quote(groupe))
responce = 'Can`t find the groupe'
if http_response.status_code == 200:
responce = ''
for lesson in parse_timetable(http_response.text):
responce += lesson
return responce
if __name__ == "__main__":
print(today_timetable('тк-71'))
| UTF-8 | Python | false | false | 1,158 | py | 3 | timetable.py | 2 | 0.67301 | 0.663495 | 0 | 39 | 28.615385 | 112 |
ArielJingZhou/MultiAgentGroup | 1,108,101,569,792 | 68390116ffb32ea9dc67d8a275ec8fd2cffcb486 | 58b56fe3cfdfe5638c8e6b850b715ed7bcc7d9cb | /python_code/Problem4_lgbm.py | 82c136ce37bfc3fbca9f7ca7f10590da2f92f11a | []
| no_license | https://github.com/ArielJingZhou/MultiAgentGroup | b373c0d307f85213b7a5039ef594117a9f9d174f | e7230dde3643171cf91ec693ea773c231b93ff20 | refs/heads/master | 2020-04-21T04:56:38.409167 | 2019-03-11T23:51:01 | 2019-03-11T23:51:01 | 169,326,957 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import lightgbm as lgb
import numpy as np
import pandas as pd
import pickle
from math import sqrt
from sklearn.metrics import mean_squared_error
print('Loading data...')
# load or create your dataset
train_set = pd.read_csv("train.csv")
valid_set = pd.read_csv("validation.csv")
test_set = pd.read_csv("test.csv")
# downsample train set, too big
def downsampling(data):
no_click = data.query('click == 0')
do_click = data.query('click == 1')
nums = len(do_click) * 700
new_no_click = no_click.sample(n=nums, random_state=42)
return pd.concat([new_no_click, do_click])
# drop user tag for problem 3 ... to be considered more
# slotprice is considered as continuous variable
def data_preprocessing(data, enforce_cols=None):
# data = data.sort_index(axis=0)
# drop features
to_drop_columns = ['bidid', 'keypage', 'userid', 'url', 'urlid',
'IP', 'domain', 'slotid', 'creative', 'usertag']
data = data.drop(to_drop_columns, axis=1)
# one hot encoding categorical variables
categoricals = ['weekday', 'hour', 'useragent', 'region', 'city', 'adexchange', 'slotwidth',
'slotheight', 'slotvisibility', 'slotformat', 'advertiser']
for tag in categoricals:
s = pd.Series(data[tag])
d = pd.get_dummies(s, dummy_na=True)
for k in d.keys():
data[tag + '_' + str(k)] = d[k]
data = data.drop(tag, axis=1)
# split usertag using ','
"""new_tags = data['usertag'].str.split(',')
new_tags = new_tags.str.join('|').str.get_dummies()
new_tags = new_tags.add_prefix('usertag_')
data = data.join(colums_split)"""
data.fillna("unknown", inplace=True)
data = pd.get_dummies(data)
# match test set and training set columns
if enforce_cols is not None:
# enforce_cols is the columns of train set, to_drop and to_add finds the difference
to_drop = np.setdiff1d(data.columns, enforce_cols)
to_add = np.setdiff1d(enforce_cols, data.columns)
data.drop(to_drop, axis=1, inplace=True)
data = data.assign(**{c: 0 for c in to_add})
data = data.reindex(sorted(data.columns), axis=1)
return data
# data preprocessing
train = downsampling(train_set)
train = data_preprocessing(train)
valid = data_preprocessing(valid_set, train.columns)
test = data_preprocessing(test_set, train.columns)
to_drop_columns = ['bidprice', 'payprice']
train = train.drop(to_drop_columns, axis=1)
valid = valid.drop(to_drop_columns, axis=1)
test = test.drop(to_drop_columns, axis=1)
test = test.drop('click', axis=1)
# split to x and y
train_x = train.drop('click', axis=1)
train_y = train['click']
valid_x = valid.drop('click', axis=1)
valid_y = valid['click']
lgb_train = lgb.Dataset(train_x, train_y)
lgb_valid = lgb.Dataset(valid_x, valid_y)
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2', 'l1'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0
}
def predict_CTR():
gbm = lgb.train(params,
lgb_train,
valid_sets=lgb_valid,
num_boost_round=20,
early_stopping_rounds=100)
'''
#save model
model_file = open('./models/lgbm_model.sav', "wb")
pickle.dump(gbm, model_file)
model_file.close()
#load model
model_file = open('./models/lgbm_model.sav', 'rb')
gbm = pickle.load(model_file)
'''
print('Starting prediction...')
y_pred = gbm.predict(train_x)
return y_pred
def non_linear_bidding(c, l, pCTRs):
# evaluate on validation.csv
clicks = 0
winning_impressions = 0
spend = 0
budget = 6250 * 1000
#bid_prices = (c / l * pCTRs + c * c) ** 0.5 - c
bid_prices = c * (((pCTRs + (c*c*l*l+pCTRs*pCTRs)**0.5)/c/l) ** (1.0/3)-(c*l/(pCTRs + (c*c*l*l+pCTRs*pCTRs)**0.5))**(1.0/3))
i = 0
for i in range(len(valid_set)):
if bid_prices[i] > budget - spend:
bid = budget - spend
else:
bid = bid_prices[i]
if bid >= valid_set['payprice'][i]:
spend += valid_set['payprice'][i]
winning_impressions += 1
if str(valid_set['click'][i]) == '1':
clicks += 1
spend /= 1000
click_through_rate = "{:.3%}".format(clicks / winning_impressions)
if clicks == 0:
average_cpm = 0
average_cpc = 0
else:
average_cpm = spend / winning_impressions * 1000
average_cpc = spend / clicks
print('\nclicks:' + str(clicks))
print('\nclick_through_rate:' + str(click_through_rate))
print('\nspend:' + str(spend))
print('\naverage_cpm:' + str(average_cpm))
print('\naverage_cpc:' + str(average_cpc))
#f = open("lgb_tuning_results1.csv", "a+")
#f.write(str(c) + "," + str(l) + "," + str(clicks) + "," + str(click_through_rate) + "," + str(spend/1000) + "," + str(average_cpm) + "," + str(average_cpc) + "\n")
#f.close()
return str(c) + "," + str(l) + "," + str(clicks) + "," + str(click_through_rate) + "," + str(spend) + "," \
+ str(average_cpm) + "," + str(average_cpc)
pCTRs = predict_CTR()
#file = open("lgb_tuning_results1.csv", "w")
#file.write("constant, lambda, clicks, CTR, spend, CPM, CPC\n")
#file.close()
#for c in range(50, 100, 5):
# for l in range(50, 70, 1):
# l = l * 10 ** (-7)
#formula 1
#non_linear_bidding(75, 5.1 * 10 ** (-6), pCTRs)
#formula 2
non_linear_bidding(85, 3 * 10 ** (-6), pCTRs)
| UTF-8 | Python | false | false | 5,775 | py | 18 | Problem4_lgbm.py | 8 | 0.569177 | 0.549437 | 0 | 184 | 29.38587 | 169 |
zhuyanlong/LeetCode | 1,443,109,019,791 | 0166d3347a843e7d1ff1dd87f77545645374cc1c | fa7c249733b9edaa45f7115ddcc1e40ca2ee0c3e | /Integer_to_Roman.py | 7dc184d6c4781cc7f00405f97e5887c4a7bd0908 | []
| no_license | https://github.com/zhuyanlong/LeetCode | 30585e4285442314e6e58f8d80aaea15b82607f4 | dc34b2d2d786a2cb6e441220b724aac460c9bb2a | refs/heads/master | 2021-07-04T09:46:25.754619 | 2020-10-05T04:25:08 | 2020-10-05T04:25:08 | 173,396,980 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #这种方法很蠢,但是时间复杂度极低
dic={1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M',4:'IV',9:'IX',40:'XL',90:'XC',400:'CD',900:'CM'}
class Solution:
def intToRoman(self, num: int) -> str:
re=''
while num!=0:
if num>=1000:
num-=1000
re+=dic[1000]
elif num>=900:
num-=900
re+=dic[900]
elif num>=500:
num-=500
re+=dic[500]
elif num>=400:
num-=400
re+=dic[400]
elif num>=100:
num-=100
re+=dic[100]
elif num>=90:
num-=90
re+=dic[90]
elif num>=50:
num-=50
re+=dic[50]
elif num>=40:
num-=40
re+=dic[40]
elif num>=10:
num-=10
re+=dic[10]
elif num>=9:
num-=9
re+=dic[9]
elif num>=5:
num-=5
re+=dic[5]
elif num>=4:
num-=4
re+=dic[4]
else:
num-=1
re+=dic[1]
return re
def main():
s=58
print(Solution.intToRoman(s,s))
main()
| UTF-8 | Python | false | false | 1,260 | py | 106 | Integer_to_Roman.py | 104 | 0.354235 | 0.261401 | 0 | 53 | 21.09434 | 104 |
zzhanghub/HW_CN | 6,631,429,506,820 | 9a3326e4655b0ccb5ca6c6697aeb53757b7ee29f | 23e962f10450a7bffe170873721f2acc33c47500 | /LINE/save_ebd.py | b628a562ffa57b836b8c1313ee4fcfe67000260c | []
| no_license | https://github.com/zzhanghub/HW_CN | a714a3500dbcfc7d684a306beea10374a09a88a7 | 8106b15ab1567f4a53e4abb563def8a923778857 | refs/heads/master | 2020-12-01T20:23:57.957760 | 2020-01-04T03:43:38 | 2020-01-04T03:43:38 | 230,758,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import torch
import numpy as np
embed = torch.load('bit_model.pth').contextnodes_embeddings
feat = embed.weight.data.numpy()
print(feat.shape)
np.save('embedings', feat)
# for idx in range(embeddings.num_embeddings):
# vector = embeddings.weight[idx].data
| UTF-8 | Python | false | false | 262 | py | 18 | save_ebd.py | 9 | 0.744275 | 0.744275 | 0 | 10 | 25.2 | 59 |
zhambylSamat/django.altyn-bilim.kz | 14,654,428,437,299 | c291481cf08a4f141d211807bae74a4df41982a1 | cfe4493a1812d6030a10b75e7454a0e3ea3d178d | /src/lessonProgress/migrations/0019_auto_20200225_1257.py | 5d52c4422d72e640327612427da2072d251df0f2 | []
| no_license | https://github.com/zhambylSamat/django.altyn-bilim.kz | 93ba4ce285c40d092bb28c171b248e1bebc4787f | 2981d47596674a4813b06168253b1a73278c9315 | refs/heads/master | 2023-02-01T12:09:00.245209 | 2020-12-18T12:03:18 | 2020-12-18T12:03:18 | 322,582,680 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.1 on 2020-02-25 06:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lessonProgress', '0018_auto_20200224_1954'),
]
operations = [
migrations.RenameField(
model_name='lessonvideoactionhistory',
old_name='lesson_group_student',
new_name='lesson_group_student_id',
),
]
| UTF-8 | Python | false | false | 417 | py | 195 | 0019_auto_20200225_1257.py | 184 | 0.613909 | 0.541966 | 0 | 18 | 22.166667 | 54 |
meReCurse/Food-Price-Aggregator-Web-App | 18,631,568,152,322 | 9afa6ad0d7d5982a50ab41df1935b2fbee490f84 | 09f4ae9cfda728c29e70dc6e9ee7dd917d3e00e3 | /backend/price_aggregator/apps/rest_api/utils/selenium_session/__init__.py | c453cf8b02f006a9cc65cf4d3c38e65ad89f4461 | []
| no_license | https://github.com/meReCurse/Food-Price-Aggregator-Web-App | 0d1d9d9caa39ce5ae92e51297facf2997436c8de | 2e72943565b2c5bc8b93abc25caccf5128da33eb | refs/heads/master | 2022-02-12T01:18:05.225286 | 2020-02-21T11:32:50 | 2020-02-21T11:32:50 | 236,166,083 | 0 | 0 | null | false | 2022-03-08T21:15:20 | 2020-01-25T12:16:59 | 2020-02-21T11:35:13 | 2022-03-08T21:15:19 | 2,401 | 0 | 0 | 2 | Python | false | false | from .manager import SessionManager
from .session import Session
__all__ = ('SessionManager', 'Session')
| UTF-8 | Python | false | false | 107 | py | 28 | __init__.py | 25 | 0.738318 | 0.738318 | 0 | 5 | 20.4 | 39 |
KhaledTaymour/University-Registration-System | 9,526,237,466,378 | 4c04dde47aa883febcd2ca206b8ca7c258e6d1e0 | 03ebe948a369349fb488eaa1620453de9d9caa45 | /helper.py | 89726a9c9a7ae80a18fb69a7b52344be014d02ba | []
| no_license | https://github.com/KhaledTaymour/University-Registration-System | d25cc653bbdd4188f18cf005b87ddf5e62ebb633 | 5ca5638dfe55863d32662141f28eb9fe66ce566f | refs/heads/main | 2023-06-02T13:28:47.834310 | 2021-06-19T11:16:34 | 2021-06-19T11:16:34 | 327,269,361 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #importing the linkedlist
from registrationLL import RegistrationLinkedList
class Helper:
#constructor having inputs: list of colleges, departments, students, courses
def __init__(self, colleges, departments, students, courses):
#colleges, departments, students, courses saved as self variables
self.colleges = colleges
self.departments = departments
self.students = students
self.courses = courses
# create an instance of the linkedlist class
self.reg = RegistrationLinkedList()
def getAllItemsOfData(self, dataList):
for x in range(len(dataList)):
print(dataList[x])
# get any of the data; colleges, departments, students or courses by passing its list and the id to search for
def getDataById(self, dataList, _id):
# iterating the data for that id
data = next((item for item in dataList if item["id"] == _id), None)
return data
# validate the student Id and Course Id given
def isInputsValid(self, stId, crsId):
self.student = Helper.getDataById(self, self.students, stId)
self.course = Helper.getDataById(self, self.courses, crsId)
if self.student == None:
return 'enter a valid Student ID'
elif self.course == None:
return 'enter a valid Course ID'
else:
return 'valid'
# add new register for a student in a course by passing student Id & course Id
def addNewRegister(self, stId=0, crsId=0):
if stId == 0 or crsId == 0:
return 'please insert correct arguments e.g. helper.addNewRegister(1, 1)'
else:
# first check inputs validity
isInputsValid = Helper.isInputsValid(self, stId, crsId)
if isInputsValid != 'valid':
return isInputsValid
else:
# if inputs are valid; prepare the complete data for the Registration Node
# college Id
clgId = Helper.getDataById(self, self.colleges, stId)["id"]
# dept Id
deptId = Helper.getDataById(self,self.departments, stId)["id"]
# call the addNewRegistration from the instance of the linkedlist class
self.reg.addNewRegistration(self.student, clgId, deptId, self.course)
# after finishing adding
return 'student registered successfully'
# get total # of registrations
def getAllRegistrationsDone(self):
return self.reg.length()
# get list & count of students registered in a course
def getRegisteredStudentsInCourse(self, crsId):
# get the course by its Id
course = Helper.getDataById(self, self.courses, crsId)
# check validity
if course == None:
return 'enter a valid Course ID'
else:
# call the getRegisteredStudentsInCourse function from the instance of the linkedlist class
self.reg.getRegisteredStudentsInCourse(course, crsId, self.students, self)
# get list & count of courses registered by a student
def getCoursesRegisteredByStudent(self, stId):
# get the student by his/her Id
student = Helper.getDataById(self, self.students, stId)
# check validity
if student == None:
return 'enter a valid Student ID'
else:
# call the getCoursesRegisteredByStudent function from the instance of the linkedlist class
self.reg.getCoursesRegisteredByStudent(student, stId, self.courses, self)
# delete a registration of a student in a course
def deleteRegistration(self, stId=0, crsId=0):
if stId == 0 or crsId == 0:
return 'please insert correct arguments e.g. helper.deleteRegistration(1, 1)'
else:
isInputsValid = Helper.isInputsValid(self, stId, crsId)
if isInputsValid != 'valid':
return isInputsValid
else:
# get the student by his/her Id
student = Helper.getDataById(self, self.students, stId)
# get the course by its Id
course = Helper.getDataById(self, self.courses, crsId)
self.reg.deleteRegistration(student, course) | UTF-8 | Python | false | false | 4,371 | py | 5 | helper.py | 3 | 0.61725 | 0.614505 | 0 | 102 | 41.784314 | 118 |
nimenki/Json-mysql-tesk_task | 12,326,556,164,312 | b491937f09b0d8c3d9a2ee2b831193e3b0447f56 | 5558e3557bff165d0a7d9c6529dbd3920ef07512 | /task1_2/task2.py | 0ecc12283aed526569aa217c4e2db74083a1db8e | []
| no_license | https://github.com/nimenki/Json-mysql-tesk_task | 031c860d3d8b978a93b982aca9e80261b7450ee3 | fbf4c5d52791f824b4f4aa373649cadf5bcb48d8 | refs/heads/master | 2023-08-14T00:25:43.427354 | 2021-09-20T11:14:28 | 2021-09-20T11:14:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from datetime import datetime
from flask import jsonify, make_response
from app import app, db
from task1_2.models import User
from task1_2.schemas import UserSchema
VOWELS = ("a", "e", "i", "o", "u")
def accummulateHoursMinutesSecondsAndMilliseconds(date) -> int:
return date.hour * 24 * 60 * 10 ** (-3) + \
date.minute + 60 * 10 ** (-3) + \
date.second * 10 ** (-3) + \
date.microsecond * 10 ** 3
@app.route('/api/users/<user_id>', methods=['PATCH'])
def patch_user(user_id):
user = User.query.get(user_id)
if not user:
return f"No user with id {user_id}", 400
if user.salary % 123 > 1 and user.name.lower().startswith(VOWELS):
user.salary *= 2
if accummulateHoursMinutesSecondsAndMilliseconds(user.data) > 43200000:
user.data = datetime(1990, 1, 1, user.data.hour, user.data.minute, user.data.second, user.data.microsecond)
db.session.add(user)
db.session.commit()
return make_response(jsonify(UserSchema().dump(user)), 200)
| UTF-8 | Python | false | false | 1,060 | py | 10 | task2.py | 8 | 0.623585 | 0.579245 | 0 | 33 | 30.121212 | 115 |
myhelloos/concurrency-python | 14,345,190,817,856 | 16e4ae12f590c225b85a660c61faa04205e33134 | 61a263e985f73b23f20d99f2a0ac123838e3677a | /app/intro/helloPythonWithThreads.py | c3b3279f4942bc22094174f553af58b799399210 | []
| no_license | https://github.com/myhelloos/concurrency-python | ee451f01bc48319641d11059f9cd63ad5413c7f8 | 30d983e77663d0b74271f1490087ee0d1e262b47 | refs/heads/master | 2020-04-19T09:40:52.817337 | 2019-02-04T02:34:11 | 2019-02-04T02:34:11 | 168,117,546 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: alfred_yuan
# Created on 2019-01-28
from threading import Thread
from time import sleep
class CookBook(Thread):
def __init__(self):
Thread.__init__(self)
self.message = "Hello Parallel Python Cookbook!!\n"
def print_message(self):
print(self.message)
def run(self):
print("Thread Starting\n")
x = 0
while (x < 10):
self.print_message()
sleep(2)
x += 1
print("Thread Ended\n")
# start the main process
print("Process Started")
# create an instance of the HelloWorld class
hello_python = CookBook()
# print the message...starting the thread
hello_python.start()
# end the main process
print("Process Ended")
| UTF-8 | Python | false | false | 770 | py | 23 | helloPythonWithThreads.py | 21 | 0.614286 | 0.596104 | 0 | 36 | 20.388889 | 59 |
tbiles01/InternshipExperience | 7,000,796,719,274 | b7d593e084cc99fb0614ead7f4fd6c9f05cb6115 | b851eb7b2ff68c97e0b65aa937884db99875e43e | /__init__.py | 0fa19ce8e1d99d8be202e30f185b8d35261c3d40 | []
| no_license | https://github.com/tbiles01/InternshipExperience | 1432e1d6b9f75a3b42b96cef91f2f78c560aad74 | 51f4162abbe255eca480603546dfd9615e6e7768 | refs/heads/main | 2023-07-04T04:19:38.261700 | 2021-08-07T16:44:37 | 2021-08-07T16:44:37 | 393,738,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 6 14:51:56 2021
@author: tiffanybiles
"""
| UTF-8 | Python | false | false | 115 | py | 3 | __init__.py | 3 | 0.608696 | 0.495652 | 0 | 7 | 15.285714 | 35 |
zhouf00/test_obj | 8,976,481,666,672 | d47cd7a5c79dced5a0c485c37a160bb254486ec4 | 4e771190fd33c6c4badfde097bfeecefea2f7682 | /APPS/crm/urls.py | 7db15b12814881e2a7fb907f3c51b1821b8cd5a3 | []
| no_license | https://github.com/zhouf00/test_obj | ac158e396a395f95a5b6a3c886ba2de58fce6e47 | cb9c5eb9190fb1c59c2e017e7540d4151408b65b | refs/heads/master | 2023-08-30T06:37:00.728159 | 2021-10-12T06:00:59 | 2021-10-12T06:00:59 | 283,736,762 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^market/$', views.MarketViewSet.as_view({'get': 'list', 'post': 'create'})),
url(r'^market/update/(?P<pk>.*)/$', views.MarketViewSet.as_view({'get': 'retrieve', 'post': 'update'})),
url(r'^market/delete/(?P<pk>.*)/$', views.MarketDeleteViewSet.as_view({'post': 'update'})),
url(r'^markettrace/$', views.MarketTraceViewSet.as_view({'get': 'list', 'post': 'create'})),
url(r'^linkman/$', views.LinkmanViewSet.as_view({'get': 'list', 'post': 'create'})),
url(r'^linkman/update/(?P<pk>.*)/$', views.LinkmanViewSet.as_view({'post': 'update'})),
url(r'^raterecord/$', views.RateRecordViewSet.as_view({'get': 'list', 'post': 'create'})),
url(r'^raterecord/update/(?P<pk>.*)/$', views.RateRecordViewSet.as_view({'post': 'update'})),
url(r'history/$', views.MarketHistoryViewSet.as_view({'get':'list', 'post': 'create'})),
url(r'history/update/(?P<pk>.*)/$', views.MarketHistoryViewSet.as_view({'put': 'update'})),
url(r'history/annals/$', views.AnnalsViewSet.as_view()),
] | UTF-8 | Python | false | false | 1,097 | py | 72 | urls.py | 70 | 0.622607 | 0.622607 | 0 | 20 | 53.9 | 108 |
YusrilHasanuddin/bangkit-capstone-CAP0166 | 18,416,819,782,037 | ccec5231dfcb293a1be0e07b1ebb4ce7fee98a7c | 0d7a7dab4402276063c43775d8734aa2e4f9fb9d | /BIG-GIANT/extract.py | ea4eafe6807495c2b152237d8992e85ecfbd4927 | [
"MIT"
]
| permissive | https://github.com/YusrilHasanuddin/bangkit-capstone-CAP0166 | 45f65589ccbd1127c5b0f565bdeb928433d660d1 | 51742f7af47fa285154793a6ea74de1d78d945b3 | refs/heads/main | 2023-05-30T03:08:24.927485 | 2021-06-09T09:21:52 | 2021-06-09T09:21:52 | 375,324,722 | 4 | 0 | MIT | true | 2021-06-09T11:04:29 | 2021-06-09T11:04:28 | 2021-06-09T09:22:36 | 2021-06-09T09:22:31 | 411,484 | 0 | 0 | 0 | null | false | false | from skimage import io
import numpy as np
from facenet_pytorch import MTCNN
import validators
import matplotlib.image as mpimg
from cv2 import cv2
import urllib.request
def is_image_from_url(url: str):
valid = validators.url(url)
if valid == True:
return True
else:
return False
class Extract:
"""
Extract class is class that responsible for extracting face
...
Attributes
----------
image : numpy.ndarray
A image with numpy.ndarray type
You can use matplotlib.image.imread(image_file)
or use cv2.imread. but remember to convert it back to BGR -> RGB
Methods
-------
extract_face_to_list(image: numpy ndarray) -> list
returning a list of individual detected image in a list, type(list[0]) == numpy.ndarray
image_from_url(image_url: str) -> image : numpy.ndarray
this method take an url image and convert it to numpy.ndarray
read_image(image_path: str) -> image : numpy.ndarray
this method read an image from a path or a url and return it as numpy.ndarray
"""
def extract_face_to_list(self, image):
mtcnn = MTCNN(margin=20, keep_all=True,
post_process=False)
faces = mtcnn(image)
list_of_faces = []
if faces is None:
list_of_faces.append("Image Not Found")
return list_of_faces
for face in faces:
face_array = face.permute(1, 2, 0).int().numpy()
face_array = np.array(face_array, dtype='uint8')
list_of_faces.append(face_array)
return list_of_faces
def image_from_url(self, image_url):
resp = urllib.request.urlopen(image_url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
def image_from_path(self, image_path):
image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
return image
def read_image(self, image: str):
from_url = is_image_from_url(image)
if from_url is True:
image_numpy = self.image_from_url(image)
else:
image_numpy = self.image_from_path(image)
return image_numpy
| UTF-8 | Python | false | false | 2,304 | py | 73 | extract.py | 20 | 0.619792 | 0.611111 | 0 | 78 | 28.538462 | 95 |
ericduval93/prepa | 541,165,910,042 | 3cd54d1458a19440000dab12971b964a37d6d5d0 | 93a63cf3e805737ef70650693f6567e856deb7d0 | /day1/method-list.py | 1b4134f9e4bc38c34caf9a716710844b0cb84cb4 | []
| no_license | https://github.com/ericduval93/prepa | 61bcfa6dc868f5a826f5562203ddb168a1002cc3 | f461159353decffb2da467edda8eaf11801bd0a0 | refs/heads/master | 2023-02-02T01:27:59.981387 | 2020-12-15T10:38:16 | 2020-12-15T10:38:16 | 320,523,601 | 0 | 0 | null | false | 2020-12-15T10:38:28 | 2020-12-11T09:15:04 | 2020-12-11T16:40:45 | 2020-12-15T10:38:26 | 8 | 0 | 0 | 0 | Python | false | false | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
foo = ['foo1', 'foo2', 'foo3', 'foo4', 'foo5', 'foo6']
bar = ['bar1', 'bar2', 'bar3', 'bar4', 'bar5', 'bar6']
print( "foo = {}".format(foo) )
print( "bar = {}".format(bar) )
print( "Index method = {}".format(bar.index('bar3')) )
bar.append('bar7')
print( "Append method = {}".format(bar))
bar.insert(2,'bar2.2')
print( "Insert method = {}".format(bar))
bar.remove('bar2.2')
print( "Remove method = {}".format(bar))
foo2 = [7,3,8,9,-1,-7,23]
foo2.sort()
print( "Sort method = {}".format(foo2))
foo2.sort(reverse=True)
print( "reverse Sort method = {}".format(foo2))
foo3 = ['a', 'z', 'A', 'Z' ]
foo3.sort()
print( "Sort method = {}".format(foo3))
foo3.sort(key=str.lower)
print( "Sort lower method = {}".format(foo3))
foo3.sort(key=str.lower,reverse=True)
print( "reverse Sort lower method = {}".format(foo3))
exit(0)
| UTF-8 | Python | false | false | 936 | py | 19 | method-list.py | 18 | 0.604701 | 0.556624 | 0 | 40 | 22.4 | 55 |
nikhil-vytla/GeospatialStore | 1,855,425,914,705 | d7e3d556ff4b9385e994c9c595dc97f723a2648c | 71fb51235bea4438a9fb7dc4653dccabcc054fba | /flask/src/models/iris_model.py | 779d0f2a02e1d0e132ac784450fbd7db70d47499 | [
"MIT"
]
| permissive | https://github.com/nikhil-vytla/GeospatialStore | 8a78aecba2a9c97176b2eaf980e2c8e9cb255fea | 369f272585afc20f7e7bac4826717240a84cb4ff | refs/heads/master | 2022-05-24T21:15:42.169813 | 2020-04-30T16:16:32 | 2020-04-30T16:16:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from sklearn.linear_model import LinearRegression
import seaborn as sns
import pandas as pd
import pickle
def train_iris_model():
""" Trains our Iris Model.
Initial un-tuned function to train and serialize a Linear Regression
model to predict petal_length given petal_width for the `Iris` dataset.
Serialized models are stored in .pkl format within the `models` directory.
"""
iris = sns.load_dataset('iris')
X = iris.petal_width.as_matrix(columns=None).reshape(-1, 1)
lm = LinearRegression()
model = lm.fit(X, iris.petal_length)
pickle.dump(model, open('models/iris_model.pkl', 'wb'))
def predict_length(petal_width: int=0)-> float:
""" Predict petal_length given petal_width.
This function loads the serialized `Iris` petal_length prediction model,
and then predicts the petal_length given the petal_width that is passed.
Used within views.py to servee the prediction results.
Args:
petal_width [int]: Petal length input by user
Returns:
float: Petal_length predicted by our linear model.
"""
lm = pickle.load(open('models/iris_model.pkl', 'rb'))
return lm.predict(pd.DataFrame({'petal_width': [petal_width]})) | UTF-8 | Python | false | false | 1,233 | py | 25 | iris_model.py | 10 | 0.688564 | 0.686131 | 0 | 40 | 29.85 | 78 |
codamin/Data-Structures-Algorithms | 9,620,726,780,392 | a5744e106ae9f984c8334e84b6d695e9cc8d7324 | 30134d697e196f58ffedbf95f40026c4265d1c88 | /CA4/q1.py | 6fa6f6b9f763d438cf5b0ce0ae18dbd75720609c | []
| no_license | https://github.com/codamin/Data-Structures-Algorithms | c919535c734f98f5a7484871a805bd4ad47c00d4 | 94ce3f18dd50fdf9871d23baf1fbd230ce0d30e8 | refs/heads/master | 2021-12-02T05:51:01.721875 | 2021-11-26T09:06:24 | 2021-11-26T09:06:24 | 196,724,634 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def dfs(graph, v, visits, maxLen):
visits[v] = 1
for i in range(len(graph[v])):
if visits[graph[v][i]] == 0:
dfs(graph, graph[v][i], visits, maxLen)
maxLen[0] = max(maxLen[0], visits.count(1))
visits[v] = 0
def hasPath(graph):
v = len(graph)
maxLen = [0]
for i in range(v):
visits = [0] * v
if len(graph[i])!=0:
dfs(graph, i, visits, maxLen)
if maxLen[0] == v:
return True
return False
def addEdge(graph, v, w, e):
graph[v].append(w)
e[v] = 1
e[w] = 1
def main():
v = int(input())
graph = [[] for x in range(v)]
dic = {}
for i in range(v):
word = input()
if 'end' + word[0] in dic:
endingWithThis = dic['end' + word[0]]
for j in endingWithThis:
graph[j] += [i]
if 'begin' + word[-1] in dic:
graph[i] += dic['begin' + word[-1]]
if 'begin' + word[0] in dic:
dic['begin' + word[0]] += [i]
else:
dic['begin' + word[0]] = [i]
if 'end' + word[-1] in dic:
dic['end' + word[-1]] += [i]
else:
dic['end' + word[-1]] = [i]
if hasPath(graph):
print('possible')
else:
print('not possible')
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 1,347 | py | 13 | q1.py | 12 | 0.443207 | 0.426875 | 0 | 53 | 24.377358 | 51 |
NateHan/PythonForProgrammers | 14,697,378,116,128 | 5efa0663234b0fae30fbdb7a3f31fe2cfab8777c | bbe309a0294bc2a0e784471f691b74062f9edbc0 | /hangman.py | aaab3e484ded0f93e222eb8d4d186066fc183df9 | []
| no_license | https://github.com/NateHan/PythonForProgrammers | 22fb904ecc8299980b0adf05ea08b4b27bda94ba | 45236eb5576dd8dd9ec427cbb2b5514f8f046ac0 | refs/heads/master | 2020-07-10T07:34:23.086329 | 2019-10-05T22:51:14 | 2019-10-05T22:51:14 | 204,206,172 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
lives = 5
word = "Apple"
blank = " _ "
def runGame():
blanks = []
guessedLetters = []
global lives
for idx in range(len(word)):
blanks.append(blank)
while lives > 0 and blank in list(blanks):
inputLetter = input("Word: {} - Lives = {} , Guessed letters: {} \n Guess a letter: ".format(blanks, lives, guessedLetters))
if letterIsInWord(inputLetter.lower(), word.lower()):
print("Correct!")
else:
print("Wrong!")
lives -= 1
guessedLetters.append(inputLetter)
genWordsAndBlanks(blanks, guessedLetters)
else:
if lives > 0: print("You win!")
else: print("You died! The word was: {}".format(word))
def letterIsInWord(letter, word):
if letter in list(word):
return True
else:
return False
def genWordsAndBlanks(blanks, guessedLetters):
for idx in range(len(word)):
if word[idx].lower() in guessedLetters:
blanks[idx] = word[idx]
return ''.join(blanks)
runGame() | UTF-8 | Python | false | false | 912 | py | 13 | hangman.py | 12 | 0.669956 | 0.66557 | 0 | 39 | 22.384615 | 126 |
saibye/project | 2,216,203,125,479 | 12c9ccda6925ef3e87c11059d51d33b307f4e49b | e476b2272b7f2995d995a83db902e26accb68d17 | /src/old/decision/name.py | cfff0101257131a82ab89c831b8d771a7e2b81e9 | []
| no_license | https://github.com/saibye/project | 722df485eeec2c467ad24fbe080f156cf6da3b94 | ec9cdc35c1f5371faf0774699cba9e6a2c5febfc | refs/heads/master | 2021-08-07T00:46:16.401667 | 2020-06-06T11:54:56 | 2020-06-06T11:54:56 | 62,984,883 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# -*- encoding: utf8 -*-
import tushare as ts
import pandas as pd
import numpy as np
from saiutil import *
from saidb import *
from saisql import *
from saicalc import *
from sailog import *
from saimail import *
from sairef import *
#######################################################################
# ST摘帽
# stXX --> XXYY
#######################################################################
"""
2016-12-25
insert into tbl_name (
stock_id, stock_old_name, stock_new_name,
inst_date, inst_time)
values ('000504', '*ST生物', '南华生物', '2017-05-29', '09:41:00');
"""
def name_record_to_db(_stock_id, _old_name, _new_name, _work_date, _db):
tm = get_time()
sql = "insert into tbl_name ( \
stock_id, stock_old_name, stock_new_name, \
inst_date, inst_time) \
values ('%s', '%s', '%s', '%s', '%s')" % (_stock_id, _old_name, _new_name, _work_date, tm)
log_debug("sql: \n%s", sql)
rv = sql_to_db_nolog(sql, _db)
if rv != 0:
log_error("error: record fupai: %s", sql)
return rv
def work_one(_stock_id, _name, _work_date, _db):
log_info("work_one [%s, %s] begin", _stock_id, _name)
begin = get_micro_second()
# new name
name = get_name(_stock_id)
if name.find("ST") != -1:
log_info("new name still keeps bad1")
return None
if name.find("退") != -1:
log_info("new name still keeps bad2")
return None
if name != _name:
log_info("nice: %s [%s => %s]", _stock_id, _name, name)
name_record_to_db(_stock_id, _name, name, _work_date, _db)
else:
log_info("old name")
name = None
log_debug("it costs %d us", get_micro_second() - begin)
return name
def name_check_to_notice(_work_date, _db):
sql = "select * from tbl_name where inst_date = '%s'" %(_work_date)
log_info("sql: %s", sql)
df = pd.read_sql_query(sql, _db);
if df is None:
log_info("'%s' not found in db", _stock_id)
return -1
else:
log_info("got data: %d lines", len(df))
content = ""
for row_index, row in df.iterrows():
stock_id = row['stock_id']
old_name = row['stock_old_name']
new_name = row['stock_new_name']
one = "%s 摘帽 [%s] => [%s] (%s)\n" % (stock_id, old_name, new_name, _work_date)
info = get_basic_info_all(stock_id, _db)
one += info
one += "++++++++++++++++++++++++++++++++++++++++\n"
log_debug("\n%s", one)
content += one
if len(content) > 0:
subject = "rename: %s" % (_work_date)
log_debug("mail: %s", subject)
log_debug("\n%s", content)
if sai_is_product_mode():
saimail(subject, content)
else:
pass
# saimail(subject, content)
def xxx(_db):
work_date = get_today()
basic = get_stock_list_df_tu()
if basic is None:
log_debug("error: get_stock_list_df_tu failure")
return -1
content = ""
for row_index, row in basic.iterrows():
stock_id = row_index
name = row['name']
if name.find("ST") != -1:
log_info("special treatment: [%s, %s]", stock_id, name)
new = work_one(stock_id, name, work_date, _db)
else:
pass
name_check_to_notice(work_date, _db)
return 0
def work():
db = db_init()
xxx(db)
db_end(db)
#######################################################################
def main():
sailog_set("name.log")
log_info("let's begin here!")
if sai_is_product_mode():
# check holiday
if today_is_weekend():
log_info("today is weekend, exit")
else:
log_info("today is workday, come on")
work()
else:
log_debug("test mode")
work()
log_info("main ends, bye!")
return
main()
exit()
#######################################################################
# name.py
| UTF-8 | Python | false | false | 3,981 | py | 175 | name.py | 168 | 0.491538 | 0.481687 | 0 | 170 | 22.288235 | 90 |
wuqiangroy/something | 16,243,566,326,712 | cd4caf3b7e9bfa6cd03e202987fff16ff5a7ef78 | 97fcdce230884a132f001381708e550c5215f7ad | /cookbook/multi_threading/12.4.py | 0837cae9cc884a2b5ede8c2ae52efb3523908cce | []
| no_license | https://github.com/wuqiangroy/something | 98138f6ab76a28eaf59f024f0ecedcb9bf049c06 | 5573f9833e33e5cc1261854307c81e5224d64219 | refs/heads/master | 2021-09-11T20:54:32.389061 | 2018-04-12T08:10:26 | 2018-04-12T08:10:26 | 71,707,794 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""對臨界區加鎖"""
import threading
class SharedCounter(object):
def __init__(self, initial_value=0):
self._value = initial_value
self._value_lock = threading.Lock()
def incr(self, delta=1):
self._value_lock.acquire()
self._value += delta
self._value_lock.release()
# with self._value_lock:
# self._value += delta
def decr(self, delta=1):
self._value_lock.acquire()
self._value -= delta
self._value_lock.release()
# with self._value_lock:
# self._value -= delta
| UTF-8 | Python | false | false | 639 | py | 93 | 12.4.py | 90 | 0.550239 | 0.54386 | 0 | 30 | 19.9 | 43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.