seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
36581229522 | # Script Name : git_repo_creator.py
# Author : Harish Tiwari
# Created : 2nd October 2020
# Last Modified : -
# Version : 1.0.0
# Modifications :
# Description : This python script will create a github repo from command line.
import requests
import json
user_name = input("Enter your github user name: ")
print(user_name)
github_token = input("Enter your github token: ")
print(github_token)
repo_name = input("Enter your repo Name: ")
print(repo_name)
repo_description = input("Enter your repo description: ")
print(repo_description)
payload = {'name': repo_name, 'description': repo_description, 'auto_init': 'true'}
repo_request = requests.post('https://api.github.com/' + 'user/repos', auth=(user_name,github_token), data=json.dumps(payload))
if repo_request.status_code == 422:
print("Github repo already exists try wih other name.")
elif repo_request.status_code == 201:
print("Github repo has created successfully.")
elif repo_request.status_code == 401:
print("You are unauthorized user for this action.")
| hastagAB/Awesome-Python-Scripts | Git_repo_creator/git_repo_creator.py | git_repo_creator.py | py | 1,065 | python | en | code | 1,776 | github-code | 13 |
73476233617 |
def buildTriangle(h):
''' Draws a triangle out of numbers with height h '''
count = 1
count1 = 0
for i in range(h):
count1 += 1
if (i < h/2):
for j in range(i):
print(count, end="")
count += 1
print("\n")
else:
count = count1
for j in range(h-i):
print(count, end="")
count += 1
count = count1 - (h - i) + 1
print("\n")
if __name__ == "__main__":
buildTriangle(8) | bsneeb/Interview-Practice-Problems | draw_number_triangle.py | draw_number_triangle.py | py | 570 | python | en | code | 0 | github-code | 13 |
35742780546 | import pygame
import settings as s
def partition(array, lowestIndex, highestIndex):
i = (lowestIndex - 1)
pivotNum = array[highestIndex]
s.numColor[highestIndex] = 1 ##pivot
s.drawScreen()
for j in range(lowestIndex, highestIndex):
s.numColor[j] = 2 ##checked num
if array[j] < pivotNum:
i += 1
s.numColor[i] = 2 ##swapped num
array[i] , array[j] = array[j] , array[i]
s.drawScreen()
s.numColor[i] = 0
s.numColor[j] = 0
array[i + 1] , array[highestIndex] = array[highestIndex], array[i + 1]
s.drawScreen()
s.numColor[highestIndex] = 0
s.numColor[lowestIndex] = 0
return(i + 1)
def quickSort(array, lowestIndex, highestIndex):
if lowestIndex < highestIndex:
s.drawScreen()
piviotIndex = partition(array, lowestIndex, highestIndex)
quickSort(array, lowestIndex, piviotIndex - 1)
for x in range (0 , piviotIndex + 1):
s.numColor[x] = 3
quickSort(array, piviotIndex + 1, highestIndex) | Mayank808/Pygames-Sorting-Visualizers- | VisualizerProgram/quickSort.py | quickSort.py | py | 1,116 | python | en | code | 0 | github-code | 13 |
2974096500 | from collections.abc import Iterator
class Company():
def __init__(self, employee_list):
self.employee = employee_list
def __iter__(self): # 自己定义迭代器时,一般不自己实现next函数,而是采用这种方法。
return MyIterator(self.employee)
def __getitem__(self, item):
return self.employee[item]
class MyIterator(Iterator):
def __init__(self, employee_list):
self.iter_list = employee_list
self.index = 0
def __next__(self):
try:
word = self.iter_list[self.index]
except IndexError:
raise StopIteration
self.index += 1
return word
if __name__ == '__main__':
company = Company(["t1", 't2'])
my_iter = iter(company) # 优先考虑__iter__如果没有再看__getitem__
for item in my_iter:
print(item)
for item in company:
print(item) | sangjianshun/Master-School | python_high_level/chapter09/iterable_iterator.py | iterable_iterator.py | py | 906 | python | en | code | 34 | github-code | 13 |
15217556092 | """
Author :Birhan Tesfaye
Last Edit :May 23
"""
from pdf import font
from pdf import natural_order
import json
SortBlocks=natural_order.SortBlocks
SortLines=natural_order.SortLines
SortSpans=natural_order.SortSpans
heading_name=["chapter","unit","part"]
heading_lvl=["zero","one","two","three","four","five","six","seven","eight","nine","ten","0","1","2","3","4","5","6","7","8","9"]
heading_sep=[" ",":"]
def remove_empty(List):
for i in List.copy():
if(i[0].strip()==""):
List.remove(i)
def identify_heading(txt,toc):
status=False
title=toc[1].lower()
text=txt[0].lower()
title=title.strip()
if(title==text):
status=True
return status
def identify_heading_name(txt):
status=False
text=txt.lower()
current_name=0
current_lvl=0
current_sep=0
while(True):
heading=heading_name[current_name]+heading_sep[current_sep]+heading_lvl[current_lvl]
if(text==heading):
status=True
else:
current_sep+=1
if(current_sep==len(heading_sep)):
current_sep=0
current_lvl+=1
if(current_lvl==len(heading_lvl)):
current_lvl=0
current_name+=1
if(current_name==len(heading_name)):
break
return status
def average(List):
total=0
for i in List:
total+=i[1]
average=total//len(List)
return average
def get_text(List):
text=''
for i in List:
text+=i[0]+' '
text=text.strip()
return text
def extractor(block,toc):
if("lines" in block.keys()):
lines=SortLines(block["lines"])
ln_text=[]
for line in lines:
if("spans" in line.keys()):
spans=SortSpans(line["spans"])
for span in spans:
text=span['text']
size=span["size"]
flag=font.flags_decomposer(span["flags"])
ln_text.append((text,size,flag))
size=average(ln_text)
remove_empty(ln_text)
text=get_text(ln_text)
text_type='content'
status=identify_heading_name(text)
if(status):
text_type="delete"
else:
is_header=identify_heading((text,size,flag),toc)
if(is_header):
text_type="heading_"+str(toc[0])
return [text,text_type]
| Birhant/PDF-summarizer | PDF Summarizer/PDF Summarizer (user edition)/pdf/extract.py | extract.py | py | 2,536 | python | en | code | 0 | github-code | 13 |
8546033382 | #-*- coding: utf-8 -*-
from tornado.gen import coroutine
from tornado.web import (authenticated, asynchronous)
from ..tools import (route, BaseHandler)
from pony.orm import (db_session,)
from ..entities import (Prestacion,)
from ..criterias import capabilityCrt
from json import dumps, loads
@route('/prestaciones/gestion')
class Gestion_Prestaciones(BaseHandler):
@authenticated
@db_session
@asynchronous
@coroutine
def get(self):
prestaciones = (pr for pr in Prestacion.select())
self.render('prestaciones/gestion.html', prestaciones=prestaciones, dumps=dumps)
@route('/prestaciones/nueva_prestacion')
class Nueva_Prestacion(BaseHandler):
@authenticated
@asynchronous
@coroutine
def get(self):
self.render('prestaciones/nueva_prestacion.html')
@asynchronous
@coroutine
def post(self):
self.set_header('Content-type', 'application/json')
status = capabilityCrt.save(**self.form2Dict())
self.finish(dumps(status))
@route('/prestaciones/modificar_prestacion')
class Modificar_prestacion(BaseHandler):
@authenticated
@db_session
@asynchronous
@coroutine
def get(self):
pr = Prestacion.get(**self.form2Dict())
self.render('prestaciones/modificar_prestacion.html', pr=pr)
@asynchronous
@coroutine
def post(self):
self.set_header('Content-type', 'application/json')
status = capabilityCrt.update(**self.form2Dict())
self.finish(dumps(status))
@route('/prestaciones/eliminar_prestacion')
class Eliminar_Prestacion(BaseHandler):
@asynchronous
@coroutine
def post(self):
self.set_header('Content-type', 'application/json')
status = capabilityCrt.delete(**self.form2Dict())
self.finish(dumps(status))
@route('/prestaciones/disponibles')
class Prestaciones_Disponibles(BaseHandler):
@db_session
@asynchronous
@coroutine
def post(self):
self.set_header('Content-type', 'application/json')
ids = loads(self.get_argument('prestaciones'))
disponibles = [dict(id_pst=pr.id_pst, nombre=pr.nombre) for pr in Prestacion.select() if pr.activo and pr.id_pst not in ids]
self.finish(dumps(disponibles)) | enlacescomunitarios/enlaces | app/views/prestaciones.py | prestaciones.py | py | 2,116 | python | en | code | 0 | github-code | 13 |
30160417328 | # -*- mode: python -*-
a = Analysis(['pyfanfou.py'],
pathex=['D:\\mcxiaoke\\pyfanfou'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='pyfanfou.exe',
debug=False,
strip=None,
upx=True,
console=False )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='pyfanfou')
| mcxiaoke/pyfanfou | pyfanfou.spec | pyfanfou.spec | spec | 607 | python | en | code | 50 | github-code | 13 |
71366111057 | from benchopt import BaseDataset, safe_import_context
from sklearn.preprocessing import StandardScaler
import numpy as np
with safe_import_context() as import_ctx:
from benchopt.datasets import make_correlated_data
class Dataset(BaseDataset):
name = "reg_sim"
parameters = {
'n_samples, n_features': [
(100, 10),
(300, 10),
(500, 10),
(700, 10),
(1000, 10)]
}
def __init__(self, n_samples=10, n_features=50, random_state=42):
self.n_samples = n_samples
self.n_features = n_features
self.random_state = random_state
def get_data(self):
X, y, _ = make_correlated_data(
n_samples=self.n_samples, n_features=self.n_features,
random_state=self.random_state
)
scaler = StandardScaler()
X = scaler.fit_transform(X)
n, d = X.shape
data = dict(X=X, y=y, q=0.1)
return data
| softmin/ReHLine-benchmark | benchmark_QR/datasets/reg_sim.py | reg_sim.py | py | 969 | python | en | code | 2 | github-code | 13 |
73539302738 | from urllib.request import urlopen
from lab_01.perceptron import *
__author__ = 'adkozlov'
def load_data(positive=1, negative=-1):
result = []
file = urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data")
for line in file.readlines():
array = line.decode("utf-8").split(',')
result.append(([1.0] + [float(f) for f in array[2:]], positive if array[1] == "M" else negative))
return result
def divide(data, fraction=0.1, speed_fraction=1.0):
np.random.shuffle(data)
data = data[:int(len(data) * speed_fraction)]
test_len = int(len(data) * fraction)
return data[test_len:], data[:test_len]
def test(data, w):
results = {'fp': 0, 'tp': 0, 'fn': 0, 'tn': 0}
for (x, y) in data:
yc = classify(w, x)
if y == 1:
results['tp' if yc == 1 else 'fn'] += 1
else:
results['tn' if yc == -1 else 'fp'] += 1
p = results['tp'] / (results['tp'] + results['fp'])
r = results['tp'] / (results['tp'] + results['fn'])
e = (results['fp'] + results['fn']) / len(data)
f_1 = 2 * p * r / (p + r)
return p, r, e, f_1
def percent(f):
return 100 * f
def main():
train_set, test_set = divide(load_data())
p, r, e, f_1 = test(test_set, train(train_set))
print('precision = %6.2f\nrecall = %6.2f\nerror = %6.2f\nF_1 = %f' % (percent(p), percent(r), percent(e), f_1))
if __name__ == "__main__":
main() | anton-bannykh/ml-2013 | andrew.kozlov/lab_01/main.py | main.py | py | 1,476 | python | en | code | 4 | github-code | 13 |
31266967552 | from utils import euler_lib
def main():
n = 10000
amicables = []
for a in range(1, n):
a_sum = sum(euler_lib.get_proper_factors(a))
# only add pair once [220, 284] not [220, 284, 284, 220]
b = a_sum
if a > b:
continue
b_sum = sum(euler_lib.get_proper_factors(b))
if a_sum == b and b_sum == a and a != b:
amicables.append(a)
amicables.append(b)
return sum(amicables)
if __name__ == "__main__":
print(main())
| stephendwillson/ProjectEuler | solutions/python/problem_21.py | problem_21.py | py | 522 | python | en | code | 0 | github-code | 13 |
26843007191 | import logging
import sys
from pathlib import Path
from http.server import HTTPServer, BaseHTTPRequestHandler
# Add repo root to path to make config_composer importable
repo_root = str(Path(__file__).absolute().parent.parent.parent)
sys.path.append(repo_root)
from config_composer.core import Config, Spec # noqa: E402s
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ConfigSpec(Spec):
host: str
port: int
db_pass: str
config = Config(config_spec=ConfigSpec, env_var="SOURCE_SPEC_PATH")
def mock_query_db():
# password = config.db_pass
return "Bob"
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
username = mock_query_db().encode()
self.send_response(200)
self.end_headers()
self.wfile.write(b"Hello, " + username)
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
logger.info(f"Serving on {config.host}:{config.port}")
server_address = (config.host, config.port)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == "__main__":
run()
| tomdottom/config-composer | examples/simple_http/server.py | server.py | py | 1,153 | python | en | code | 0 | github-code | 13 |
6226696465 | import numpy as np
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return result
def frombits(bits):
chars = []
for b in range(len(bits) // 8):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
#Recibe una matriz de pixeles y el mensajes a encriptar
#La encriptación se basa en la converisión de cada valor R, G y V. Si estos son pares
#entonces arrojarán un valor 0 y si son pares un 1, con la combinación de 3 pixeles RGB
#se forma un número binario de 9 dígitos, 8 se usan para obtener el valor ascii y el último se usa para saber
# si restan caracteres para codificar, 0 para continuar y y para detenerse
def encode(data,message):
messageCounter = 0
data = np.array(data)
char = tobits(message[0])
bitCounter = 0;
for row in range(data.shape[0]):#Recorrer pixel por pixel
for cell in range(data.shape[1]):
for color in range(3):
if(bitCounter==8):
bitCounter = -1
messageCounter+=1
if(messageCounter>=len(message)):
if(data[row][cell][color]%2==0):
data[row][cell][color] -= 1
return(data)
else:
if(data[row][cell][color]%2==1):
data[row][cell][color] -=1
char = tobits(message[messageCounter])#Convertir el siguiente caracter
elif(data[row][cell][color]%2 != char[bitCounter]):
data[row][cell][color] += -1
bitCounter+=1
print(data)
def decode(data):
message = ""
data = np.array(data)
bitStack = []
for row in range(data.shape[0]):
for cell in range(data.shape[1]):
for color in range(3):
bitStack.append(data[row][cell][color]%2)
if(len(bitStack)==8):
message += frombits(bitStack)
elif(len(bitStack)==9):
bitStack = []
if(data[row][cell][color]%2 == 1):
return message
| AlexGlz/Queztal-Copiler | Código/Steganography.py | Steganography.py | py | 2,339 | python | es | code | 0 | github-code | 13 |
28105217059 | #!/usr/bin/env python3
class Day01:
def __init__(self, file):
self.numbers = [int(line) for line in open(file).readlines()]
def run_part1(self):
return sum(self.numbers)
def run_part2(self):
sums = set()
freq = 0
while True:
for number in self.numbers:
freq += number
if freq in sums:
return freq
sums.add(freq)
def test1():
test_day01 = Day01('./day01-test.input')
assert test_day01.run_part1() == 2
assert test_day01.run_part2() == 2
day01 = Day01('./day01.input')
assert day01.run_part1() == 556
assert day01.run_part2() == 448
if __name__ == '__main__':
print("advent of code: day01")
day01 = Day01('./day01.input')
print(f"part 1: {day01.run_part1()}")
print(f"part 2: {day01.run_part2()}")
| danschaffer/aoc | 2018/day01.py | day01.py | py | 873 | python | en | code | 0 | github-code | 13 |
73605357138 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
from collections import Counter
# @Author: 花菜
# @File: 424替换后的最长重复字符.py
# @Time : 2023/5/17 17:02
# @Email: lihuacai168@gmail.com
# 给你一个字符串
# s
# 和一个整数
# k 。你可以选择字符串中的任一字符,并将其更改为任何其他大写英文字符。该操作最多可执行
# k
# 次。
#
# 在执行上述操作后,返回包含相同字母的最长子字符串的长度。
#
#
#
# 示例
# 1:
#
# 输入:s = "ABAB", k = 2
# 输出:4
# 解释:用两个
# 'A'
# 替换为两个
# 'B', 反之亦然。
# 示例
# 2:
#
# 输入:s = "AABABBA", k = 1
# 输出:4
# 解释:
# 将中间的一个
# 'A'
# 替换为
# 'B', 字符串变为
# "AABBBBA"。
# 子串
# "BBBB"
# 有最长重复字母, 答案为
# 4。
# 可能存在其他的方法来得到同样的结果。
# 滑动窗口
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# 设置左右指针为窗口的两边
# 右边指针开始滑动
# 把元素加入到窗口
# 更新最长的重复长度
# 如果统计窗口内,除了最多的元素外,其他元素个数大于k时,移除窗口最左侧的元素
window = []
left, right = 0, 0
max_repeat = 1
while right < len(s):
window.append(s[right])
# 会超时
c = Counter(window)
if len(c.keys()) > 1 and c.most_common(1):
if len(window) - c.most_common(1)[0][1] > k:
window.pop(0)
max_repeat = max(max_repeat, len(window))
right += 1
return max_repeat
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# 设置左右指针为窗口的两边
# 右边指针开始滑动
# 把元素加入到窗口
# 更新最长的重复长度
# 如果统计窗口内,除了最多的元素外,其他元素个数大于k时,移除窗口最左侧的元素
count = [0] * 26 # 另类窗口
left = right = 0
max_count = 0
mex_len = 0
while right < len(s):
count[ord(s[right]) - ord("A")] += 1
max_count = max(max_count, count[ord(s[right]) - ord("A")])
if right - left + 1 > max_count + k:
# 窗口左侧移除
count[ord(s[left]) - ord("A")] -= 1
left += 1
max_len = max(mex_len, right - left + 1)
right += 1
return max_len
| lihuacai168/LeetCode | 字符串/424替换后的最长重复字符.py | 424替换后的最长重复字符.py | py | 2,578 | python | zh | code | 4 | github-code | 13 |
8276196702 |
#num is a identifer and 10 is the value
c_name="luminarTechnolagy"
location="kakande"
print("company",c_name,"is_located",location)
name="ajay"
age="29"
print(name,"is",age,"years old") | deepak368/luminarpython | LanguageFundamentals/Identifiers.py | Identifiers.py | py | 189 | python | en | code | 0 | github-code | 13 |
22249702886 | """
calculate BIC and WBIC
"""
from __future__ import print_function
import argparse
import glob
import os
import pickle
import pandas as pd
from _information_criterion import get_n_injections, get_n_params
from _information_criterion import load_model, get_values_from_trace_files
from _information_criterion import log_likelihood_trace
from _information_criterion import bic_bootstrap, wbic_bootstrap, aic_bootstrap
parser = argparse.ArgumentParser()
parser.add_argument("--two_component_mcmc_dir", type=str,
default="/home/tnguye46/bayesian_itc_racemic/07.twocomponent_mcmc/pymc3_nuts_2")
parser.add_argument("--racemic_mixture_mcmc_dir", type=str,
default="/home/tnguye46/bayesian_itc_racemic/08.racemicmixture_mcmc/pymc3_nuts_2")
parser.add_argument("--enantiomer_mcmc_dir", type=str,
default="/home/tnguye46/bayesian_itc_racemic/09.enantiomer_mcmc/pymc3_nuts_2")
parser.add_argument("--repeat_prefix", type=str, default="repeat_")
parser.add_argument("--exclude_repeats", type=str, default="")
parser.add_argument("--model_pickle", type=str, default="pm_model.pickle")
parser.add_argument("--trace_pickle", type=str, default="trace_obj.pickle")
parser.add_argument("--heat_data_dir", type=str, default="/home/tnguye46/bayesian_itc_racemic/04.heat_in_origin_format")
parser.add_argument("--experiments", type=str,
default="Fokkens_1_a Fokkens_1_b Fokkens_1_c Fokkens_1_d Fokkens_1_e Baum_57 Baum_59 Baum_60_1 Baum_60_2 Baum_60_3 Baum_60_4")
parser.add_argument("--bootstrap_repeats", type=int, default=1000)
args = parser.parse_args()
def is_path_excluded(path, exclude_kws):
for kw in exclude_kws:
if kw in path:
return True
return False
exclude_repeats = args.exclude_repeats.split()
exclude_repeats = [args.repeat_prefix + r for r in exclude_repeats]
print("exclude_repeats:", exclude_repeats)
experiments = args.experiments.split()
print("experiments", experiments)
bics = {}
wbics = {}
aics = {}
for exper in experiments:
print("\n\n", exper)
bics[exper] = {}
wbics[exper] = {}
aics[exper] = {}
dirs_2c = glob.glob(os.path.join(args.two_component_mcmc_dir, args.repeat_prefix + "*", exper, args.trace_pickle))
dirs_2c = [os.path.dirname(p) for p in dirs_2c]
dirs_2c = [p for p in dirs_2c if not is_path_excluded(p, exclude_repeats)]
print("dirs_2c:", dirs_2c)
dirs_rm = glob.glob(os.path.join(args.racemic_mixture_mcmc_dir, args.repeat_prefix + "*", exper, args.trace_pickle))
dirs_rm = [os.path.dirname(p) for p in dirs_rm]
dirs_rm = [p for p in dirs_rm if not is_path_excluded(p, exclude_repeats)]
print("dirs_rm:", dirs_rm)
dirs_em = glob.glob(os.path.join(args.enantiomer_mcmc_dir, args.repeat_prefix + "*", exper, args.trace_pickle))
dirs_em = [os.path.dirname(p) for p in dirs_em]
dirs_em = [p for p in dirs_em if not is_path_excluded(p, exclude_repeats)]
print("dirs_em:", dirs_em)
heat_file = os.path.join(args.heat_data_dir, exper + ".DAT")
n_injections = get_n_injections(heat_file)
print("n_injections:", n_injections)
model_2c = load_model(os.path.join(dirs_2c[0], args.model_pickle))
model_rm = load_model(os.path.join(dirs_rm[0], args.model_pickle))
model_em = load_model(os.path.join(dirs_em[0], args.model_pickle))
n_params_2c = get_n_params(model_2c)
n_params_rm = get_n_params(model_rm)
n_params_em = get_n_params(model_em)
trace_files_2c = [os.path.join(d, args.trace_pickle) for d in dirs_2c]
trace_files_rm = [os.path.join(d, args.trace_pickle) for d in dirs_rm]
trace_files_em = [os.path.join(d, args.trace_pickle) for d in dirs_em]
traces_2c = get_values_from_trace_files(model_2c, trace_files_2c)
traces_rm = get_values_from_trace_files(model_rm, trace_files_rm)
traces_em = get_values_from_trace_files(model_em, trace_files_em)
log_llhs_2c = log_likelihood_trace(model_2c, traces_2c)
log_llhs_rm = log_likelihood_trace(model_rm, traces_rm)
log_llhs_em = log_likelihood_trace(model_em, traces_em)
# BIC
bic, bic_std = bic_bootstrap(log_llhs_2c, n_injections, n_params_2c, repeats=args.bootstrap_repeats)
bics[exper]["2C"] = bic
bics[exper]["2C_std"] = bic_std
bic, bic_std = bic_bootstrap(log_llhs_rm, n_injections, n_params_rm, repeats=args.bootstrap_repeats)
bics[exper]["RM"] = bic
bics[exper]["RM_std"] = bic_std
bic, bic_std = bic_bootstrap(log_llhs_em, n_injections, n_params_em, repeats=args.bootstrap_repeats)
bics[exper]["EM"] = bic
bics[exper]["EM_std"] = bic_std
# WBIC
wbic, wbic_std = wbic_bootstrap(log_llhs_2c, n_injections, repeats=args.bootstrap_repeats)
wbics[exper]["2C"] = wbic
wbics[exper]["2C_std"] = wbic_std
wbic, wbic_std = wbic_bootstrap(log_llhs_rm, n_injections, repeats=args.bootstrap_repeats)
wbics[exper]["RM"] = wbic
wbics[exper]["RM_std"] = wbic_std
wbic, wbic_std = wbic_bootstrap(log_llhs_em, n_injections, repeats=args.bootstrap_repeats)
wbics[exper]["EM"] = wbic
wbics[exper]["EM_std"] = wbic_std
# AIC
aic, aic_std = aic_bootstrap(log_llhs_2c, n_params_2c, repeats=args.bootstrap_repeats)
aics[exper]["2C"] = aic
aics[exper]["2C_std"] = aic_std
aic, aic_std = aic_bootstrap(log_llhs_rm, n_params_rm, repeats=args.bootstrap_repeats)
aics[exper]["RM"] = aic
aics[exper]["RM_std"] = aic_std
aic, aic_std = aic_bootstrap(log_llhs_em, n_params_em, repeats=args.bootstrap_repeats)
aics[exper]["EM"] = aic
aics[exper]["EM_std"] = aic_std
bics = pd.DataFrame(bics).T
wbics = pd.DataFrame(wbics).T
aics = pd.DataFrame(aics).T
bics.to_csv("bic.csv", float_format="%0.5f", index=True)
wbics.to_csv("wbic.csv", float_format="%0.5f", index=True)
aics.to_csv("aic.csv", float_format="%0.5f", index=True)
print("DONE")
| nguyentrunghai/bayesian_itc_racemic | scripts/run_cal_information_criterion.py | run_cal_information_criterion.py | py | 5,861 | python | en | code | 0 | github-code | 13 |
34511433150 | #!/usr/bin/python
# -*- coding: utf8 -*-
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Luis F. Simoes
# Joerg H. Mueller
import numpy as np
from .util import *
def brute_force(n, k):
"""
Determines the score of all k-subset sequences according to the objective.
Runs through all possible permutations of k-subset sequences and scores
them according to the objective.
Runs for up to n = 5 in a reasonable amount of time. Higher values for
n are not recommended.
"""
def _score_sequence(scenes, sequence):
score = 0
removed = len(scenes) + len(sequence)
for i, subset in enumerate(sequence):
matched = np.bitwise_and(scenes, subset) == subset
# score it's the (i + 1)th index and the other +1 is for the scene == subset (which is not included in scenes)
last = removed
removed = (matched.sum() + 1)
# if only interested in the number of optimal solutions, the next
# two lines can skip sequences not having the monotonicity property.
#if removed > last:
# return -1
score += removed * (i + 1)
scenes = scenes[~matched]
return score
def _perm(n):
p = np.arange(n + 1) - 1
p[0] = 0
yield p[1:]
while True:
i = n - 1
while p[i] > p[i + 1]:
i -= 1
if i < 1:
return
j = n
while p[i] > p[j]:
j -= 1
p[[i, j]] = p[[j, i]]
r = n
s = i + 1
while r > s:
p[[r, s]] = p[[s, r]]
r -= 1
s += 1
yield p[1:]
scenes, sequence = make_scenario(n, k)
scores = {}
for permutation in _perm(len(sequence)):
seq = sequence[permutation]
score = _score_sequence(scenes, seq)
if score in scores:
scores[score] += 1
else:
scores[score] = 1
return scores
##### --------------------------------------------------------------------
def tree_search(n, k):
"""
Finds one optimal k-subset sequence according to the objective.
Uses several properties of the objective to prune branches of the tree
that are guaranteed to contain at best solutions equal to the current
best.
Runs for up to n = 6 in a reasonable amount of time. Higher values for
n are not recommended.
"""
def _check_group(groups, value):
# Note: this algorithm does not exclude all possible element permutations!
# It's good enough though for the values of n, k that the tree_search can handle.
new_groups = []
for group, shift in groups:
a = (value >> shift) & group
if a & (a >> 1) != (a >> 1):
return False
if a != 0 and a != group:
lens = bit_count_32([group, a])
if lens[0] > 1:
new_groups.append(((group & (~a)) >> lens[1], shift + lens[1]))
if lens[1] > 1:
new_groups.append((a, shift))
else:
new_groups.append((group, shift))
return new_groups
scenes, seq = make_scenario(n, k)
seq_len = len(seq)
best_seq = [seq.copy()]
best_score = len(scenes) * seq_len
removed_scenes = [[] for i in seq]
stack = []
group_stack = []
score_stack = []
removed = len(scenes) + seq_len
groups = [((1 << n) - 1, 0)]
# the first grouping would remove all other elements, so we can just start
# with [0] instead of range(seq_len)
for i in [0]:
stack.append((0, i, False))
stack.append((0, i, True))
group_stack.append(groups.copy())
score_stack.append((0, removed))
while stack != []:
start, index, enter = stack.pop()
seq[start], seq[index] = seq[index], seq[start]
if enter:
groups = group_stack.pop()
score, last_removed = score_stack.pop()
if start == seq_len - 1:
score = score + start + 1
if score < best_score:
best_score = score
best_seq = [seq.copy()]
elif score == best_score:
best_seq.append(seq.copy())
else:
if groups != []:
groups = _check_group(groups, seq[start])
if groups == False:
continue
matched = np.bitwise_and(scenes, seq[start]) == seq[start]
# removed scenes are the matched scenes plus the scene that equals the sequence
removed = matched.sum() + 1
if removed > last_removed or removed == 1:
continue
# ttd = start + 1
score += removed * (start + 1)
remaining_scenes = len(scenes) - removed + 1
quick_remove = remaining_scenes // (removed - 1)
last_remove = remaining_scenes % (removed - 1)
last_remove_start = start + quick_remove
# an even closer bound, but computationally more expensive (so less performant) would be:
#if score + (start + seq_len + 2) * (seq_len - start - 1) // 2 + last_remove * (last_remove_start + 1) + quick_remove * (last_remove_start - 4 - start) * (last_remove_start + 2 + start) // 2 > best_score:
if score + (start + seq_len + 2) * (seq_len - start - 1) // 2 + (start + 1) * (len(scenes) - removed) > best_score:
continue
removed_scenes[start] = scenes[matched]
scenes = scenes[~matched]
if len(scenes) == 0:
stack.append((seq_len - 1, seq_len - 1, False))
stack.append((seq_len - 1, seq_len - 1, True))
group_stack.append(groups.copy())
score_stack.append((score + np.sum(np.arange(start + 2, seq_len)), 1))
else:
for i in range(start + 1, seq_len):
stack.append((start + 1, i, False))
stack.append((start + 1, i, True))
group_stack.append(groups.copy())
score_stack.append((score, removed))
else: # exit
scenes = np.array(np.hstack([removed_scenes[start], scenes]), dtype=np.uint32)
removed_scenes[start] = []
return best_seq, best_score
##### --------------------------------------------------------------------
def gse(n, k, lex_order = True, keep_order = True):
"""
Greedy Scene Elimination sequence.
Iterator over the `k`-element subsets drawn out of `n` elements.
Produces at each step the subset discovering the highest number
of scenes considering all undiscovered scenes so far.
The default base is the lexicographic order and can be changed to
colexicographic with the parameter `lex_order` set to False.
Ties are broken with the first element in the remaining sequence
eliminating the highest number of scenes.
The `keep_order` parameter ensures that ties resolve in the order
of the base sequence. If set to False this order is not kept
similar to an unstable sorting algorithm.
"""
scenes, seq = make_scenario(n, k)
if lex_order:
from itertools import combinations
seq = [int(np.bitwise_or.reduce(1 << np.array(x))) for x in combinations(range(n), k)]
seq_len = len(seq)
# at the beginning every subset removes 2 ** (n - k) scenes (including the subset itself)
removing = np.ones(seq_len) * (2 ** (n - k) - 1)
for start in range(seq_len):
max_i = np.argmax(removing[start:]) + start
matched = np.bitwise_and(scenes, seq[max_i]) == seq[max_i]
if max_i != start:
# the following line preserves the original order
if keep_order:
temp = seq[start]
seq[start] = seq[max_i]
seq[start + 2:max_i + 1] = seq[start + 1:max_i]
seq[start + 1] = temp
temp = removing[start]
removing[start] = removing[max_i]
removing[start + 2:max_i + 1] = removing[start + 1:max_i]
removing[start + 1] = temp
else:
seq[start], seq[max_i] = seq[max_i], seq[start]
removing[start], removing[max_i] = removing[max_i], removing[start]
matched_scenes = scenes[matched]
scenes = scenes[~matched]
if len(scenes) == 0: # early stopping
break
for i in range(start + 1, seq_len):
new_matched = np.bitwise_and(matched_scenes, seq[i]) == seq[i]
removing[i] -= np.sum(new_matched)
return binary_to_sequence(seq, n)
##### --------------------------------------------------------------------
def mis(n, k, keep_order = True):
"""
Minimally intersecting subsets sequence.
Iterator over the `k`-element subsets drawn out of `n` elements.
Produces at each step the subset having the lowest degree of
overlap with all the subsets produced up to that point (ties
broken in favour of lowest rank in a lexicographic ordering).
"""
assert n <= 32, 'Only implemented for n <= 32.'
# generate all possible subsets, represented as unsigned ints
sequence = np.array(list(colex_uint(n,k)), dtype=np.uint32)
# cumulative score by which to rate subsets
cumul_score = np.zeros(len(sequence), dtype=np.uint64)
for start in range(len(sequence) - 1):
# find among the remaining subsets, the index to the one with
# lowest degree of overlap with all the subsets produced so far
ix = cumul_score.argmin()
max_i = ix + start
subset = sequence[max_i]
if max_i != start:
# the following line preserves the original order
if keep_order:
temp = sequence[start]
sequence[start] = sequence[max_i]
sequence[start + 2:max_i + 1] = sequence[start + 1:max_i]
sequence[start + 1] = temp
else:
sequence[start], sequence[max_i] = sequence[max_i], sequence[start]
#sequence[ix:-1] = sequence[ix+1:]
cumul_score[ix:-1] = cumul_score[ix+1:]
#sequence = sequence[:-1]
cumul_score = cumul_score[:-1]
# number of common elements among subset `subs[ix]` and all those in sub
nr_common = bit_count_32(np.bitwise_and(subset, sequence[start + 1:]))
# increment the ratings of each subset in `m` by `base` raised
# to the power of the number of elements in common with the
# last yielded subset
cumul_score += (1 << nr_common) - 1
return binary_to_sequence(sequence, n)
##### --------------------------------------------------------------------
def base_unrank(n, k, base=2, unrank_func=None):
"""
k-element subsets generation by "Base Unranking"
"""
from math import log, ceil
from itertools import product
# unranking function to use; one of:
# k_subset_lex_unrank, k_subset_colex_unrank, k_subset_revdoor_unrank
if unrank_func is None:
from .ksubsets import revdoor_unrank
unrank_func = revdoor_unrank
# get the number of subsets in the sequence
seq_len = bin_coef(n, k)
# get the number of digits required in the given numeral system `base`
# to count up to `seq_len`
nr_digits = int(ceil(log(seq_len) / log(base)))
# count from 0 to base**nr_digits - 1, by prioritizing increments to the
# most significant digits, skipping values greater than `seq_len`, and
# "unranking" the remaining ones (unranking generates the n-th subset
# in a given reference sequence, such as lex, colex, or revdoor).
for s in product(*[ [j*(base**i) for j in range(base)] for i in range(nr_digits) ]):
rank = sum(s)
if rank >= seq_len:
continue
yield unrank_func(n, k, rank)
##### --------------------------------------------------------------------
# --------------------------------------------------------------------
# Pattern generation algorithm based on:
#
# Mortari, D., Samaan, M. A., Bruccoleri, C., & Junkins, J. L.
# (2004). The pyramid star identification technique. Navigation,
# 51(3), 171-183.
# --------------------------------------------------------------------
def pattern_generator(n, k, base=None):
"""
k-element subsets generation by pattern repetition of some base sequence.
By default a recursive pattern generator.
"""
if base is None:
base = pattern_generator
if k == 0:
yield []
return
for pattern in base(n - 1, k - 1):
pattern = [0] + [i+1 for i in pattern]
yield pattern
while pattern[-1] != n-1:
pattern = [i+1 for i in pattern]
yield pattern
| neXyon/k-subsets | ksubsets/algorithms.py | algorithms.py | py | 13,268 | python | en | code | 0 | github-code | 13 |
34795623659 | #!/usr/bin/env python3
# File name : move.py
# Description : Control Motor
# Product : PiCar-C
# Website : www.adeept.com
# Author : William
# Date : 2019/11/21
import time
import RPi.GPIO as GPIO
# motor_EN_A: Pin7 | motor_EN_B: Pin11
# motor_A: Pin8,Pin10 | motor_B: Pin13,Pin12
Motor_A_EN = 4
Motor_B_EN = 17
Motor_A_Pin1 = 14
Motor_A_Pin2 = 15
Motor_B_Pin1 = 27
Motor_B_Pin2 = 18
Dir_forward = 0
Dir_backward = 1
pwn_A = 0
pwm_B = 0
def motorStop():#Motor stops
GPIO.output(Motor_A_Pin1, GPIO.LOW)
GPIO.output(Motor_A_Pin2, GPIO.LOW)
GPIO.output(Motor_B_Pin1, GPIO.LOW)
GPIO.output(Motor_B_Pin2, GPIO.LOW)
GPIO.output(Motor_A_EN, GPIO.LOW)
GPIO.output(Motor_B_EN, GPIO.LOW)
def setup():#Motor initialization
global pwm_A, pwm_B
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(Motor_A_EN, GPIO.OUT)
GPIO.setup(Motor_B_EN, GPIO.OUT)
GPIO.setup(Motor_A_Pin1, GPIO.OUT)
GPIO.setup(Motor_A_Pin2, GPIO.OUT)
GPIO.setup(Motor_B_Pin1, GPIO.OUT)
GPIO.setup(Motor_B_Pin2, GPIO.OUT)
motorStop()
try:
pwm_A = GPIO.PWM(Motor_A_EN, 1000)
pwm_B = GPIO.PWM(Motor_B_EN, 1000)
except:
pass
def motor_A(direction, speed):#Motor 2 positive and negative rotation
if direction == Dir_backward:
GPIO.output(Motor_B_Pin1, GPIO.HIGH)
GPIO.output(Motor_B_Pin2, GPIO.LOW)
pwm_A.start(100)
pwm_A.ChangeDutyCycle(speed)
elif direction == Dir_forward:
GPIO.output(Motor_B_Pin1, GPIO.LOW)
GPIO.output(Motor_B_Pin2, GPIO.HIGH)
pwm_A.start(100)
pwm_A.ChangeDutyCycle(speed)
def motor_B(direction, speed):#Motor 1 positive and negative rotation
if direction == Dir_forward:#
GPIO.output(Motor_A_Pin1, GPIO.HIGH)
GPIO.output(Motor_A_Pin2, GPIO.LOW)
pwm_B.start(100)
pwm_B.ChangeDutyCycle(speed)
elif direction == Dir_backward:
GPIO.output(Motor_A_Pin1, GPIO.LOW)
GPIO.output(Motor_A_Pin2, GPIO.HIGH)
pwm_B.start(0)
pwm_B.ChangeDutyCycle(speed)
def move(speed, direction): # 0 < radius <= 1
if direction == 'forward':
motor_A(0, speed)
motor_B(1, speed)
elif direction == 'backward':
motor_A(1, speed)
motor_B(0, speed)
elif direction == 'no':
motorStop()
else:
pass
def destroy():
motorStop()
GPIO.cleanup() # Release resource
if __name__ == '__main__':
try:
setup()
move(100, 'forward')
time.sleep(1.3)
motorStop()
destroy()
except KeyboardInterrupt:
destroy()
| adeept/adeept_picar-b | server/GUImove.py | GUImove.py | py | 2,408 | python | en | code | 21 | github-code | 13 |
72543473299 | from gspread import Client as GSpreadClient
import requests
import json
import openai
from oauth2client.service_account import ServiceAccountCredentials
# from dotenv import load_dotenv
# load_dotenv()
def write_expense_to_spreadsheet(Product_Codes, Price, Client, Client_Code, Orders, Total):
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('filename', scope)
gspread_client = GSpreadClient(creds)
spreadsheet_id = ""
sheet = gspread_client.open_by_key(spreadsheet_id).sheet1
sheet.append_row([Product_Codes, Price, Client, Client_Code, Orders, Total])
WEBHOOK_URL = ""
def post_message_to_slack_via_webhook(message):
payload = {'text': message}
response = requests.post(
WEBHOOK_URL, data=json.dumps(payload),
headers={'Content-Type': 'application/json'}
)
if response.ok:
print('Message sent successfully')
else:
print('Failed to send message. Error:', response.text)
openai.api_key = "OPENAI_API"
def run_conversation():
user_input=input("user_input:")
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=[
{"role": "system", "content": "You are the best assistant ever!"},
{"role": "user", "content": user_input}],
functions=[
{
"name": "write_expense_to_spreadsheet",
"description": "Cosmetics Inc.",
"parameters": {
"type": "object",
"properties": {
"Product Codes": {"type": "number"},
"Price": {"type": "number"},
"Client": {"type": "number"},
"Client Code": {"type": "string"},
"Orders" : {"type": "number"},
"Total" : {"type": "number"},
},
"required": ["Product Codes", "Price", "Client", "Client Code", "Orders", "Total"],
},
},
{
"name": "post_message_to_slack_via_webhook",
"description": "Post a message to Slack",
"parameters": {
"type": "object",
"properties": {
"message": {"type": "string"},
},
"required": ["message"],
},
}
],
function_call="auto",
)
message = response["choices"][0]["message"]
except Exception as Error:
print('here text :',Error)
if message.get("function_call"):
function_name = message["function_call"]["name"]
arguments = json.loads(message["function_call"]["arguments"])
# print(arguments)
print(message["function_call"]["arguments"])
if function_name == "write_expense_to_spreadsheet":
function_response = write_expense_to_spreadsheet(
Product_Codes=arguments.get("Product Codes"),
Price=arguments.get("Price"),
Client=arguments.get("Client"),
Client_Code=arguments.get("Client Code"),
Orders=arguments.get("Orders"),
Total=arguments.get("Total")
)
elif function_name == "post_message_to_slack_via_webhook":
function_response = post_message_to_slack_via_webhook(
message=arguments.get("message"),
)
else:
raise NotImplementedError()
second_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
# get user input
messages=[
{"role": "user", "content": user_input},
message,
{
"role": "function",
"name": function_name,
"content": str(function_response),
},
],
)
return second_response
else:
return response
print("response:", run_conversation()["choices"][0]["message"]["content"], "\n\n")
| tarikkaoutar/OPENAI_Function | cold_email.py | cold_email.py | py | 4,504 | python | en | code | 0 | github-code | 13 |
20771771152 | import cx_Freeze
executables = [cx_Freeze.Executable(
script="game_principal.py", icon="assets/pikachu.ico")]
cx_Freeze.setup(
name="Pokémon Dodge",
options={"build_exe": {"packages": ["pygame"],
"include_files": ["assets"]
}},
executables=executables
) | DolAndi/game_Imed2d- | setup.py | setup.py | py | 325 | python | en | code | 0 | github-code | 13 |
16883639774 | import os
import cv2
import glob
import numpy as np
import pandas as pd
participants = next(os.walk('/home/ausmanpa/gp/VEGA/experiments/E01/data/.'))[1]
participants = [part for part in participants if len(glob.glob('/home/ausmanpa/gp/VEGA/experiments/E01/data/'+part+'/*.jpg'))==34]
partInts = [int(x) for x in participants]
stimFNames = glob.glob('/home/ausmanpa/gp/VEGA/experiments/E01/data/001/*.jpg')
stimFNames = [x[-10:] for x in stimFNames]
for stimulus in stimFNames:
print('Numbering stimulus '+stimulus+' for all participants...')
if not os.path.isdir('/home/ausmanpa/gp/VEGA/experiments/E01/numberedPartStimImages/'+stimulus[0:-4]):
os.mkdir('/home/ausmanpa/gp/VEGA/experiments/E01/numberedPartStimImages/'+stimulus[0:-4])
numberedStimImage = cv2.imread('/home/ausmanpa/gp/VEGA/experiments/E01/stimuli/numbered_jpg/'+stimulus)
for part in participants:
partImage = cv2.imread('/home/ausmanpa/gp/VEGA/experiments/E01/data/'+part+'/'+stimulus)
partImage = np.delete(partImage, (3300), axis=0)
partImage[np.where(numberedStimImage!=255)] = numberedStimImage[np.where(numberedStimImage!=255)]
cv2.imwrite('/home/ausmanpa/gp/VEGA/experiments/E01/numberedPartStimImages/'+stimulus[0:-4]+'/p'+part+'_'+stimulus[0:-4]+'.jpg',partImage)
| pjrice/VEGA | experiments/E01/numberStimImages.py | numberStimImages.py | py | 1,349 | python | en | code | 0 | github-code | 13 |
34129714162 | from tkinter import *
import math
class Main_menu(Frame):
def __init__(self,master,db,admin_access):
super(Main_menu,self).__init__(master)
self.grid(sticky=N+S+W+E)
self.master=master
self.admin_access=admin_access
self.db=db
self.create_widgets()
def create_widgets(self):
self.frames=["Equipment Entry","Software details","AMC Details"
,"Update/Repair Details", "Vendor Details","Transfer Details",
"Item Issue/ Return Details","Purchase Order Details"]
self.admin_frames=["Staff Master","User Master","Item Master","Department Master"]
self.user_cnt=8;
if self.admin_access:
self.user_cnt=0;
self.frames.extend(self.admin_frames)
self.count=1;
textfont=('verdana',10)
width=(self.master.winfo_screenwidth())//(14*len(self.frames))
mainframe = Frame(self,bg="#34495e")
mainframe.grid(row=0,column=0,columnspan=3,sticky=N+W+E)
self.opt=[]
for items in self.frames:
self.opt.append(Button(mainframe,
text=items,
relief=GROOVE,
font=textfont,
bg="#bdc3c7",
activebackground="#bdc3c7",
height=2,
wraplength=110,
width=width,
command=lambda name=items,ref=self.count-1:self.selection(ref,name)
))
self.opt[-1].grid(row=0,
column=self.count,
ipadx=16+self.user_cnt,
sticky=N+S+W+E)
self.count+=1
self.dashboard=Frame(self,bg="#34495e")
self.dashboard.grid(row=1,column=0,sticky=N+S+W+E)
#X=__import__('dashboard')
#X.Dashboard(self.dashboard,self.db)
self.content=Frame(self,bg="#34495e")
self.content.grid(row=1,column=1,sticky=N+S+W+E)
self.opt[0].config(bg="black",fg="white")
self.content.depts=self.master.depts
self.content.admin_access=self.admin_access
X=__import__('src.dependencies.Equipment',fromlist=('Equipment'))
X.Equipment(self.content,self.db,True)
self.error=Frame(self,bg="#34495e")
self.error.grid(row=1,column=2,sticky=N+S+W+E)
#X=__import__('dashboard')
#X.Dashboard(self.error,self.db)
self.master.rowconfigure(0,weight=1)
self.master.columnconfigure(0,weight=1)
self.columnconfigure(0,weight=1)
#self.columnconfigure(1,weight=1)
self.columnconfigure(2,weight=1)
self.rowconfigure(1,weight=1)
def selection(self,ref,item):
for cnt in range(self.count-1):
self.opt[cnt].config(bg="#bdc3c7",fg="black")
self.opt[ref].config(bg="black",fg="white")
self.content.destroy()
self.content = Frame(self,bg="#34495e",relief=GROOVE)
self.content.grid(row=1,column=1,sticky=N+S+W+E)
self.content.admin_access=self.admin_access
self.content.focus_set()
self.content.depts=self.master.depts
if item == "Equipment Entry":
X = __import__('src.dependencies.Equipment',fromlist=('Equipment'))
X.Equipment(self.content,self.db,True)
elif item=="Software details":
X=__import__('src.dependencies.Software_master',fromlist=('Software_master'))
X.Software_master(self.content,self.db)
elif item=="AMC Details":
X=__import__('src.dependencies.Amc_details',fromlist=('Amc_details'))
X.Amc_details(self.content,self.db)
elif item=="Update/Repair Details":
X=__import__('src.dependencies.Update_details',fromlist=('Update_details'))
X.Update_details(self.content,self.db)
elif item=="Vendor Details":
X=__import__('src.dependencies.Vendor_details',fromlist=('Vendor_details'))
X.Vendor_details(self.content,self.db,True)
elif item=="Transfer Details":
X=__import__('src.dependencies.Transfer_details',fromlist=('Transfer_details'))
X.Transfer_details(self.content,self.db)
elif item=="Item Issue/ Return Details":
X=__import__('src.dependencies.Item_issue',fromlist=('Item_issue'))
X.Item_issue(self.content,self.db)
elif item=="Purchase Order Details":
X=__import__('src.dependencies.Purchase_details',fromlist=('Purchase_details'))
X.Purchase_details(self.content,self.db,True)
elif item=="Staff Master":
X=__import__('src.dependencies.Staff_master',fromlist=('Staff_master'))
X.Staff_master(self.content,self.db,True)
elif item=="User Master":
X=__import__('src.dependencies.User_master',fromlist=('User_master'))
X.User_master(self.content,self.db)
elif item=="Item Master":
X=__import__('src.dependencies.Item_master',fromlist=('Item_master'))
X.Item_master(self.content,self.db,True)
elif item=="Department Master":
X=__import__('src.dependencies.Department_master',fromlist=('Department_master'))
X.Department_master(self.content,self.db,True)
| SohailChamadia/Digital-Assets | src/dependencies/Main_menu.py | Main_menu.py | py | 5,597 | python | en | code | 1 | github-code | 13 |
39194903379 | """Script for Tkinter GUI chat client."""
# https://medium.com/swlh/lets-write-a-chat-app-in-python-f6783a9ac170
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
import time
global py
try:
import pygame
py=True
except:
print('WARNING, could not load pygame, so system.sound with no adjusment will be use')
py=False
def receive():
bipfile = './clochette.wav'
if py :
pygame.mixer.init()
"""Handles receiving of messages."""
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
msg_list.insert(tkinter.END, msg)
if py :
v = vol.get() # volume only with pygame mixer
pygame.mixer.music.set_volume(float(v)/10) # Met le volume à 0.5 (moitié)
pygame.mixer.music.load(bipfile)
pygame.mixer.music.play()
time.sleep(1)
else:
top.bell()
except OSError: # Possibly client has left the chat.
break
def send(event=None): # event is passed by binders.
"""Handles sending of messages."""
msg = my_msg.get()
my_msg.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
my_msg.set("{quit}")
send()
global top
top = tkinter.Tk()
top.geometry("700x500")
top.title("Listic net")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar() # For the messages to be sent.
my_msg.set("Here...")
if py :
vol = tkinter.Scale(top, from_=0, to=10)
vol.pack(side=tkinter.LEFT, fill=tkinter.Y)
scrollbar = tkinter.Scrollbar(messages_frame) # To navigate through past messages.
# Following will contain the messages.
msg_list = tkinter.Listbox(messages_frame, yscrollcommand=scrollbar.set,font=('Fixed', 12)) # height=15, width=50
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=1)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
messages_frame.pack(fill=tkinter.BOTH, expand=1)
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack(fill=tkinter.X)
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.resizable(True, True)
top.protocol("WM_DELETE_WINDOW", on_closing)
#----Now comes the sockets part----
HOST = '192.168.168.117' # input('Enter host: ')
PORT = 1552 # input('Enter port: ')
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop() # Starts GUI execution
| hermann74/listictac | client2.py | client2.py | py | 2,848 | python | en | code | 0 | github-code | 13 |
965417010 | import codecs
import sys
sys.path.append("..")
from utils.data_helper import load_attr_data, load_w2v, load_ab_test, load_abp_data, parse_json, load_abp_raw
import polarity_level_aspect.networks as networks
import utils.train_single as train_single
from utils.Data import Data, Data2, Data3
from utils.evaluate import score2
import argparse
import numpy as np
import torch
from collections import Counter
import os
import shutil
import time
import pickle
from sklearn.linear_model import LogisticRegression
# from mlxtend.classifier import StackingCVClassifier, StackingClassifier
# import xgboost as xgb
# from lightgbm import LGBMClassifier
parser = argparse.ArgumentParser()
parser.add_argument("--EPOCHS", type=int, default=5)
parser.add_argument("--n_hidden", type=int, default=128)
parser.add_argument("--optimizer", type=str, default="Adam")
parser.add_argument("--model", type=str, default="HEAT")
parser.add_argument("--lr", type=float, default=0.2)
parser.add_argument("--freeze", type=bool, default=True)
parser.add_argument("--use_dev", type=bool, default=False)
parser.add_argument("--use_elmo", type=int, default=0)
parser.add_argument("--save", type=int, default=1)
parser.add_argument("--dropout", type=float, default=0.0)
parser.add_argument("--pretrain", type=int, default=1)
parser.add_argument("--check_dir", type=str, default="cp_New")
parser.add_argument("--mode", type=int, default=2)
parser.add_argument("--folds", type=int, default=5)
parser.add_argument("--seed", type=int, default=1024)
parser.add_argument("--torch_seed", type=int, default=42)
# parser.add_argument("--test_model", type=str, default="TD_3LSTM_0.7626.pt")
parser.add_argument("--test_dir", type=str, default="cp_HEAT_0#cp_AT_LSTM_0#cp_HEAT_ft2#cp_AT_LSTM_ft2#cp_HEAT_2#cp_AT_LSTM_2#cp_HEAT_tc#cp_AT_LSTM_tc#cp_GCAE_0#cp_GCAE_2#cp_GCAE_ft2#cp_GCAE_tc#cp_Bert")
parser.add_argument("--saved", type=int, default=1)
parser.add_argument("--train_mode", type=int, default=1)
parser.add_argument("--w2v", type=str, default="merge")
args = parser.parse_args()
# torch.set_printoptions(profile="full")
print(args)
# seed = 314159
torch.manual_seed(args.torch_seed)
# seed = torch.initial_seed()
# print(seed)
class Classifier: # Neural network method
def __init__(self):
self.classifier = None
self.trained = False
pass
def train_from_data(self, train_raw_data, test_raw_data, W, word2index, polarity_dict, aspect_dict, args, Folds=0):
word_embed_dim = W.shape[1]
hidden_size = args.n_hidden
vocab_size = len(W)
output_size = len(polarity_dict)
aspect_size = len(aspect_dict)
if args.model == 'LSTM':
self.classifier = networks.LSTM(word_embed_dim, output_size, vocab_size, args)
elif args.model == 'Average_LSTM':
self.classifier = networks.Average_LSTM(word_embed_dim, output_size, vocab_size, args)
elif args.model == 'CNN':
self.classifier = networks.CNN(word_embed_dim, output_size, vocab_size, args)
elif args.model == 'AT_LSTM':
self.classifier = networks.AT_LSTM(word_embed_dim, output_size, vocab_size, aspect_size, args)
elif args.model == 'ATAE_LSTM':
self.classifier = networks.ATAE_LSTM(word_embed_dim, output_size, vocab_size, aspect_size, args)
elif args.model == 'GCAE':
self.classifier = networks.GCAE(word_embed_dim, output_size, vocab_size, aspect_size, args)
elif args.model == 'HEAT':
self.classifier = networks.HEAT(word_embed_dim, output_size, vocab_size, aspect_size, args)
train_elmo, test_elmo = [], []
if args.use_elmo != 0:
import h5py
elmo_dict = h5py.File('../embedding/embeddings_elmo_ly-1.hdf5', 'r')
for s in train_raw_data[0]:
sentence = '\t'.join(s)
sentence = sentence.replace('.', '$period$')
sentence = sentence.replace('/', '$backslash$')
# print(sentence)
embeddings = torch.from_numpy(np.asarray(elmo_dict[sentence]))
train_elmo.append(embeddings)
for s in test_raw_data[0]:
sentence = '\t'.join(s)
sentence = sentence.replace('.', '$period$')
sentence = sentence.replace('/', '$backslash$')
embeddings = torch.from_numpy(np.asarray(elmo_dict[sentence]))
test_elmo.append(embeddings)
elmo_dict.close()
print("finish elmo")
if args.pretrain != 0:
aspect_e_l = np.zeros((aspect_size, word_embed_dim))
for a in aspect_dict:
a_i = aspect_dict[a]
# print(a)
if a == '舒适性':
a = '舒适'
a_e = W[word2index[a]]
aspect_e_l[a_i] = a_e
aspect_embeds = torch.from_numpy(aspect_e_l).float()
# print(aspect_embeds)
print("initial aspect")
# print(attr_dict)
self.classifier.AE.weight = torch.nn.Parameter(aspect_embeds)
if args.train_mode == 1:
train_data = Data3(train_raw_data, word2index, polarity_dict, args, target_dict=aspect_dict)
# if args.use_dev:
# dev_data = Data(args, dev_input_s, dev_input_t, dev_y_tensor)
# else:
# dev_data = None
test_data = Data3(test_raw_data, word2index, polarity_dict, args, target_dict=aspect_dict)
if args.use_elmo != 0:
train_data.add_feature(train_elmo)
test_data.add_feature(test_elmo)
best_dict, max_acc = train_single.train(self.classifier, train_data, test_data, test_data, polarity_dict, W, args=args)
best_model = "%s/checkpoint_%s_%.6f_%d.pt" % (args.check_dir, args.model, max_acc, Folds)
if args.save != 0:
torch.save(best_dict, best_model)
pass
def split_dev(self, train_texts, train_t, train_ow):
instances_index = []
curr_s = ""
curr_i = -1
for i, s in enumerate(train_texts):
s = ' '.join(s)
if s == curr_s:
instances_index[curr_i].append(i)
else:
curr_s = s
instances_index.append([i])
curr_i += 1
print(curr_i)
print(len(instances_index))
assert curr_i+1 == len(instances_index)
length = len(instances_index)
np.random.seed(1024)
index_list = np.random.permutation(length).tolist()
# np.random.shuffle(index_list)
train_index = [instances_index[i] for i in index_list[0:length-length//5]]
dev_index = [instances_index[i] for i in index_list[length-length//5:]]
train_i_index = [i for l in train_index for i in l]
dev_i_index = [i for l in dev_index for i in l]
dev_texts, dev_t, dev_ow = ([train_texts[i] for i in dev_i_index], [train_t[i] for i in dev_i_index],
[train_ow[i] for i in dev_i_index])
train_texts, train_t, train_ow = ([train_texts[i] for i in train_i_index], [train_t[i] for i in train_i_index],
[train_ow[i] for i in train_i_index])
return train_texts, train_t, train_ow, dev_texts, dev_t, dev_ow
def predict(self, rnn, test_raw_data, word2index, args):
test_texts = test_raw_data[0]
test_t = test_raw_data[1]
test_ow = test_raw_data[2]
test_input_s = [self.to_tensor(s, word2index) for s in test_texts]
# print(train_input_s[0])
test_elmo = []
if args.use_elmo:
import h5py
elmo_dict = h5py.File('data/%s/elmo_layers.hdf5' % args.ds, 'r')
for i, current_sentence in enumerate(test_texts):
current_sentence = ' '.join(current_sentence)
embeddings = torch.from_numpy(np.asarray(elmo_dict[current_sentence]))
test_elmo.append(embeddings)
elmo_dict.close()
# print(train_input_s[0])
test_input_t = [torch.LongTensor(t) for t in test_t]
test_y_tensor = [torch.LongTensor(y) for y in test_ow]
test_data = Data(args, test_input_s, test_input_t, test_y_tensor, features=test_elmo)
with torch.no_grad():
test_predict = predict(rnn, test_data, args)
pred_acc_t = score(test_predict, test_data.labels)
print("p:%.4f, r:%.4f, f:%.4f" % (pred_acc_t[0], pred_acc_t[1], pred_acc_t[2]))
return test_predict
def kfold_split(length, k=5):
np.random.seed(args.seed)
index_list = np.random.permutation(length)
l = length // k
folds = []
for i in range(k):
test_idx = np.zeros(length, dtype=bool)
test_idx[i*l:(i+1)*l] = True
folds.append((index_list[~test_idx], index_list[test_idx]))
return folds
def splits(fo, train_index, dev_index):
train_texts, train_labels, train_aspects, test_texts, test_labels, test_aspects = [], [], [], [], [], []
for i in train_index:
line = fo[i]
splits = line.strip('\n').split('\t')
# text = text.lower()
text = splits[0].strip().split(' ')
for pair in splits[1:]:
aspect = pair.split('#')[0]
p = pair.split('#')[1]
train_texts.append(text)
train_labels.append(p)
train_aspects.append(aspect)
for i in dev_index:
line = fo[i]
splits = line.strip('\n').split('\t')
# text = text.lower()
text = splits[0].strip().split(' ')
for pair in splits[1:]:
aspect = pair.split('#')[0]
p = pair.split('#')[1]
test_texts.append(text)
test_labels.append(p)
test_aspects.append(aspect)
return train_texts, train_labels, train_aspects, test_texts, test_labels, test_aspects
def count_instance(fo):
count = 0
index_list = []
for line in fo:
current_index = []
splits = line.strip('\n').split('\t')
for p in splits[1:]:
assert '#' in p
current_index.append(count)
count += 1
index_list.append(current_index)
return count, index_list
def ensemble():
f_train = "../data/train.txt"
if args.w2v == "merge":
f_w2v = "../embedding/embedding_all_merge_300.txt"
elif args.w2v == "fasttext2":
f_w2v = "../embedding/embedding_all_fasttext2_300.txt"
elif args.w2v == "tencent":
f_w2v = "../embedding/embedding_all_tencent_200.txt"
else:
print("error, no embedding")
exit(-1)
f_dict1 = "../dataset/polarity.json"
f_dict2 = "../dataset/attribute.json"
print(f_train)
print(f_w2v)
if not os.path.exists("%s" % args.check_dir):
os.mkdir("%s" % args.check_dir)
W, word2index2 = load_w2v(f_w2v)
word2index = pickle.load(open("../data/vocabulary.pkl", 'rb'))
assert word2index == word2index2
polarity_list, polarity_dict = parse_json(f_dict1)
attr_list, attr_dict = parse_json(f_dict2)
kf = 0
fo = load_abp_raw(f_train)
for train_index, test_index in kfold_split(len(fo), args.folds):
kf += 1
print("FOLD:", kf)
# print("TRAIN:", train_index, '\n', "TEST:", test_index, str(len(test_index)))
train_texts, train_labels, train_aspects, test_texts, test_labels, test_aspects = splits(fo, train_index, test_index)
print(len(train_texts))
print(len(test_texts))
# print(list(attr_dict.keys()))
model = Classifier()
print(attr_list)
print(attr_dict)
# exit(-1)
# print(train_texts)
model.train_from_data((train_texts, train_labels, train_aspects), (test_texts, test_labels, test_aspects),
W, word2index, polarity_dict, attr_dict, args, kf)
def main():
f_train = "../data/train.txt"
f_test = "data/test_p.txt"
if args.w2v == "merge":
f_w2v = "../embedding/embedding_all_merge_300.txt"
elif args.w2v == "fasttext":
f_w2v = "../embedding/embedding_all_fasttext_300.txt"
elif args.w2v == "fasttext2":
f_w2v = "../embedding/embedding_all_fasttext2_300.txt"
elif args.w2v == "tencent":
f_w2v = "../embedding/embedding_all_tencent_200.txt"
else:
print("error, no embedding")
exit(-1)
f_dict1 = "../dataset/polarity.json"
f_dict2 = "../dataset/attribute.json"
print(f_w2v)
# train_texts, train_labels = load_attr_data(filename=f_train)
# # test_text, test_labels = load_attr_data(filename=f_test)
# train_texts, train_labels, test_texts, test_labels = split_dev(train_texts, train_labels)
train_texts, train_labels, train_aspects, test_texts, test_labels, test_aspects = load_abp_data(f_train, folds=5)
if not os.path.exists("%s" % args.check_dir):
os.mkdir("%s" % args.check_dir)
print(len(train_texts))
print(len(test_texts))
W, word2index2 = load_w2v(f_w2v)
word2index = pickle.load(open("../data/vocabulary.pkl", 'rb'))
assert word2index == word2index2
polarity_list, polarity_dict = parse_json(f_dict1)
attr_list, attr_dict = parse_json(f_dict2)
# print(list(attr_dict.keys()))
model = Classifier()
print(polarity_list)
print(polarity_dict)
# exit(-1)
# print(train_texts)
model.train_from_data((train_texts, train_labels, train_aspects), (test_texts, test_labels, test_aspects),
W, word2index, polarity_dict, attr_dict, args)
def test():
# model = Classifier()
test_file1 = "../attribute_level/data/attribute_test.txt"
test_file2 = "../attribute_level/test_predict.txt"
test_texts, test_aspects = load_ab_test(test_file1, test_file2)
f_w2v = "../embedding/embedding_all_merge_300.txt"
W, word2index = load_w2v(f_w2v)
f_dict1 = "../dataset/polarity.json"
f_dict2 = "../dataset/attribute.json"
polarity_list, polarity_dict = parse_json(f_dict1)
attr_list, attr_dict = parse_json(f_dict2)
assert len(test_texts) == len(test_aspects)
files = [
"checkpoint_HEAT_0.7189.pt",
"checkpoint_HEAT_0.7062.pt"
]
predicts = []
for check_point in files:
predict = []
classifier = torch.load(check_point)
for text, aspect in zip(test_texts, test_aspects):
if aspect != '':
if aspect is None:
print("error")
test_data = Data3(([text], [None], [aspect]), word2index, polarity_dict, args, target_dict=attr_dict)
test_predict = train_single.predict(classifier, test_data, args)
assert len(test_predict) == 1
polarity = str(test_predict[0].item()-1)
else:
print(aspect)
print(text)
polarity = '0'
# fw.write(aspect+','+polarity+'\n')
predict.append(aspect+','+polarity)
predicts.append(predict)
print(len(predicts))
print(len(predicts[0]))
fw = codecs.open("test_predict_polarity_ensemble.txt", 'w', encoding='utf-8')
for j in range(len(predicts[0])):
votes = [predicts[i][j] for i in range(len(predicts))]
voted = Counter(votes).most_common(1)
fw.write(voted+'\n')
def load_elmo(test_texts):
test_elmo = []
import h5py
elmo_dict = h5py.File('../embedding/embeddings_elmo_ly-1.hdf5', 'r')
for s in test_texts:
sentence = '\t'.join(s)
sentence = sentence.replace('.', '$period$')
sentence = sentence.replace('/', '$backslash$')
embeddings = torch.from_numpy(np.asarray(elmo_dict[sentence]))
test_elmo.append(embeddings)
elmo_dict.close()
print("finish elmo")
return test_elmo
def get_oof(clfs, fo, test_data, word2index, polarity_dict, attr_dict):
NFOLDS = len(clfs)
n_train, sentence2instance = count_instance(fo)
print(n_train)
n_test = len(test_data.sentences)
class_num = 3
oof_train = np.zeros((n_train, class_num))
oof_train_y = np.zeros((n_train, 1))
oof_test = np.zeros((n_test, class_num))
oof_test_skf = np.zeros((NFOLDS, n_test, class_num))
kf = 0
for (train_index, test_index), checkpoint in zip(kfold_split(len(fo), NFOLDS), clfs):
print(checkpoint)
clf = torch.load(checkpoint)
kf += 1
print("FOLD:", kf)
print("TRAIN:", str(len(train_index)), "TEST:", str(len(test_index)))
# train_index, test_index = train_index.tolist(), test_index.tolist()
train_texts, train_labels, train_aspects, dev_texts, dev_labels, dev_aspects = splits(fo, train_index,
test_index)
dev_data = Data3((dev_texts, dev_labels, dev_aspects), word2index, polarity_dict, args, target_dict=attr_dict)
if args.use_elmo != 0:
dev_elmo = load_elmo(dev_texts)
dev_data.add_feature(dev_elmo)
with torch.no_grad():
dev_predict, oof_dev = train_single.predict_with_logit(clf, dev_data, args)
pred_acc_p = score2(dev_predict, dev_data.labels)
print("[p:%.4f, r:%.4f, f:%.4f] acc:%.4f" %
(pred_acc_p[0], pred_acc_p[1], pred_acc_p[2], pred_acc_p[3]))
# label_prf = label_analysis(dev_predict, dev_data.labels)
# for i in range(len(label_prf)):
# print("%s : [%.4f, %.4f, %.4f] %.4f" %
# (list(attr_dict.keys())[i], label_prf[i][0], label_prf[i][1], label_prf[i][2], label_prf[i][3]))
test_i_index = [i_index for sentence_index in test_index for i_index in sentence2instance[sentence_index]]
assert len(test_i_index) == len(oof_dev)
oof_train[test_i_index] = oof_dev
dev_y = [l.detach().numpy() for l in dev_data.labels]
oof_train_y[test_i_index] = dev_y
_, oof_test_skf[kf - 1, :, :] = train_single.predict_with_logit(clf, test_data, args)
oof_test[:] = oof_test_skf.mean(axis=0)
dir = os.path.dirname(clfs[0])
if not os.path.exists(os.path.join(dir, 'npy')):
os.mkdir(os.path.join(dir, 'npy'))
print(dir)
np.save(os.path.join(dir, 'npy', "oof_train"), oof_train)
np.save(os.path.join(dir, 'npy', "oof_train_y"), oof_train_y)
np.save(os.path.join(dir, 'npy', "oof_test"), oof_test)
return oof_train, oof_train_y, oof_test
def get_oof_test(clfs, test_data):
NFOLDS = len(clfs)
n_test = len(test_data.sentences)
class_num = 3
oof_test = np.zeros((n_test, class_num))
oof_test_skf = np.zeros((NFOLDS, n_test, class_num))
kf = 0
for checkpoint in clfs:
print(checkpoint)
clf = torch.load(checkpoint)
kf += 1
print("FOLD:", kf)
_, oof_test_skf[kf - 1, :, :] = train_single.predict_with_logit(clf, test_data, args)
oof_test[:] = oof_test_skf.mean(axis=0)
dir = os.path.dirname(clfs[0])
if not os.path.exists(os.path.join(dir, 'npy')):
os.mkdir(os.path.join(dir, 'npy'))
print(dir)
np.save(os.path.join(dir, 'npy', "oof_test"), oof_test)
return oof_test
def load_oof_dir(dir):
oof_train = np.load(os.path.join(dir, 'npy', "oof_train.npy"))
oof_train_y = np.load(os.path.join(dir, 'npy', "oof_train_y.npy"))
oof_test = np.load(os.path.join(dir, 'npy', "oof_test.npy"))
print("loaded from: " + dir)
return oof_train, oof_train_y, oof_test
def load_oof_test(dir):
oof_test = np.load(os.path.join(dir, 'npy', "oof_test.npy"))
print("loaded from: " + dir)
return oof_test
def load_oof(clfs, fo, test_data, word2index, polarity_dict, attr_dict):
dir = os.path.dirname(clfs[0])
if os.path.isfile(os.path.join(dir, 'npy', "oof_train.npy")):
oof_train = np.load(os.path.join(dir, 'npy', "oof_train.npy"))
oof_train_y = np.load(os.path.join(dir, 'npy', "oof_train_y.npy"))
oof_test = np.load(os.path.join(dir, 'npy', "oof_test.npy"))
print("loaded from: " + dir)
else:
oof_train, oof_train_y, oof_test = get_oof(clfs, fo, test_data, word2index, polarity_dict=polarity_dict,
attr_dict=attr_dict)
return oof_train, oof_train_y, oof_test
def load_oof3(clfs, fo, test_data, word2index, polarity_dict, attr_dict): # re test
dir = os.path.dirname(clfs[0])
if os.path.isfile(os.path.join(dir, 'npy', "oof_train.npy")):
oof_train = np.load(os.path.join(dir, 'npy', "oof_train.npy"))
oof_train_y = np.load(os.path.join(dir, 'npy', "oof_train_y.npy"))
oof_test = get_oof_test(clfs, test_data)
print("loaded from: " + dir)
else:
oof_train, oof_train_y, oof_test = get_oof(clfs, fo, test_data, word2index, polarity_dict=polarity_dict,
attr_dict=attr_dict)
return oof_train, oof_train_y, oof_test
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
print(e_x.shape)
return e_x / e_x.sum(axis=-1, keepdims=True)
def stacking():
# saved = True if args.saved != 0 else False
saved = args.saved
f_train = "../data/train.txt"
test_file1 = "../data/test.txt"
test_file2 = "../data/test_predict_aspect_ensemble.txt"
test_texts, test_aspects = load_ab_test(test_file1, test_file2)
# print(test_aspects)
fo = load_abp_raw(f_train)
word2index = pickle.load(open("../data/vocabulary.pkl", 'rb'))
f_dict = "../dataset/polarity.json"
polarity_list, polarity_dict = parse_json(f_dict)
f_dict2 = "../dataset/attribute.json"
attr_list, attr_dict = parse_json(f_dict2)
paths = args.test_dir.split('#')
models_files = []
for path in paths:
models_files.append([os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
test_data = Data3((test_texts, None, test_aspects), word2index, polarity_dict, args, target_dict=attr_dict)
if args.use_elmo != 0:
test_elmo = load_elmo(test_texts)
test_data.add_feature(test_elmo)
x_train = []
y_train = []
x_test = []
for dir, checkpoints_per_model in zip(paths, models_files):
print(dir, checkpoints_per_model)
if saved == 1:
oof_train, oof_train_y, oof_test = load_oof_dir(dir)
else:
print(checkpoints_per_model)
NFOLDS = len(checkpoints_per_model)
print(NFOLDS)
# assert NFOLDS == args.folds
clfs = [None for i in range(NFOLDS)]
for cp in checkpoints_per_model:
fold = int(cp.replace('_', '.').split('.')[-2])
clfs[fold-1] = cp
if saved == 2:
oof_train, oof_train_y, oof_test = load_oof(clfs, fo, test_data, word2index, polarity_dict=polarity_dict,
attr_dict=attr_dict)
elif saved == 3:
oof_train, oof_train_y, oof_test = load_oof3(clfs, fo, test_data, word2index, polarity_dict=polarity_dict,
attr_dict=attr_dict)
elif saved == 0:
oof_train, oof_train_y, oof_test = get_oof(clfs, fo, test_data, word2index, polarity_dict=polarity_dict,
attr_dict=attr_dict)
else:
print("saved error, [0:3]")
exit(-1)
x_train.append(oof_train)
oof_train_y = oof_train_y.reshape(oof_train_y.shape[0], )
if y_train == []:
y_train = oof_train_y
else:
assert (y_train == oof_train_y).all()
x_test.append(oof_test)
x_train = np.concatenate(x_train, axis=1)
x_test = np.concatenate(x_test, axis=1)
y_train = np.asarray(y_train).reshape((len(y_train),))
meta_clf = LogisticRegression()
meta_clf.fit(x_train, y_train)
test_predict = meta_clf.predict_proba(x_test)
fw = codecs.open("../data/test_predict_polarity_ensemble.txt", 'w', encoding='utf-8')
for j, prob in enumerate(test_predict):
polarity = np.argmax(prob)-1
fw.write(test_aspects[j] + ',' + str(polarity) + '\n')
time_stamp = time.asctime().replace(':', '_').split()
fw.close()
shutil.copy2("../data/test_predict_polarity_ensemble.txt",
"../data/backup/test_predict_polarity_ensemble_%s.txt" % time_stamp)
def blending():
# saved = True if args.saved != 0 else False
saved = args.saved
test_file1 = "../data/test.txt"
test_file2 = "../data/test_predict_aspect_ensemble.txt"
test_texts, test_aspects = load_ab_test(test_file1, test_file2)
# print(test_aspects)
word2index = pickle.load(open("../data/vocabulary.pkl", 'rb'))
f_dict = "../dataset/polarity.json"
polarity_list, polarity_dict = parse_json(f_dict)
f_dict2 = "../dataset/attribute.json"
attr_list, attr_dict = parse_json(f_dict2)
paths = args.test_dir.split('#')
models_files = []
for path in paths:
models_files.append([os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
test_data = Data3((test_texts, None, test_aspects), word2index, polarity_dict, args, target_dict=attr_dict)
if args.use_elmo != 0:
test_elmo = load_elmo(test_texts)
test_data.add_feature(test_elmo)
x_test = []
for dir, checkpoints_per_model in zip(paths, models_files):
print(dir, checkpoints_per_model)
if saved == 1:
oof_test = load_oof_test(dir)
else:
clfs = checkpoints_per_model
oof_test = get_oof_test(clfs, test_data)
x_test.append(oof_test)
x_test = np.stack(x_test, axis=1)
print(x_test)
print(x_test.shape)
test_predict = np.mean(x_test, axis=1)
fw = codecs.open("../data/test_predict_polarity_ensemble.txt", 'w', encoding='utf-8')
for j, prob in enumerate(test_predict):
polarity = np.argmax(prob)-1
fw.write(test_aspects[j] + ',' + str(polarity) + '\n')
time_stamp = time.asctime().replace(':', '_').split()
fw.close()
shutil.copy2("../data/test_predict_polarity_ensemble.txt",
"../data/backup/test_predict_polarity_ensemble_%s.txt" % time_stamp)
if __name__ == '__main__':
if args.mode == 0:
main()
elif args.mode == 1:
ensemble()
elif args.mode == 2:
stacking()
| yilifzf/BDCI_Car_2018 | polarity_level_aspect/ab_polarity.py | ab_polarity.py | py | 26,637 | python | en | code | 421 | github-code | 13 |
17698153049 | from Functions import calculate, enter_operation, enter_number
valid_operations = ('+', '-', '*', '/', '**')
try:
first_numb = enter_number()
first_operation = enter_operation(valid_operations)
second_numb = enter_number()
second_operation = enter_operation(valid_operations)
third_numb = enter_number()
except Exception as exc_one:
print(exc_one, '. Try again.', sep='')
else:
try:
print(calculate(calculate(first_numb, second_numb, first_operation), third_numb, second_operation))
except:
print('Try again.') | oshevelo/feb_py | Calculator/Calculator2.py | Calculator2.py | py | 560 | python | en | code | 0 | github-code | 13 |
6282325666 | # Demonstration of splitting up a program
# Demonstration of working with program files
from classes import ingredients
from classes.ingredients import Ingredient
class Inventory(object):
""" Class for Inventory.
A Dictionary with item names as key and quantity as values.
"""
def __init__(self, items: dict):
""" Sets up the Inventory.
Input is a dictionary with item names as key and quantity as values.
"""
self.items = items
def sort(self):
""" Sorts the items in the inventory alphabetically (ASCII order)
"""
sorted_tuple = sorted(self.items.items(), key=lambda x: x[0])
self.items = dict(sorted_tuple)
def add(self, item: Ingredient, quantity=1):
""" Adds an item to the inventory.
Requires item name (string) and quantity (int).
If quantity not provided, it assumes a default value of 1.
"""
if item.title in self.items:
self.items[item.title] += quantity
else:
self.items[item.title] = quantity
# Sort after adding new item
self.sort()
def remove(self, item: Ingredient, quantity=1):
""" Removes an item from the inventory.
Requires item name (string) and quantity (int).
If quantity not provided, it assumes a default value of 1.
"""
if item.title in self.items:
if self.items[item.title] < quantity:
self.items[item.title] = 0
else:
self.items[item.title] -= quantity
def has(self, item: str):
""" Checks if a particular item is in the inventory.
"""
if item in self.items and self.items[item] != 0:
return True
else:
return False
def print_inventory(self):
""" Prints the current inventory.
No arguments needed.
"""
for item in self.items:
print("{item} - {quantity}".format(item=item, quantity=self.items[item]))
def load_inventory_from_file():
""" Loads the inventory from inventory.txt file.
Created only for demonstration purposes.
Not compatible with other files and hence redundant.
"""
# Open the file
file = open('inventory.txt')
lines = file.readlines()
items = {}
# Add items from the file
for line in lines:
line = line.strip('\n')
line = line.split('\t')
item = Ingredient(title=line[0])
items[item] = int(line[1])
inventory = Inventory(items)
inventory.sort()
# Close the file
file.close()
return inventory
def write_inventory_to_file(inventory: Inventory):
""" Writes the contents in inventory to inventory.txt file.
Created only for demonstration purposes.
Not compatible with other files and hence redundant.
"""
# Opening the file
file = open('inventory.txt', 'w')
# Writing items
for item in inventory.items:
file.write("{name}\t{quantity}\n".format(name=item, quantity=inventory.items[item]))
# Closing the file
file.close()
def load_inventory():
""" Used for creating and updating the inventory to be used by other codes.
"""
# Defining the inventory
inventory = Inventory(items={})
# Shipment from 28th October
inventory.add(ingredients.bamboo_shoot, 3)
inventory.add(ingredients.carrot, 2)
inventory.add(ingredients.crab, 1)
inventory.add(ingredients.ham, 1)
inventory.add(ingredients.jueyun_chili, 2)
inventory.add(ingredients.lotus_head, 2)
inventory.add(ingredients.matsutake, 1)
inventory.add(ingredients.sugar, 1)
# Update for 11th November
inventory.add(ingredients.berry, 1)
inventory.add(ingredients.crab, 2)
inventory.add(ingredients.raw_meat, 1)
inventory.add(ingredients.shrimp_meat, 1)
inventory.remove(ingredients.bamboo_shoot, 1)
inventory.remove(ingredients.carrot, 2)
inventory.remove(ingredients.jueyun_chili, 2)
inventory.remove(ingredients.lotus_head, 2)
return inventory
| shuvo2109/one-moon-restaurant | classes/inventory.py | inventory.py | py | 4,109 | python | en | code | 0 | github-code | 13 |
20680499448 | import os
import argparse
import rlcard
from rlcard.agents import DQNAgent, RandomAgent
from rlcard.utils import get_device, set_seed, tournament, reorganize, Logger
def load_model(model_path, env=None, position=None, device=None):
if os.path.isfile(model_path): # Torch model
import torch
agent = torch.load(model_path, map_location=device)
if model_path == 'experiments/uno_dqn_result/model.pth':
agent.set_device(device)
elif model_path == 'random': # Random model
from rlcard.agents import RandomAgent
agent = RandomAgent(num_actions=env.num_actions)
elif model_path == 'sameNumberRule':
from agents.same_number_agent import SameNumberAgent
agent = SameNumberAgent(num_actions=env.num_actions)
elif model_path == 'bestRule':
from agents.best_rule_agent import BestRuleAgent
agent = BestRuleAgent(num_actions=env.num_actions)
else: # A model in the model zoo
from rlcard import models
agent = models.load(model_path).agents[position]
return agent
def evaluate(args):
# Check whether gpu is available
device = get_device()
# Seed numpy, torch, random
set_seed(args.seed)
# Make the environment with seed
env = rlcard.make(args.env, config={'seed': args.seed})
# Load models
agents = []
for position, model_path in enumerate(args.models):
agents.append(load_model(model_path, env, position, device))
env.set_agents(agents)
# Evaluate
rewards = tournament(env, args.num_games)
for position, reward in enumerate(rewards):
print(position, args.models[position], reward)
if __name__ == '__main__':
parser = argparse.ArgumentParser("Uno Agent Evaluation in RLCard")
parser.add_argument('--env', type=str, default='uno')
parser.add_argument('--models', nargs='*', default=['random', 'experiments/uno_qn_result/model.pth', 'experiments/uno_qn_result/model.pth', 'experiments/uno_dqn_result/model.pth', 'sameNumberRule'])
parser.add_argument('--cuda', type=str, default='')
parser.add_argument('--seed', type=int, default=42)
parser.add_argument('--num_games', type=int, default=200)
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = args.cuda
evaluate(args) | Derrc/UnoRL | UnoRL/evaluate.py | evaluate.py | py | 2,320 | python | en | code | 1 | github-code | 13 |
12596099984 | import sys
import tensorflow as tf
from PIL import Image
import numpy as np
# Load the pre-trained MobileNetV2 model
model = tf.keras.applications.MobileNetV2(weights='imagenet')
# Prepare the image
def prepare_image(image_path):
img = Image.open(image_path).resize((224, 224))
img_array = np.array(img) / 255.0
return np.expand_dims(img_array, axis=0)
# Predict the class of the image
def predict_image(image_path):
image = prepare_image(image_path)
predictions = model.predict(image)
decoded_predictions = tf.keras.applications.mobilenet_v2.decode_predictions(predictions, top=1)
return decoded_predictions[0][0]
# Check if the image is a cat or a dog
def is_cat_or_dog(image_path):
prediction = predict_image(image_path)
label, name, confidence = prediction
if name == "tiger_cat" or name == "Egyptian_cat" or "tabby" in name:
return "cat"
elif "dog" in name or "hound" in name:
return "dog"
else:
return "unknown"
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python cat_dog_classifier.py path_to_image")
sys.exit(1)
image_path = sys.argv[1]
result = is_cat_or_dog(image_path)
print(f"The image is a: {result}")
| InsideousBot/Cats-and-Dogs-AI | Cats and Dogs AI.py | Cats and Dogs AI.py | py | 1,245 | python | en | code | 0 | github-code | 13 |
7972500983 | from test.db import TEST_DB_NAME
import pytest
from pytest_mock import MockerFixture
import app.meal as meal
@pytest.fixture(autouse=True)
def use_test_db(db_connection, mocker: MockerFixture):
mocker.patch.object(meal, "DB_NAME", TEST_DB_NAME)
def test_it_deletes_meal():
# given
weekday = "teisipäev"
meal_type = "hommik"
any_meal = meal.add_empty_meal(weekday, meal_type)
# when
result = meal.delete_meal(weekday, meal_type)
# then
assert result == any_meal
def test_it_returns_none_for_missing_meal():
# given
weekday = "teisipäev"
meal_type = "hommik"
# when
result = meal.delete_meal(weekday, meal_type)
# then
assert result is None
| e1004/toiduplaneerija | test/test_meal_delete.py | test_meal_delete.py | py | 717 | python | en | code | 0 | github-code | 13 |
7958830406 | import os
import sys
operations = ["help", "create table", "delete table", "add data", "delete data", "run", "quit"]
source = "to_do.sql" # I'm using a variable as it will save time
def add_to_file(source, text):
with open(source, "r") as read:
lines = read.readlines()
lines.append(text + "\n")
with open(source, "w") as write:
for line in lines:
write.write(line)
user = input("Please enter your MySQL username: ")
database = input("Please enter the database to use: ")
with open(source, "w") as write:
write.write("# This is where all the SQL commands go \n") # This is so that everytime the document opens, the previous is cleared
add_to_file(source, "USE " + database + ";")
ready = False
while ready == False:
do = input("What do you want to do? \n")
do = do.lower()
if do not in operations:
print("Sorry, you can't do that. Type help to show allowed commands. \n")
else:
if do == "help":
print(operations)
elif do == "create table":
values = {}
values_list = []
done = False
table_name = input("What do you want to name this table? \n")
print("What values (columns) do you want for you table? Enter each value's name and type.")
while done != True:
value = input("What is the name of this value? \n")
value = value.lower()
value_type = input("What type is this? \n")
value_type = value_type.upper()
while value_type != "TEXT" and value_type != "INTEGER":
value_type = input("That's not a registered value type. Please enter either text or integer as a value type. \n")
value_type = value_type.upper()
values[value] = value_type
done = input("Do you want to add in any other values?\n")
done = done.lower()
while done != "yes" and done != "no":
done = input("Please enter either yes or no\n")
done = done.lower()
if done == "no":
done = True # No need for an else statment, because done would still not be equal to True, so the loop would continue.
for value in values:
values_list.append(value + " " + values[value])
values = ", ".join(values_list)
print(values)
add_to_file(source, "CREATE TABLE " + table_name + " (" + values + ");")
elif do == "delete table":
table = input("What is the table you want to delete?")
add_to_file(source, "DROP TABLE " + table)
elif do == "add data":
done = False
variables = []
values = []
table = input("Which table do you want to add to?\n")
print("Please enter each variable and the value of each variable.")
while done != True:
variables.append(input("Please enter the variable."))
value = input("What is the value of this variable")
type = input("Is the variable a string or an integer?")
type = type.lower()
while type != "string" and type != "integer":
type = input("Please enter either string or integer")
type = type.lower()
if type == "string":
value = "\"" + value + "\""
values.append(value)
done = input("Do you want to add in any other values?\n")
done = done.lower()
while done != "yes" and done != "no":
done = input("Please enter either yes or no\n")
done = done.lower()
if done == "no":
done = True
variables = ", ".join(variables)
values = ", ".join(values)
add_to_file(source, "INSERT INTO " + table + " (" + variables + ") VALUES (" + values + ");")
elif do == "delete data":
table = input("Which table do you want to delete data from?")
value = input("What is the value you want to delete?")
variable = input("What variable is it under?")
type = input("Is the variable a string or an integer?")
type = type.lower()
while type != "string" and type != "integer":
type = input("Please enter either string or integer")
type = type.lower()
if type == "string":
value = "\"" + value + "\""
add_to_file(source, "DELETE FROM " + table + " WHERE " + variable + " = " + value +";")
elif do == "run":
os.system("mysql -u " + user + " -p < to_do.sql")
elif do == "quit":
sys.exit()
| JohnyNich/Python-MySQL-Interface | mysql_interface.py | mysql_interface.py | py | 4,864 | python | en | code | 0 | github-code | 13 |
35129175589 | class Solution:
def totalNQueens(self, n: int) -> int:
# based on solution used in N-Queens
board = [['.'] * n for _ in range(n)]
cols = set()
posDiag = set() # (r + c)
negDiag = set() # (r - c)
def backtrack(r):
if r == n:
return 1
output = 0
for c in range(n):
if c in cols or (r + c) in posDiag or (r - c) in negDiag:
continue
cols.add(c)
posDiag.add(r + c)
negDiag.add(r - c)
board[r][c] = 'Q'
output += backtrack(r + 1)
cols.remove(c)
posDiag.remove(r + c)
negDiag.remove(r - c)
board[r][c] = '.'
return output
return backtrack(0)
| aakanksha-j/LeetCode | Backtracking/52. N-Queens II/backtracking_1.py | backtracking_1.py | py | 859 | python | en | code | 0 | github-code | 13 |
37949285318 | # example MC11 jO file that shows how to use PythiaResMod class
# PythiaResMod class:
# * for W',Z' [ISUB 141,142]:
# * - take out Breit-Wigner dependence +
# * - supress low mass events from parton luminosities
# implementation: PythiaModified/pysgex.F
from AthenaCommon.AlgSequence import AlgSequence
topAlg = AlgSequence("TopAlg")
from PythiaExo_i.PythiaResMod_iConf import PythiaResMod
topAlg += PythiaResMod()
PythiaResMod = topAlg.PythiaResMod
theApp.EvtMax = 10
#----------------------------------------------------------------------------------------------------------------------
# enable using the modified pysgex.F
#(default: UseResMod=0; do not use modified pysgex.F)
#(UseResMod=1; use modified pysgex.F)
PythiaResMod.UseResMod=1
# Zprime resonance mass (in GeV)
ZprimeMass = 1000
# Minimum mass for Drell-Yan production (in GeV)
ckin1 = 100
# relevant proc. setup
PythiaResMod.PythiaCommand += [
"pysubs msel 0",
"pysubs msub 141 1", # Z',Z,g with interference
# Z' decays - quarks
"pydat3 mdme 289 1 0",
"pydat3 mdme 290 1 0",
"pydat3 mdme 291 1 0",
"pydat3 mdme 292 1 0",
"pydat3 mdme 293 1 0",
"pydat3 mdme 294 1 0",
# Z' decays - leptons
"pydat3 mdme 297 1 0",
"pydat3 mdme 298 1 0",
"pydat3 mdme 299 1 1", #Z'-> mu+ mu-
"pydat3 mdme 300 1 0",
"pydat3 mdme 301 1 0", #Z'-> tau+ tau-
"pydat3 mdme 302 1 0",
# tau decays are left open
"pysubs ckin 1 "+str(ckin1), # sqrhat > 500
# "pysubs ckin 13 -3", #
# "pysubs ckin 14 3", # eta cuts
# "pysubs ckin 15 -3", # |eta| < 3
# "pysubs ckin 16 3", #
"pydat1 mstu 1 0",
"pydat1 mstu 2 0",
"pydat2 pmas 32 1 "+str(ZprimeMass)
]
PythiaResMod.PythiaCommand += ["pydat1 parj 90 200000",
"pydat3 mdcy 15 1 0"]
include ( "MC11JobOptions/MC11_Tauola_Fragment.py" )
include ( "MC11JobOptions/MC11_Photos_Fragment.py" )
| rushioda/PIXELVALID_athena | athena/Generators/PythiaExo_i/share/PythiaResModZprime.py | PythiaResModZprime.py | py | 2,017 | python | en | code | 1 | github-code | 13 |
27302884025 | import re
class Paragraph(object):
def __init__(self, source_string):
self.str = source_string
self._paragraph_re = re.compile(r"""^(?!\s|#\. |\* |- |\.\. ).*?(?=\n^\s*$)""",
flags=re.MULTILINE + re.DOTALL)
@staticmethod
def _paragraph(matchobj):
content = matchobj.group(0)
content = content.replace('\n', ' ')
return content
def convert(self):
output = self.str
output = self._paragraph_re.sub(self._paragraph, output)
return output
| codio/book-converter | converter/rst/paragraph.py | paragraph.py | py | 559 | python | en | code | 2 | github-code | 13 |
74675210256 | from mstk.topology import Topology
from mstk.trajectory import Frame
from mstk.trajectory.handler import TrjHandler
class Gro(TrjHandler):
'''
Read and write cell, atomic positions and optionally velocities from/to GRO file.
'''
def __init__(self, file, mode='r'):
super().__init__()
if mode not in ('r', 'w', 'a'):
raise Exception('Invalid mode')
if mode == 'r':
# open it in binary mode so that we can correctly seek despite of line ending
self._file = open(file, 'rb')
elif mode == 'a':
self._file = open(file, 'ab')
elif mode == 'w':
self._file = open(file, 'wb')
def get_info(self):
try:
self._file.readline()
self.n_atom = int(self._file.readline())
except:
print('Invalid gro file')
raise
self._file.seek(0)
# read in the file once and build a list of line offsets
# the last element is the length of whole file
self._line_offset = [0]
offset = 0
for line in self._file:
offset += len(line)
self._line_offset.append(offset)
self._file.seek(0)
# build a list of frame offsets
self.n_frame = len(self._line_offset) // (3 + self.n_atom)
self._frame_offset = []
for i in range(self.n_frame + 1):
line_start = (3 + self.n_atom) * i
self._frame_offset.append(self._line_offset[line_start])
return self.n_atom, self.n_frame
def read_frame(self, i_frame, frame):
# skip to frame i and read only this frame
self._file.seek(self._frame_offset[i_frame])
lines = self._file.read(self._frame_offset[i_frame + 1] - self._frame_offset[i_frame]) \
.decode().splitlines()
# assume there are velocities. we'll see later
frame.has_velocity = True
for i in range(self.n_atom):
line = lines[i + 2]
x = float(line[20:28])
y = float(line[28:36])
z = float(line[36:44])
frame.positions[i][:] = x, y, z
if frame.has_velocity:
try:
vx = float(line[44:52])
vy = float(line[52:60])
vz = float(line[60:68])
except:
frame.has_velocity = False
else:
frame.velocities[i][:] = vx, vy, vz
_box = tuple(map(float, lines[self.n_atom + 2].split()))
if len(_box) == 3:
frame.cell.set_box(_box)
elif len(_box) == 9:
ax, by, cz, ay, az, bx, bz, cx, cy = _box
frame.cell.set_box([[ax, ay, az], [bx, by, bz], [cx, cy, cz]])
else:
raise ValueError('Invalid box')
def write_frame(self, frame, topology, subset=None, write_velocity=False, **kwargs):
'''
Write a frame into the opened GRO file
Parameters
----------
frame : Frame
topology : Topology
subset : list of int, optional
write_velocity : bool
Whether or not velocities should be written.
If set to True but velocities not available in frame, an Exception will be raised.
kwargs : dict
Ignored
'''
if subset is None:
subset = list(range(len(frame.positions)))
if write_velocity and not frame.has_velocity:
raise Exception('Velocities are requested but not exist in frame')
string = 'Created by mstk: step= %i, t= %f ps\n' % (frame.step, frame.time)
string += '%i\n' % len(subset)
for id in subset:
atom = topology.atoms[id]
residue = atom.residue
pos = frame.positions[id]
string += '%5i%5s%5s%5i%8.3f%8.3f%8.3f' % (
(residue.id + 1) % 100000, residue.name[:5], atom.symbol[:5], (atom.id + 1) % 100000,
pos[0], pos[1], pos[2])
if write_velocity:
vel = frame.velocities[id]
string += '%8.4f%8.4f%8.4f' % (vel[0], vel[1], vel[2])
string += '\n'
a, b, c = frame.cell.vectors
string += ' %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f\n' % (
a[0], b[1], c[2], a[1], a[2], b[0], b[2], c[0], c[1])
self._file.write(string.encode())
self._file.flush()
TrjHandler.register_format('.gro', Gro)
| z-gong/mstk | mstk/trajectory/io/gro.py | gro.py | py | 4,476 | python | en | code | 7 | github-code | 13 |
19468864461 | import pygame
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
class QUI:
def __init__(self, game_display):
self.game_display = game_display
self.font = pygame.font.SysFont('arial', 36)
def get_coordinates_for_frame(self, cell, indices, shifts):
"""
returns the coordinates for the frame(triangle coordinates)
:param cell:
:param indices:
:param shifts: shifts for triangle
"""
return [[cell.coordinates[indices[0]][indices[1]],
cell.coordinates[indices[2]][indices[3]]],
[cell.coordinates[indices[0]][indices[1]] + shifts[0],
cell.coordinates[indices[2]][indices[3]] + shifts[1]],
[cell.coordinates[indices[0]][indices[1]] + shifts[2],
cell.coordinates[indices[2]][indices[3]] + shifts[3]]]
def draw_side(self, field, color, indices, shifts, fr, to, step=1):
"""draws the side of the frame
:param field: instance of Field class
:param color: color for side
"""
for i in range(fr, to, step):
coordinates = self.get_coordinates_for_frame(field.cells[i], indices, shifts)
pygame.draw.polygon(self.game_display, color, coordinates)
def draw_frame(self, field):
"""draws a frame
:param field: instance of Field class"""
self.draw_side(field, RED, [0, 0, 0, 1], [0, -20, -20, 10], 1, field.size)
self.draw_side(field, RED, [1, 0, 1, 1], [0, 20, 20, -10], field.size ** 2 - field.size + 1, field.size ** 2)
self.draw_side(field, BLUE, [4, 0, 4, 1], [20, 10, 20, 30], field.size - 1, field.size ** 2 - 1, field.size)
self.draw_side(field, BLUE, [1, 0, 1, 1], [0, 20, 20, 30], 0, field.size ** 2 - field.size, field.size)
def draw_field(self, field):
"""
draws a frame
:param field: instance of Field class
"""
for cell in field.cells:
if cell.visited:
if cell.color == 'red':
pygame.draw.polygon(self.game_display, RED, cell.coordinates)
if cell.color == 'blue':
pygame.draw.polygon(self.game_display, BLUE, cell.coordinates)
pygame.draw.polygon(self.game_display, WHITE, cell.coordinates, 2)
def print_message(self, message: str, pos):
"""prints a message on the screen
:param message: message text
:param pos: position of the text on the screen
"""
surf = self.font.render(message, False, WHITE)
rect = surf.get_rect(center=pos)
self.game_display.blit(surf, rect)
def update(self, field):
"""
draws the current state of all game objects
:param field: instance of Field class
"""
if field.player_win:
self.print_message('You win', (550, 300))
elif field.ai_win:
self.print_message('You lose', (550, 300))
else:
self.draw_frame(field)
self.draw_field(field)
| LeraTrubetskikh/hex | game/gui.py | gui.py | py | 3,081 | python | en | code | 0 | github-code | 13 |
73271467216 | #For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understanding of those concepts.
#Question: Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function).
#Sample Output:
#>>> Enter your First [space] Last name only: Bill Newman
#>>> Unique flower name with the first letter: Bellflower
# Write your code here
# HINT: create a dictionary from flowers.txt
def flowers_dict(filename):
"""
This function opens the flowers.txt, reads every line in it, and saves it as a dictionary.
"""
flowers = {} #initialize the flowers' dictionary
with open(filename) as f: # open the text file as f.
for line in f: # reads every line in text file.
letter = line.split(": ")[0].lower() # splits the line by ":" and takes the first index i.e letter in lower case
flower = line.split(": ")[1] # splits the line by ":" and takes the second index i.e flower
#print(flower)
flowers[letter] = flower # enters the letter and flower as value pairs in the flowers' dictionary.
return flowers
# HINT: create a function
def main():
"""
The main function as described in the instructions.
"""
flowers = flowers_dict('flowers.txt') # creates the dictionary
full_name = input("Enter your First [space] Last name only: ") # user input
first_name = full_name[0].lower() # takes the first index of the full_name i.e first name.
first_letter = first_name[0] # takes the first letter (index) of the first name.
print("Unique flower name with the first letter: {}".format(flowers[first_letter])) # prints the flower name that matches the first letter
main() # call the main function | Babawale/WeJapaInternship | Labs/Wave_4_labs/Scripting labs/match_flower_name.py | match_flower_name.py | py | 2,262 | python | en | code | 0 | github-code | 13 |
25505961432 | from keras.callbacks import TensorBoard, ModelCheckpoint
from net import AutoEncoder
from return_corpus import ReutersMuscleCorpus
from functions import get_logger, load_vectors
from config import LOGDIR, JAWIKI_MODEL, MUSCLE_CORPUS, MUSCLE_MODEL
seq_size = 15
batch_size = 4
n_epoch = 20
latent_size = 512
def main():
logger = get_logger(LOGDIR)
logger.info('start')
logger.info('1. Load Japanese word2vec embeddings.')
embed_matrix, vocab = load_vectors(JAWIKI_MODEL)
logger.info('embedding shape is {}'.format(embed_matrix.shape))
logger.info('2. Prepare the corpus.')
corpus = ReutersMuscleCorpus()
corpus.build(embed_matrix, vocab, seq_size)
corpus.save(MUSCLE_CORPUS)
logger.info('3. Make autoencoder model.')
ae = AutoEncoder(seq_size=seq_size, embed_size=embed_matrix.shape[1], latent_size=latent_size)
ae.build()
logger.info('4. Train model.')
ae.model.compile(optimizer="adam", loss="mse")
train_iter = corpus.batch_iter(batch_size)
train_step = corpus.get_step_count(batch_size)
valid_iter = corpus.batch_iter(batch_size)
valid_step = corpus.get_step_count(batch_size)
ae.model.fit_generator(
train_iter,
train_step,
epochs=n_epoch,
validation_data=valid_iter,
validation_steps=valid_step,
callbacks=[
TensorBoard(log_dir=LOGDIR),
ModelCheckpoint(filepath=MUSCLE_MODEL, save_best_only=True)
]
)
logger.info('end')
if __name__ == '__main__':
main()
| trtd56/MuscleQA | src/ae_train.py | ae_train.py | py | 1,539 | python | en | code | 0 | github-code | 13 |
31543203840 | # -*- coding: utf-8 -*-
# encoding = utf8
import re
import time
from math import floor
# from background_task import background
from django.db.models import F
from django.template.loader import get_template
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.csrf import csrf_exempt
from twilio.rest import Client
from keys.manhattan import manhattan, parse, parseTest
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.template import loader
from keys.models import Keys, Users, Temp_User, Temp_Keys, Temp_Input, Temp_Mouse, Data, RecoveryAttempt, LoginAttempt, \
Impostors_Keys, Dropdown, Temp_Dropdown, Attacks
from keys.models import Input
from keys.models import Mouse
from datetime import date, datetime as dt
import datetime
# from passlib.hash import pbkdf2_sha256
from fuzzywuzzy import fuzz
from django.core.mail import EmailMultiAlternatives, EmailMessage
import random
# Global parameters
REPEAT1 = 5
REPEAT2 = 5
REPEAT3 = 10
min_enrol = 5
recoveryThreshold = 1.2
loginThreshold = 0.6
weeklyLogin = 20
weeklyAR = 5
total = 10
INTERVAL = 30
testdetails = {}
# @background(schedule=0)
def SaveAsImpostorKeys(ip_address, claimed_id, iteration, intention):
""" Save impostor keystrokes data """
keys = Data.objects.filter(ip=ip_address, iteration=iteration)
# Get last attempt number
user = Users.objects.get(memberID=claimed_id)
imp_attempts_no = user.imp_attempts_no + 1
Users.objects.filter(memberID=claimed_id).update(imp_attempts_no=imp_attempts_no)
if keys:
for i in keys:
imp_keys = Impostors_Keys(ip=ip_address, claimed_id=claimed_id, key_name=i.key_name, release=i.release,
timestamp=i.timestamp, widgetName=i.widgetName,
intention=iteration + str(imp_attempts_no))
imp_keys.save()
Data.objects.filter(ip=ip_address, iteration=iteration).delete()
def clear(ip_address):
Data.objects.filter(ip=ip_address).delete()
def getIP(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip_address = x_forwarded_for.split(',')[0]
else:
ip_address = request.META.get('REMOTE_ADDR')
request.session['ip_address'] = ip_address
return ip_address
def checkWeeklyTasks(request):
context = ''
loginWeeklyTaskLeft = -1
all_users_list = Users.objects.all()
for user in all_users_list:
f_name = str(user.first_name.lower()) + ' ' + str(user.last_name.lower())
if fuzz.ratio(f_name, request.session['sessionUserFullname'].lower()) > 80:
"""Found the user"""
d1 = datetime.datetime.strptime(date.today().strftime("%m/%d/%Y"), "%m/%d/%Y") # Current time
d2 = datetime.datetime.strptime(user.last_visited, "%m/%d/%Y") # Last visited
if abs((d2 - d1).days) >= 1:
# update last visited and reset weekly tasks
Users.objects.filter(memberID=user.memberID).update(last_visited=date.today().strftime("%m/%d/%Y"))
if user.login_attempt < 100:
if (100 - user.login_attempt) < weeklyLogin:
Users.objects.filter(memberID=user.memberID).update(
login_weekly_task_left=(100 - user.login_attempt))
else:
Users.objects.filter(memberID=user.memberID).update(login_weekly_task_left=weeklyLogin)
if user.AR_attempt < 20:
if (20 - user.AR_attempt) < weeklyAR:
Users.objects.filter(memberID=user.memberID).update(AR_weekly_task_left=(20 - user.AR_attempt))
else:
Users.objects.filter(memberID=user.memberID).update(AR_weekly_task_left=weeklyAR)
loginWeeklyTaskLeft = weeklyLogin
recovWeeklyTaskLeft = weeklyAR
else:
loginWeeklyTaskLeft = user.login_weekly_task_left
context = {'showWelcomeMessage': False, 'tasksleft': loginWeeklyTaskLeft}
break
else:
context = {'showWelcomeMessage': False, 'tasksleft': loginWeeklyTaskLeft} # Unregistered user
return context
def useKeystrokesDynamics(request, ip_address, username, pwd, phone, email, isTrueUser, user):
context = {}
# Get profile keystrokes
all_keys = Keys.objects.filter(user=attempt_user)
p1 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if i.release == 0 and
i.widgetName == 'userName' and i.genuine == 1 and i.decision == 'granted'])
p2 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if i.release == 0 and
(
i.widgetName == 'password' or i.widgetName == 'reTypePwd') and i.genuine == 1 and i.decision == 'granted'])
# Get test samples
samples = Data.objects.filter(ip=ip_address)
s1 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'userName')])
s2 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'password' or i.widgetName == 'reTypePwd')])
# calculate distance score
score1, sharedDigraph1 = manhattan(p1, s1)
if score1 != -1:
score2, sharedDigraph2 = manhattan(p2, s2)
if score2 != -1:
c = sharedDigraph1 + sharedDigraph2
w1 = sharedDigraph1 / c
w2 = sharedDigraph2 / c
distance_score = (w1 * score1 + w2 * score2) * 0.5
min_digraph = floor(0.8 * (len(username) + len(pwd))) # 80% shared digraph
if c >= min_digraph:
# Get the last iteration in DB
lastAttempt = (
Keys.objects.filter(user=attempt_user, iteration__startswith='UL').last()).iteration
lastAttempt = int(lastAttempt.replace('UL', '')) + 1
if distance_score <= loginThreshold:
request.session['is_loggedin'] = True
request.session['loggedin_user'] = fullname
# Save data
if isTrueUser:
status = "Granted (TA)"
# Update weekly task left
if user.login_weekly_task_left > 0:
Users.objects.filter(memberID=attempt_user).update(
login_weekly_task_left=(user.login_weekly_task_left - 1))
# Update login attempt count
Users.objects.filter(memberID=attempt_user).update(
login_attempt=user.login_attempt + 1)
# Push keystrokes and mouse data to database
addKeystrokesToProfile('UL', ip_address, attempt_user, 1, 'granted',
lastAttempt)
addMouseToProfile('UL', ip_address, attempt_user, 1, 'granted', lastAttempt)
else:
status = "Granted (FA)"
# Update user record with the attacked attempt
Users.objects.filter(memberID=attempt_user).update(
login_attacked=user.login_attacked + 1)
# Update Attacks table with impostor attempt
try:
print('Impostor ID:', impostorID)
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.login_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
login_attempts=F("login_attempts") + 1)
except:
print('Could not find attacker or attacked user')
addKeystrokesToProfile('UL', ip_address, attempt_user, 0, 'granted',
lastAttempt)
addMouseToProfile('UL', ip_address, attempt_user, 0, 'granted', lastAttempt)
# Save attempt
attempt = LoginAttempt(ip=ip_address, claimed_id=attempt_user,
timestamp=int(time.time()),
score='%.3f' % (distance_score),
threshold=loginThreshold, status=status)
attempt.save()
response = redirect('http://127.0.0.1:8000/soteria/landingpage')
return response
else:
# TODO: Enable OTP only as second factor if keystrokes fail
if isTrueUser:
status = "Denied (FR)"
else:
status = "Denied (TR)"
# Update Attacks table with impostor attempt
try:
print('Impostor ID:', impostorID)
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.login_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
login_attempts=F("login_attempts") + 1)
except:
print('Could not find attacker or attacked user')
# Update attacked attempt count
Users.objects.filter(memberID=attempt_user).update(
login_attacked=user.login_attacked + 1)
# Push keystrokes and mouse data to database
addKeystrokesToProfile('UL', ip_address, attempt_user, 0, 'denied', lastAttempt)
addMouseToProfile('UL', ip_address, attempt_user, 0, 'denied', lastAttempt)
# Save attempt
attempt = LoginAttempt(ip=ip_address, claimed_id=attempt_user,
timestamp=int(time.time()), score='%.3f' % (distance_score),
threshold=loginThreshold, status=status)
attempt.save()
# Escalate Login process by splitting OTP
otp1 = random.randint(000, 999)
otp2 = random.randint(000, 999)
otp = str(otp1) + str(otp2)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(expire_at=int(time.time() + 600))
sendSMS("The first half of your login verification code is : " + str(
otp1) + ". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA",
phone)
context_mail = {'fn': user.first_name, 'otp2': otp2, 'otp': True}
SendCustomEmail([email], context_mail, "Verification Required")
context = {'enterOTP': True, 'split': True}
url = 'home2.html'
return render(request, url, context)
else:
# Insufficient keystrokes
if isTrueUser:
status = "Insufficient Keystrokes (FR)"
else:
status = "Insufficient Keystrokes (TR)"
# Get the last iteration in DB
lastAttempt = (Keys.objects.filter(user=attempt_user,
iteration__startswith='UL').last()).iteration
lastAttempt = int(lastAttempt.replace('UL', '')) + 1
# Update Attacks table with impostor attempt
try:
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.login_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
login_attempts=F("login_attempts") + 1)
except:
print('Could not find attacker or attacked user')
# Update attacked attempt count
Users.objects.filter(memberID=attempt_user).update(
login_attacked=user.login_attacked + 1)
# Push keystrokes and mouse data to database
addKeystrokesToProfile('UL', ip_address, attempt_user, 0, 'denied', lastAttempt)
addMouseToProfile('UL', ip_address, attempt_user, 0, 'denied', lastAttempt)
# Save attempt
attempt = LoginAttempt(ip=ip_address, claimed_id=attempt_user,
timestamp=int(time.time()), score='%.3f' % (distance_score),
threshold=loginThreshold, status=status)
attempt.save()
# Escalate Login process by splitting OTP
otp1 = random.randint(000, 999)
otp2 = random.randint(000, 999)
otp = str(otp1) + str(otp2)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(expire_at=int(time.time() + 600))
sendSMS("The first half of your login verification code is : " + str(
otp1) + ". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA",
phone)
context_mail = {'fn': user.first_name, 'otp2': otp2, 'otp': True}
SendCustomEmail([email], context_mail, "Verification Required")
context = {'enterOTP': True, 'split': True}
url = 'home2.html'
return render(request, url, context)
else:
context = {'error': 'ACCESS DENIED.',
'tasksleft': loginWeeklyTaskLeft} # Invalid Data. Ensure content is typed
else:
context = {'error': 'ACCESS DENIED.',
'tasksleft': loginWeeklyTaskLeft} # Invalid Data. Ensure content is typed
return context
def home(request):
global fullname, attempt_user, impostorPhone, loginWeeklyTaskLeft, impostorID
ip_address = getIP(request)
print(request.session['ip_address'])
request.session['counter'] = 0
request.session['phase'] = 0
# Default
loginWeeklyTaskLeft = -1
context = {'showWelcomeMessage': False, 'tasksleft': loginWeeklyTaskLeft}
# Check the session user or show welcome message
if request.session.get('sessionUserFullname', '') == '':
context = {'showWelcomeMessage': True, 'tasksleft': loginWeeklyTaskLeft}
else:
_return = checkWeeklyTasks(request)
if isinstance(_return, dict):
context = _return
else:
return _return
request.session['action'] = 'login'
# Sign out all users when here
request.session['is_loggedin'] = False
request.session['loggedin_user'] = 'Unknown User'
try:
username = request.POST.get('userName')
pwd = request.POST.get('password')
if Users.objects.filter(username=request.POST['userName']).exists():
print('User found')
user = Users.objects.get(username=username)
true_pwd, true_username, attempt_user = user.password, user.username, user.memberID
fullname = user.first_name.lower() + ' ' + user.last_name.lower()
phone, email, login_template = user.phone, user.mail, user.login_template
# Only used by OTP page, clear elsewhere
request.session['tempUser'] = attempt_user
if request.session.get('sessionUserFullname', '') != '':
if fuzz.ratio(fullname, request.session['sessionUserFullname'].lower()) > 80:
isTrueUser = True
else:
isTrueUser = False
impostorPhone = ''
all_users_list = Users.objects.all()
for imp_user in all_users_list:
fulname = str(imp_user.first_name.lower()) + ' ' + str(imp_user.last_name.lower())
if fuzz.ratio(fulname, request.session['sessionUserFullname'].lower()) > 80:
# That's the impostor, get the phone and ID'
impostorPhone = imp_user.phone
impostorID = imp_user.memberID
print('Impostor phone is: ' + impostorPhone)
break
else:
context = {'error': 'Session Expired.', 'showWelcomeMessage': True}
url = 'home2.html'
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
return render(request, url, context)
# auth = pbkdf2_sha256.verify(pwd, true_pwd)
if true_username == username and pwd == true_pwd: # credentials are correct, check keystrokes
# check if user has at least 4 password enrollment sample
if isTrueUser and login_template < 4:
# Use single OTP
otp = random.randint(00000, 99999)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(expire_at=int(time.time() + 600))
sendSMS("Your login verification code is : " + str(
otp) + ". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA",
phone)
context = {'enterOTP': True}
return render(request, 'home2.html', context)
else:
_return1 = useKeystrokesDynamics(request, ip_address, username, pwd, phone, email, isTrueUser, user)
if isinstance(_return1, dict):
context = _return1
else:
return _return1
clear(ip_address)
clearMouseData(ip_address)
url = 'home2.html'
return render(request, url, context)
else:
context = {'error': 'ACCESS DENIED.', 'tasksleft': loginWeeklyTaskLeft}
clear(ip_address)
clearMouseData(ip_address)
url = 'home2.html'
if isTrueUser:
status = "Wrong Credentials (FR)"
else:
status = "Wrong Credentials (TR)"
attempt = LoginAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()), score=0,
threshold=loginThreshold, status=status)
attempt.save()
return render(request, url, context)
else:
print('Wrong login credentials.')
context = {'error': 'ACCESS DENIED.', 'tasksleft': loginWeeklyTaskLeft}
url = 'home2.html'
clear(ip_address)
clearMouseData(ip_address)
return render(request, url, context)
except MultiValueDictKeyError:
try: # Check OTP validation
otp = request.POST.get('otp')
attempt_user = request.session['tempUser']
user = Users.objects.get(memberID=attempt_user)
if str(otp) == str(user.otp):
# Check if OTP has expired
if int(user.expire_at) < int(time.time()):
clear(ip_address)
clearMouseData(ip_address)
context = {'error': 'OTP Expired.', 'tasksleft': loginWeeklyTaskLeft}
# Delete the tempUser
request.session.pop('tempUser', None)
return render(request, 'home2.html', context)
print('OTP is valid!')
request.session['is_loggedin'] = True
request.session['loggedin_user'] = user.first_name + ' ' + user.last_name
print("Building Template")
# Save attempt
attempt = LoginAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score='%.3f' % (0), threshold=loginThreshold, status='Building Template')
attempt.save()
# Get the last iteration in DB
if Keys.objects.filter(user=attempt_user, iteration__startswith='UL').exists():
lastAttempt = (Keys.objects.filter(user=attempt_user, iteration__startswith='UL').last()).iteration
lastAttempt = int(lastAttempt.replace('UL', '')) + 1
else:
lastAttempt = user.login_attempt + 1
# Update login template count
if fuzz.ratio(user.first_name.lower() + ' ' + user.last_name.lower(), request.session['sessionUserFullname'].lower()) > 80:
# True user
Users.objects.filter(memberID=attempt_user).update(login_template=(user.login_template + 1))
if user.login_weekly_task_left > 0:
Users.objects.filter(memberID=attempt_user).update(
login_weekly_task_left=(user.login_weekly_task_left - 1))
# Update login attempt count
Users.objects.filter(memberID=attempt_user).update(login_attempt=user.login_attempt + 1)
# Save login keystrokes to profile
addKeystrokesToProfile('UL', ip_address, attempt_user, 1, 'granted', lastAttempt)
addMouseToProfile('UL', ip_address, attempt_user, 1, 'granted', lastAttempt)
response = redirect('http://127.0.0.1:8000/soteria/landingpage')
return response
elif otp is None:
clear(ip_address)
clearMouseData(ip_address)
request.session.pop('tempUser', None)
return render(request, 'home2.html', context)
else:
clear(ip_address)
clearMouseData(ip_address)
context = {'enterOTP': True, 'error': 'WRONG OTP, Please retry.'}
return render(request, 'home2.html', context)
except (MultiValueDictKeyError, KeyError):
print("Welcome")
clear(ip_address)
clearMouseData(ip_address)
# Delete the tempUser
request.session.pop('tempUser', None)
return render(request, 'home2.html', context)
# @background(schedule=0)
def addKeystrokesToProfile(iteration, ip_address, memberID, genuine, decision, login_attempt):
# Save user keystrokes
data = Data.objects.filter(ip=ip_address, iteration=iteration)
if data:
for i in data:
keys = Keys(user=memberID, key_name=i.key_name, release=i.release, timestamp=i.timestamp,
widgetName=i.widgetName,
iteration=i.iteration + str(login_attempt), genuine=genuine, decision=decision)
keys.save()
Data.objects.filter(ip=ip_address, iteration=iteration).delete()
# @background(schedule=0)
def addMouseToProfile(iteration, ip_address, attempt_user, genuine, decision, login_attempt):
# Save user Mouse
user_mouse = Temp_Mouse.objects.filter(user=ip_address)
if user_mouse:
for i in user_mouse:
mouse = Mouse(user=attempt_user, event=i.event, widgetType=i.widgetType, widgetName=i.widgetName,
page=i.page, timestamp=i.timestamp, genuine=genuine, decision=decision,
iteration=iteration + str(login_attempt), resolution=i.resolution, x_pos=i.x_pos,
y_pos=i.y_pos)
mouse.save()
Temp_Mouse.objects.filter(user=ip_address).delete()
def sendSMS(message, phone):
if '+' not in str(phone):
phone = '+1' + str(phone)
account_sid = '*******************************'
auth_token = '*******************************'
client = Client(account_sid, auth_token)
client.messages.create(to=phone, from_='+13233363926', body=message)
def index(request):
latest_question_list = ''
template = loader.get_template('index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
# For Account Recovery
def listen(request):
m = 'RFA'
username = request.session.get('memberID', '')
if username == '': exit()
iterat = m[request.session.get('phase', 0)] + str(request.session['counter'] + 1)
e = eval(request.path.split('n/')[-1])
saveKeys(username, e, iterat)
return HttpResponse(request)
# comment - @background(schedule=0)
def saveKeys(username, e, iterat):
b = Keys(user=username, key_name=e.get("k"), release=e.get("r"), timestamp=e.get("t"),
widgetName=e.get("s"), iteration=iterat)
b.save()
# For Enrollment
def temp_keys_listen(request):
username = request.session.get('memberID', '')
if username == '': exit()
iterat = 'R' + str(request.session['counter'] + 1)
e = eval(request.path.split('n/')[-1])
saveTempKeys(username, e, iterat)
return HttpResponse(request)
# comment - @background(schedule=0)
def saveTempKeys(username, e, iterat):
b = Temp_Keys(user=username, key_name=e.get("k"), release=e.get("r"), timestamp=e.get("t"),
widgetName=e.get("s"), iteration=iterat)
b.save()
# For Account Recovery
def dropdwnln(request):
ip_address = request.session.get('ip_address', '')
if ip_address == '': exit()
e = eval(request.path.split('dropdwnln')[-1])
saveDropdown(ip_address, e, '')
return HttpResponse(request)
# For Enrollment
def dropdwnlisten2(request):
ip_address = request.session.get('ip_address', '')
if ip_address == '': exit()
e = eval(request.path.split('dropdwnlisten2')[-1])
iterat = 'R' + str(request.session['counter'] + 1)
saveDropdown(ip_address, e, iterat)
return HttpResponse(request)
# comment - @background(schedule=0)
def saveDropdown(ip_address, e, iterat):
b = Temp_Dropdown(user=ip_address, timestamp=e['t'], widgetName=e['w'], widgetStatus=e['s'], action=e['a'],
iteration=iterat)
b.save()
# For Account Recovery
def mousee(request):
data = eval(request.path.split('mousee')[-1])
ip_address = request.session.get('ip_address', '')
if ip_address == '': exit()
saveMouse(ip_address, data, '')
return HttpResponse(request)
# For Enrollment
def mousee2(request):
data = eval(request.path.split('mousee2')[-1])
ip_address = request.session.get('ip_address', '')
if ip_address == '': exit()
iterat = 'R' + str(request.session['counter'] + 1)
saveMouse(ip_address, data, iterat)
return HttpResponse(request)
# comment - @background(schedule=0)
def saveMouse(ip_address, data, iterat):
if data.get("e") != 'mouse_move': # It is mouseovers, else mouse coordinates
b = Temp_Mouse(user=ip_address, event=data.get("e"), widgetType=data.get("w"),
widgetName=data.get("c"), page=data.get("p"), timestamp=data.get("t"), iteration=iterat)
else:
b = Temp_Mouse(user=ip_address, event=data.get("e"), x_pos=data.get("x_po"), y_pos=data.get("y_po"),
page=data.get("p"), timestamp=data.get("t"), resolution=data.get("r"), iteration=iterat)
b.save()
def listn2(request):
ip_address = request.session.get('ip_address', '')
if ip_address == '': exit()
if request.session['action'] == 'account_recovery':
iterat = 'AR' # AR stands for Account Recovery keystrokes
e = eval(request.path.split('2/')[-1])
saveTempData2(ip_address, e, iterat) # Store Asynchronously
else:
iterat = 'UL' # UL stands for User Login keystrokes
e = eval(request.path.split('2/')[-1])
saveTempData(ip_address, e, iterat) # Store synchronously
return HttpResponse(request)
# @background(schedule=0)
def saveTempData(ip_address, e, iterat):
b = Data(ip=ip_address, key_name=e.get("k"), release=e.get("r"), timestamp=e.get("t"),
widgetName=e.get("s"), iteration=iterat)
b.save()
# @background(schedule=0)
def saveTempData2(ip_address, e, iterat):
b = Data(ip=ip_address, key_name=e.get("k"), release=e.get("r"), timestamp=e.get("t"),
widgetName=e.get("s"), iteration=iterat)
b.save()
def informedconsent(request):
return render(request, "informed_consent.html", {})
def forgotpwd1(request):
recovWeeklyTaskLeft = -1 # Default
request.session['action'] = 'account_recovery'
if request.session.get('sessionUserFullname', '') == '':
context = {'showWelcomeMessage': True, 'taskLeft': -1}
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/')
return response
else:
all_users_list = Users.objects.all()
for user in all_users_list:
fulname = str(user.first_name.lower()) + ' ' + str(user.last_name.lower())
if fuzz.ratio(fulname, request.session['sessionUserFullname'].lower()) > 80:
d1 = datetime.datetime.strptime(date.today().strftime("%m/%d/%Y"), "%m/%d/%Y") # Current time
d2 = datetime.datetime.strptime(user.last_visited, "%m/%d/%Y") # Last visited
if abs((d2 - d1).days) >= 1:
# update last visited
Users.objects.filter(memberID=user.memberID).update(last_visited=date.today().strftime("%m/%d/%Y"))
Users.objects.filter(memberID=user.memberID).update(login_weekly_task_left=weeklyLogin)
Users.objects.filter(memberID=user.memberID).update(AR_weekly_task_left=weeklyAR)
recovWeeklyTaskLeft = weeklyAR
else:
recovWeeklyTaskLeft = user.AR_weekly_task_left
break
ip_address = request.session.get('ip_address', '')
clear(ip_address)
clearMouseData(ip_address)
context = {'taskLeft': recovWeeklyTaskLeft}
return render(request, 'forgotpwd1.html', context)
def forgotpwd2(request):
request.session['action'] = 'account_recovery'
testdetails.clear()
request.session['memberID'] = request.POST.get('memberId')
request.session['toEmail'] = request.POST.get('email')
ip_address = request.session.get('ip_address', '')
if request.session.get('sessionUserFullname', '') == '':
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/')
return response
j = 0
for i in request.POST:
if i == 'csrfmiddlewaretoken' or i == 'day' or i == 'year' or i == 'reTypeEmail': continue
if i == 'month':
testdetails[request.session['memberID'] + '_' + str(j)] = dt(int(request.POST.get('year')),
int(request.POST.get('month')),
int(request.POST.get('day')))
elif i == 'zipcode':
testdetails[request.session['memberID'] + '_' + str(j)] = int(request.POST.get(i).strip())
else:
testdetails[request.session['memberID'] + '_' + str(j)] = request.POST.get(i).strip().lower()
j += 1
print(testdetails)
context = {'user_name': {'fn': request.POST.get('fullFname'), 'ln': request.POST.get('fullLname')}, }
return render(request, 'forgotpwd2.html', context)
def forgotpwd3(request):
global impostorEmail, context, impostorID
request.session['action'] = 'account_recovery'
declaretext1 = request.POST.get('declaretext', '')
attempt_user = request.session.get('memberID', '')
ip_address = request.session.get('ip_address', '')
if request.session.get('sessionUserFullname', '') == '':
context = {'showWelcomeMessage': True}
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/')
return response
try:
# check if the declare text is at least 85% accurate
declaretext2 = 'I declare that I am ' + testdetails[request.session['memberID'] + '_1'] + ' ' + \
testdetails[request.session['memberID'] + '_2'] + ' and everything I type here is true.'
info = fuzz.ratio(declaretext1, declaretext2)
# Get the user actual details
if Users.objects.filter(memberID=attempt_user).exists():
user_details = Users.objects.get(memberID=attempt_user)
AR_template = user_details.AR_template
phone = user_details.phone
# Check who the current user is
impostorID = ''
fulname = str(user_details.first_name.lower()) + ' ' + str(user_details.last_name.lower())
if fuzz.ratio(fulname, request.session['sessionUserFullname'].lower()) > 80:
owner = True # It's true owner
else:
owner = False # Not true owner
imp_users_list = Users.objects.all()
for imp_user in imp_users_list:
fulname = str(imp_user.first_name.lower()) + ' ' + str(imp_user.last_name.lower())
if fuzz.ratio(fulname, request.session['sessionUserFullname'].lower()) > 80:
# That's the impostor, get the email address'
impostorEmail = imp_user.mail
impostorID = imp_user.memberID
break
if info < 85:
print("Incorrect declare statement")
context = {'access_denied': True, 'message': 'ACCESS DENIED'}
if owner:
status = "Wrong info (FR)"
clear(ip_address)
clearMouseData(ip_address)
else:
status = "Wrong info (TR)"
clear(ip_address)
clearMouseData(ip_address)
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()), score=0,
threshold=recoveryThreshold, status=status)
attempt.save()
# The declare texts were not entered correctly
return render(request, 'forgotpwd3.html', context)
details = [user_details.memberID, user_details.first_name.lower(), user_details.last_name.lower(),
user_details.dob, user_details.address.lower(), user_details.city.lower(),
user_details.state.lower(), user_details.zipcode, user_details.country.lower(),
user_details.phone,
user_details.mail.lower()]
for eachdetail in testdetails:
i = int(eachdetail[-1])
# check if dob match
if i == 3:
if str(details[i]) != str(testdetails[eachdetail])[:10]:
# Some information provided are not correct
print("DOB not correct")
context = {'access_denied': True, 'message': 'ACCESS DENIED'}
if owner:
status = "Wrong info (FR)"
else:
status = "Wrong info (TR)"
clear(ip_address)
clearMouseData(ip_address)
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score=0, threshold=recoveryThreshold, status=status)
attempt.save()
return render(request, 'forgotpwd3.html', context)
# check if Fname, Lname and Email perfectly match
elif i in [1, 2, 5, 6, 7, 8, 9]: # The numbers are the position of items in "details" array
info = fuzz.ratio(testdetails[eachdetail], details[i])
if info < 100:
print(details[i], " not correct")
context = {'access_denied': True,
'message': 'ACCESS DENIED'} # Some information provided are not correct
if owner:
status = "Wrong info (FR)"
else:
status = "Wrong info (TR)"
clear(ip_address)
clearMouseData(ip_address)
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score=0, threshold=recoveryThreshold, status=status)
attempt.save()
return render(request, 'forgotpwd3.html', context)
# check if other fields are at least 80% accurate
else:
if eachdetail[-2:] == '10':
info = fuzz.ratio(testdetails[eachdetail], details[10])
else:
info = fuzz.ratio(testdetails[eachdetail], details[i])
if info < 80:
print('Failed here ', i)
context = {'access_denied': True,
'message': 'ACCESS DENIED'} # Some of the information provided are not correct
if owner:
status = "Wrong info (FR)"
else:
status = "Wrong info (TR)"
clear(ip_address)
clearMouseData(ip_address)
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score=0, threshold=recoveryThreshold, status=status)
attempt.save()
return render(request, 'forgotpwd3.html', context)
# Check if account recovery samples is at least 4
if AR_template < 4:
otp = random.randint(00000, 99999)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(expire_at=int(time.time() + 600))
sendSMS("Your account recovery verification code is : " + str(otp) +
". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA", phone)
context = {'enterOTP': True}
return render(request, 'forgotpwd3.html', context)
# Get profile
all_keys = Keys.objects.filter(user=attempt_user)
if not all_keys:
context = {'access_denied': True,
'message': 'ACCESS DENIED'} # The user does not exist. Ensure you type in a valid Member ID
return render(request, 'forgotpwd3.html', context)
# Use all keystroke (granted or denied) that belongs to the true user
all_keys = Keys.objects.filter(user=attempt_user)
p1 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if i.release == 0 and
(i.widgetName == 'Fname' or i.widgetName == 'Lname') and i.genuine == 1 and i.decision == 'granted'])
p2 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if
i.release == 0 and (i.widgetName == 'declare') and i.genuine == 1 and i.decision == 'granted'])
p3 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if
i.release == 0 and (i.widgetName == 'address') and i.genuine == 1 and i.decision == 'granted'])
p4 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if
i.release == 0 and (i.widgetName == 'city') and i.genuine == 1 and i.decision == 'granted'])
p5 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if
i.release == 0 and (i.widgetName == 'zip') and i.genuine == 1 and i.decision == 'granted'])
p6 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if
i.release == 0 and (i.widgetName == 'phone') and i.genuine == 1 and i.decision == 'granted'])
p7 = sorted([(i.timestamp, i.key_name, i.release) for i in all_keys if i.release == 0 and
(i.widgetName == 'email' or i.widgetName == 'reEmail') and i.genuine == 1 and i.decision == 'granted'])
# Get test samples
samples = Data.objects.filter(ip=ip_address)
s1 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'Fname' or i.widgetName == 'Lname')])
s2 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'declare')])
s3 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'address')])
s4 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'city')])
s5 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'zip')])
s6 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'phone')])
s7 = sorted([(i.timestamp, i.key_name, i.release) for i in samples if
i.release == 0 and (i.widgetName == 'email' or i.widgetName == 'reEmail')])
profile_lst = [p1, p2, p3, p4, p5, p6, p7]
sample_lst = [s1, s2, s3, s4, s5, s6, s7]
scores, sharedDigraphs = [], []
for i in range(len(profile_lst)):
score__, sharedDigraph__ = manhattan(profile_lst[i], sample_lst[i])
if score__ == -1:
clear(ip_address)
clearMouseData(ip_address)
context = {'access_denied': True, 'message': 'ACCESS DENIED.'}
return render(request, 'forgotpwd3.html', context)
scores.append(score__)
sharedDigraphs.append(sharedDigraph__)
distance_score = ((scores[0] * 0.15) + (scores[1] * 0.25) + (scores[2] * 0.05) + (
scores[3] * 0.1) + (scores[4] * 0.05) + (scores[5] * 0.05) + (scores[6] * 0.35))
c = sum(sharedDigraphs)
print('final score: ', distance_score)
min_digraph = floor(0.8 * (len(testdetails[request.session['memberID'] + '_1']) + len(
testdetails[request.session['memberID'] + '_2']) + len(
testdetails[request.session['memberID'] + '_4']) + len(
testdetails[request.session['memberID'] + '_5']) + len(
str(testdetails[request.session['memberID'] + '_7'])) + len(
str(testdetails[request.session['memberID'] + '_9'])) + 2 * (len(
testdetails[request.session['memberID'] + '_10'])))) # 80% information shared digraph
print('Min_Digraph: ', min_digraph)
if c >= min_digraph:
# Get the last iteration in DB
lastAttempt = (Keys.objects.filter(user=attempt_user, iteration__startswith='AR').last()).iteration
lastAttempt = int(lastAttempt.replace('AR', '')) + 1
if distance_score <= recoveryThreshold:
# Check session user fullname
if owner:
status = "Granted (TA)"
# Update weekly task left
if user_details.AR_weekly_task_left > 0:
Users.objects.filter(memberID=attempt_user).update(AR_weekly_task_left=(user_details.AR_weekly_task_left - 1))
# Update the recovery attempt
AR_attempt = user_details.AR_attempt + 1
Users.objects.filter(memberID=attempt_user).update(AR_attempt=AR_attempt)
# Save login keystrokes to profile
addKeystrokesToProfile('AR', ip_address, attempt_user, 1, 'granted', lastAttempt)
moveMouseData('AR', ip_address, attempt_user, 1, 'granted', lastAttempt)
context = {'message': 'Welcome back, ' + attempt_user + '. ' +
'You have passed our credential checking.', 'owner': owner}
else:
status = "Granted (FA)"
# Update Attacks table with impostor attempt
try:
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.AR_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
AR_attempts=F("AR_attempts") + 1)
except:
print('Attacker or Attacked user not found!')
# Update attacked attempt count
Users.objects.filter(memberID=attempt_user).update(
AR_attacked=user_details.AR_attacked + 1)
# Save login keystrokes to profile
addKeystrokesToProfile('AR', ip_address, attempt_user, 0, 'granted', lastAttempt)
moveMouseData('AR', ip_address, attempt_user, 0, 'granted', lastAttempt)
context = {'message': 'Welcome back, ' + attempt_user + '. ' +
'You have passed our credential checking.', 'owner': owner}
# Save successful attempt
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score='%.3f' % (distance_score), threshold=recoveryThreshold, status=status)
attempt.save()
# Clear Temp_Keys before storing new password keystokes
Temp_Keys.objects.filter(user=attempt_user).delete()
context = {'user_name': {'fn': user_details.first_name, 'ln': user_details.last_name}}
return render(request, 'forgotpwd4.html', context)
else:
if owner:
status = "Denied (FR)"
# Save keystrokes only after OTP is verified
else:
status = "Denied (TR)"
# Update Attacks table with impostor attempt
try:
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.AR_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
AR_attempts=F("AR_attempts") + 1)
except:
print('Attacker or Attacked user not found!')
# Update attacked attempt count
Users.objects.filter(memberID=attempt_user).update(AR_attacked=user_details.AR_attacked + 1)
# Save login keystrokes to profile
addKeystrokesToProfile('AR', ip_address, attempt_user, 0, 'denied', lastAttempt)
moveMouseData('AR', ip_address, attempt_user, 0, 'denied', lastAttempt)
# Save attempt
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score='%.3f' % distance_score, threshold=recoveryThreshold, status=status)
attempt.save()
# User OTP
print("Keystrokes failed.")
# Escalate Login process by splitting OTP
otp1 = random.randint(000, 999)
otp2 = random.randint(000, 999)
otp = str(otp1) + str(otp2)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(expire_at=int(time.time() + 600))
sendSMS(
"The first half of your account recovery verification code is : " + str(otp1) +
". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA", phone)
context_mail = {'fn': user_details.first_name, 'otp2': otp2, 'otp': True}
SendCustomEmail([user_details.mail], context_mail, "Verification Required")
context = {'enterOTP': True, 'split': True}
return render(request, 'forgotpwd3.html', context)
else:
if owner:
status = "Insufficient Keystrokes (FR)"
else:
status = "Denied (TR)"
# Get the last iteration in DB
lastAttempt = (Keys.objects.filter(user=attempt_user, iteration__startswith='AR').last()).iteration
lastAttempt = int(lastAttempt.replace('AR', '')) + 1
# Update Attacks table with impostor attempt
try:
if Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).exists():
attack_count = Attacks.objects.get(attacker=impostorID, attacks=attempt_user)
if attack_count.AR_attempts < 10:
Attacks.objects.filter(attacker=impostorID, attacks=attempt_user).update(
AR_attempts=F("AR_attempts") + 1)
except:
print('Attacker or Attacked user not found!')
# Update attacked attempt count
Users.objects.filter(memberID=attempt_user).update(AR_attacked=user_details.AR_attacked + 1)
# Save login keystrokes to profile
addKeystrokesToProfile('AR', ip_address, attempt_user, 0, 'denied', lastAttempt)
moveMouseData('AR', ip_address, attempt_user, 0, 'denied', lastAttempt)
# Save attempt
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score='%.3f' % distance_score, threshold=recoveryThreshold, status=status)
attempt.save()
# User OTP
print("Keystrokes failed: Insufficient keystrokes")
# Escalate Login process by splitting OTP
otp1 = random.randint(000, 999)
otp2 = random.randint(000, 999)
otp = str(otp1) + str(otp2)
Users.objects.filter(memberID=attempt_user).update(otp=otp)
# Set expiration
Users.objects.filter(memberID=attempt_user).update(
expire_at=int(time.time() + 600))
sendSMS("The first half of your account recovery verification code is : " + str(otp1) +
". It expires in 10 minutes. Please ignore if you did not request for this. SOTERIA", phone)
context_mail = {'fn': user_details.first_name, 'otp2': otp2, 'otp': True}
SendCustomEmail([user_details.mail], context_mail, "Verification Required")
context = {'enterOTP': True, 'split': True}
return render(request, 'forgotpwd3.html', context)
else:
ip_address = request.session.get('ip_address', '')
clear(ip_address)
clearMouseData(ip_address)
context = {'access_denied': True,
'message': 'ACCESS DENIED'} # The user does not exist. Ensure you type in a valid Member ID
return render(request, 'forgotpwd3.html', context)
except:
print('Value Error: Something went wrong.')
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/soteria/forgotpwd1')
return response
def forgotpwd4(request):
global AR_attempt
if request.session.get('sessionUserFullname', '') == '':
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/')
return response
otp = request.POST.get('otp')
attempt_user = request.session['memberID']
user = Users.objects.get(memberID=attempt_user)
ip_address = request.session.get('ip_address', '')
if str(otp) == str(user.otp):
# Check if OTP has expired
if int(user.expire_at) < int(time.time()):
clear(ip_address)
clearMouseData(ip_address)
context = {'access_denied': True, 'message': 'OTP Expired.'}
return render(request, 'forgotpwd3.html', context)
if user.AR_weekly_task_left > 0:
Users.objects.filter(memberID=attempt_user).update(AR_weekly_task_left=(user.AR_weekly_task_left - 1))
# Update the recovery attempt
AR_attempt = user.AR_attempt + 1
Users.objects.filter(memberID=attempt_user).update(AR_attempt=AR_attempt)
if user.AR_attempt != 0:
# Get the last iteration in DB and increment
lastAttempt = (Keys.objects.filter(user=attempt_user, iteration__startswith='AR').last()).iteration
lastAttempt = int(lastAttempt.replace('AR', '')) + 1
else:
lastAttempt = user.AR_attempt + 1
# Update template
Users.objects.filter(memberID=attempt_user).update(AR_template=user.AR_template + 1)
addKeystrokesToProfile('AR', ip_address, attempt_user, 1, 'granted', lastAttempt)
moveMouseData('AR', ip_address, attempt_user, 1, 'granted', lastAttempt)
# Save attempt
print("Building Template")
attempt = RecoveryAttempt(ip=ip_address, claimed_id=attempt_user, timestamp=int(time.time()),
score='%.3f' % 0, threshold=loginThreshold, status='Building Template')
attempt.save()
context = {'user_name': {'fn': user.first_name, 'ln': user.last_name}}
return render(request, 'forgotpwd4.html', context)
else:
context = {'enterOTP': True, 'error': 'Wrong OTP, please try again.'}
return render(request, 'forgotpwd3.html', context)
def resendEmail(request):
attempt_user = request.session.get('memberID', '')
user_details = Users.objects.get(memberID=attempt_user)
pwd = str(user_details.password)
code = pwd[(len(pwd) // 2) - 7: (len(pwd) // 2) + 7]
title = 'Password Reset Link'
ip_address = request.session.get('ip_address', '')
link = 'http://127.0.0.1:8000/soteria/forgotpwd4?code=' + code + '&ip=' + ip_address + '&id=' + attempt_user + '&pwd_status=' + \
request.session['pwd_status']
context_mail = {'fn': user_details.first_name, 'link': link, 'pwd_reset': True}
SendCustomEmail([request.session['toEmail']], context_mail, title)
context = {'email_resent': True, 'message': 'Link has been sent. Please check your email'}
return render(request, 'resend_email.html', context)
def email_resend(request):
mID = request.session.get('memberID', '')
newUser = Temp_User.objects.get(memberID=mID)
pwd = newUser.password
mail = newUser.mail
fn, ln = newUser.first_name, newUser.last_name
# Send verification email
code = pwd[(len(pwd) // 2) - 7: (len(pwd) // 2) + 7]
if '#' in code:
code = code.split("#", 1)[0]
title = 'Email Verification'
link = 'http://127.0.0.1:8000/soteria/email_verification?code=' + str(code) + '&id=' + mID
context = {'fn': fn, 'mID': mID, 'link': link, 'signup': True}
SendCustomEmail([mail], context, title)
context = {
'user_name': {'fn': fn, 'ln': ln},
'email': mail
}
return render(request, "signup_verification.html", context)
# This clears the select widget data also
def clearMouseData(ip_address):
Temp_Mouse.objects.filter(user=ip_address).delete()
Temp_Dropdown.objects.filter(user=ip_address).delete()
def cleanTempKeys(user):
Temp_Keys.objects.filter(user=user, widgetName='password').delete()
Temp_Keys.objects.filter(user=user, widgetName='reTypePwd').delete()
def success2(request):
# Check if session has expired
global lastAttempt
if request.session.get('sessionUserFullname', '') == '':
context = {'showWelcomeMessage': True}
ip_address = getIP(request)
clear(ip_address)
clearMouseData(ip_address)
response = redirect('http://127.0.0.1:8000/')
return response
attempt_user = request.session.get('memberID', '')
user_details = Users.objects.get(memberID=attempt_user)
NewP = request.POST.get('reTypePwd')
# Ensure password requirements are met
if NewP != user_details.username and len(NewP) >= 8 and bool(re.search(r'\d', NewP)) and NewP.lower().islower():
if NewP != user_details.password:
Users.objects.filter(memberID=attempt_user).update(login_template=0)
# Save new password to users table
pwd = request.POST.get('reTypePwd')
Users.objects.filter(memberID=request.session['memberID']).update(password=pwd)
# Get the last iteration in DB without increment
lastAttempt = (Keys.objects.filter(user=attempt_user, iteration__startswith='AR').last()).iteration
lastAttempt = int(lastAttempt.replace('AR', ''))
if fuzz.ratio(user_details.first_name.lower() + ' ' + user_details.last_name.lower(), request.session['sessionUserFullname'].lower()) > 80:
# True User
# Add new password keystrokes
addKeystrokesToProfile('AR', request.session['ip_address'], attempt_user, 1, 'granted', lastAttempt)
moveMouseData('AR', request.session['ip_address'], attempt_user, 1, 'granted', lastAttempt)
else:
# Add new password keystrokes
addKeystrokesToProfile('AR', request.session['ip_address'], attempt_user, 0, 'granted', lastAttempt)
moveMouseData('AR', request.session['ip_address'], attempt_user, 0, 'granted', lastAttempt)
pwd_status = request.session.get('pwd_status', '0')
Users.objects.filter(memberID=request.session['memberID']).update(pwd_status=pwd_status)
if pwd_status == '2' or pwd_status == '1':
homeLink = "http://127.0.0.1:8000"
context = {'status': homeLink, 'message': 'Your password has been updated.'}
else:
homeLink = "http://127.0.0.1:8000"
context = {'status': homeLink}
return render(request, 'success.html', context)
else:
context = {'message': '* Ensure new password meets all requirements'}
return render(request, 'forgotpwd4.html', context)
# comment - @background(schedule=3)
def moveNewPasswordData(user):
# Create new user
data1 = Temp_Keys.objects.filter(user=user, widgetName='password')
data2 = Temp_Keys.objects.filter(user=user, widgetName='reTypePwd')
if data1:
for i in data1:
keys = Keys(user=i.user, key_name=i.key_name, release=i.release, timestamp=i.timestamp,
widgetName=i.widgetName,
iteration=i.iteration)
keys.save()
Temp_Keys.objects.filter(user=user, widgetName='password').delete()
if data2:
for i in data2:
keys = Keys(user=i.user, key_name=i.key_name, release=i.release, timestamp=i.timestamp,
widgetName=i.widgetName,
iteration=i.iteration)
keys.save()
Temp_Keys.objects.filter(user=user, widgetName='reTypePwd').delete()
# @background(schedule=0)
def moveMouseData(iteration, ip_address, attempt_user, genuine, decision, AR_attempt):
user_Dropdwn = Temp_Dropdown.objects.filter(user=ip_address)
if user_Dropdwn:
for i in user_Dropdwn:
dropdwn = Dropdown(user=attempt_user, timestamp=i.timestamp, widgetName=i.widgetName,
widgetStatus=i.widgetStatus, action=i.action, genuine=genuine, decision=decision,
iteration=iteration + str(AR_attempt))
dropdwn.save()
Temp_Dropdown.objects.filter(user=ip_address).delete()
# Save user Mouse
user_mouse = Temp_Mouse.objects.filter(user=ip_address)
if user_mouse:
for i in user_mouse:
mouse = Mouse(user=attempt_user, event=i.event, widgetType=i.widgetType, widgetName=i.widgetName,
page=i.page, timestamp=i.timestamp, genuine=genuine, decision=decision,
iteration=iteration + str(AR_attempt), resolution=i.resolution, x_pos=i.x_pos, y_pos=i.y_pos)
mouse.save()
Temp_Mouse.objects.filter(user=ip_address).delete()
# comment - @background(schedule=0)
def movedata(userID, ip_address):
# Create new user
new_user = Temp_User.objects.filter(memberID=userID).first()
if new_user:
user = Users(memberID=new_user.memberID, first_name=new_user.first_name, dob=new_user.dob,
last_name=new_user.last_name, address=new_user.address, city=new_user.city, state=new_user.state,
zipcode=new_user.zipcode, country=new_user.country, mail=new_user.mail, phone=new_user.phone,
username=new_user.username, password=new_user.password)
user.save()
Temp_User.objects.filter(memberID=userID).delete()
# Save user keystrokes
user_keys = Temp_Keys.objects.filter(user=userID)
if user_keys:
for i in user_keys:
keys = Keys(user=i.user, key_name=i.key_name, release=i.release, timestamp=i.timestamp,
widgetName=i.widgetName,
iteration=i.iteration)
keys.save()
Temp_Keys.objects.filter(user=userID).delete()
# Save user input
user_input = Temp_Input.objects.filter(memberID=userID)
if user_input:
for i in user_input:
inputs = Input(memberID=i.memberID, fname=i.fname, dob=i.dob, lname=i.lname, address=i.address, city=i.city,
state=i.state, zipcode=i.zipcode, country=i.country, mail=i.mail, phone=i.phone)
inputs.save()
Temp_Input.objects.filter(memberID=userID).delete()
# Save user mouse clicks
user_mouse = Temp_Mouse.objects.filter(user=ip_address)
if user_mouse:
for i in user_mouse:
mouse = Mouse(user=userID, event=i.event, widgetType=i.widgetType, widgetName=i.widgetName, page=i.page,
timestamp=i.timestamp, genuine=1, iteration=i.iteration)
mouse.save()
Temp_Mouse.objects.filter(user=ip_address).delete()
# Save user dropdown
user_dropdwn = Temp_Dropdown.objects.filter(user=ip_address)
if user_dropdwn:
for i in user_dropdwn:
dropdwn = Dropdown(user=i.user, timestamp=i.timestamp, widgetName=i.widgetName, widgetStatus=i.widgetStatus,
action=i.action, genuine=1, iteration=i.iteration)
dropdwn.save()
Temp_Dropdown.objects.filter(user=ip_address).delete()
# @background(schedule=0)
def createNewUser(userID):
# Create new user
new_user = Temp_User.objects.filter(memberID=userID).first()
if new_user:
user = Users(memberID=new_user.memberID, first_name=new_user.first_name, dob=new_user.dob,
last_name=new_user.last_name, address=new_user.address, city=new_user.city, state=new_user.state,
zipcode=new_user.zipcode, country=new_user.country, mail=new_user.mail, phone=new_user.phone,
username=new_user.username, password=new_user.password)
user.save()
Temp_User.objects.filter(memberID=userID).delete()
def memberID(request):
import os
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'ids.txt')
request.session['counter'] = 0
ids = open(file_path).read().strip().split('\n')
p = ids[Input.objects.values('memberID').distinct().count()]
template = loader.get_template('memberID.html')
return HttpResponse(template.render({}, request))
def signup1(request):
# Send signed Informed Consent Form to user via mail
signatureName = request.POST.get('fullname')
print(signatureName)
request.session['action'] = 'account_recovery'
return render(request, "signup1.html", {})
def signup2(request):
ip_address = getIP(request)
request.session['counter'] = 0
username = request.POST.get('userName').strip()
password = request.POST.get('password').strip()
if password != username and len(password) >= 8 and bool(re.search(r'\d', password)) and password.lower().islower():
fn = request.POST.get('fullFname').strip()
ln = request.POST.get('fullLname').strip()
mID = request.POST.get('memberId').strip()
bd = request.POST.get('day')
bm = request.POST.get('month')
by = request.POST.get('year')
daob = dt(int(by), int(bm), int(bd))
add = request.POST.get('address').strip()
cit = request.POST.get('city').strip()
sta = request.POST.get('state')
zipc = request.POST.get('zipcode').strip()
phone = request.POST.get('phone').strip()
count = request.POST.get('country')
mail = request.POST.get('email').strip()
pwd = request.POST.get('password').strip()
# Clear old unused data
Temp_Keys.objects.filter(user=mID).delete()
Temp_Input.objects.filter(memberID=mID).delete()
Temp_Mouse.objects.filter(user=mID).delete()
Temp_Dropdown.objects.filter(user=mID).delete()
# Check if username exist
if Users.objects.filter(username=username).exists():
context = {'message': 'Username has been used by another user'}
# Check if memberID exist
elif Users.objects.filter(memberID=mID).exists():
context = {'message': 'MemberID has been used by another user'}
elif (Users.objects.filter(first_name=fn).exists() and Users.objects.filter(
last_name=request.POST['fullLname']).exists()):
context = {'message': 'Name has been used by another user'}
else:
if Temp_User.objects.filter(memberID=mID).exists():
print('Record found.')
# Delete previous
Temp_User.objects.get(memberID=mID).delete()
# Save user input details
temp = Temp_User(memberID=mID, first_name=fn, dob=daob, last_name=ln, address=add, city=cit, state=sta,
zipcode=zipc, country=count, mail=mail, phone=phone, username=username, password=pwd,
activation=0)
temp.save()
# Send verification email
code = pwd[(len(pwd) // 2) - 7: (len(pwd) // 2) + 7]
if '#' in code:
code = code.split("#", 1)[0]
title = 'Email Verification'
link = 'http://127.0.0.1:8000/soteria/email_verification?code=' + str(code) + '&id=' + mID + '&ip=' + ip_address
context = {'fn': fn, 'mID': mID, 'link': link, 'signup': True}
SendCustomEmail([mail], context, title)
# Send proof of signed Informed Consent Form
context_mail = {'fn': fn, 'ln': ln, 'mID': mID, 'link': link, 'informed_consent': True}
SendCustomEmail([mail], context_mail, 'Proof of Consent')
request.session['memberID'] = mID
for i in request.POST:
request.session[i] = request.POST[i]
context = {'user_name': {'fn': fn, 'ln': ln}, 'enrol_count': REPEAT1, 'email': mail}
return render(request, "signup_verification.html", context)
else:
context = {'message': 'Ensure password requirements are met.'}
return render(request, "signup_verification.html", context)
def email_verification(request):
request.session['memberID'] = request.GET.get('id')
ip_address = request.GET.get('ip')
code = request.GET.get('code')
if Temp_User.objects.filter(memberID=request.session['memberID']).exists():
user_details = Temp_User.objects.get(memberID=request.session['memberID'])
if code in str(user_details.password):
# Link is genuine and has not been previously used
print(request.session['memberID'])
createNewUser(request.session['memberID'])
addKeystrokesToProfile('AR', ip_address, request.session['memberID'], 1, 'granted', 1) # First keystrokes data in profile
moveMouseData('AR', ip_address, request.session['memberID'], 1, 'granted', 1) # First mouse data in profile
context = { 'user_name': {'fn': user_details.first_name, 'ln': user_details.last_name}, 'enrol_count': REPEAT1}
else:
context = {'message': 'This link has either been used or does not exist.'}
else:
context = {'message': 'This link has either been used or does not exist.'}
return render(request, 'signup2.html', context)
def landingpage(request):
try:
if not request.session['is_loggedin']:
response = redirect('http://127.0.0.1:8000/')
else:
fullname = request.session['loggedin_user'].title()
context = {'userName': fullname}
url = 'landing_page.html'
return render(request, url, context)
except MultiValueDictKeyError:
response = redirect('http://127.0.0.1:8000/')
except KeyError:
response = redirect('http://127.0.0.1:8000/')
request.session['is_loggedin'] = False
return response
def SendCustomEmail(toEmail, context, title):
html_template = get_template('email_template.html')
text_template = get_template('email_template.txt')
html_alternative = html_template.render(context)
text_alternative = text_template.render(context)
msg = EmailMultiAlternatives(title, text_alternative, 'wahabaa@clarkson.edu', toEmail)
msg.attach_alternative(html_alternative, "text/html")
msg.send(fail_silently=False)
print('Mail sent')
@csrf_exempt
def update_session(request):
body = str(request.body)
sessionUserFullname = body.split("b'", 1)[1].rsplit("'")[0]
request.session['sessionUserFullname'] = sessionUserFullname.lower()
print(sessionUserFullname)
return HttpResponse(request)
def participant_list(request):
ip = getIP(request)
if str(ip) not in ['67.249.20.200']: # The only IP that can access this page
response = redirect('http://127.0.0.1:8000/')
return response
userlist = Users.objects.all()
for eachUser in userlist:
d1 = datetime.datetime.strptime(date.today().strftime("%m/%d/%Y"), "%m/%d/%Y") # Current time
d2 = datetime.datetime.strptime(eachUser.last_visited, "%m/%d/%Y") # Last visited
# update last visited and reset weekly tasks
if eachUser.login_attempt < 100:
if abs((d2 - d1).days) >= 1:
if (100 - eachUser.login_attempt) < weeklyLogin: # Total Login task left is less than weekly tasks of 20
Users.objects.filter(memberID=eachUser.memberID).update(login_weekly_task_left=(100 - eachUser.login_attempt))
else:
Users.objects.filter(memberID=eachUser.memberID).update(login_weekly_task_left=weeklyLogin)
else:
if eachUser.login_weekly_task_left != 0:
Users.objects.filter(memberID=eachUser.memberID).update(login_weekly_task_left=0) # Force it to 0
if eachUser.AR_attempt < 20:
if abs((d2 - d1).days) >= 1:
if (20 - eachUser.AR_attempt) < weeklyAR: # Total AR task left is less than weekly tasks of 5
Users.objects.filter(memberID=eachUser.memberID).update(AR_weekly_task_left=(20 - eachUser.AR_attempt))
else:
Users.objects.filter(memberID=eachUser.memberID).update(AR_weekly_task_left=weeklyAR)
else:
if eachUser.AR_weekly_task_left != 0:
Users.objects.filter(memberID=eachUser.memberID).update(AR_weekly_task_left=0)
context = {'object_userlist': Users.objects.all()}
return render(request, 'participant_list.html', context)
@csrf_exempt
def sendUserReminder(request):
ip = getIP(request)
if str(ip) not in ['67.249.20.200']: # The only IP that can access this page
response = redirect('http://127.0.0.1:8000/')
return response
global context_mail
userlist = Users.objects.all()
for eachUser in userlist:
link = 'http://127.0.0.1:8000'
d1 = datetime.datetime.strptime(date.today().strftime("%m/%d/%Y"), "%m/%d/%Y") # Current time
d2 = datetime.datetime.strptime(eachUser.last_visited, "%m/%d/%Y") # Last visited
if eachUser.login_attempt < 100 or eachUser.AR_attempt < 20:
if str(eachUser.memberID) in ['6239364', '0812678']: # User want to unsubscribe
continue
if eachUser.login_weekly_task_left > 0 or eachUser.AR_weekly_task_left > 0:
context_mail = {'fn': eachUser.first_name, 'link': link, 'login_attempts': eachUser.login_attempt,
'AR_attempts': eachUser.AR_attempt, 'login_left': eachUser.login_weekly_task_left,
'AR_left': eachUser.AR_weekly_task_left, 'weekly_task': True}
elif abs((d2 - d1).days) >= 1:
context_mail = {'fn': eachUser.first_name, 'link': link, 'login_attempts': eachUser.login_attempt,
'AR_attempts': eachUser.AR_attempt, 'login_left': weeklyLogin,
'AR_left': weeklyAR, 'weekly_task': True}
else:
continue
SendCustomEmail([eachUser.mail], context_mail, 'Your daily tasks reminder')
elif eachUser.login_attempt >= 100 and eachUser.AR_attempt >= 20:
# User have completed genuine login and recovery
if eachUser.pwd_status == 0:
# Send a completion email ONLY ONCE
Users.objects.filter(memberID=eachUser.memberID).update(pwd_status=2) # NOTE: 2 means genuine tasks completion email has been sent
context_mail = {'fn': eachUser.first_name, 'ln': eachUser.last_name, 'link': link, 'login_attempts': eachUser.login_attempt,
'AR_attempts': eachUser.AR_attempt, 'login_left': eachUser.login_weekly_task_left,
'AR_left': eachUser.AR_weekly_task_left, 'genuine_tasks_completed': True}
SendCustomEmail([eachUser.mail], context_mail, 'Congratulations, Genuine Tasks Completed')
else: continue
return HttpResponse(request)
@csrf_exempt
def sendAttackReminder(request):
ip = getIP(request)
if str(ip) not in ['67.249.20.200']: # The only IP that can access this page
response = redirect('http://127.0.0.1:8000/')
return response
global title, message
attackList = Attacks.objects.exclude(login_attempts=total,
AR_attempts=total) # Get currunt users connected to an impostor
for impostor in attackList:
# Look up impostor and user information
impostorInfo = Users.objects.get(memberID=impostor.attacker)
realInfo = Users.objects.get(memberID=impostor.attacks)
if impostor.login_attempts < total and impostor.AR_attempts < total:
message = 'Kindly complete ' + str(total - impostor.login_attempts) + ' IMPOSTOR LOGIN and ' + str(
total - impostor.AR_attempts) + ' ACCOUNT RECOVERY attempts using the information provided below. Each impostor attempt is considered successful once you get to the OTP screen.'
title = "Impostor tasks reminder for today"
elif impostor.login_attempts < total:
message = 'Kindly complete ' + str(
total - impostor.login_attempts) + ' IMPOSTOR LOGIN attempts using the information provided below. Each impostor attempt is considered successful once you get to the OTP screen.'
title = "Impostor Login tasks for today"
elif impostor.AR_attempts < total:
message = 'Kindly complete ' + str(
total - impostor.AR_attempts) + ' IMPOSTOR ACCOUNT RECOVERY attempts using the information provided below. Each impostor attempt is considered successful once you get to the OTP screen.'
title = "Impostor account recovery tasks for today"
else:
continue
link = 'http://127.0.0.1:8000/'
context_mail = {'fn': impostorInfo.first_name, 'mID': realInfo.memberID, 'fn2': realInfo.first_name,
'ln2': realInfo.last_name, 'dob': realInfo.dob,
'address': realInfo.address, 'city': realInfo.city, 'state': realInfo.state,
'zip': realInfo.zipcode, 'country': realInfo.country,
'email': realInfo.mail, 'phone': realInfo.phone, 'username': realInfo.username,
'pwd': realInfo.password, 'link': link, 'message': message,
'title': title, 'impostor': True}
SendCustomEmail([impostorInfo.mail], context_mail, "Impostor tasks for today")
return HttpResponse(request)
def attack_list(request):
ip = getIP(request)
if str(ip) not in ['67.249.20.200']: # The only IP that can access this page
response = redirect('http://127.0.0.1:8000/')
return response
link = 'http://127.0.0.1:8000'
userlist = Users.objects.all() # Get all users
for eachUser in userlist: # Loop through users
if eachUser.login_attempt >=100 and eachUser.AR_attempt >=20: # User must have completed login and AR tasks
if Attacks.objects.filter(attacker=eachUser.memberID).exists(): # Check if user has ever been assigned an impostor
if Attacks.objects.filter(attacker=eachUser.memberID).count() < 5: # Check is user has completed all impostor attacks on 5 other users
attackProfile = Attacks.objects.filter(attacker=eachUser.memberID).last()
if attackProfile.login_attempts >= total and attackProfile.AR_attempts >= total: # Check if user has completed impostor attack on the current profile
# Ensure random user is not same as impostor or has not been previously attacked by same user
recursiveCount = 0
while recursiveCount < 20: # Users must have sufficient profile
recursiveCount += 1
random_user = getRandomUser()
if random_user.memberID == eachUser.memberID or Attacks.objects.filter(attacker=eachUser.memberID,
attacks=random_user.memberID).exists() or random_user.login_attempt < 100 or random_user.AR_attempt < 20\
or random_user.login_template < 4 or random_user.AR_template < 4:
continue
else:
newEntry = Attacks(attacker=eachUser.memberID, attacks=random_user.memberID)
newEntry.save()
break
elif Attacks.objects.filter(attacker=eachUser.memberID).count() >= 5:
attackProfile = Attacks.objects.filter(attacker=eachUser.memberID).last()
if attackProfile.login_attempts >= total and attackProfile.AR_attempts >= total:
# Send a completion email ONLY ONCE
particular_user = Users.objects.get(memberID=eachUser.memberID)
if particular_user.pwd_status == 2:
Users.objects.filter(memberID=eachUser.memberID).update(pwd_status=3) # NOTE: 3 means impostor tasks completion email has been sent
link = 'http://127.0.0.1:8000/'
context_mail = {'fn': eachUser.first_name, 'ln': eachUser.last_name, 'link': link, 'impostor_tasks_completed': True}
SendCustomEmail([eachUser.mail], context_mail, 'Congratulations, Impostor Tasks Completed')
else:
# Ensure random user is not same as impostor
recursiveCount = 0
while recursiveCount < 20: # Users must have sufficient profile
random_user = getRandomUser()
recursiveCount += 1
if random_user.memberID == eachUser.memberID or random_user.login_attempt < 100 or random_user.AR_attempt < 20\
or random_user.login_template < 4 or random_user.AR_template < 4:
continue
else:
newEntry = Attacks(attacker=eachUser.memberID, attacks=random_user.memberID)
newEntry.save()
break
context = {'object_attacklist': Attacks.objects.all().order_by('attacker')}
return render(request, 'attack_list.html', context)
def getRandomUser():
random_user = Users.objects.all()[random.randint(0, Users.objects.count() - 1)]
return random_user
| wahabaa/keystroke-web-MFA | keys/views.py | views.py | py | 84,010 | python | en | code | 1 | github-code | 13 |
41106121476 | from mrjob.job import MRJob
from mrjob.step import MRStep
class partB(MRJob):
def mapperB1(self, _, line):
fields = line.split(',')
try:
if len(fields) == 7:
address = fields[2]
value = int(fields[3])
yield address, (1,value)
elif len(fields) == 5:
address1 = fields[0]
yield address1, (2,1)
except:
pass
def reducerB1(self, key, values):
f = False
allv = []
for m in values:
if m[0]==1:
allv.append(m[1])
elif m[0] == 2:
f = True
if f:
yield key, sum(allv)
def mapperB2(self, key,value):
yield None, (key,value)
def reducerB2(self, _, keys):
sortedv = sorted(keys, reverse = True, key = lambda x: x[1])
for i in sortedv[:10]:
yield i[0], i[1]
def steps(self):
return [MRStep(mapper = self.mapperB1, reducer=self.reducerB1), MRStep(mapper = self.mapperB2, reducer = self.reducerB2)]
if __name__ == '__main__':
partB.run()
| SoniaKoplickat13/Ethereum-Analysis | partB.py | partB.py | py | 904 | python | en | code | 0 | github-code | 13 |
20406170559 | from abc import abstractmethod
from datetime import datetime
from dateutil import parser
import importlib
import json
import os
import six
import threading
import time
import etcd
from tendrl.commons.event import Event
from tendrl.commons.message import ExceptionMessage
from tendrl.notifier.utils.central_store_util import get_alerts
from tendrl.notifier.utils.central_store_util import update_alert_delivery
from tendrl.notifier.utils.util import list_modules_in_package_path
CLEARING_ALERT = "INFO"
class PluginMount(type):
def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'):
cls.plugins = []
else:
cls.register_plugin(cls)
def register_plugin(cls, plugin):
instance = plugin()
cls.plugins.append(instance)
@six.add_metaclass(PluginMount)
class NotificationPlugin(object):
def __init__(self):
super(NotificationPlugin, self).__init__()
self.name = ''
@abstractmethod
def save_config_help(self):
raise NotImplementedError()
@abstractmethod
def set_destinations(self):
raise NotImplementedError()
@abstractmethod
def get_alert_destinations(self):
raise NotImplementedError()
@abstractmethod
def format_message(self, alert):
raise NotImplementedError()
@abstractmethod
def dispatch_notification(self, msg):
raise NotImplementedError()
class NotificationPluginManager(threading.Thread):
def load_plugins(self):
try:
path = os.path.dirname(os.path.abspath(__file__)) + '/handlers'
pkg = 'tendrl.notifier.notification.handlers'
notif_handlers = list_modules_in_package_path(path, pkg)
for name, handler_fqdn in notif_handlers:
importlib.import_module(handler_fqdn)
except (SyntaxError, ValueError, ImportError) as ex:
Event(
ExceptionMessage(
priority="debug",
publisher="notifier",
payload={
"message": 'Failed to load the time series db'
'plugins.',
"exception": ex
}
)
)
raise ex
def __init__(self):
super(NotificationPluginManager, self).__init__()
self.daemon = True
try:
self.load_plugins()
notification_medium = []
self.complete = threading.Event()
for plugin in NotificationPlugin.plugins:
notification_medium.append(plugin.name)
NS.notifier.objects.NotificationMedia(
media=notification_medium
).save()
except (
AttributeError,
SyntaxError,
ValueError,
KeyError,
ImportError,
etcd.EtcdException
) as ex:
Event(
ExceptionMessage(
priority="debug",
publisher="notifier",
payload={
"message": 'Failed to intialize notification '
'manager',
"exception": ex
}
)
)
raise ex
def run(self):
_sleep = 0
while not self.complete.is_set():
if _sleep > 5:
_sleep = int(
NS.config.data["notification_check_interval"]
)
else:
_sleep += 1
try:
lock = None
alerts = get_alerts()
for alert in alerts:
if alert.severity == CLEARING_ALERT:
if (datetime.utcnow() - parser.parse(
alert.time_stamp
).replace(tzinfo=None)).seconds < 120:
# If alert is info then wait for 120 sec
# to confirm no changes in alert severity
continue
alert.tags = json.loads(alert.tags)
if str(alert.delivered).lower() == "false":
lock = etcd.Lock(
NS._int.wclient,
'alerting/alerts/%s' % alert.alert_id
)
lock.acquire(
blocking=True,
lock_ttl=60
)
if lock.is_acquired:
# renew a lock
lock.acquire(lock_ttl=60)
for plugin in NotificationPlugin.plugins:
plugin.dispatch_notification(alert)
update_alert_delivery(alert)
lock.release()
except(
AttributeError,
SyntaxError,
ValueError,
KeyError,
TypeError,
etcd.EtcdException
)as ex:
Event(
ExceptionMessage(
priority="debug",
publisher="notifier",
payload={
"message": "Exception caught in notification "
"dispatch"
" handlers.",
"exception": ex
}
)
)
finally:
if isinstance(lock, etcd.lock.Lock) and lock.is_acquired:
lock.release()
time.sleep(_sleep)
def stop(self):
self.complete.set()
| Tendrl/notifier | tendrl/notifier/notification/__init__.py | __init__.py | py | 5,813 | python | en | code | 2 | github-code | 13 |
41341725019 | import sys
with open('day2.txt') as f:
line = f.readline()
splitted = line.split(',')
data = [int(x) for x in splitted]
def run_program(arg1, arg2):
program = data.copy()
program[1] = arg1
program[2] = arg2
iptr = 0
while program[iptr] != 99:
op, load1, load2, store = program[iptr], program[iptr + 1], program[iptr + 2], program[iptr + 3]
if op == 1:
program[store] = program[load1] + program[load2]
elif op == 2:
program[store] = program[load1] * program[load2]
elif op != 99:
raise Exception('unexpected instruction')
iptr += 4
return program[0]
for noun in range(0, 99):
for verb in range(0, 99):
if run_program(noun, verb) == 19690720:
print(100 * noun + verb)
| mfep/advent-of-code | 2019/2/day2.py | day2.py | py | 805 | python | en | code | 2 | github-code | 13 |
36983933283 | import os
from datetime import datetime
import pandas as pd
import pytz
from project_path import *
users = User.objects.all().order_by("?")
user_excel_file_path = "/home/dubsy/Desktop/Data Analysis/user.xlsx"
user_csv_file_path = "/home/dubsy/Desktop/Data Analysis/user.csv"
def user_date_module():
user_joined_date = []
date_joined = [
user.date_joined.strftime("%Y-%m-%d %H:%M") if user.date_joined else ""
for user in users
]
for date in date_joined:
time_zone = pytz.timezone("Africa/Lagos")
striped_date = datetime.strptime(date, "%Y-%m-%d %H:%M")
new_date = striped_date.replace(tzinfo=pytz.utc)
loc_user_dt = new_date.astimezone(time_zone)
final_user_date = loc_user_dt.strftime("%Y-%m-%d %H:%M")
user_joined_date.append(final_user_date)
return user_joined_date
def users_data(date):
user_data = {
"Username": [user.username if user.username else "" for user in users],
"First Name": [user.first_name if user.first_name else "" for user in users],
"Last Name": [user.last_name if user.last_name else "" for user in users],
"Email": [user.email if user.email else "" for user in users],
"Age": [user.age if user.age else "" for user in users],
"Age Group": [user.age_group if user.age_group else "" for user in users],
"Gender": [user.gender if user.gender else "" for user in users],
"Country": [user.country if user.country else "" for user in users],
"State": [user.state if user.state else "" for user in users],
"Date joined": [date for date in date],
}
return user_data
def export_user_data(data, excel_file_path, csv_file_path):
df = pd.DataFrame(data)
df.to_excel(excel_file_path, index=False, sheet_name="User Table")
df.to_csv(
csv_file_path,
index=False,
)
print(f"Successfully Exported data to {excel_file_path} and {csv_file_path}")
| Suboms/data_analysis | order/export/export_user_data.py | export_user_data.py | py | 1,977 | python | en | code | 1 | github-code | 13 |
31963064421 | reg = [0,0]
ip = 0
p = [line for line in open('23.txt')]
def run(a,b):
reg = [a,b]
ip = 0
while 0 <= ip < len(p):
ins = p[ip].split(" ")
#print(ip, ins, reg, end=" -> ")
if ins[0]=='hlf':
r = 0 if ins[1][0]=='a' else 1
reg[r] /= 2
ip += 1
elif ins[0]=='tpl':
r = 0 if ins[1][0]=='a' else 1
reg[r] *= 3
ip += 1
elif ins[0]=='inc':
r = 0 if ins[1][0]=='a' else 1
reg[r] += 1
ip += 1
elif ins[0]=='jmp':
offset = int(ins[1])
ip += offset
elif ins[0]=='jie':
r = 0 if ins[1][0]=='a' else 1
offset = int(ins[2])
if reg[r]%2==0: ip += offset
else: ip += 1
elif ins[0]=='jio':
r = 0 if ins[1][0]=='a' else 1
offset = int(ins[2])
if reg[r]==1: ip += offset # ==1, not 'is odd'
else: ip += 1
else:
print("Invalid:", ins)
exit(1)
#print(ip, reg)
print(reg[1])
run(0,0)
run(1,0)
| sgdavies/aoc2015 | 23.py | 23.py | py | 989 | python | en | code | 0 | github-code | 13 |
28560510322 | from bzrlib import (
errors,
inventory,
osutils,
)
from bzrlib.inventory import (
InventoryDirectory,
InventoryEntry,
InventoryFile,
InventoryLink,
TreeReference,
)
from bzrlib.tests.per_inventory import TestCaseWithInventory
from bzrlib.symbol_versioning import (
deprecated_in,
)
class TestInventory(TestCaseWithInventory):
def make_init_inventory(self):
inv = inventory.Inventory('tree-root')
inv.revision = 'initial-rev'
inv.root.revision = 'initial-rev'
return self.inv_to_test_inv(inv)
def make_file(self, file_id, name, parent_id, content='content\n',
revision='new-test-rev'):
ie = InventoryFile(file_id, name, parent_id)
ie.text_sha1 = osutils.sha_string(content)
ie.text_size = len(content)
ie.revision = revision
return ie
def make_link(self, file_id, name, parent_id, target='link-target\n'):
ie = InventoryLink(file_id, name, parent_id)
ie.symlink_target = target
return ie
def prepare_inv_with_nested_dirs(self):
inv = inventory.Inventory('tree-root')
for args in [('src', 'directory', 'src-id'),
('doc', 'directory', 'doc-id'),
('src/hello.c', 'file', 'hello-id'),
('src/bye.c', 'file', 'bye-id'),
('zz', 'file', 'zz-id'),
('src/sub/', 'directory', 'sub-id'),
('src/zz.c', 'file', 'zzc-id'),
('src/sub/a', 'file', 'a-id'),
('Makefile', 'file', 'makefile-id')]:
ie = inv.add_path(*args)
if args[1] == 'file':
ie.text_sha1 = osutils.sha_string('content\n')
ie.text_size = len('content\n')
return self.inv_to_test_inv(inv)
class TestInventoryCreateByApplyDelta(TestInventory):
"""A subset of the inventory delta application tests.
See test_inv which has comprehensive delta application tests for
inventories, dirstate, and repository based inventories.
"""
def test_add(self):
inv = self.make_init_inventory()
inv = inv.create_by_apply_delta([
(None, "a", "a-id", self.make_file('a-id', 'a', 'tree-root')),
], 'new-test-rev')
self.assertEqual('a', inv.id2path('a-id'))
def test_delete(self):
inv = self.make_init_inventory()
inv = inv.create_by_apply_delta([
(None, "a", "a-id", self.make_file('a-id', 'a', 'tree-root')),
], 'new-rev-1')
self.assertEqual('a', inv.id2path('a-id'))
inv = inv.create_by_apply_delta([
("a", None, "a-id", None),
], 'new-rev-2')
self.assertRaises(errors.NoSuchId, inv.id2path, 'a-id')
def test_rename(self):
inv = self.make_init_inventory()
inv = inv.create_by_apply_delta([
(None, "a", "a-id", self.make_file('a-id', 'a', 'tree-root')),
], 'new-rev-1')
self.assertEqual('a', inv.id2path('a-id'))
a_ie = inv['a-id']
b_ie = self.make_file(a_ie.file_id, "b", a_ie.parent_id)
inv = inv.create_by_apply_delta([("a", "b", "a-id", b_ie)], 'new-rev-2')
self.assertEqual("b", inv.id2path('a-id'))
def test_illegal(self):
# A file-id cannot appear in a delta more than once
inv = self.make_init_inventory()
self.assertRaises(errors.InconsistentDelta, inv.create_by_apply_delta, [
(None, "a", "id-1", self.make_file('id-1', 'a', 'tree-root')),
(None, "b", "id-1", self.make_file('id-1', 'b', 'tree-root')),
], 'new-rev-1')
class TestInventoryReads(TestInventory):
def test_is_root(self):
"""Ensure our root-checking code is accurate."""
inv = self.make_init_inventory()
self.assertTrue(inv.is_root('tree-root'))
self.assertFalse(inv.is_root('booga'))
ie = inv['tree-root'].copy()
ie.file_id = 'booga'
inv = inv.create_by_apply_delta([("", None, "tree-root", None),
(None, "", "booga", ie)], 'new-rev-2')
self.assertFalse(inv.is_root('TREE_ROOT'))
self.assertTrue(inv.is_root('booga'))
def test_ids(self):
"""Test detection of files within selected directories."""
inv = inventory.Inventory('TREE_ROOT')
for args in [('src', 'directory', 'src-id'),
('doc', 'directory', 'doc-id'),
('src/hello.c', 'file'),
('src/bye.c', 'file', 'bye-id'),
('Makefile', 'file')]:
ie = inv.add_path(*args)
if args[1] == 'file':
ie.text_sha1 = osutils.sha_string('content\n')
ie.text_size = len('content\n')
inv = self.inv_to_test_inv(inv)
self.assertEqual(inv.path2id('src'), 'src-id')
self.assertEqual(inv.path2id('src/bye.c'), 'bye-id')
def test_non_directory_children(self):
"""Test path2id when a parent directory has no children"""
inv = inventory.Inventory('tree-root')
inv.add(self.make_file('file-id','file', 'tree-root'))
inv.add(self.make_link('link-id','link', 'tree-root'))
self.assertIs(None, inv.path2id('file/subfile'))
self.assertIs(None, inv.path2id('link/subfile'))
def test_iter_entries(self):
inv = self.prepare_inv_with_nested_dirs()
# Test all entries
self.assertEqual([
('', 'tree-root'),
('Makefile', 'makefile-id'),
('doc', 'doc-id'),
('src', 'src-id'),
('src/bye.c', 'bye-id'),
('src/hello.c', 'hello-id'),
('src/sub', 'sub-id'),
('src/sub/a', 'a-id'),
('src/zz.c', 'zzc-id'),
('zz', 'zz-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries()])
# Test a subdirectory
self.assertEqual([
('bye.c', 'bye-id'),
('hello.c', 'hello-id'),
('sub', 'sub-id'),
('sub/a', 'a-id'),
('zz.c', 'zzc-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries(
from_dir='src-id')])
# Test not recursing at the root level
self.assertEqual([
('', 'tree-root'),
('Makefile', 'makefile-id'),
('doc', 'doc-id'),
('src', 'src-id'),
('zz', 'zz-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries(
recursive=False)])
# Test not recursing at a subdirectory level
self.assertEqual([
('bye.c', 'bye-id'),
('hello.c', 'hello-id'),
('sub', 'sub-id'),
('zz.c', 'zzc-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries(
from_dir='src-id', recursive=False)])
def test_iter_just_entries(self):
inv = self.prepare_inv_with_nested_dirs()
self.assertEqual([
'a-id',
'bye-id',
'doc-id',
'hello-id',
'makefile-id',
'src-id',
'sub-id',
'tree-root',
'zz-id',
'zzc-id',
], sorted([ie.file_id for ie in inv.iter_just_entries()]))
def test_iter_entries_by_dir(self):
inv = self. prepare_inv_with_nested_dirs()
self.assertEqual([
('', 'tree-root'),
('Makefile', 'makefile-id'),
('doc', 'doc-id'),
('src', 'src-id'),
('zz', 'zz-id'),
('src/bye.c', 'bye-id'),
('src/hello.c', 'hello-id'),
('src/sub', 'sub-id'),
('src/zz.c', 'zzc-id'),
('src/sub/a', 'a-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir()])
self.assertEqual([
('', 'tree-root'),
('Makefile', 'makefile-id'),
('doc', 'doc-id'),
('src', 'src-id'),
('zz', 'zz-id'),
('src/bye.c', 'bye-id'),
('src/hello.c', 'hello-id'),
('src/sub', 'sub-id'),
('src/zz.c', 'zzc-id'),
('src/sub/a', 'a-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('a-id', 'zzc-id', 'doc-id', 'tree-root',
'hello-id', 'bye-id', 'zz-id', 'src-id', 'makefile-id',
'sub-id'))])
self.assertEqual([
('Makefile', 'makefile-id'),
('doc', 'doc-id'),
('zz', 'zz-id'),
('src/bye.c', 'bye-id'),
('src/hello.c', 'hello-id'),
('src/zz.c', 'zzc-id'),
('src/sub/a', 'a-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('a-id', 'zzc-id', 'doc-id',
'hello-id', 'bye-id', 'zz-id', 'makefile-id'))])
self.assertEqual([
('Makefile', 'makefile-id'),
('src/bye.c', 'bye-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('bye-id', 'makefile-id'))])
self.assertEqual([
('Makefile', 'makefile-id'),
('src/bye.c', 'bye-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('bye-id', 'makefile-id'))])
self.assertEqual([
('src/bye.c', 'bye-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('bye-id',))])
self.assertEqual([
('', 'tree-root'),
('src', 'src-id'),
('src/bye.c', 'bye-id'),
], [(path, ie.file_id) for path, ie in inv.iter_entries_by_dir(
specific_file_ids=('bye-id',), yield_parents=True)])
class TestInventoryFiltering(TestInventory):
def test_inv_filter_empty(self):
inv = self.prepare_inv_with_nested_dirs()
new_inv = inv.filter([])
self.assertEqual([
('', 'tree-root'),
], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
def test_inv_filter_files(self):
inv = self.prepare_inv_with_nested_dirs()
new_inv = inv.filter(['zz-id', 'hello-id', 'a-id'])
self.assertEqual([
('', 'tree-root'),
('src', 'src-id'),
('src/hello.c', 'hello-id'),
('src/sub', 'sub-id'),
('src/sub/a', 'a-id'),
('zz', 'zz-id'),
], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
def test_inv_filter_dirs(self):
inv = self.prepare_inv_with_nested_dirs()
new_inv = inv.filter(['doc-id', 'sub-id'])
self.assertEqual([
('', 'tree-root'),
('doc', 'doc-id'),
('src', 'src-id'),
('src/sub', 'sub-id'),
('src/sub/a', 'a-id'),
], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
def test_inv_filter_files_and_dirs(self):
inv = self.prepare_inv_with_nested_dirs()
new_inv = inv.filter(['makefile-id', 'src-id'])
self.assertEqual([
('', 'tree-root'),
('Makefile', 'makefile-id'),
('src', 'src-id'),
('src/bye.c', 'bye-id'),
('src/hello.c', 'hello-id'),
('src/sub', 'sub-id'),
('src/sub/a', 'a-id'),
('src/zz.c', 'zzc-id'),
], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
def test_inv_filter_entry_not_present(self):
inv = self.prepare_inv_with_nested_dirs()
new_inv = inv.filter(['not-present-id'])
self.assertEqual([
('', 'tree-root'),
], [(path, ie.file_id) for path, ie in new_inv.iter_entries()])
| ag1455/OpenPLi-PC | pre/python/lib/python2.7/dist-packages/bzrlib/tests/per_inventory/basics.py | basics.py | py | 12,017 | python | en | code | 19 | github-code | 13 |
26717026338 | # 0. 配合 EasyGui,给“下载一只猫“的代码增加互动:
# 让用户输入尺寸;
# 如果用户不输入尺寸,那么按默认宽400,高600下载喵;
# 让用户指定保存位置。
import easygui as Eg
import urllib.request as Ur
import os
import time
def user_in():
e = Eg.multenterbox(msg='请输入要下载的图片尺寸', title='下载一只喵', fields=('宽:', '高:'), values=(400, 600))
# 返回的e是一个宽高的list
return e
def choice_save():
f = Eg.diropenbox(msg='请选择存放喵的位置', title='随便选', default=os.curdir)
# 返回的f是一个文件夹位置的字符串
return f
def get_data():
# 通过Eg输入获得宽高
pic = user_in()
width = pic[0]
heigth = pic[1]
# 把宽高带入到链接进去,读出byte数据
url = 'http://placekitten.com/' + width + '/' + heigth
response = Ur.urlopen(url)
data = response.read()
return data
def save():
# 加载数据要费点时间,打印个提示
print('获取数据中,请等待...')
data = get_data()
folder = choice_save()
# 用时间戳来给文件命名,保证绝不会出现重名
path = folder + '/kitten_' + str(time.time()) +'.jpg'
with open(path, 'wb')as f:
try:
f.write(data)
except IOError:
Eg.msgbox('出错了,没存起')
else:
Eg.msgbox('保存完毕')
if __name__ == "__main__":
save()
| HimriZngz/Code | 小甲鱼练习/习题054-0.py | 习题054-0.py | py | 1,499 | python | zh | code | 0 | github-code | 13 |
21131063796 | #-*- coding:utf-8 -*-
from detectron2.utils.logger import setup_logger
from detectron2.data import MetadataCatalog, DatasetCatalog
from detectron2.data.datasets import register_coco_instances
from detectron2.engine import default_setup
from adet.config import get_cfg
import detectron2.utils.comm as comm
def custom_arg_parser(arg_parser):
arg_parser.add_argument("--train_dataset_names", type=str, default="train2017",
help="train_custom_dataset_names, use ':' to integrate names just like 'a:b' ")
arg_parser.add_argument("--train_json_paths",
type=str,
default="dataset/coco/annotations/instance_train20171.json",
help="train_json_paths_as_same_order_as_train_datasets_names, use ':' to integrate")
arg_parser.add_argument("--train_img_dirs",
type=str,
default="dataset/coco/train2017",
help="train_img_dirs_as_same_order_as_train_datasets_names, use ':' to integrate")
arg_parser.add_argument("--test_dataset_names", type=str, default="test2017",
help="test_custom_dataset_names, use ':' to integrate names just like 'a:b' ")
arg_parser.add_argument("--test_json_paths",
type=str,
default="dataset/coco/annotations/instance_test20171.json",
help="test_json_paths_as_same_order_as_test_datasets_names, use ':' to integrate")
arg_parser.add_argument("--test_img_dirs",
type=str,
default="dataset/coco/test2017",
help="test_img_dirs_as_same_order_as_test_datasets_names, use ':' to integrate")
return arg_parser
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
train_dataset_names = args.train_dataset_names.split(":")
train_json_paths = args.train_json_paths.split(":")
train_img_dirs = args.train_img_dirs.split(":")
for name, json_path, img_dir in zip(train_dataset_names, train_json_paths, train_img_dirs):
register_coco_instances(name, {}, json_path, img_dir)
MetadataCatalog.get(name)
DatasetCatalog.get(name)
test_dataset_names = args.test_dataset_names.split(":")
test_json_paths = args.test_json_paths.split(":")
test_img_dirs = args.test_img_dirs.split(":")
for name, json_path, img_dir in zip(test_dataset_names, test_json_paths, test_img_dirs):
register_coco_instances(name, {}, json_path, img_dir)
MetadataCatalog.get(name)
DatasetCatalog.get(name)
cfg.DATASETS.TRAIN = tuple(train_dataset_names)
cfg.DATASETS.TEST = tuple(test_dataset_names)
classes_num = max([len(MetadataCatalog.get(name).thing_classes)
for name in train_dataset_names + test_dataset_names])
cfg.MODEL.FCOS.NUM_CLASSES = classes_num
cfg.MODEL.BASIS_MODULE.NORM = "BN"
cfg.MODEL.FCPOSE.BASIS_MODULE.BN_TYPE = "BN"
default_setup(cfg, args)
setup_logger().info("set cfg.MODEL.FCOS.NUM_CLASSES to {}".format(classes_num))
rank = comm.get_rank()
setup_logger(cfg.OUTPUT_DIR, distributed_rank=rank, name="adet")
return cfg | hanjianwei92/capture_and_train | train/custom_setting.py | custom_setting.py | py | 3,428 | python | en | code | 0 | github-code | 13 |
24856482348 | import RPi.GPIO as GPIO # Import GPIO library
import time # Import time library
import threading
import logging
GPIO.setmode(GPIO.BCM) # Set GPIO pin numbering
TRIG = 24 # Associate pin 23 to TRIG
ECHO = 23 # Associate pin 24 to ECHO
logging.info("Distance measurement in progress")
GPIO.setup(TRIG, GPIO.OUT) # Set pin as GPIO out
GPIO.setup(ECHO, GPIO.IN) # Set pin as GPIO in
GPIO.output(TRIG, False) # Set TRIG as LOW
logging.info("Waitng For 2 seconds for Sensor To Settle")
time.sleep(2) # Delay of 2 seconds
meas = [] # Global list of ultrasonic sensor measurements
def add_measurement(m, size=10):
"""
m: measurement
"""
meas.append(m)
if len(meas) > size:
meas.pop(0)
def sensor_loop():
oor = False
while True:
GPIO.output(TRIG, True) # Set TRIG as HIGH
time.sleep(0.00001) # Delay of 0.00001 seconds
GPIO.output(TRIG, False) # Set TRIG as LOW
while GPIO.input(ECHO) == 0: # Check whether the ECHO is LOW
pass
pulse_start = time.time() # Saves the last known time of LOW pulse
while GPIO.input(ECHO) == 1: # Check whether the ECHO is HIGH
pass
pulse_duration = time.time() - pulse_start
distance = pulse_duration * 17150 # Multiply pulse duration by 17150 to get distance
distance = round(distance, 2) # Round to two decimal points
if distance < 40: # Check whether the distance is within range
if oor:
add_measurement(999)
oor = False
else:
add_measurement(distance)
else:
add_measurement(999)
oor = True
class sensorThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
logging.info("Starting: " + self.name)
sensor_loop()
logging.info("Stopping: " + self.name)
thread1 = sensorThread(1, "Sensor Measurement Loop")
thread1.start()
| Naurislv/self-driving-RCcar | ultrasonic_sensor_HCSR04/SonicSensor.py | SonicSensor.py | py | 2,079 | python | en | code | 4 | github-code | 13 |
42050661068 | K = int(input())
def search(d, digits, count):
if d == 1:
return (digits if count == 1 else None), (count-1)
s = digits[-1]
for i in range(max(s-1, 0), min(s+2, 10)):
answer, count = search(d-1, digits + [i], count)
if answer:
return answer, count
return None, count
def solve():
count = K # count down
d = 1 # num of digits
while True:
for i in range(1,10):
answer, count = search(d, [i], count)
if answer:
return answer
d += 1
print(''.join(str(d) for d in solve()))
| keijak/comp-pub | atcoder/abc161/d.py | d.py | py | 595 | python | en | code | 0 | github-code | 13 |
12803846081 | def make_range_list(start, end, prefix='net_', suffix=''):
rlist = []
for x in xrange(start, end + 1):
rlist.append(prefix + str(x) + suffix)
return rlist
SSH_PASS = 'hpvse1'
admin_credentials = {'userName': 'Administrator', 'password': 'wpsthpvse1'}
admin_credentials_TB = {'userName': 'Administrator', 'password': 'wpsthpse1'}
serveradmin_credentials = {'userName': 'Serveradmin', 'password': 'Serveradmin'}
network_admin = {'userName': 'Networkadmin', 'password': 'Networkadmin'}
backup_admin = {'userName': 'Backupadmin', 'password': 'Backupadmin'}
readonly_user = {'userName': 'readonly', 'password': 'readonly'}
vcenter = {'server': '15.199.230.130', 'user': 'GopalK', 'password': 'hpvse1'}
ligs = [{'name': 'LIG1',
'type': 'logical-interconnect-groupV400',
'enclosureType': 'C7000',
'interconnectMapTemplate': [{'enclosure': 1, 'enclosureIndex': 1, 'bay': 1, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'},
{'enclosure': 1, 'enclosureIndex': 1, 'bay': 2, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'}],
'uplinkSets': [],
'stackingMode': 'Enclosure',
'ethernetSettings': None,
'state': 'Active',
'telemetryConfiguration': None,
'snmpConfiguration': None,
'qosConfiguration':None},
{'name': 'LIG2',
'type': 'logical-interconnect-groupV400',
'enclosureType': 'C7000',
'interconnectMapTemplate': [{'enclosure': 1, 'enclosureIndex': 1, 'bay': 1, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'},
{'enclosure': 1, 'enclosureIndex': 1, 'bay': 2, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'}
],
'uplinkSets': [],
'stackingMode': 'Enclosure',
'ethernetSettings': None,
'state': 'Active',
'telemetryConfiguration': None,
'snmpConfiguration': None,
'qosConfiguration':None}
]
enc_group2 = [{'name': 'EG1',
'type': 'EnclosureGroupV700',
'enclosureTypeUri': '/rest/enclosure-types/c7000',
'stackingMode': 'Enclosure',
'interconnectBayMappingCount': 8,
'configurationScript': None,
'interconnectBayMappings':
[{'interconnectBay': 1, 'logicalInterconnectGroupUri': 'LIG:LIG1'},
{'interconnectBay': 2, 'logicalInterconnectGroupUri': 'LIG:LIG1'},
{'interconnectBay': 3, 'logicalInterconnectGroupUri': None},
{'interconnectBay': 4, 'logicalInterconnectGroupUri': None},
{'interconnectBay': 5, 'logicalInterconnectGroupUri': None},
{'interconnectBay': 6, 'logicalInterconnectGroupUri': None},
{'interconnectBay': 7, 'logicalInterconnectGroupUri': None},
{'interconnectBay': 8, 'logicalInterconnectGroupUri': None}]}
]
encss = [{'hostname': '15.245.129.23', 'username': 'Administrator', 'password': 'wpsthpvse1', 'enclosureGroupUri': 'EG:EG2', 'force': 'true', 'licensingIntent': 'OneViewNoiLO'}]
appliance = {'type': 'ApplianceNetworkConfiguration',
'applianceNetworks':
[{'device': 'eth0',
'macAddress': None,
'interfaceName': 'VLAN 106',
'activeNode': '1',
'unconfigure': False,
'ipv4Type': 'DHCP',
'ipv6Type': 'UNCONFIGURE',
'hostname': 'portmon.usa.hp.com',
'confOneNode': True,
'domainName': 'usa.hp.com',
'aliasDisabled': True}]}
timeandlocale = {'type': 'TimeAndLocale', 'dateTime': None, 'timezone': 'UTC', 'ntpServers': ['192.173.0.23'], 'locale': 'en_US.UTF-8'}
users = [{'userName': 'Serveradmin', 'password': 'Serveradmin', 'fullName': 'Serveradmin', 'roles': ['Server administrator'], 'emailAddress': 'sarah@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Networkadmin', 'password': 'Networkadmin', 'fullName': 'Networkadmin', 'roles': ['Network administrator'], 'emailAddress': 'nat@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Backupadmin', 'password': 'Backupadmin', 'fullName': 'Backupadmin', 'roles': ['Backup administrator'], 'emailAddress': 'backup@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Readonly', 'password': 'readonly', 'fullName': 'readonly', 'roles': ['Read only'], 'emailAddress': 'rheid@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Storageonly', 'password': 'storageonly', 'fullName': 'storageadmin', 'roles': ['Storage administrator'], 'emailAddress': 'rheid@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'FullRole', 'password': 'fullroleonly', 'fullName': 'fullroleadmin', 'roles': ['Infrastructure administrator'], 'emailAddress': 'rheid@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Software', 'password': 'softwareonly', 'fullName': 'softwareadmin', 'roles': ['Software administrator'], 'emailAddress': 'rheid@hp.com', 'officePhone': '970-555-0003', 'mobilePhone': '970-500-0003', 'type': 'UserAndRoles'}
]
usercred = [{'userName': 'Networkadmin', 'password': 'Networkadmin'},
{'userName': 'Backupadmin', 'password': 'Backupadmin'},
{'userName': 'Readonly', 'password': 'readonly'},
{'userName': 'Storageonly', 'password': 'storageonly'},
{'userName': 'FullRole', 'password': 'fullroleonly'},
{'userName': 'Software', 'password': 'softwareonly'},
{'userName': 'Serveradmin', 'password': 'Serveradmin'},
]
POSITIVE_USERS = ['Administrator', 'Networkadmin']
NEGATIVE_USERS = ['Serveradmin', 'Backupadmin', 'readonly']
ethernet_networks = [{'name': 'net_100', 'type': 'ethernet-networkV400', 'vlanId': 100, 'purpose': 'General', 'smartLink': True, 'privateNetwork': False, 'connectionTemplateUri': None, 'ethernetNetworkType': 'Tagged'},
{'name': 'net_101', 'type': 'ethernet-networkV400', 'vlanId': 101, 'purpose': 'General', 'smartLink': True, 'privateNetwork': False, 'connectionTemplateUri': None, 'ethernetNetworkType': 'Tagged'},
{'name': 'net_102', 'type': 'ethernet-networkV400', 'vlanId': 102, 'purpose': 'General', 'smartLink': True, 'privateNetwork': False, 'connectionTemplateUri': None, 'ethernetNetworkType': 'Tagged'}]
ENC1 = 'CN754404R2'
ENC2 = 'CN754406W5'
fcoe_networks = [{'name': 'fcoe_103', 'type': 'fcoe-networkV300', 'vlanId': 103}]
les = {'le1':
{'name': 'LE1',
'enclosureUris': ['ENC:' + ENC1, 'ENC:' + ENC2],
'enclosureGroupUri': 'EG:EG1',
'firmwareBaselineUri': None,
'forceInstallFirmware': False
}}
enc_group_TB = {'enc_group1':
{'name': 'EG1',
'type': 'EnclosureGroupV300',
'enclosureCount': 2,
'enclosureTypeUri': '/rest/enclosure-types/SY12000',
'stackingMode': 'Enclosure',
'interconnectBayMappingCount': 0,
'configurationScript': None,
'interconnectBayMappings':
[{'interconnectBay': 3, 'logicalInterconnectGroupUri': 'LIG:LIG1'},
{'interconnectBay': 6, 'logicalInterconnectGroupUri': 'LIG:LIG1'}
],
'ipAddressingMode': 'External',
'ipRangeUris': [],
'powerMode': 'RedundantPowerFeed'
}}
enc_group1 = {'name': 'EG2', "interconnectBayMappings": [
{"interconnectBay": 1, "logicalInterconnectGroupUri": 'LIG:LIG1'},
{"interconnectBay": 2, "logicalInterconnectGroupUri": 'LIG:LIG1'},
{"interconnectBay": 3, "logicalInterconnectGroupUri": None},
{"interconnectBay": 4, "logicalInterconnectGroupUri": None},
{"interconnectBay": 5, "logicalInterconnectGroupUri": None},
{"interconnectBay": 6, "logicalInterconnectGroupUri": None},
{"interconnectBay": 7, "logicalInterconnectGroupUri": None},
{"interconnectBay": 8, "logicalInterconnectGroupUri": None}],
"ipRangeUris": [],
"enclosureCount": 1,
"osDeploymentSettings": None,
"configurationScript": None,
"powerMode": None,
"ambientTemperatureMode": "Standard"}
encs = [{'hostname': '15.245.129.23', 'username': 'Administrator', 'password': 'wpsthpvse1', 'enclosureGroupUri': 'EG:EG1', 'force': 'true', 'licensingIntent': 'OneViewNoiLO'}, {'hostname': '15.199.229.79', 'username': 'Administrator', 'password': 'compaq', 'enclosureGroupUri': 'EG:EG2', 'force': 'true', 'licensingIntent': 'OneViewNoiLO'}]
ENC1 = 'Enc-79'
LIG3 = 'LIG2'
BAY = '1'
LIGS_TB = [{'name': 'LIG2',
'type': 'logical-interconnect-groupV300',
'enclosureType': 'SY12000',
'interconnectMapTemplate': [{'bay': 3, 'enclosure': 1, 'type': 'Virtual Connect SE 40Gb F8 Module for Synergy - 794502-B23', 'enclosureIndex': 1},
{'bay': 6, 'enclosure': 1, 'type': 'Virtual Connect SE 40Gb F8 Module for Synergy - 794502-B23', 'enclosureIndex': 1}
],
'uplinkSets': [],
'enclosureIndexes': [1],
'interconnectBaySet': 3,
'redundancyType':'Redundant',
'internalNetworkUris': [],
'qosConfiguration': None,
'snmpConfiguration': {'type': 'snmp-configuration',
'readCommunity': 'public',
'systemContact': '',
'enabled': 'true',
'category': 'snmp-configuration'
}
}]
ls = [{'logicalSwitch': {'name': 'LS-56xx',
'state': 'Active',
'status': None,
'description': None,
'uri': None,
'category': None,
'eTag': None,
'created': None,
'modified': None,
'type': 'logical-switchV300',
'switchMap': None,
'logicalSwitchGroupUri': 'LSG:LSG-56xx-1',
'switchCredentialConfiguration': [{'snmpV1Configuration': {'communityString': 'nexus'},
'snmpV3Configuration': {'authorizationProtocol': None,
'privacyProtocol': None,
'securityLevel': None},
'logicalSwitchManagementHost': '15.199.203.171',
'snmpVersion': 'SNMPv1', 'snmpPort': 161}]},
'logicalSwitchCredentials': [{'connectionProperties': [{'propertyName': 'SshBasicAuthCredentialUser',
'value': 'admin',
'valueFormat': 'Unknown',
'valueType': 'String'},
{'propertyName': 'SshBasicAuthCredentialPassword',
'value': 'HPvse123', 'valueFormat': 'SecuritySensitive',
'valueType': 'String'}]}]},
]
li_uplink_sets = {'us1': {'name': 'Invalid-Uses-AnalyzerPort',
'ethernetNetworkType': 'Tagged',
'networkType': 'Ethernet',
'networkUris': ['net_100'],
'fcNetworkUris': [],
'fcoeNetworkUris': [],
'lacpTimer': 'Short',
'logicalInterconnectUri': None,
'primaryPortLocation': None,
'manualLoginRedistributionState': 'NotSupported',
'connectionMode': 'Auto',
'nativeNetworkUri': None,
'portConfigInfos': [{'bay': '3', 'port': 'X10', 'desiredSpeed': 'Auto', 'enclosure': ENC1}]},
}
server_profiles = [{'type': 'ServerProfileV6', 'serverHardwareUri': ENC1 + ', bay 1',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:' + ENC1, 'enclosureGroupUri': 'EG:EG',
'serialNumberType': 'Physical', 'macType': 'Physical', 'wwnType': 'Physical',
'name': 'Profile1', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-a',
'requestedMbps': '2500', 'networkUri': 'ETH:net_101',
'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'FibreChannel', 'portId': 'Flb 1:1-b',
'requestedMbps': '2500', 'networkUri': 'FCOE:fcoe_103',
'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c',
'requestedMbps': '2500', 'networkUri': 'ETH:net_102',
'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''}]},
]
ethnets = [
{
"type": "ethernet-networkV300",
"ethernetNetworkType": "Tagged",
"name": "Net1",
"privateNetwork": False,
"purpose": "General",
"smartLink": True,
"vlanId": 10
},
{
"type": "ethernet-networkV300",
"ethernetNetworkType": "Tagged",
"name": "Net2",
"privateNetwork": False,
"purpose": "General",
"smartLink": True,
"vlanId": 20
}
]
fcnets = [
{
"name": "FC1",
"linkStabilityTime": "30",
"autoLoginRedistribution": True,
"fabricType": "FabricAttach",
"type": "fc-networkV300"
},
{
"name": "FC2",
"linkStabilityTime": "30",
"autoLoginRedistribution": True,
"fabricType": "FabricAttach",
"type": "fc-networkV300"
}
]
fcoenets = [
{
"name": "FCoE1",
"vlanId": "10",
"type": "fcoe-networkV300"
},
{
"name": "FCoE2",
"vlanId": "20",
"type": "fcoe-networkV300"
}
]
ethnetsets = [
{
"name": "EthNetSet1",
"networkUris": [],
"type": "network-setV300",
},
{
"name": "EthNetSet2",
"networkUris": [],
"type": "network-setV300",
}
]
scopes = [
{
"name": "Scope1",
"description": "Scope1 for testing",
"type": "Scope"
},
{
"name": "Scope2",
"description": "Scope2 for Testing",
"type": "Scope"
}
]
serveradmin_user = {"type": "UserAndRoles", "userName": "serveradmin", "fullName": "serveradmin", "password": "serveradmin", "emailAddress": "", "officePhone": "", "mobilePhone": "", "enabled": True, "roles": ["Server administrator"]}
scope_resources = {"addedResourceUris": [], "removedResourceUris": []}
scope_1 = [
{
"name": "S1",
"description": "Scope1 for testing",
"type": "Scope"
},
{
"name": "S2",
"description": "Scope2 for Testing",
"type": "Scope"
}
]
scope_2 = {"name": "ScopeTest",
"description": "Scope1 for testing",
"type": "Scope"}
LSG_1 = [
{
"type": "logical-switch-groupV300",
"name": "LSG-56xx-1",
"state": "Active",
"switchMapTemplate": {
"switchMapEntryTemplates": [{
"logicalLocation": {
"locationEntries": [{
"relativeValue": 1,
"type": "StackingMemberId"}]
},
"permittedSwitchTypeUri": "SW"}]}
},
{
"type": "logical-switch-groupV300",
"name": "LSG-56xx-2",
"state": "Active",
"switchMapTemplate": {
"switchMapEntryTemplates": [{
"logicalLocation": {
"locationEntries": [{
"relativeValue": 1,
"type": "StackingMemberId"}]},
"permittedSwitchTypeUri": "SW"}]}
}
]
LIG1 = 'LIG1'
LIG3 = 'LE1-LIG_1'
type_switch = ["C56XX"]
enc_group = [{'name': 'EG1',
'type': 'EnclosureGroupV300',
'enclosureTypeUri': '/rest/enclosure-types/SY12000',
'stackingMode': 'Enclosure',
'interconnectBayMappingCount': 2,
'configurationScript': None,
'powerMode': 'RedundantPowerFeed',
'ipAddressingMode': 'DHCP',
'enclosureCount': 1,
'interconnectBayMappings':
[{'interconnectBay': 3, 'logicalInterconnectGroupUri': 'LIG2'},
{'interconnectBay': 6, 'logicalInterconnectGroupUri': 'LIG2'}]}]
QoS_Fcoe = {'qosConfiguration':
{
'activeQosConfig': {
'type': 'QosConfiguration',
'configType': 'CustomWithFCoE',
'uplinkClassificationType': 'DOT1P_AND_DSCP',
'downlinkClassificationType': 'DOT1P_AND_DSCP',
'qosTrafficClassifiers': [
{
'qosTrafficClass': {
'bandwidthShare': '55',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Best effort',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [
1,
0
],
'dscpClassMapping':[
'DSCP 10, AF11',
'DSCP 12, AF12',
'DSCP 14, AF13',
'DSCP 8, CS1',
'DSCP 0, CS0'
]
}
},
{
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class1',
'enabled': False
},
'qosClassificationMapping': None
},
{
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class2',
'enabled': False
},
'qosClassificationMapping': None
},
{
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class4',
'enabled': False
},
'qosClassificationMapping': None
},
{
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 1,
'maxBandwidth': 10,
'realTime': False,
'className': 'Class5',
'enabled': True
},
'qosClassificationMapping': None
},
{
'qosTrafficClass': {
'bandwidthShare': 'fcoe',
'egressDot1pValue': 3,
'maxBandwidth': 100,
'realTime': False,
'className': 'FCoE lossless',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [
3
],
'dscpClassMapping':[
]
}
},
{
'qosTrafficClass': {
'bandwidthShare': '25',
'egressDot1pValue': 2,
'maxBandwidth': 100,
'realTime': False,
'className': 'Medium',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [
4,
3,
2
],
'dscpClassMapping':[
'DSCP 18, AF21',
'DSCP 20, AF22',
'DSCP 22, AF23',
'DSCP 26, AF31',
'DSCP 28, AF32',
'DSCP 30, AF33',
'DSCP 34, AF41',
'DSCP 36, AF42',
'DSCP 38, AF43',
'DSCP 16, CS2',
'DSCP 24, CS3',
'DSCP 32, CS4'
]
}
},
{
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 5,
'maxBandwidth': 10,
'realTime': True,
'className': 'Real time',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [
5,
6,
7
],
'dscpClassMapping':[
'DSCP 46, EF',
'DSCP 40, CS5',
'DSCP 48, CS6',
'DSCP 56, CS7'
]
}
}
],
'name': None,
'state': None,
'description': None,
'status': None,
'eTag': None,
'category': 'qos-aggregated-configuration',
'uri': None
},
'inactiveFCoEQosConfig': None,
'inactiveNonFCoEQosConfig': None,
'type': 'qos-aggregated-configuration',
'name': None,
'state': None,
'status': None,
'eTag': None,
'category': 'qos-aggregated-configuration',
'uri': None
}}
QoS_NoFcoe = {'qosConfiguration': {
'activeQosConfig': {
'type': 'QosConfiguration',
'configType': 'CustomNoFCoE',
'downlinkClassificationType': 'DOT1P',
'uplinkClassificationType': 'DSCP',
'qosTrafficClassifiers': [{
'qosTrafficClass': {
'bandwidthShare': '55',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Best effort',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [1, 0],
'dscpClassMapping': ['DSCP 10, AF11', 'DSCP 12, AF12', 'DSCP 14, AF13', 'DSCP 8, CS1', 'DSCP 0, CS0']
}
}, {
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 1,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class1',
'enabled': True
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class2',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class3',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class4',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class5',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '25',
'egressDot1pValue': 2,
'maxBandwidth': 100,
'realTime': False,
'className': 'Medium',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [4, 3, 2],
'dscpClassMapping': ['DSCP 18, AF21', 'DSCP 20, AF22', 'DSCP 22, AF23', 'DSCP 26, AF31', 'DSCP 28, AF32', 'DSCP 30, AF33', 'DSCP 34, AF41', 'DSCP 36, AF42', 'DSCP 38, AF43', 'DSCP 16, CS2', 'DSCP 24, CS3', 'DSCP 32, CS4']
}
}, {
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 5,
'maxBandwidth': 10,
'realTime': True,
'className': 'Real time',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [5, 6, 7],
'dscpClassMapping': ['DSCP 46, EF', 'DSCP 40, CS5', 'DSCP 48, CS6', 'DSCP 56, CS7']
}
}],
'name': None,
'state': None,
'description': None,
'status': None,
'eTag': None,
'category': 'qos-aggregated-configuration',
'uri': None
},
'inactiveFCoEQosConfig': None,
'inactiveNonFCoEQosConfig': None,
'type': 'qos-aggregated-configuration',
'name': None,
'state': None,
'status': None,
'eTag': None,
'category': 'qos-aggregated-configuration',
'uri': None
}}
Li_Qos = {
'activeQosConfig': {
'type': 'QosConfiguration',
'configType': 'CustomWithFCoE',
'uplinkClassificationType': 'DOT1P',
'downlinkClassificationType': 'DOT1P_AND_DSCP',
'qosTrafficClassifiers': [{
'qosTrafficClass': {
'bandwidthShare': '65',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Best effort',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [1, 0],
'dscpClassMapping': ['DSCP 10, AF11', 'DSCP 12, AF12', 'DSCP 14, AF13', 'DSCP 8, CS1', 'DSCP 0, CS0']
}
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class1',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class2',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class3',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': '0',
'egressDot1pValue': 0,
'maxBandwidth': 100,
'realTime': False,
'className': 'Class4',
'enabled': False
},
'qosClassificationMapping': None
}, {
'qosTrafficClass': {
'bandwidthShare': 'fcoe',
'egressDot1pValue': 3,
'maxBandwidth': 100,
'realTime': False,
'className': 'FCoE lossless',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [3],
'dscpClassMapping': []
}
}, {
'qosTrafficClass': {
'bandwidthShare': '25',
'egressDot1pValue': 2,
'maxBandwidth': 100,
'realTime': False,
'className': 'Medium',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [4, 3, 2],
'dscpClassMapping': ['DSCP 18, AF21', 'DSCP 20, AF22', 'DSCP 22, AF23', 'DSCP 26, AF31', 'DSCP 28, AF32', 'DSCP 30, AF33', 'DSCP 34, AF41', 'DSCP 36, AF42', 'DSCP 38, AF43', 'DSCP 16, CS2', 'DSCP 24, CS3', 'DSCP 32, CS4']
}
}, {
'qosTrafficClass': {
'bandwidthShare': '10',
'egressDot1pValue': 5,
'maxBandwidth': 10,
'realTime': True,
'className': 'Real time',
'enabled': True
},
'qosClassificationMapping': {
'dot1pClassMapping': [5, 6, 7],
'dscpClassMapping': ['DSCP 46, EF', 'DSCP 40, CS5', 'DSCP 48, CS6', 'DSCP 56, CS7']
}
}],
'name': None,
'state': None,
'description': None,
'status': None,
'eTag': None,
'modified': None,
'created': None,
'category': 'qos-aggregated-configuration',
'uri': None
},
'inactiveFCoEQosConfig': None,
'inactiveNonFCoEQosConfig': None,
'type': 'qos-aggregated-configuration',
'name': None,
'state': None,
'status': None,
'eTag': None,
'modified': None,
'created': None,
'category': 'qos-aggregated-configuration',
'uri': None
}
LE = 'LE'
Logical_Enclosure = [{'name': LE,
'enclosureUris': ['ENC:' + ENC1],
'enclosureGroupUri': 'EG:EG1',
'firmwareBaselineUri': None,
'forceInstallFirmware': False}]
Bulk_enet = {
"vlanIdRange": "1-5",
"namePrefix": "Enet",
"privateNetwork": "false",
"smartLink": "true",
"purpose": "General",
"type": "bulk-ethernet-network",
"bandwidth": {
"maximumBandwidth": 20000,
"typicalBandwidth": 2500
}}
| richa92/Jenkin_Regression_Testing | robo4.2/fusion/tests/wpst_crm/feature_tests/C7000/F861_API/data_variables.py | data_variables.py | py | 36,858 | python | en | code | 0 | github-code | 13 |
31037473082 | from Nguoi import Nguoi
class HoGiaDinh:
family_list = []
def __init__(self):
self.address = None
self.number_of_member = 0
self.member_list = []
def input_info(self):
self.address = input("Nhập địa chỉ hộ gia đình: ")
while True:
option = input("Bạn có muốn nhập thêm thành viên (y/n)?: ")
if option == "y":
nguoi_moi = Nguoi()
self.member_list.append(nguoi_moi)
self.number_of_member +=1
elif option == "n":
break
else:
continue
def output_info(self):
print("Hộ gia đình: "+self.address)
for member in self.member_list:
member.output_info() | nhatelecom/practice_python | 19-06hogiadinh/HoGiaDinh.py | HoGiaDinh.py | py | 781 | python | vi | code | 0 | github-code | 13 |
73111217617 | import pandas as pd
import get_raw_data
import geocoder
import numpy as np
import datetime
from dateutil.relativedelta import relativedelta
import streamlit as st
import json
import requests
def get_semestral_dates(start_last_month=True):
"""
return a dict with the dates from the imediate previous and the second previous trimester
start_last_month: if True, the final date it's the last day of the imediate previous month
monthly_report: if True, only get last month, not trimesters
"""
if start_last_month:
now = datetime.datetime.now()
final_date = datetime.date(
now.year, now.month, 1) + relativedelta(days=-1)
begin_date = final_date + \
relativedelta(months=-5)
begin_date = datetime.date(
begin_date.year, begin_date.month, 1)
else:
# aqui nao tem nada em relação ao monthly report, avaliar se vale a pena
final_date = datetime.datetime.now()
begin_date = final_date + relativedelta(months=-5)
return {
'final_date': pd.to_datetime(final_date),
'begin_date': pd.to_datetime(begin_date),
}
def do_geocoder(x):
try:
print('add')
return geocoder.arcgis(x, readtimeout=15).latlng
except:
print('errou \n')
print(x)
def get_dataset_for_alugados():
df_sami_not_in_orion = get_raw_data.get_imoveis_sami()
df_orion_for_alugados = get_raw_data.get_distinct_orion()
df_sami = get_raw_data.get_distinct_sami()
columns_to_lambda = [i for i in df_sami_not_in_orion.columns.tolist() if i not in ['cod_imov_sami', 'comodidades']]
dict_to_agg = {i: lambda x: max(x) for i in columns_to_lambda}
dict_to_agg['comodidades'] = lambda x: ', '.join(x) if x.any() else float("NaN")
df_sami_not_in_orion['DataOcupacaoCont_CadCont'] = pd.to_datetime(df_sami_not_in_orion['DataOcupacaoCont_CadCont'])
columns_to_lambda = [i for i in df_sami_not_in_orion.columns.tolist() if i not in ['cod_imov_sami', 'comodidades']]
df_sami_not_in_orion = df_sami_not_in_orion.groupby('cod_imov_sami').agg(dict_to_agg).reset_index()
df_sami_not_in_orion['sacada'] = df_sami_not_in_orion['comodidades'].apply(lambda x: 'Sim' if isinstance(x, str) and 'Sacada' in x else 'Não')
df_sami_not_in_orion['churrasqueira'] = df_sami_not_in_orion['comodidades'].apply(lambda x: 'Sim' if isinstance(x, str) and 'Churrasqueira' in x else 'Não')
df_sami_not_in_orion['valor_condominio'] /= 100
df_sami_not_in_orion['valor_iptu_mensal'] /= 100
df_sami_not_in_orion['mobiliado'] = df_sami_not_in_orion['mobiliado'].apply(lambda x: 'Sim' if x == 1 else 'Semi' if x == 2 else 'Não')
df_sami_not_in_orion['finalidade'] = df_sami_not_in_orion['finalidade'].apply(lambda x: 'Residencial' if x == 'R' else 'Comercial' if x == 'C' else 'Box')
if df_sami_not_in_orion[df_sami_not_in_orion['latitude'] == 0].shape[0] > 0:
print('passou')
import swifter
df_sami_not_in_orion['coordinates'] = df_sami_not_in_orion.apply(lambda x: [x['latitude'], x['longitude']] if x['latitude'] != 0 else do_geocoder(x['endereco']), axis=1)
df_sami_not_in_orion['latitude'] = df_sami_not_in_orion['coordinates'].apply(lambda x: x[0] if type(x)==list or type(x)==tuple else eval(x)[0])
df_sami_not_in_orion['longitude'] = df_sami_not_in_orion['coordinates'].apply(lambda x: x[1] if type(x)==list or type(x)==tuple else eval(x)[1])
df_sami_not_in_orion.drop(columns=['coordinates'], inplace=True)
con = get_raw_data.conectar_sami()
cursor = con.cursor()
sql_update = "UPDATE loc_cadimov SET CoordenadaX_CadImov = %s, CoordenadaY_CadImov = %s WHERE CodImovel_CadImov = %s"
for index, row in df_sami_not_in_orion.iterrows():
cursor.execute(sql_update, tuple(row[['latitude', 'longitude', 'cod_imov_sami']].values))
con.commit()
con.close()
df_orion_for_alugados = df_orion_for_alugados.drop_duplicates(subset='codigo_sistema', keep='last')
df_orion_for_alugados['sacada'] = df_orion_for_alugados['comodidades'].apply(lambda x: 'Sim' if isinstance(x, str) and 'Sacada' in x else 'Não')
df_orion_for_alugados['churrasqueira'] = df_orion_for_alugados['comodidades'].apply(lambda x: 'Sim' if isinstance(x, str) and 'Churrasqueira' in x else 'Não')
df_sami['DataOcupacaoCont_CadCont'] = pd.to_datetime(df_sami['DataOcupacaoCont_CadCont'])
df_sami['NumContratoInterno_CadCont'] = df_sami['NumContratoInterno_CadCont'].replace({'': 0, 'ID': ''}, regex=True).astype(int)
# df_sami_filtered = df_sami.loc[df_sami['DataOcupacaoCont_CadCont'].between('2021-05-01', '2021-10-31')]
dates = get_semestral_dates(start_last_month=True)
df_sami_filtered = df_sami.loc[df_sami['DataOcupacaoCont_CadCont'].between(dates['begin_date'], dates['final_date'])]
df_merged_alugados = df_sami_filtered.merge(df_orion_for_alugados, left_on='NumContratoInterno_CadCont', right_on='codigo_sistema', how='left')
columns = ['finalidade', 'tipologia', 'bairro', 'valor_aluguel', 'valor_condominio', 'valor_iptu_mensal', 'dormitorios',
'suites', 'banheiros', 'vagas_garagem', 'area_privativa', 'mobiliado', 'latitude', 'longitude', 'sacada', 'churrasqueira']
for index, row in df_merged_alugados.loc[df_merged_alugados['codigo_sistema'].isnull()].iterrows():
for column in columns:
df_merged_alugados.loc[index, column] = df_sami_not_in_orion.loc[df_sami_not_in_orion['cod_contrato'] == row['CodContrato_CadCont']][column].squeeze()
df_merged_alugados.replace({0: float("NaN"), '0': float("NaN")}, inplace=True)
df_merged_alugados.dropna(subset=['area_privativa'], inplace=True)
isencao_condominio = ['Casa', 'Box', 'Pavilhão', 'Terreno', 'Chácara', 'Outros', 'Galpão', 'Prédio', 'Lote', 'Casa Comercial']
# onde o valor do condominio é menor que e se não está dentro dos imóveis em que a tipologia é isenta de condominio, atribua nulo para fazer o fillna
df_merged_alugados.loc[df_merged_alugados['tipologia'].isin(isencao_condominio), 'valor_condominio'] = 0
# estamos transformando em 0 todos os kitnets e imóveis comerciais que não são casas ou casas comerciais
df_merged_alugados.loc[(df_merged_alugados['tipologia'] == 'Kitnet') | (df_merged_alugados['finalidade'] == 'Comercial') & (df_merged_alugados['tipologia'] != 'Casa Comercial') & (df_merged_alugados['tipologia'] != 'Casa'), 'dormitorios'] = 0
columns = ['area_privativa', 'finalidade', 'bairro', 'banheiros', 'dormitorios', 'latitude', 'longitude', 'mobiliado', 'suites', 'tipologia', 'vagas_garagem', 'valor_condominio', 'valor_iptu_mensal', 'sacada', 'churrasqueira', 'valor_aluguel', 'alugado']
df_merged_alugados['alugado'] = 1
return df_merged_alugados[columns]
def get_dataset_for_scraper():
df_scraper = get_raw_data.get_distinct_scraper(last_monday=True)
df_orion_for_scraper = get_raw_data.get_distinct_orion(last_monday=True)
df_orion_for_scraper.insert(1, 'imobiliaria', 'Órion')
df_merged_scraper = pd.concat([df_scraper, df_orion_for_scraper])
df_merged_scraper['mobiliado'] = df_merged_scraper['mobiliado'].apply(lambda x: 'Não' if x not in ['Sim', 'Semi'] else x)
df_merged_scraper.replace({0: float("NaN"), '0': float("NaN")}, inplace=True)
df_merged_scraper['banheiros'].fillna(1, inplace=True)
df_merged_scraper['dormitorios'].fillna(0, inplace=True)
df_merged_scraper = df_merged_scraper.loc[df_merged_scraper['valor_aluguel'] < 20000]
# df_merged_scraper = df_merged_scraper.loc[(df_merged_scraper['valor_condominio'] > 5) | (df_merged_scraper['valor_condominio'].isnull())]
# df_merged_scraper = df_merged_scraper.loc[(df_merged_scraper['valor_iptu_mensal'] <= 300) | (df_merged_scraper['valor_iptu_mensal'].isnull())]
df_merged_scraper = df_merged_scraper.loc[(df_merged_scraper['longitude'] > -54.5) & (df_merged_scraper['longitude'] < -53)]
df_merged_scraper = df_merged_scraper.loc[(df_merged_scraper['latitude'] > -29.78) & (df_merged_scraper['latitude'] < -28)]
df_merged_scraper['sacada'] = 'Não'
df_merged_scraper['churrasqueira'] = 'Não'
searchfor = ['Sacada', 'sacada', 'BALCONY', 'balcony', 'Sacadas', 'sacadas', 'Sacad', 'sacad']
df_merged_scraper.loc[df_merged_scraper['comodidades'].fillna('').str.contains('|'.join(searchfor)), 'sacada'] = 'Sim'
searchfor = ['Churrasqueira', 'churrasqueira', 'BARBECUE_GRILL', 'churras', 'Churras']
df_merged_scraper.loc[df_merged_scraper['comodidades'].fillna('').str.contains('|'.join(searchfor)), 'churrasqueira'] = 'Sim'
df_merged_scraper.drop(columns=['comodidades'], inplace=True)
isencao_condominio = ['Casa', 'Box', 'Pavilhão', 'Terreno', 'Chácara', 'Outros', 'Galpão', 'Prédio', 'Lote', 'Casa Comercial']
# onde o valor do condominio é menor que e se não está dentro dos imóveis em que a tipologia é isenta de condominio, atribua nulo para fazer o fillna
df_merged_scraper.loc[df_merged_scraper['tipologia'].isin(isencao_condominio), 'valor_condominio'] = 0
df_merged_scraper.loc[(df_merged_scraper['valor_condominio'] < 50) & ~(df_merged_scraper['tipologia'].isin(isencao_condominio)), 'valor_condominio'] = np.nan
# df_merged_scraper.loc[(df_merged_scraper['valor_condominio'] < 50), 'valor_condominio'] = np.nan
df_merged_scraper.loc[(df_merged_scraper['valor_iptu_mensal'] < 8.4) | (df_merged_scraper['valor_iptu_mensal'] >= 300), 'valor_iptu_mensal'] = np.nan
# estamos transformando em 0 todos os kitnets e imóveis comerciais que não são casas ou casas comerciais
df_merged_scraper.loc[(df_merged_scraper['tipologia'] == 'Kitnet') | (df_merged_scraper['finalidade'] == 'Comercial') & (df_merged_scraper['tipologia'] != 'Casa Comercial') & (df_merged_scraper['tipologia'] != 'Casa'), 'dormitorios'] = 0
df_merged_scraper['alugado'] = 0
columns = ['link', 'imobiliaria', 'area_privativa', 'finalidade', 'bairro', 'banheiros', 'dormitorios', 'latitude', 'longitude', 'mobiliado', 'suites', 'tipologia', 'vagas_garagem', 'valor_condominio', 'valor_iptu_mensal', 'sacada', 'churrasqueira', 'valor_aluguel', 'alugado']
return df_merged_scraper[columns]
def rower(data):
s = data.index % 2 != 0
s = pd.concat([pd.Series(s)] * data.shape[1], axis=1) #6 or the n of cols u have
z = pd.DataFrame(np.where(s, 'background-color:#f2f2f2', ''),
index=data.index, columns=data.columns)
return z
def real_br_money_mask(my_value):
a = '{:,.2f}'.format(float(my_value))
b = a.replace(',','v')
c = b.replace('.',',')
return c.replace('v','.')
# @st.cache(hash_funcs={"_thread.RLock": lambda _: None, 'builtins.weakref': lambda _: None}, show_spinner=False)
def get_corretores_vendas_table(type_of_report, data_inicio, data_termino):
if type_of_report == 'Compacto':
df = get_raw_data.get_comissao_corretores(compacto=True, data_inicio=data_inicio, data_termino=data_termino)
# df['Soma de Valor do Aluguel'] = df['Soma de Valor do Aluguel'].astype(int)
df['Soma de Valor do Aluguel'] = df['Soma de Valor do Aluguel'].apply(real_br_money_mask)
elif type_of_report == 'Detalhado':
df = get_raw_data.get_comissao_corretores(compacto=False, data_inicio=data_inicio, data_termino=data_termino)
# df['Valor do Aluguel'] = df['Valor do Aluguel'].astype(int)
df['Valor do Aluguel'] = df['Valor do Aluguel'].apply(real_br_money_mask)
df['Endereço do Imóvel'] = df['Endereço do Imóvel'].str.title()
df['Nome do Inquilino'] = df['Nome do Inquilino'].str.title()
# return df.style.apply(rower, axis=None)
return df
# @st.cache(hash_funcs={"_thread.RLock": lambda _: None, 'builtins.weakref': lambda _: None}, show_spinner=False)
def get_df_usuarios(only_vendas, only_exibir_site=True, all_users=False):
"""
Retorna df do vista com todos os usuários de locação.
"""
headers = {
'accept': 'application/json'
}
for page in range(1, 100):
if only_exibir_site:
if only_vendas:
# exclui o gerente pq no de ag comissoes aparecia o vitor e quero testar
# "Gerente": ["Nao"]
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Exibirnosite": ["Sim"], "Atua\\u00e7\\u00e3oemvenda": ["Sim"], "Corretor": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
elif all_users:
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Exibirnosite": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
else:
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Exibirnosite": ["Sim"], "Corretor": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
else:
if only_vendas:
# exclui o gerente pq no de ag comissoes aparecia o vitor e quero testar
# "Gerente": ["Nao"]
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Atua\\u00e7\\u00e3oemvenda": ["Sim"], "Corretor": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
elif all_users:
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Atua\\u00e7\\u00e3oemvenda": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
else:
url = f'http://brasaolt-rest.vistahost.com.br/usuarios/listar?key={st.secrets["api_vista_key"]}&pesquisa={{"fields":["Codigo", "Nomecompleto", "Nome", "E-mail", "Atua\\u00e7\\u00e3oemloca\\u00e7\\u00e3o", "Atua\\u00e7\\u00e3oemvenda", "Corretor", "Gerente", "Agenciador", "Administrativo", "Observacoes", "Fone", "Foto", {{"Equipe": ["Nome"]}}], "filter": {{"Corretor": ["Sim"]}}, "paginacao":{{"pagina":{page}, "quantidade":50}}}}&Equipe={{"fields:["Nome"]}}'
response = requests.get(url, headers=headers)
if response.content == b'[]':
break
df_usuarios = pd.DataFrame(json.loads(response.content))[1:].T
df_usuarios['Equipe'] = df_usuarios['Equipe'].apply(lambda x: [x[key] for key in x][0]['Nome'] if type(x) == dict else x)
df_usuarios.reset_index(inplace=True, drop=True)
return df_usuarios.sort_values(by="Nomecompleto")
# @st.cache(hash_funcs={"_thread.RLock": lambda _: None, 'builtins.weakref': lambda _: None}, show_spinner=False, allow_output_mutation=True)
def get_agenciamentos_tables(type_of_report, data_inicio, data_termino, agenciadores_vista, dict_replace_agenciadores, type_of_status, groupby_type=None):
if type_of_report == 'Compacto':
df_vista = get_raw_data.get_vista_api(json.dumps(data_inicio), json.dumps(data_termino), json.dumps(agenciadores_vista))
df = get_raw_data.get_vista_api_historicos(df_vista, type_of_status)
df['Agenciador'] = df['Agenciador'].replace(dict_replace_agenciadores)
df = df.groupby(groupby_type, as_index=False).size().rename(columns={"size": "Quantidade"}).sort_values(by="Quantidade", ascending=False).reset_index(drop=True)
elif type_of_report == 'Detalhado':
df_vista = get_raw_data.get_vista_api(json.dumps(data_inicio), json.dumps(data_termino), json.dumps(agenciadores_vista))
df = get_raw_data.get_vista_api_historicos(df_vista, type_of_status)
df['Agenciador'] = df['Agenciador'].replace(dict_replace_agenciadores)
# return df.style.apply(rower, axis=None)
return df
# @st.cache(hash_funcs={"_thread.RLock": lambda _: None, 'builtins.weakref': lambda _: None}, show_spinner=False, allow_output_mutation=True)
def get_agenciamentos_comissoes(dataframe_imoveis_locados, type_of_report, codigo_usuarios_gerente):
# if type_of_report == 'Compacto':
df = get_raw_data.get_detail_imovel_vista(dataframe_imoveis_locados, codigo_usuarios_gerente)
# df['Corretor'] = df['Corretor'].apply(lambda x: [dict_replace_agenciadores.get(agenciador) for agenciador in x])
# elif type_of_report == 'Detalhado':
# pass
return df
| arturlunardi/orion_dp | create_dataset.py | create_dataset.py | py | 17,730 | python | pt | code | 0 | github-code | 13 |
12135504633 | '''
拟合轮廓的最小包围圆
'''
import cv2
import numpy as np
img = cv2.imread('../data/cloud.png')
cv2.imshow('img', img)
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
t, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('binary', binary)
# 查找轮廓
cnts, hie = cv2.findContours(binary,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
# 根据轮廓坐标点生成拟合轮廓的参数
center,radius = cv2.minEnclosingCircle(cnts[0])
# print('圆心:{},半径:{}'.format(center,radius))
center = (int(center[0]),int(center[1]))
radius = int(radius)
cv2.circle(img,center,radius,(0,0,255),2)
cv2.imshow('res',img)
cv2.waitKey()
cv2.destroyAllWindows()
| 15149295552/Code | Month08/day14/12_minEnclosingCircle.py | 12_minEnclosingCircle.py | py | 761 | python | en | code | 1 | github-code | 13 |
36674636889 | import requests
import csv
import os
import json
from mysklearn.mypytable import MyPyTable
OMDB_API_URL = "http://www.omdbapi.com/?apikey=60a1d5e4&"
FIELDS = ['title', 'year', 'rated', 'release_date', 'runtime',
'genre', 'director', 'writer', 'actors', 'plot',
'language', 'country', 'awards', 'poster',
'ratings', 'metascore', 'imdbrating', 'imdbvotes',
'imdbid', 'type', 'dvd', 'boxoffice', 'production',
'website', 'response']
def get_data():
file_exists = os.path.exists('input_data/omdb_data.csv')
if not(file_exists):
download_from_start()
else:
download_from_given_place()
def get_list_of_titles():
file_name = ("input_data/movie_names.csv")
table = MyPyTable().load_from_file(file_name)
return table
def download_from_start():
table = get_list_of_titles()
movie_result = []
movie_list = []
for movie in table.data:
movie_list.append(movie[0])
for count, movie in enumerate(movie_list): #Only allowed 1000 calls a day
r_params = {"t":movie}
r = requests.get(url = OMDB_API_URL, params=r_params)
if r.status_code == 200:
r_data = r.json()
if "False" in r_data:
print(r_data)
try:
r_data = json.dumps(r_data)
r_data = json.loads(r_data)
if ['False', 'Movie not found!']!= list(r_data.values()):
movie_result.append(list(r_data.values()))
except:
print("Could not find", movie)
elif r.status_code == 401:
r_data = r.json()
if r_data["Error"] == 'Request limit reached!':
break;
with open('input_data/omdb_data.csv', 'w') as file:
write = csv.writer(file)
write.writerow(FIELDS)
write.writerows(movie_result)
file.close()
with open('input_data/left_off_at.txt', 'w') as file:
file.write(str(count))
file.close()
def download_from_given_place():
table = get_list_of_titles()
movie_result = []
movie_list = []
with open('input_data/left_off_at.txt', 'r') as file:
previous_count = int(file.readline())
file.close()
for movie in table.data[previous_count:]:
movie_list.append(movie[0])
for count, movie in enumerate(movie_list): #Only allowed 1000 calls a day
r_params = {"t":movie}
r = requests.get(url = OMDB_API_URL, params=r_params)
if r.status_code == 200:
r_data = r.json()
try:
r_data = json.dumps(r_data)
r_data = json.loads(r_data)
if ['False', 'Movie not found!']!= list(r_data.values()):
movie_result.append(list(r_data.values()))
except:
print("Could not find", movie)
elif r.status_code == 401:
r_data = r.json()
if r_data["Error"] == 'Request limit reached!':
break;
with open('input_data/omdb_data.csv', 'a') as file:
write = csv.writer(file)
write.writerows(movie_result)
with open('input_data/left_off_at.txt', 'w') as file:
file.write(str(count + previous_count))
file.close()
if __name__ == "get_data":
get_data() | tbech12/CPSC322-Final-Project | get_omdb_data.py | get_omdb_data.py | py | 3,300 | python | en | code | 0 | github-code | 13 |
25137345360 | ###
### GPAW benchmark: Carbon Nanotube
###
from __future__ import print_function
from gpaw.mpi import size, rank
from gpaw import GPAW, Mixer, PoissonSolver, ConvergenceError
from gpaw.occupations import FermiDirac
try:
from ase.build import nanotube
except ImportError:
from ase.structure import nanotube
# dimensions of the nanotube
n = 6
m = 6
length = 10
# other parameters
txt = 'output.txt'
maxiter = 16
conv = {'eigenstates' : 1e-4, 'density' : 1e-2, 'energy' : 1e-3}
# uncomment to use ScaLAPACK
#parallel = {'sl_auto': True}
# uncomment to use GPUs
#gpu = {'cuda': True, 'hybrid_blas': False}
# check which GPU backend (if any) is used
if 'gpu' in locals():
use_cuda = gpu.get('cuda', False)
else:
use_cuda = False
# output benchmark parameters
if rank == 0:
print("#"*60)
print("GPAW benchmark: Carbon Nanotube")
print(" nanotube dimensions: n=%d, m=%d, length=%d" % (n, m, length))
print(" MPI tasks: %d" % size)
print(" using GPU: " + str(use_cuda))
print("#"*60)
print("")
# setup parameters
args = {'h': 0.2,
'nbands': -60,
'occupations': FermiDirac(0.1),
'mixer': Mixer(0.1, 5, 50),
'poissonsolver': PoissonSolver(eps=1e-12),
'eigensolver': 'rmm-diis',
'maxiter': maxiter,
'convergence': conv,
'txt': txt}
if use_cuda:
args['gpu'] = gpu
args['xc_thread'] = False
try:
args['parallel'] = parallel
except: pass
# setup the system
atoms = nanotube(n, m, length)
atoms.center(vacuum=4.068, axis=0)
atoms.center(vacuum=4.068, axis=1)
calc = GPAW(**args)
atoms.set_calculator(calc)
# execute the run
try:
atoms.get_potential_energy()
except ConvergenceError:
pass
| mlouhivu/gpaw-benchmarks | carbon-nanotube/input.py | input.py | py | 1,713 | python | en | code | 1 | github-code | 13 |
73729678738 | from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
#======================LIST VIEW========================
def list(request):
return render(request,'newsBlog/files/listBlog.html',{'nav':'common/nav.html','posts':Post.published.all(),'css':'newsBlog/files/listBlogCss.html','js':'newsBlog/files/listBlogJs.html'})
#====================END LIST VIEW=======================
#======================DETAIL VIEW========================
def detail(request,year,month,day,post):
post = get_object_or_404(Post, slug=post, status='published', publish__year=year,publish__month=month, publish__day=day,)
comments = post.comments.filter(active=True)
return render(request,'newsBlog/files/detailBlog.html',{'nav':'common/nav.html','css':'newsBlog/files/detailBlogCss.html','post':post,'comments':comments,'js':'newsBlog/files/detailBlogJs.html',})
#====================END DETAIL VIEW=======================
@login_required
@require_POST
def comment(request):
post = get_object_or_404(Post, slug=request.POST.get('slug'), status='published', publish__year=request.POST.get('year'),publish__month=request.POST.get('month'), publish__day=request.POST.get('day'))
newComment = request.POST.get('newComment')
newCommentModel = Comment()
newCommentModel.post = post
newCommentModel.name = request.user.first_name
newCommentModel.username = request.user.username
newCommentModel.body = newComment
newCommentModel.save()
return JsonResponse({'status':'ok'})
@login_required
@require_POST
def deletePost(request):
post = Post.objects.filter(author=request.user,id=request.POST.get("id"))
post.delete()
return JsonResponse({'status':'ok'}) | khanshoaib3/newsWebsite | project/newsBlog/views.py | views.py | py | 1,891 | python | en | code | 1 | github-code | 13 |
74875911376 | import os
import warnings
import shutil
import pandas as pd
import numpy as np
from itertools import cycle
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import enet_path
from sklearn import datasets
# Import mlflow
import mlflow
import mlflow.sklearn
def plot_enet_descent_path(X, y, l1_ratio):
# Compute paths
eps = 5e-3 # the smaller it is the longer is the path
# Reference the global image variable
global image
print("Computing regularization path using ElasticNet.")
alphas_enet, coefs_enet, _ = enet_path(
X, y, eps=eps, l1_ratio=l1_ratio, fit_intercept=False)
# Display results
fig = plt.figure(1)
plt.gca()
colors = cycle(['b', 'r', 'g', 'c', 'k'])
neg_log_alphas_enet = -np.log10(alphas_enet)
for coef_e, c in zip(coefs_enet, colors):
plt.plot(neg_log_alphas_enet, coef_e, linestyle='--', c=c)
plt.xlabel('-Log(alpha)')
plt.ylabel('coefficients')
title = 'ElasticNet Path by alpha for l1_ratio = ' + str(l1_ratio)
plt.title(title)
plt.axis('tight')
# Display images
image = fig
# Save figure
fig.savefig("out/ElasticNet-paths_l1_ratio_{}_.png".format(str(l1_ratio)))
# Close plot
plt.close(fig)
# Return images
return image
def eval_metrics(actual, pred):
rmse = np.sqrt(mean_squared_error(actual, pred))
mae = mean_absolute_error(actual, pred)
r2 = r2_score(actual, pred)
return rmse, mae, r2
def train_diabetes(data, in_alpha, in_l1_ratio):
warnings.filterwarnings("ignore")
np.random.seed(40)
mlflow.set_experiment("diabetes_experiment")
# Split the data into training and test sets. (0.75, 0.25) split.
train, test = train_test_split(data)
# The predicted column is "progression" which is a quantitative measure of
# disease progression one year after baseline
train_x = train.drop(["progression"], axis=1)
test_x = test.drop(["progression"], axis=1)
train_y = train[["progression"]]
test_y = test[["progression"]]
if float(in_alpha) is None:
alpha = 0.05
else:
alpha = float(in_alpha)
if float(in_l1_ratio) is None:
l1_ratio = 0.05
else:
l1_ratio = float(in_l1_ratio)
# Start an MLflow run
with mlflow.start_run():
lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)
lr.fit(train_x, train_y)
predicted_qualities = lr.predict(test_x)
(rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)
# Print out ElasticNet model metrics
print("Elasticnet model (alpha=%f, l1_ratio=%f):" % (alpha, l1_ratio))
print(" RMSE: %s" % rmse)
print(" MAE: %s" % mae)
print(" R2: %s" % r2)
# Set tracking_URI first and then reset it back to not specifying port
# Note, we had specified this in an earlier cell
# mlflow.set_tracking_uri(mlflow_tracking_URI)
# Log mlflow attributes for mlflow UI
mlflow.log_param("alpha", alpha)
mlflow.log_param("l1_ratio", l1_ratio)
mlflow.log_metric("rmse", rmse)
mlflow.log_metric("r2", r2)
mlflow.log_metric("mae", mae)
mlflow.sklearn.log_model(lr, "model")
modelpath = "models/model-%f-%f" % (
alpha, l1_ratio)
mlflow.sklearn.save_model(lr, modelpath)
# Call plot_enet_descent_path
plot_enet_descent_path(X, y, l1_ratio)
# Log artifacts (output files)
mlflow.log_artifact(
"out/ElasticNet-paths_l1_ratio_{}_.png".format(str(l1_ratio)))
if __name__ == "__main__":
# Load Diabetes datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
# Create pandas DataFrame for sklearn ElasticNet linear_model
Y = np.array([y]).transpose()
d = np.concatenate((X, Y), axis=1)
cols = ["age", "sex", "bmi", "bp", "s1", "s2",
"s3", "s4", "s5", "s6", "progression"]
data = pd.DataFrame(d, columns=cols)
if os.path.exists("models"):
shutil.rmtree("models")
os.mkdir("models")
if os.path.exists("out"):
set
shutil.rmtree("out")
os.mkdir("out")
train_diabetes(data, 0.01, 0.01)
train_diabetes(data, 0.01, 0.75)
train_diabetes(data, 0.01, .5)
train_diabetes(data, 0.01, 1)
| banuatav/mlflow_serve_model | train.py | train.py | py | 4,517 | python | en | code | 0 | github-code | 13 |
8841855178 | from django.conf import settings
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from product.models.product import Product
from product.models.review import ProductReview
from product.serializers.review import ProductReviewSerializer
languages = [lang["code"] for lang in settings.PARLER_LANGUAGES[settings.SITE_ID]]
default_language = settings.PARLER_DEFAULT_LANGUAGE_CODE
User = get_user_model()
class ProductReviewViewSetTestCase(APITestCase):
user: User = None
product: Product = None
product_review: ProductReview = None
def setUp(self):
self.user = User.objects.create_user(
email="test@test.com", password="test12345@!"
)
# Login to authenticate
self.client.login(email="test@test.com", password="test12345@!")
self.client.force_authenticate(user=self.user)
self.product = Product.objects.create(
slug="sample-product",
name="Sample Product",
description="Sample Product Description",
price=100.0,
active=True,
stock=10,
)
self.product_review = ProductReview.objects.create(
product=self.product,
user=self.user,
rate=5,
status="New",
)
for language in languages:
self.product_review.set_current_language(language)
self.product_review.comment = f"Sample Comment {language}"
self.product_review.save()
self.product_review.set_current_language(default_language)
@staticmethod
def get_product_review_detail_url(pk):
return reverse("product-review-detail", args=[pk])
@staticmethod
def get_product_review_list_url():
return reverse("product-review-list")
def test_list(self):
url = self.get_product_review_list_url()
response = self.client.get(url)
reviews = ProductReview.objects.all()
serializer = ProductReviewSerializer(reviews, many=True)
self.assertEqual(response.data["results"], serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_create_valid(self):
product_2 = Product.objects.create(
slug="sample-product-2",
name="Sample Product 2",
description="Sample Product Description 2",
price=100.0,
active=True,
stock=10,
)
payload = {
"product": product_2.pk,
"user": self.user.pk,
"rate": 5,
"status": "NEW",
"translations": {},
}
for language in languages:
language_code = language[0]
language_name = language[1]
translation_payload = {
"comment": f"New Review comment in {language_name}",
}
payload["translations"][language_code] = translation_payload
url = self.get_product_review_list_url()
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_create_invalid(self):
payload = {
"product": "invalid_product",
"user": "invalid_user",
"rate": "invalid_rate",
"status": "invalid_status",
"translations": {
"invalid_language": {
"comment": "invalid_comment",
}
},
}
url = self.get_product_review_list_url()
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_retrieve_valid(self):
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.get(url)
review = ProductReview.objects.get(pk=self.product_review.pk)
serializer = ProductReviewSerializer(review)
self.assertEqual(response.data, serializer.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_retrieve_invalid(self):
invalid_product_review_pk = 999999
url = self.get_product_review_detail_url(invalid_product_review_pk)
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_update_valid(self):
payload = {
"product": self.product.pk,
"user": self.user.pk,
"rate": 1,
"status": "NEW",
"translations": {},
}
for language in languages:
language_code = language[0]
language_name = language[1]
translation_payload = {
"comment": f"Updated Review comment in {language_name}",
}
payload["translations"][language_code] = translation_payload
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.put(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_update_invalid(self):
payload = {
"product": "invalid_product",
"user": "invalid_user",
"rate": "invalid_rate",
"status": "invalid_status",
"translations": {
"invalid_language": {
"comment": "invalid_comment",
}
},
}
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.put(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_partial_update_valid(self):
payload = {
"rate": 1,
"translations": {
default_language: {
"comment": "Updated Review comment",
}
},
}
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.patch(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_partial_update_invalid(self):
payload = {
"rate": "invalid_rate",
"translations": {
"invalid_language": {
"comment": "invalid_comment",
}
},
}
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.patch(url, data=payload, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_destroy_valid(self):
url = self.get_product_review_detail_url(self.product_review.pk)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertFalse(
ProductReview.objects.filter(pk=self.product_review.pk).exists()
)
def test_destroy_invalid(self):
invalid_product_review_pk = 999999
url = self.get_product_review_detail_url(invalid_product_review_pk)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def tearDown(self) -> None:
super().tearDown()
self.user.delete()
self.product.delete()
self.product_review.delete()
| vasilistotskas/grooveshop-django-api | tests/integration/product/review/test_view_product_review.py | test_view_product_review.py | py | 7,509 | python | en | code | 4 | github-code | 13 |
24956822149 | import cv2
import numpy as np
class ImageTransform(object):
def rotateImage(self,img_main,contour):
# Rotate Image-------------------------------------------------------------------------
approximation = cv2.approxPolyDP(contour, 0.02 * cv2.arcLength(contour, True), True)
h1 = np.sqrt(np.power((approximation[0][0][0] - approximation[3][0][0]), 2) + np.power(
(approximation[0][0][1] - approximation[3][0][1]), 2))
h2 = np.sqrt(np.power((approximation[1][0][0] - approximation[2][0][0]), 2) + np.power(
(approximation[1][0][1] - approximation[2][0][1]), 2))
h = (h1 + h2) / 2
w1 = np.sqrt(np.power((approximation[0][0][0] - approximation[1][0][0]), 2) + np.power(
(approximation[0][0][1] - approximation[1][0][1]), 2))
w2 = np.sqrt(np.power((approximation[2][0][0] - approximation[3][0][0]), 2) + np.power(
(approximation[2][0][1] - approximation[3][0][1]), 2))
w = (w1 + w2) / 2
arr = approximation
arr = [[arr[1][0][0], arr[1][0][1]], [arr[0][0][0], arr[0][0][1]], [arr[3][0][0], arr[3][0][1]],
[arr[2][0][0], arr[2][0][1]]]
pts1 = np.float32(arr[:3])
pts2 = np.float32([[0, 0], [w, 0], [w, h]])
M = cv2.getAffineTransform(pts1, pts2)
dest = cv2.warpAffine(img_main, M, (int(w), int(h)))
return dest
# /Rotate image--------------------------------------------------------------
def get_verticle_line_angles(self,edges):
lines = cv2.HoughLines(edges, 1, np.pi / 180, 300)
good_lines = []
for line in lines:
for rho, theta in line:
if np.abs(theta) > 0 and np.abs(theta) < 0.05:
a = np.cos(theta)
b = np.sin(theta)
good_lines.append(theta)
# print(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 10000 * (-b))
y1 = int(y0 + 10000 * (a))
x2 = int(x0 - 10000 * (-b))
y2 = int(y0 - 10000 * (a))
return good_lines
def sort_corners(self,approximation):
minx = approximation[0][0][0]
miny = approximation[0][0][1]
maxx = approximation[0][0][0]
maxy = approximation[0][0][1]
for a in approximation:
if minx > a[0][0]:
minx = a[0][0]
if maxx < a[0][0]:
maxx = a[0][0]
if miny > a[0][1]:
miny = a[0][1]
if maxy < a[0][1]:
maxy = a[0][1]
return [[[minx, miny]], [[maxx, miny]], [[maxx, maxy]], [[minx, maxy]]]
| chamil-prabodha/Opencv_Voting_System | ImageTransform.py | ImageTransform.py | py | 2,737 | python | en | code | 0 | github-code | 13 |
21236156712 | """
This script demonstrates how to read holding current from ABF files.
You may need to install pyABF using the command "pip install pyabf"
"""
import pyabf
import numpy as np
# the R before the string tells Python to ignore backslashes
abfFilePath = R"C:\Users\scott\Documents\GitHub\pyABF\data\abfs\2019_05_02_DIC2_0011.abf"
abf = pyabf.ABF(abfFilePath)
# Let's calculate the mean current for a portion of every sweep (2-5 seconds)
for i in range(abf.sweepCount):
abf.setSweep(i)
pointsPerSecond = abf.dataRate
index1 = pointsPerSecond * 2
index2 = pointsPerSecond * 5
segment = abf.sweepY[index1:index2]
segmentMean = np.mean(segment)
print(f"sweep {i} mean current = {segmentMean} pA")
| shengwanhui/Lab-Analysis-2019-2021- | dev/abf-files/holding-current.py | holding-current.py | py | 723 | python | en | code | 2 | github-code | 13 |
12002287866 | import MeCab
import collections
R=[]
q1 = defaultdict(int)
mecab = MeCab.Tagger()
co=0
from collections import defaultdict
d = defaultdict(int)
n=""
with open('/Users/takeidaichi/Library/Mobile Documents/com~apple~CloudDocs/大学院 授业/自然言语処理/neko.txt', 'r') as fin:
for line in fin.readlines():
r = mecab.parse(line)
for s in r.split("。"):
for p in s.split("\n"):
for t in p.split("\t"):
q1[t]+=1
if co==0:
if len(t)>0 and (t!="EOS"):
d["BOS"+t]+=1
co+=1
else:
d[n+t]+=1
if len(t)>0 and (t!="EOS"):
n=t
co+=1
break
d[n+"EOS"]+=1
co=0
q1["BOS"]+=1
P1=d.values()
P2=d.keys()
S=zip(P1,P2)
S=sorted(S,reverse=True)
P1,P2=zip(*S)
k = defaultdict(int)
for i in range(len(P1)):
k[P2[i]]=P1[i]
W=Me()
print((k["BOS吾辈"]/q1["BOS"])*
(k["吾辈は"]/q1["吾辈"])*
(k["は猫"]/q1["は"])*
(k["猫で"]/q1["猫"])*
(k["では"]/q1["で"])*
(k["はない"]/q1["は"])*
(k["ないEOS"]/q1["ない"])
)
print((k["BOS名前"]/q1["BOS"])*
(k["名前は"]/q1["名前"])*
(k["はまだ"]/q1["は"])*
(k["まだない"]/q1["まだ"])*
(k["ないEOS"]/q1["ない"])
)
print((k["BOS吾辈"]/q1["BOS"])*
(k["吾辈は"]/q1["吾辈"])*
(k["は犬"]/q1["は"])*
(k["犬で"]/q1["犬"])*
(k["である"]/q1["で"])*
(k["あるEOS"]/q1["ある"])
)
| tk-q/- | NLP/Kadai4/-3.py | -3.py | py | 1,727 | python | zh | code | 0 | github-code | 13 |
16063940387 | # Noel Wafuko
# nww010 # 11308656
# For Instructor Jeff Long
def hasMajority ( ls ):
"""
Determines if the input list " ls " includes the majority element or not .
: param ls : an arbitrary list with comparable elements
: return : True if the input list has a majority element ; False otherwise .
’’’"""
# initialize the dictionary with keys are the elements in ls ,
# and values are the count the key in ls .
counts = {}
# update the dictionary of counts by loop in the list
for i in ls :
if i in counts :
counts [ i ] += 1
else :
counts [ i ] = 0
# generate the max count of all values in the list
max_count = max ( counts . values ())
# generate the result
result = max_count > len ( ls )//2
return result
isMajorityList ([1 ,2 ,3 ,1 ,1]) | collinskoech11/BlackBoxTestPy | a9q3.py | a9q3.py | py | 852 | python | en | code | 0 | github-code | 13 |
18757746735 | import numpy as np
import h5py
import os
def print_size(file_name):
try:
st = os.stat(file_name)
print(str(st.st_size) + ' bytes')
except OSError as e:
print(e)
# create dataset without compression
matrix1 = [['abcde'] * 1000] * 1000
matrix2 = [['abcde'] * 1000] * 1000
matrix3 = [['abcde'] * 1000] * 1000
matrix4 = [['abcde'] * 1000] * 1000
with h5py.File('./hdf5_groups_no_compression.h5', 'w') as hdf:
# create group1
g1 = hdf.create_group('Group1')
# create datasets inside g1
g1.create_dataset('dataset1', data=matrix1)
g1.create_dataset('dataset2', data=matrix2)
# create group2 with subgroups g3 & g4
g3 = hdf.create_group('Group2/SubGroup1')
g3.create_dataset('dataset3', data=matrix3)
g4 = hdf.create_group('Group2/SubGroup2')
g4.create_dataset('dataset4', data=matrix4)
# create dataset with compression
with h5py.File('./hdf5_groups_compressed.h5', 'w') as hdf:
# create group1
g1 = hdf.create_group('Group1')
# create datasets inside g1
g1.create_dataset('dataset1', data=matrix1, compression="gzip", compression_opts=9)
g1.create_dataset('dataset2', data=matrix2, compression="gzip", compression_opts=9)
# create group2 with subgroups g3 & g4
g3 = hdf.create_group('Group2/SubGroup1')
g3.create_dataset('dataset3', data=matrix3, compression="gzip", compression_opts=9)
g4 = hdf.create_group('Group2/SubGroup2')
g4.create_dataset('dataset4', data=matrix4, compression="gzip", compression_opts=9)
print_size('./hdf5_groups_no_compression.h5')
print_size('./hdf5_groups_compressed.h5')
| MohamedAboBakr/HDF5 | Data_compression.py | Data_compression.py | py | 1,567 | python | en | code | 0 | github-code | 13 |
46201298894 | import os
from typing import List, Union, Type
from yapim import Task, DependencyInput
class KofamscanExecAnnotation(Task):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.output = {
"kegg": self.wdir.joinpath(self.record_id + ".kegg.txt")
}
@staticmethod
def requires() -> List[Union[str, Type]]:
return []
@staticmethod
def depends() -> List[DependencyInput]:
return []
def run(self):
"""
Run kofamscan.exec_annotation
"""
self.parallel(
self.program[
"--cpu", self.threads,
"--format", "detail",
"-o", self.output["kegg"],
"--tmp-dir", os.path.join(self.wdir, "tmp"),
self.input["prot"],
"-p", self.config["profiles"],
"-k", self.config["kolist"]
]
) | cjneely10/EukMetaSanity | EukMetaSanity/src/dependencies/kofamscan/kofamscan.py | kofamscan.py | py | 939 | python | en | code | 17 | github-code | 13 |
24814370595 | # import the necessary packages
from threading import Thread
import cv2
class WebcamVideoStream:
def __init__(self, src=0,resolution=None,framerate=30):
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
self.src = src
self.resolution = list(resolution)
self.framerate = framerate
def start(self):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = cv2.VideoCapture(self.src)
self.stream.set(cv2.CAP_PROP_FPS, self.framerate)
if(self.resolution != None):
self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, int(self.resolution[0]))
self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, int(self.resolution[1]))
self.resolution[0] = self.stream.get(cv2.CAP_PROP_FRAME_WIDTH)
self.resolution[1] = self.stream.get(cv2.CAP_PROP_FRAME_HEIGHT)
(self.grabbed, self.frame) = self.stream.read()
# start the thread to read frames from the video stream
self.__thread = Thread(target=self.update, args=())
self.__thread.daemon = True
self.__thread.start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
break
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
self.stream.release()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
self.__thread.join()
| MinervaBots/Trekking | firmware/pi/videoStream/WebcamVideoStream.py | WebcamVideoStream.py | py | 1,874 | python | en | code | 1 | github-code | 13 |
41432703513 | import requests
# import json
class BankRate:
def __init__(self, balance=5000, term=12, rate=1.50, compounded=12):
self.term = term
self.rate = rate
self.monthly_rate = None
self.balance = balance
self.compounded = compounded
self.month_return = (self.balance * ((self.rate / 100) / 12))
# dec = self.rate / 100
# month_rate = dec / 12
# self.monthly_rate = month_rate
# self.month_return = self.monthly_rate * self.balance
def __str__(self):
return F"With a starting balance of ${self.balance:.2f}\tand an APY of {self.rate:.2f}% \n" \
F"you will end the month with a gain of ${self.month_return:.2f}."
class Treasury:
"""amount ia a multiple of 100 for if you have 10 of 100 you have 1000 (the min on td-ameritrade)"""
def __init__(self, data_json, amount=10):
self.term = data_json['term']
self.term_day = data_json['securityTermDayMonth']
self.amount = amount
self.total = 0
self.price_per100 = float(data_json['highPrice'])
self.returnamount = (100 * amount) - (self.price_per100 * amount)
self.line_one = "term -> " + self.term
self.line_two = F"Annualized return -> {self.total:.2f}%"
self.line_three = F"return amount -> ${self.returnamount:.2f}"
def totals(self):
yieldper = ((100 - self.price_per100) / self.price_per100) * 100
term = int(self.term_day.split("-")[0])
anreturn = yieldper * (365 / term)
self.total = anreturn
def __str__(self):
return "\tterm -> " + self.term + f"\nAnnualized return -> {self.total:.2f}%\n return amount -> ${self.returnamount:.2f}"
def t_bill(amount: int):
listof = []
# base = "http://www.treasurydirect.gov/TA_WS"
# formats = "format=json"
# page = "pagesize=15"
days = "5"
# types = "types=Bill"
#
# # data = requests.get("{}+/securities/auctioned?{}&{}".format(base, formats, page))
# # data.json()
data = requests.get(F"http://www.treasurydirect.gov/TA_WS/securities/auctioned?format=json&type=Bill&days={days}")
# print(data.json())
file = open("data.json", "w")
file.write(str(data.json()))
data = data.json()
for i in range(len(data)):
cusip = data[i]['cusip']
# if data[i]['securityTerm'] == "4-Week":
data2 = requests.get(
"http://www.treasurydirect.gov/TA_WS/securities/search?cusip=" + cusip + "&format=json")
data2 = data2.json()
for indx in range(len(data2)):
# data2[i]['securityTerm'] = data2[i]['lowDiscountRate']
# a = t_rate(data2[i], data2[i]['securityTerm'], data2[i]['lowDiscountRate'])
listof.append(Treasury(data2[indx], amount=amount))
for inx in listof:
inx.totals()
return listof
def t_bill_print(list_of_data, printlist_one="|", print_l_2="|", p_l_3="|"):
if len(list_of_data) == 0:
return "####there may be en error in the Treasury Direct API used to acquire this data####"
p1 = printlist_one
p2 = print_l_2
p3 = p_l_3
for i in range(len(list_of_data)):
if list_of_data[i].term != "":
p1 += F"{list_of_data[i].line_one:^25}\t|\t"
p2 += F"{list_of_data[i].line_two:^25}\t|\t"
p3 += F"{list_of_data[i].line_three:^25}\t|\t"
p1 += F"\n{p2}\n{p3}"
return p1
#
# def recommend(bank_obj:object, t_bill_obj_list:list):
# dictionary = {}
# for each in range(len(t_bill_obj_list)):
# dictionary[F'{t_bill_obj_list[each].term}'] = F'{t_bill_obj_list[each].returnamount}'
#
#
#
# new_val = dictionary.values()
# maximum_val = max(new_val)
# print("Maximum value from dict:",maximum_val)
def disclaimer():
"""Disclaimer was taken from https://www.stockopedia.com/learn/account-billing/disclaimer-463143/"""
return """\t\tDisclaimer
This script is meant only for informational purposes
Before using this please make sure that you note the following important information:\n\t\tDo Your Own Research
Our content is intended to be used and must be used for information and education purposes only. It is very important
to do your own analysis before making any investment based on your own personal circumstances. You should take
independent financial advice from a professional in connection with, or independently research and verify,
any information that you find on and wish to rely upon, whether for the purpose of making an investment decision or otherwise."""
def main():
print(disclaimer())
amount_int = 0
amount_valid = True
while amount_valid:
amount = input("\nHow much money are you looking to invest? (Must be a multiple of 1000)\t>>\t")
amount_int = int(amount)
if amount_int % 1000 == 0:
amount_valid = False
apy = float(input("What is the APY for your bank account, CD or similar account?\t>>\t"))
t_bill_data = t_bill(amount=amount_int / 100)
print(F"\nBased on Historical Data from the past 5 days Treasury auctions.")
print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-" * len(t_bill_data))
print(t_bill_print(t_bill_data))
print("_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-" * len(t_bill_data))
bank = BankRate(amount_int, rate=apy)
print(F"{bank}")
main()
| ausward/Treasury-vs-Bank-Account | advise.py | advise.py | py | 5,501 | python | en | code | 9 | github-code | 13 |
3103119660 | # 4. Sorted insert in a Link list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insert(self, head, value):
dummy = ListNode(-1)
dummy.next = head
cur = dummy
while cur.next and cur.next.val <= value:
cur = cur.next
temp = cur.next
newNode = ListNode(value)
cur.next = newNode
newNode.next = temp
return dummy.next
head = ListNode(1, ListNode(2, ListNode(4, ListNode(5))))
value = 1
solution = Solution()
solution.insert(head, value)
print(head.val)
print(head.next.val)
print(head.next.next.val)
print(head.next.next.next.val)
print(head.next.next.next.next.val)
| jsong0727/Fall2022_DataStructuresAlgo | Midterm/p4.py | p4.py | py | 742 | python | en | code | 0 | github-code | 13 |
31195615301 | import refnx.util.general as general
import refnx
import numpy as np
from pathlib import Path
from numpy.testing import assert_almost_equal, assert_, assert_allclose
def test_version():
# check that we can retrieve a version string
refnx.__version__
class TestGeneral:
def setup_method(self):
self.pth = Path(__file__).absolute().parent
def test_q(self):
q = general.q(1.0, 2.0)
assert_almost_equal(q, 0.1096567037)
def test_q2(self):
qx, qy, qz = general.q2(1.0, 2.0, 0.0, 2.0)
assert_almost_equal(qz, 0.1096567037)
def test_wavelength_velocity(self):
speed = general.wavelength_velocity(20.0)
assert_almost_equal(speed, 197.8017006541796, 5)
def test_wavelength(self):
wavelength = general.wavelength(0.1096567037, 1.0)
assert_almost_equal(wavelength, 2.0)
def test_angle(self):
angle = general.angle(0.1096567037, 2.0)
assert_almost_equal(angle, 1.0)
def test_dict_compare(self):
c = {"f": np.arange(10)}
d = {"f": np.arange(10)}
assert_(general._dict_compare(c, d))
d = {"f": np.arange(11)}
assert_(not general._dict_compare(c, d))
d = {"f": 2}
assert_(not general._dict_compare(c, d))
assert_(general._dict_compare({"a": 1}, {"a": 1}))
def test_neutron_transmission(self):
try:
import periodictable as pt
except ImportError:
return
mat = pt.formula("N2", density=1.25e-3)
ntd = general._neutron_transmission_depth(mat, 2)
assert_allclose(ntd, 1365.8010284973458 * 10)
t = general.neutron_transmission(
"N2", 1.25e-3, 2, 1365.8010284973458 * 10
)
assert_almost_equal(t, np.exp(-1.0))
# check that we can vectorise
t = general.neutron_transmission(
"N2", 1.25e-3, [2, 2.0], [1365.8010284973458 * 10] * 2
)
assert_almost_equal(t, [np.exp(-1.0)] * 2)
| refnx/refnx | refnx/util/test/test_general.py | test_general.py | py | 2,006 | python | en | code | 31 | github-code | 13 |
33630595332 | import os,json,yaml
from datetime import datetime
def _create_json():
now = datetime.now()
json_file= {
"dt":str(now.year)+"-"+str(now.month)+"-"+str(now.day)
}
json_object = json.dumps(json_file, indent=4)
filename = f"/opt/airflow/include/db/{str(now.year)}/{str(now.month)}/{str(now.day)}/{str(now.minute)}"
if not os.path.exists(filename):
os.makedirs(filename)
with open(f"{filename}/sample.json", "w") as outfile:
outfile.write(json_object)
print(outfile)
if __name__ == "__main__":
_create_json() | yusufgzb/AirFlow-example | scripts/proje3.1_create_json.py | proje3.1_create_json.py | py | 575 | python | en | code | 0 | github-code | 13 |
38407954636 | from rest_framework.decorators import api_view
from rest_framework.response import Response
from book.models import Book
from book.serializers import BookSerializer
from rest_framework import status
@api_view(['GET'])
def api_overview(request):
api_roots = {
'List view': 'api/v1/get_books/',
'Detail view': 'api/v1/get_book/<int:pk>/',
'Update view': 'api/v1/update_book/<int:pk>/',
'Create view': 'api/v1/create_book/',
'Delete view': 'api/v1/delete_book/<int:pk>/',
}
return Response(api_roots)
@api_view(['GET'])
def get_books(request):
queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
return Response(serializer.data)
@api_view(['GET'])
def get_book(request, pk):
queryset = Book.objects.get(id=pk)
serializer = BookSerializer(queryset)
return Response(serializer.data)
@api_view(['GET', 'POST'])
def create_book(request):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['PUT', 'PATCH'])
def update_book(request, pk):
queryset = Book.objects.get(id=pk)
serializer = BookSerializer(instance=queryset, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def delete_book(request, pk):
queryset = Book.objects.get(id=pk)
queryset.delete()
return Response(status=status.HTTP_200_OK)
| daniltop3309/drf_books | book/views.py | views.py | py | 1,517 | python | en | code | 0 | github-code | 13 |
15952025521 | import torch
import numpy as np
def partition_data_based_on_labels(dataset, n_clients=3, random_seed=1, alpha=0.1):
y_s = torch.tensor([dataset.__getitem__(i)[1] for i in range(len(dataset))])
labels = torch.unique(y_s)
n_classes = len(labels)
np.random.seed(random_seed)
dist = np.random.dirichlet(np.ones(n_clients) * alpha, n_classes)
labels_ind = {
j: [] for j in range(n_classes)
}
labels_map = {
label.item(): j for j, label in enumerate(labels)
}
for i, y in enumerate(y_s):
labels_ind[labels_map[y.item()]].append(i)
labels_len = np.array([len(labels_ind[j]) for j in range(n_classes)])
dist = np.cumsum(dist, axis=1) * labels_len.reshape(n_classes, 1)
dist = dist.astype(int)
dist = np.concatenate([np.zeros((n_classes, 1), int), dist], axis=1)
clients_ind = {
i: [] for i in range(n_clients)
}
for i in range(n_clients):
for j in range(n_classes):
clients_ind[i].extend(labels_ind[j][dist[j, i]:dist[j, i + 1]])
return clients_ind
| SamuelHorvath/Simple_FL_Simulator | fl_sim/data_funcs/utils.py | utils.py | py | 1,076 | python | en | code | 7 | github-code | 13 |
2194362347 | from django.db import models
from model_utils.models import TimeStampedModel
from products.models import ProductColor,Product
from .order import Order
class OrderItemManager(models.Manager):
def create(self, **obj_data):
instance = super().create(**obj_data)
instance.item_cost = instance.product.price
instance.total_cost = instance.item_cost * instance.quantity
p = Product.objects.filter(pk=instance.product.id)
if p[0].stock < instance.quantity:
raise Exception("Stock shortage for product " + str(p[0]))
p.update(stock=instance.product.stock - instance.quantity)
instance.save()
return instance
class OrderItem(TimeStampedModel):
order = models.ForeignKey(Order,related_name='order_items',on_delete=models.CASCADE,blank=False)
product = models.ForeignKey(Product,on_delete=models.BLANK_CHOICE_DASH,blank=False)
color = models.ForeignKey(ProductColor,on_delete=models.BLANK_CHOICE_DASH,blank=False)
quantity = models.IntegerField(default=1)
item_cost = models.IntegerField(default=0)
total_cost = models.IntegerField(default=0)
objects = OrderItemManager()
def __str__(self):
return "OrderID: {}, ItemID {}".format(self.order.id,self.id) | aahmadsaleem95/tarzkarX | backend/orders/models/order_item.py | order_item.py | py | 1,264 | python | en | code | 0 | github-code | 13 |
26454732503 | def bubble_sort(arr): # 3 2 1
count = 0
for i in range(len(arr)): # 0 1 2 -> 0
for j in range(len(arr)-1): # 0 1 -> 0
if arr[j] > arr[j+1]: # 3 > 2 -> 3 > 1
count = count + 1
arr[j+1], arr[j] = arr[j], arr[j+1] # 2 3 1 -> 2 1 3
return arr, count
if __name__ == '__main__':
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
sorted_arr, count = bubble_sort(a)
print(f"Array is sorted in {count} swaps.\nFirst Element: {sorted_arr[0]}\nLast Element: {sorted_arr[len(sorted_arr)-1]}") | Eyakub/Problem-solving | HackerRank/30DaysOfCode/Python/day_20_sorting.py | day_20_sorting.py | py | 671 | python | en | code | 3 | github-code | 13 |
34419908590 | while True:
ch=int(input("Enter your choice: (Press 1 to continue and 0 to close):-"))
if ch==1:
email=input("Enter your E-Mail Address: ")
k,j,d = 0,0,0
# print(email)
if len(email)>=6: #checking condintion length should be more than 6 char
if email[0].isalpha(): #checking Email should be alphabate
if ("@" in email) and (email.count("@")==1): #checking @ should be in th email
if (email[-4]=='.') ^ (email[-3]=='.'): #using -ve index number to check last 3 element should be "."
for i in email: #breaking the char and check via if condition
if i==i.isspace(): #checking char should be space or not
k=1
elif i==i.isupper(): #check char is alphabate or not text converting to be upper case
j = 1
elif i==i.isdigit(): #checking condition is digit or not
continue #if condition is true then loop return to inital state by using continue
elif i=="_" or i=="." or i=="@":
continue
else:
d=1
if k==1 or j==1 or d==1:
print("'Wrong Email'--> Email should not be space between text")
else:
pirnt("Correct Email")
else:
print("'Wrong Email' Last 3rd index should be .")
else:
print("'Wrong Email' there have one @ Should be in email")
else:
print("'Wrong Email' 1st Char should be Alphabate")
else:
print("Wrong Email--> Email should me min 6 char")
elif ch==0:
break
else:
print("Invalid Operation. Try Again......") | GauravGurv/Python_Program | Email_Validation.py | Email_Validation.py | py | 2,169 | python | en | code | 0 | github-code | 13 |
30063959206 | input_list = []
while True:
try:
num = int(input("Enter an integer (or any non-integer to finish): "))
input_list.append(num)
except ValueError:
break
print("Integers in reverse order:")
for num in reversed(input_list):
print(num)
print("Without reversed function ")
#without reversed
len = len(input_list)
for i in range (len-1,-1,-1):
print(input_list[i])
| amrutahabbu/python_programs | reverse_integers.py | reverse_integers.py | py | 419 | python | en | code | 0 | github-code | 13 |
6977645020 | from bogof_rule import BogofRule
from bulk_discount import BulkDiscount
from storage import Storage
class Checkout:
def __init__(self, pricing_rules=[]):
self.pricing_rules = pricing_rules
self.basket = []
self.products = Storage().products
def scan(self, product_code):
for product in self.products:
if product.code == product_code:
self.basket.append(product)
def total(self):
total = sum(item.price for item in self.basket)
total -= sum(rule(self.basket).discount() for rule in self.pricing_rules)
return total
| Davidslv/checkout.py | checkout.py | checkout.py | py | 614 | python | en | code | 0 | github-code | 13 |
4786470467 | # coding=utf-8
from main import log
import model
from config import key_state as default_key
def judge_phase(content,Express_Company):
guess = []
if default_key.get(Express_Company):
key_state = default_key.get(Express_Company)
# print(key_state,Express_Company)
else:
key_state = {
'打包': '途中',
'发出': '途中',
'收入': '途中',
'发往': '途中',
'到达': '途中',
'到件扫描': '揽件',
'称重扫描': '途中',
'进行分拨': '途中',
'【反馈】扫描': '途中',
'离开': '途中',
'卸车扫描': '途中',
'【称重】扫描': '途中',
'【到件】扫描': '途中',
'【卸车】扫描': '途中',
'【分发】扫描': '途中',
'快件扫描': '途中',
'已拆包': '途中',
'签收': '签收',
'代收': '签收',
'为您服务': '签收',
'派件': '派件',
'【派送】扫描': '派件',
'收件': '揽收',
'揽收': '揽收',
'揽件': '揽收',
'揽件扫描': '揽收',
'问题件': '异常',
'开始配送': '派件',
'等待配送': '途中',
'正在投递':'派件',
'已收寄':'揽收',
'接收':'途中',
}
for k, v in key_state.items():
if k in content:
guess.append(v)
result = set(guess)
situation = len(result)
if situation == 1:
# log.debug('成功=>' + content + '=>' + guess[0])
return (1, guess[0])
if situation > 1:
if '问题件' in guess:
log.debug('歧义=>' + content + '=>' + '问题件')
return (1, '异常')
if '已揽件' in content or '已揽收' in content:
log.debug('歧义=>' + content + '=>' + '揽收')
return (1, '揽收')
if '已签收' in content or '签收人' in content:
log.debug('歧义=>' + content + '=>' + '签收')
return (1, '签收')
if '代收' in content and '取件' in content:
log.debug('歧义=>' + content + '=>' + '签收')
return (1, '签收')
if '途中' in guess and '收件' in guess:
log.debug('歧义=>' + content + '=>' + '途中')
return (1, '途中')
if '途中' in guess and '签收' in guess:
log.debug('歧义=>' + content + '=>' + '签收')
return (1, '签收')
if '已被' in guess and '代签收' in content:
log.debug('歧义=>' + content + '=>' + '签收')
return (1, '签收')
if '派件' in content and '代收' in content:
log.debug('歧义=>' + content + '=>' + '签收')
return (1, '签收')
if '进行扫描' in content:
log.debug('歧义=>' + content + '=>' + '途中')
return (1, '途中')
if '派件' in content:
log.debug('歧义=>' + content + '=>' + '派件')
return (1, '派件')
log.debug('歧义=>分析失败=>' + content + '=>' + ','.join(result))
# 关键字优先级
key_sort = ['签收','揽收','派件','异常','途中']
for i in key_sort:
if i in guess:
return (1, i)
return (1, guess[0])
if situation == 0:
if '快件异常' in content:
log.debug('歧义=>' + content + '=>' + '异常')
return (1, '异常')
log.debug('失败=>' + content)
return (0, content)
def manual_check_judge_phase(type):
"""
手动更新状态
:param type:全部更新或只更新未知部分
:return:
"""
pass
# db = model.Express_by_MS()
| SmallPotY/request_express | helper.py | helper.py | py | 3,930 | python | en | code | 0 | github-code | 13 |
31625878304 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 9 11:34:19 2017
@author: ajaver
"""
import glob
import os
import pymysql
import pandas as pd
from calculate_features import exec_parallel
from check_real_data import read_feat_summary
training_dir = '/Volumes/behavgenom$/Kezhi/Classifier_DL/training'
fnames = glob.glob(os.path.join(training_dir, '**', '*.hdf5'), recursive=True)
base_names = [os.path.basename(x).replace('_eig.hdf5', '') for x in fnames]
sql = '''
SELECT results_dir, base_name
FROM experiments
WHERE base_name IN ({})
'''.format(','.join(["'"+x+"'" for x in base_names]))
conn = pymysql.connect(host='localhost', database='single_worm_db')
cur = conn.cursor()
cur.execute(sql)
results = cur.fetchall()
conn.close()
train_files = [os.path.join(x[0], x[1] + '_features.hdf5') for x in results]
train_files = [x for x in train_files if os.path.exists(x)]
train_feats = exec_parallel(train_files, read_feat_summary)
train_feats = pd.concat(train_feats)
train_feats.to_csv('train_features.csv')
| ver228/work-in-progress | work_in_progress/kezhi_paper/training_basenames.py | training_basenames.py | py | 1,043 | python | en | code | 0 | github-code | 13 |
12695998410 | from db import *
from math import ceil
from random import choice
import functions
bjplayers = {}
cards = ('A', 'K', 'Q', 'J', 10, 9, 8, 7, 6, 5, 4, 3, 2)
class blackjack():
def __init__(self, author, bet=0):
self.id = author.id
self.name = str(author.name)
self.mention = author.mention
self.player = author
self.bet = int(bet)
self.hand = []
self.sum = 0
self.dealer_hand = []
self.dealer_sum = 0
self.status = 'playing'
updatemoney(self.id, (self.bet * -1))
[self.getcard() for i in range(2)]
[self.dealer_getcard() for i in range(2)]
self.epicwin()
def what_is_value_of_card(self, card):
if card in ('A', 'Q', 'K', 'J'):
if card == 'A':
if (self.sum + 11) > 21:
return 1
else:
return 11
else:
return 10
else:
return card
def checkMySum(self):
self.sum = 0
for i in self.hand:
if i == 'A':
pass
elif i in ('Q', 'K', 'J'):
self.sum += 10
else:
self.sum += i
for i in self.hand:
if i == 'A':
if self.sum + 11 > 21:
self.sum += 1
else:
self.sum += 11
def checkDealerSum(self):
self.dealer_sum = 0
for i in self.dealer_hand:
if i == 'A':
pass
elif i in ('Q', 'K', 'J'):
self.dealer_sum += 10
else:
self.dealer_sum += i
for i in self.dealer_hand:
if i == 'A':
if self.dealer_sum + 11 > 21:
self.dealer_sum += 1
else:
self.dealer_sum += 11
# getting cards
def getcard(self):
card = choice(cards)
self.hand.append(card)
self.checkMySum()
def dealer_getcard(self):
card = choice(cards)
self.dealer_hand.append(card)
functions.log(f'Blackjack {self.player} Dealer {card}', type='debug') # ---
self.checkDealerSum()
# main return
def maininfo(self):
self.whowin()
if self.status == 'tie':
updatemoney(self.id, self.bet)
return f'```{self.name}, Твои карты: {self.hand}, сумма: {self.sum}, \n\
Карты диллера: [{str(self.dealer_hand)}]`, сумма {self.dealer_sum}.```\
{self.mention}, Это ничья!'
elif self.status == 'win':
updatemoney(self.id, int(self.bet * 2))
return f'```{self.name}, Твои карты: {self.hand}, сумма: {self.sum}, \n\
Карты диллера: [{str(self.dealer_hand)}]`, сумма {self.dealer_sum}.```\
{self.mention} выиграл {self.bet} nedocoins!'
elif self.status == 'lose':
return f'```{self.name}, Твои карты: {self.hand}, сумма: {self.sum}, \n\
Карты диллера: [{str(self.dealer_hand)}]`, сумма {self.dealer_sum},```\
{self.mention}, Ты проиграл!`'
elif self.status == 'epic-win':
updatemoney(self.id, ceil(self.bet * 2.5))
return f'```{self.name}, Твои карты: {self.hand}, сумма: {self.sum}, \n\
Карты диллера: [{str(self.dealer_hand)}]`, сумма {self.dealer_sum}.```\
{self.mention} выиграл {ceil(self.bet*1.5)} nedocoins!'
else:
return f'```{self.name}, Твои карты: {self.hand}, сумма: {self.sum}\n\
Карты диллера: [{str(self.dealer_hand[0])}, ?], сумма: {self.what_is_value_of_card(self.dealer_hand[0])},```\
{self.mention}, Взять ещё карту или достаточно?'
# win types
def whowin(self):
if self.status == 'playing':
if self.dealer_sum > 21:
self.status = 'win'
elif self.sum > 21:
self.status = 'lose'
elif len(self.hand) >= 5:
self.status = 'win'
elif len(self.dealer_hand) >= 5:
self.status = 'lose'
def epicwin(self):
if self.sum == self.dealer_sum == 21:
self.status = 'tie'
elif self.sum == 21:
self.status = 'epic-win'
# to-do defs
def hit(self):
self.getcard()
def stay(self):
self.whowin()
if self.status != 'playing':
return
elif self.sum == self.dealer_sum > 17:
self.status = 'tie'
elif self.sum < self.dealer_sum:
self.status = 'lose'
else:
self.dealer_getcard()
self.stay()
| SpaceProjects/nedobotapp | blackjack.py | blackjack.py | py | 4,778 | python | en | code | 0 | github-code | 13 |
18322806016 | import pydub
import pytube
output_path = "C:/Users/epics/Music"
segments = []
playlist = pytube.Playlist("https://youtube.com/playlist?list=PL3PHwew8KnCl2ImlXd9TQ6UnYveqK_5MC")
for i in range(0,16):
segments.append(pydub.AudioSegment.from_file(f"{output_path}/.ytmp3_cache/{i}.mp3",format="mp4"))
sum(segments).export(f"{output_path}/{sanitize_filename(playlist.title)}.mp3", format="mp3")
| epicshepich/Grimoire-Lazulum | temp.py | temp.py | py | 397 | python | en | code | 1 | github-code | 13 |
27253342479 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.tsa import stattools
from arch import arch_model
SHret = pd.read_table('TRD_IndexSum.txt', index_col='Trddt', sep='\t')
SHret.index = pd.to_datetime(SHret.index)
SHret = SHret.sort_index()
plt.subplot(211)
plt.plot(SHret**2)
plt.xticks([])
plt.title('Squared Daily Return of SH Index')
plt.subplot(212)
plt.plot(np.abs(SHret))
plt.title('Absolute Daily Return of SH Index')
LjungBox = stattools.q_stat(stattools.acf(SHret**2)[1:13], len(SHret))
print(LjungBox[1][-1])
am = arch_model(SHret)
model = am.fit(update_freq=0)
print(model.summary()) | FunkyungJz/Some-thing-interesting-for-me | 量化投资书/量化投资以Python为工具/ch25/01.py | 01.py | py | 634 | python | en | code | null | github-code | 13 |
11154402642 | from django.shortcuts import render
from Web.models import *
from util.Pagination import *
from django.http import *
from datetime import datetime
# Create your views here.
def validate(request):
try:
request.session["adminid"]
except KeyError:
try:
userid = request.session["userid"]
except KeyError:
return False
else:
user = User.objects.get(id=userid)
if user.type == 0:
return False
elif user.type == 1:
return True
else:
return True
def index(request):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
return render(request, "Admin/index.html")
def login(request):
if validate(request):
return render(request, "Admin/index.html")
error_message = ""
success_message = ""
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
autologin = request.POST.get('autologin')
user_type = request.POST.get('type')
try:
if user_type == "admin":
admin_origin = Administrator.objects.get(username=username)
elif user_type == "user":
admin_origin = User.objects.get(username=username)
except:
error_message = '用户名不存在'
else:
if password == admin_origin.password:#验证成功
if user_type == "admin":
request.session['adminid'] = admin_origin.id
elif user_type == "user":
request.session['userid'] = admin_origin.id
if not autologin:
request.session.set_expiry(0)
return HttpResponseRedirect("/admin/index")
else:
error_message = '密码错误'
context = {"success_message": success_message, "error_message": error_message}
return render(request, "Admin/login.html", context)
def logout(request):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
success_message = ""
try:
del request.session["adminid"]
except Exception as e:
del request.session["userid"]
else:
success_message = "退出成功"
context = {"success_message": success_message}
return render(request, "Admin/login.html", context)
def visit(request, current_page=1, success_message="", error_message=""):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
all_visitor = Visitor.objects.order_by("-visitTime")
show_visitor, page_list, current_page, previous_page, next_page, last_page = paginate(all_visitor, current_page, 5)
context = {'success_message': success_message, "error_message": error_message,
'show_visitor': show_visitor, 'page_list': page_list,
'current_page': current_page, 'next_page': next_page,
'previous_page': previous_page, 'last_page': last_page}
return render(request, "Admin/visit.html", context)
def delete_visitor(request, visitorid):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
try:
visitor = Visitor.objects.get(id=visitorid)
visitor.delete()
except Exception as e:
error_message = "删除失败:" + str(e)
else:
success_message = "删除成功"
return visit(request, 1, success_message=success_message,error_message=error_message)
def notice(request, current_page=1, success_message="", error_message=""):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
try:
current_page = int(current_page)
except TypeError:
current_page = 1
page_size = 3
if request.method == "POST":
title = request.POST.get("title")
content = request.POST.get("content")
adminid = request.session["adminid"]
admin = Administrator.objects.get(id=adminid)
try:
notice = Notice.objects.create(title=title, content=content,
createTime=datetime.now(), admin=admin)
notice.save()
except Exception as e:
error_message = "发表失败:"+str(e)
else:
success_message = "发表成功"
all_notice = Notice.objects.all().order_by("-createTime")
show_notice, page_list, current_page, previous_page, next_page, last_page = paginate(all_notice, current_page, page_size)
context = {'success_message': success_message, "error_message": error_message,
'show_notice': show_notice, 'page_list': page_list,
'current_page': current_page, 'next_page': next_page,
'previous_page': previous_page, 'last_page': last_page}
return render(request, "Admin/notice.html", context)
def delete_notice(request, noticeid):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
try:
notice_temp = Notice.objects.get(id=noticeid)
notice_temp.delete()
success_message = "删除成功"
except Exception as e:
error_message = "删除失败:"+str(e)
return notice(request, current_page=1, success_message=success_message, error_message=error_message)
def changepassowrd(request):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
if request.method == "POST":
try:
admin = Administrator.objects.get(id=request.session.get("adminid"))
password_old = request.POST.get("password_old")
password1 = request.POST.get("password1")
password2 = request.POST.get("password2")
if password1 != password2:
error_message = "两次输入的密码不一致"
elif password_old != admin.password:
error_message = "旧密码输入不正确"
else:
admin.password = password1
admin.save()
success_message = "修改成功"
except Exception as e:
error_message = "修改失败:"+str(e)
context = {"error_message": error_message, "success_message": success_message}
return render(request, "Admin/changePassword.html", context)
def message(request, current_page=1, success_message="", error_message=""):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
try:
current_page = int(current_page)
except TypeError:
current_page = 1
page_size = 5
all_message = Message.objects.all().order_by("-createTime")
show_message, page_list, current_page, previous_page, next_page, last_page = paginate(all_message, current_page, page_size)
context = {'success_message': success_message, "error_message": error_message,
'show_message': show_message, 'page_list': page_list,
'current_page': current_page, 'next_page': next_page,
'previous_page': previous_page, 'last_page': last_page}
return render(request, "Admin/message.html", context)
def delete_message(request, messageid):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
try:
message_temp = Message.objects.get(id=messageid)
message_temp.delete()
success_message = "删除成功"
except Exception as e:
error_message = "删除失败:"+str(e)
return message(request, 1, success_message, error_message)
def userSetting(request, current_page=1, success_message="", error_message=""):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
try:
current_page = int(current_page)
except TypeError:
current_page = 1
page_size = 5
all_user = User.objects.all().order_by("-registryTime")
show_user, page_list, current_page, previous_page, next_page, last_page = paginate(all_user, current_page, page_size)
context = {'success_message': success_message, "error_message": error_message,
'show_user': show_user, 'page_list': page_list,
'current_page': current_page, 'next_page': next_page,
'previous_page': previous_page, 'last_page': last_page}
return render(request, "Admin/userSetting.html", context)
def setAdmin(request, userid):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
try:
user = User.objects.get(id=userid)
user.type = 1
user.save()
except Exception as e:
error_message = "操作失败:"+str(e)
else:
success_message = "操作成功"
return userSetting(request, 1, success_message=success_message,error_message=error_message)
def resetAdmin(request, userid):
if not validate(request):
context = {"success_message": "", "error_message": "请先登录账号或该账号没有权限"}
return render(request, "Admin/login.html", context)
error_message = ""
success_message = ""
try:
user = User.objects.get(id=userid)
user.type = 0
user.save()
except Exception as e:
error_message = "操作失败:"+str(e)
else:
success_message = "操作成功"
return userSetting(request, 1, success_message=success_message,error_message=error_message)
| jinbaizhe/DjangoProject | Admin/views.py | views.py | py | 10,884 | python | en | code | 0 | github-code | 13 |
41507805619 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from collections import OrderedDict
from collections import namedtuple
import os
import socket
import threading
import time
def tcplink(sock, addr):
def memory_stat():
mem = {}
f = open("/proc/meminfo")
lines = f.readlines()
f.close()
for line in lines:
if len(line) < 2: continue
name = line.split(':')[0]
var = line.split(':')[1].split()[0]
mem[name] = long(var) * 1024.0
mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
memreturn = {'MemTotal':mem['MemTotal'], 'MemFree':mem['MemFree']}
return memreturn
def cpu_stat():
cpu = []
cpuinfo = {}
f = open("/proc/cpuinfo")
lines = f.readlines()
f.close()
for line in lines:
if line == 'n':
cpu.append(cpuinfo)
cpuinfo = {}
if len(line) < 2: continue
name = line.split(':')[0].rstrip()
var = line.split(':')[1]
cpuinfo[name] = var
return cpuinfo
def net_stat():
net = []
f = open("/proc/net/dev")
lines = f.readlines()
f.close()
for line in lines[2:]:
con = line.split()
"""
intf = {}
intf['interface'] = con[0].lstrip(":")
intf['ReceiveBytes'] = int(con[1])
intf['ReceivePackets'] = int(con[2])
intf['ReceiveErrs'] = int(con[3])
intf['ReceiveDrop'] = int(con[4])
intf['ReceiveFifo'] = int(con[5])
intf['ReceiveFrames'] = int(con[6])
intf['ReceiveCompressed'] = int(con[7])
intf['ReceiveMulticast'] = int(con[8])
intf['TransmitBytes'] = int(con[9])
intf['TransmitPackets'] = int(con[10])
intf['TransmitErrs'] = int(con[11])
intf['TransmitDrop'] = int(con[12])
intf['TransmitFifo'] = int(con[13])
intf['TransmitFrames'] = int(con[14])
intf['TransmitCompressed'] = int(con[15])
intf['TransmitMulticast'] = int(con[16])
"""
intf = dict(
zip(
( 'interface','ReceiveBytes','ReceivePackets',
'ReceiveErrs','ReceiveDrop','ReceiveFifo',
'ReceiveFrames','ReceiveCompressed','ReceiveMulticast',
'TransmitBytes','TransmitPackets','TransmitErrs',
'TransmitDrop', 'TransmitFifo','TransmitFrames',
'TransmitCompressed','TransmitMulticast' ),
( con[0].rstrip(":"),int(con[1]),int(con[2]),
int(con[3]),int(con[4]),int(con[5]),
int(con[6]),int(con[7]),int(con[8]),
int(con[9]),int(con[10]),int(con[11]),
int(con[12]),int(con[13]),int(con[14]),
int(con[15]),int(con[16]), )
)
)
net.append(intf)
return net
def uptime_stat():
uptime = {}
f = open("/proc/uptime")
con = f.read().split()
f.close()
all_sec = float(con[0])
MINUTE,HOUR,DAY = 60,3600,86400
uptime['day'] = int(all_sec / DAY )
uptime['hour'] = int((all_sec % DAY) / HOUR)
uptime['minute'] = int((all_sec % HOUR) / MINUTE)
uptime['second'] = int(all_sec % MINUTE)
uptime['Free rate'] = float(con[1]) / float(con[0])
return uptime
def disk_stat(): #磁盘使用空间,单位Byte
import os
hd={}
disk = os.statvfs("/")
hd['available'] = disk.f_bsize * disk.f_bavail
hd['capacity'] = disk.f_bsize * disk.f_blocks
hd['used'] = disk.f_bsize * disk.f_bfree
return hd
sendpacket = {'cpu_stat':cpu_stat(), 'mem_stat':memory_stat(), 'net_stat':net_stat(), 'runtime_stat':uptime_stat(), 'disk_stat':disk_stat()}
sock.send(str(sendpacket))
time.sleep(1)
#socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 9999))
s.listen(5)
print('Waiting for connection...')
while True:
sock, addr = s.accept()
while True:
tcplink(sock, addr)
| Shapooo/linux-remote | getinfo-srv.py | getinfo-srv.py | py | 4,495 | python | en | code | 1 | github-code | 13 |
9521394917 | from inspect import isclass
from django.contrib.admin.utils import model_format_dict
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.utils.html import escape as html_escape
from django.utils.safestring import mark_safe
def get_admin_url(django_entity, anchored=True, safe=True, escape=True, text=None) -> str:
"""
:param django_entity: Can be an instance of a model or a model class.
:param anchored: Whether to wrap with html <a> tags.
:param safe: Whether the content is considered html safe.
:param escape: Whether the content needs to be html escaped.
:param text: Optional text for the anchored URL.
"""
obj = django_entity if not isclass(django_entity) else None
klass = django_entity if not obj else obj.__class__
if not text:
if obj:
text = obj.__str__()
else:
text = model_format_dict(django_entity)["verbose_name"]
content_type = ContentType.objects.get_for_model(klass)
if obj:
url = reverse(
f"admin:{content_type.app_label}_{content_type.model}_change",
args=(obj.id,),
)
else:
url = reverse(
f"admin:{content_type.app_label}_{content_type.model}_changelist",
)
if escape:
text = html_escape(text)
if anchored:
url = f"<a href={url}>{text}</a>"
if safe:
url = mark_safe(url)
return url
| silverapp/silver | silver/utils/admin.py | admin.py | py | 1,464 | python | en | code | 292 | github-code | 13 |
26854057525 | import tornado.web
import tornado.ioloop
import os
from tornado.options import define, options
from common.url_router import include, url_wrapper
from common.models import init_db
from conf.base import (
SERVER_PORT,
SERVER_HEADER
)
from views.questioners.questioners_views import LoginHandler
class Application(tornado.web.Application):
def __init__(self):
init_db()
handles = url_wrapper([
(r"/", LoginHandler),
(r"/questioners/", include('views.questioners.questioners_urls')),
(r"/questionnaires/", include('views.questionnaires.questionnaires_urls')),
(r"/questions/", include('views.questions.questions_urls')),
(r"/respondents/", include('views.respondents.respondents_urls')),
(r"/answers/", include('views.answers.answers_urls')),
(r"/summer/", include('views.summer.summer_urls')),
])
settings = dict(
debug=True,
static_path=os.path.join(os.path.dirname(__file__), "static"),
csrf_cookies=False
)
tornado.web.Application.__init__(self, handles, **settings)
if __name__ == '__main__':
print("Tornado server is ready for service\r")
print("run in " + SERVER_HEADER)
tornado.options.parse_command_line()
Application().listen(SERVER_PORT, xheaders=True)
tornado.ioloop.IOLoop.instance().start()
| xiaoyuerova/questionnaireServer | main.py | main.py | py | 1,409 | python | en | code | 0 | github-code | 13 |
44040793016 | import cv2
import cv2
video = cv2.VideoCapture(0)
while True:
status, frame = video .read()
#resize
#print(frame.shape)
#frame=cv2.resize(frame,(frame.shape[1]//2, frame.shape[0]//2))
cv2.rectangle(frame, (100,100), (200,200), (0,255,0),2)
cv2.putText(frame,'Live', (150,80),
cv2.FONT_HERSHEY_PLAIN, 2, (0,0,0),2, cv2.LINE_AA,False)
cv2.imshow("webcam 0", frame)
if cv2.waitKey(1) == ord('q'):
break
video.release()
cv2.destroyAllWindows() | itzzyashpandey/python-data-science | DataScience/webcam_annotated.py | webcam_annotated.py | py | 508 | python | en | code | 0 | github-code | 13 |
14411527274 |
import unittest
from CardSet import *
from Grid import *
class GridTest(unittest.TestCase):
def setUp(self):
self.grid = Grid()
self.grid.init_crazy_turtle_game()
def test_exception_grid_card(self):
self.assertRaises(GridCardNotFound, self.grid.set_card, Card("TJTBTVCJ"), 1, 1)
def test_change_cardset(self):
c = CardSet()
c.init_crazy_turtle_cardset_home()
self.grid.set_cardset(c)
self.assertTrue(Card("TRTBCVCJ") in self.grid.get_cardset())
self.assertTrue(Card("CBTVTJCR") in self.grid.get_cardset())
def test_equals(self):
self.grid.set_card(Card("TBTVCRTJ"), 1, 1)
self.grid.set_card(Card("CBTJCRTJ"), 0, 0)
other_grid = self.grid.copy()
self.assertNotEqual(self.grid, other_grid)
self.assertTrue(self.grid.equals(other_grid))
self.grid.add_card_to_cardset(Card("TVCRTJTB"))
self.assertRaises(GridCardAlreadyInCardSet, self.grid.add_card_to_cardset, Card("TVCRTJTB"))
self.grid.set_card(Card("TVCRTJTB"), 1, 1)
self.assertFalse(self.grid.equals(other_grid))
self.grid.add_card_to_cardset(Card("TBTVCRTJ"))
self.grid.set_card(Card("TBTVCRTJ"), 1, 1)
self.assertTrue(self.grid.equals(other_grid))
def test_copy(self):
self.grid.set_card(Card("TBTVCRTJ"), 1, 1)
self.grid.set_card(Card("CBTJCRTJ"), 0, 0)
other_grid = self.grid.copy()
self.assertNotEqual(self.grid, other_grid)
self.assertNotEqual(self.grid.cardset, other_grid.cardset)
self.assertTrue(self.grid.cardset.equals(other_grid.cardset))
self.assertNotEqual(self.grid.get_card(1,1), other_grid.get_card(1,1))
self.assertTrue(self.grid.get_card(1,1).has_same_configuration_as(other_grid.get_card(1,1)))
self.assertNotEqual(self.grid.get_card(0,0), other_grid.get_card(0,0))
self.assertTrue(self.grid.get_card(0,0).has_same_configuration_as(other_grid.get_card(0,0)))
for i in range(3):
for j in range(3):
self.assertNotEqual(self.grid.matrix[i][j], other_grid.matrix[i][j])
self.assertTrue(self.grid.matrix[i][j].equals(other_grid.matrix[i][j]))
def test_configuration(self):
self.grid.set_card(Card("TBTVCRTJ"), 1, 1)
self.grid.set_card(Card("CBTJCRTJ"), 0, 0)
self.assertEqual(self.grid.number_of_cards_left(), 7)
a = self.grid.matrix[0][1].get_possible_card_configurations()
self.assertTrue(a[0].equals(Card("TRCJCRTV")))
def test_exist_valid_card_for_all_places(self):
self.grid.set_card(Card("TRTVCBCJ"), 0, 0)
self.grid.set_card(Card("TBTRCBCV"), 0, 1)
self.grid.set_card(Card("TBCVCJCV"), 0, 2)
self.grid.set_card(Card("TJTBTVCR"), 1, 1)
self.assertFalse(self.grid.exist_valid_card_for_all_next_places())
def test_init(self):
self.assertTrue(isinstance(self.grid, Grid))
self.assertEqual(self.grid.number_of_cards_left(), 9)
self.grid.set_card(Card("TJTBTVCR"),1,1)
self.assertEqual(self.grid.number_of_cards_left(), 8)
new_places = self.grid.get_new_places_for_cards()
self.assertEqual(len(new_places), 4)
place = new_places[0]
self.assertTrue(isinstance(place, Place))
card_configuration_list = place.get_possible_card_configurations()
self.assertEqual(len(card_configuration_list), 5)
self.assertTrue(isinstance(card_configuration_list[0], Card))
next_grid = place.get_grid_for_card_configuration(card_configuration_list[0])
self.assertEqual(next_grid.number_of_cards_left(), 7)
self.assertNotEqual(self.grid, next_grid)
self.assertTrue(next_grid.get_card(1,1).equals(Card("TJTBTVCR")))
self.assertTrue(next_grid.get_card(0,1).equals(Card("TBTRCBCV")))
next_new_places = next_grid.get_new_places_for_cards()
self.assertEqual(len(next_new_places), 5)
place = next_grid.get_place(x=1,y=0)
card_list = place.get_possible_card_configurations()
card = card_list[0]
next_next_grid = place.get_grid_for_card_configuration(card)
place = next_next_grid.get_place(0,0)
card_list = place.get_possible_card_configurations()
def test_next_step(self):
cardset = self.grid.get_cardset()
first_card = cardset[0]
self.grid.set_card(first_card, 1, 1)
grid_set = self.grid.next_step()
for grid in grid_set:
self.assertEquals(grid.number_of_cards_left(), 7)
result = []
for grid in grid_set:
result += grid.next_step()
if __name__ == "__main__":
unittest.main()
| mrcanard/CrazyTurtleSolver | GridTest.py | GridTest.py | py | 4,808 | python | en | code | 0 | github-code | 13 |
6571333975 | from bs4 import BeautifulSoup
import requests
response = requests.get("https://www.empireonline.com/movies/features/best-movies-2/")
soup = BeautifulSoup(response.text, "html.parser")
film_href_tags = soup.find_all(name="a")
films = reversed([film_href.text.split("Read Empire's review of ")[1] for film_href in film_href_tags if film_href.text.__contains__("Read Empire's review of")])
out_text = ""
for idx, film in enumerate(films):
out_text += f"{idx + 1}. {film}\n"
with open("films.txt", "w", encoding="utf-8") as file:
file.write(out_text) | YofiTofi/beautifulsoup_films | main.py | main.py | py | 556 | python | en | code | 0 | github-code | 13 |
15523831323 | from itertools import chain, tee
def build_matrix(s, t, m, n):
M = [[[] for x in range(n + 1)] for y in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
M[i][j] = 0
elif s[i - 1] == t[j - 1]:
M[i][j] = M[i - 1][j - 1] + 1
else:
M[i][j] = max(M[i - 1][j], M[i][j - 1])
return M
def lcsq(data):
s, t, *_ = [s[1] for s in gen_seqs(data)]
i, j = len(s), len(t)
table = build_matrix(s, t, i, j)
seq = ""
while i > 0 and j > 0:
if s[i - 1] == t[j - 1]:
seq = s[i - 1] + seq
i -= 1
j -= 1
elif table[i - 1][j] > table[i][j - 1]:
i -= 1
else:
j -= 1
return seq
def gen_seqs(data):
idx_lines = (n for (n, l) in enumerate(data) if l.startswith(">"))
# Add last line to iter
idx_lines = chain(idx_lines, (len(data),))
for i, j in pairwise(idx_lines):
id_seq, seq = data[i], "".join(data[i + 1 : j])
yield id_seq, seq
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
DATA_FILE = "dat/rosalind_lcsq.txt"
SAMPLE_DATA = """
>Rosalind_23
AACCTTGG
>Rosalind_64
ACACTGTGA"""
SAMPLE_OUTPUT = "ACCTGG"
if __name__ == "__main__":
# Assert sample
SAMPLE_DATA = SAMPLE_DATA.lstrip().split("\n")
assert lcsq(SAMPLE_DATA) == SAMPLE_OUTPUT
# Read data
with open(DATA_FILE, "r") as f:
data = [l.strip() for l in f.readlines()]
# Produce output
print(lcsq(data))
| neumann-mlucas/rosalind | src/rosalind_lcsq.py | rosalind_lcsq.py | py | 1,603 | python | en | code | 0 | github-code | 13 |
2510550323 | from .exceptions import SchemaConflictException
from .exceptions import StopConsumer
from .exceptions import UnhandledMessage
from .exceptions import UnregisteredSchemaException
from .kafka import KafkaTopicManager
from .utils import resolve_dotted_name
from functools import partial
from pydantic import BaseModel
from pydantic import ValidationError
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
from typing import Type
import aiokafka
import aiokafka.errors
import aiokafka.structs
import argparse
import asyncio
import fnmatch
import inspect
import logging
import orjson
import pydantic
import signal
logger = logging.getLogger("kafkaesk")
class Subscription:
def __init__(self, stream_id: str, func: Callable, group: str):
self.stream_id = stream_id
self.func = func
self.group = group
def __repr__(self) -> str:
return f"<Subscription stream: {self.stream_id} >"
class SchemaRegistration:
def __init__(
self,
id: str,
version: int,
model: Type[pydantic.BaseModel],
retention: Optional[int] = None,
streams: Optional[List[str]] = None,
):
self.id = id
self.version = version
self.model = model
self.retention = retention
self.streams = streams
def __repr__(self) -> str:
return f"<SchemaRegistration id: {self.id}, version: {self.version} >"
def _pydantic_msg_handler(
model: Type[BaseModel], record: aiokafka.structs.ConsumerRecord, data: Dict[str, Any]
) -> BaseModel:
try:
return model.parse_obj(data["data"])
except ValidationError:
raise UnhandledMessage(f"Error parsing data: {model}")
def _raw_msg_handler(
record: aiokafka.structs.ConsumerRecord, data: Dict[str, Any]
) -> Dict[str, Any]:
return data
def _bytes_msg_handler(record: aiokafka.structs.ConsumerRecord, data: Dict[str, Any]) -> bytes:
return record.value
def _record_msg_handler(
record: aiokafka.structs.ConsumerRecord, data: Dict[str, Any]
) -> aiokafka.structs.ConsumerRecord:
return record
class SubscriptionConsumer:
def __init__(
self,
app: "Application",
subscription: Subscription,
event_handlers: Optional[Dict[str, List[Callable]]] = None,
):
self._app = app
self._subscription = subscription
self._event_handlers = event_handlers or {}
async def emit(self, name: str, *args: Any, **kwargs: Any) -> None:
for func in self._event_handlers.get(name, []):
try:
await func(*args, **kwargs)
except StopConsumer:
raise
except Exception:
logger.warning(f"Error emitting event: {name}: {func}")
async def __call__(self) -> None:
try:
while True:
await self.__run()
except aiokafka.errors.UnrecognizedBrokerVersion:
logger.error("Could not determine kafka version. Exiting")
except aiokafka.errors.KafkaConnectionError:
logger.warning("Connection error", exc_info=True)
except (RuntimeError, asyncio.CancelledError, StopConsumer):
logger.info("Consumer stopped, exiting")
async def __run(self) -> None:
consumer = aiokafka.AIOKafkaConsumer(
bootstrap_servers=cast(List[str], self._app._kafka_servers),
loop=asyncio.get_event_loop(),
group_id=self._subscription.group,
api_version=self._app._kafka_api_version,
**self._app._kafka_settings or {},
)
pattern = fnmatch.translate(self._app.topic_mng.get_topic_id(self._subscription.stream_id))
listener = CustomConsumerRebalanceListener(consumer, self._app, self._subscription.group)
consumer.subscribe(pattern=pattern, listener=listener)
await consumer.start()
msg_handler = _raw_msg_handler
sig = inspect.signature(self._subscription.func)
param_name = [k for k in sig.parameters.keys()][0]
annotation = sig.parameters[param_name].annotation
if annotation and annotation != sig.empty:
if annotation == bytes:
msg_handler = _bytes_msg_handler # type: ignore
elif annotation == aiokafka.structs.ConsumerRecord:
msg_handler = _record_msg_handler # type: ignore
else:
msg_handler = partial(_pydantic_msg_handler, annotation) # type: ignore
await self.emit("started", subscription_consumer=self)
try:
# Consume messages
async for record in consumer:
try:
logger.info(f"Handling msg: {record}")
msg_data = orjson.loads(record.value)
it = iter(sig.parameters.keys())
kwargs: Dict[str, Any] = {next(it): msg_handler(record, msg_data)}
for key in it:
if key == "schema":
kwargs["schema"] = msg_data["schema"]
elif key == "record":
kwargs["record"] = record
await self._subscription.func(**kwargs)
except UnhandledMessage:
# how should we handle this? Right now, fail hard
logger.warning(f"Could not process msg: {record}", exc_info=True)
finally:
await self.emit("message", record=record)
finally:
try:
await consumer.commit()
except Exception:
logger.info("Could not commit current offsets", exc_info=True)
try:
await consumer.stop()
except Exception:
logger.warning("Could not properly stop consumer", exc_info=True)
class Application:
"""
Application configuration
"""
_producer: Optional[aiokafka.AIOKafkaProducer]
def __init__(
self,
kafka_servers: Optional[List[str]] = None,
topic_prefix: str = "",
kafka_settings: Optional[Dict[str, Any]] = None,
replication_factor: Optional[int] = None,
kafka_api_version: str = "auto",
):
self._subscriptions: List[Subscription] = []
self._schemas: Dict[str, SchemaRegistration] = {}
self._kafka_servers = kafka_servers
self._kafka_settings = kafka_settings
self._producer = None
self._intialized = False
self._locks: Dict[str, asyncio.Lock] = {}
self._kafka_api_version = kafka_api_version
self._topic_prefix = topic_prefix
self._replication_factor = replication_factor
self._topic_mng: Optional[KafkaTopicManager] = None
self._event_handlers: Dict[str, List[Callable[[], Awaitable[None]]]] = {}
def on(self, name: str, handler: Callable[[], Awaitable[None]]) -> None:
if name not in self._event_handlers:
self._event_handlers[name] = []
self._event_handlers[name].append(handler)
async def _call_event_handlers(self, name: str) -> None:
handlers = self._event_handlers.get(name)
if handlers is not None:
for handler in handlers:
await handler()
@property
def topic_mng(self) -> KafkaTopicManager:
if self._topic_mng is None:
self._topic_mng = KafkaTopicManager(
cast(List[str], self._kafka_servers),
self._topic_prefix,
replication_factor=self._replication_factor,
)
return self._topic_mng
def get_lock(self, name: str) -> asyncio.Lock:
if name not in self._locks:
self._locks[name] = asyncio.Lock()
return self._locks[name]
def configure(
self,
kafka_servers: Optional[List[str]] = None,
topic_prefix: Optional[str] = None,
kafka_settings: Optional[Dict[str, Any]] = None,
api_version: Optional[str] = None,
replication_factor: Optional[int] = None,
) -> None:
if kafka_servers is not None:
self._kafka_servers = kafka_servers
if topic_prefix is not None:
self._topic_prefix = topic_prefix
if kafka_settings is not None:
self._kafka_settings = kafka_settings
if api_version is not None:
self._kafka_api_version = api_version
if replication_factor is not None:
self._replication_factor = replication_factor
async def publish(
self, stream_id: str, data: BaseModel, key: Optional[bytes] = None
) -> Awaitable[aiokafka.structs.ConsumerRecord]:
if not self._intialized:
async with self.get_lock("_"):
await self.initialize()
schema_key = getattr(data, "__key__", None)
if schema_key not in self._schemas:
raise UnregisteredSchemaException(model=data)
data_ = data.dict()
topic_id = self.topic_mng.get_topic_id(stream_id)
async with self.get_lock(stream_id):
if not await self.topic_mng.topic_exists(topic_id):
reg = self.get_schema_reg(data)
await self.topic_mng.create_topic(
topic_id,
replication_factor=self._replication_factor,
retention_ms=reg.retention * 1000 if reg.retention is not None else None,
)
logger.info(f"Sending kafka msg: {stream_id}")
producer = await self._get_producer()
return await producer.send(
topic_id, value=orjson.dumps({"schema": schema_key, "data": data_}), key=key
)
async def flush(self) -> None:
if self._producer is not None:
await self._producer.flush()
def subscribe(self, stream_id: str, group: str,) -> Callable:
def inner(func: Callable) -> Callable:
subscription = Subscription(stream_id, func, group or func.__name__)
self._subscriptions.append(subscription)
return func
return inner
def get_schema_reg(self, model_or_def: BaseModel) -> SchemaRegistration:
key = model_or_def.__key__ # type: ignore
return self._schemas[key]
def schema(
self,
_id: str,
*,
version: Optional[int] = None,
retention: Optional[int] = None,
streams: Optional[List[str]] = None,
) -> Callable:
version = version or 1
def inner(cls: Type[BaseModel]) -> Type[BaseModel]:
key = f"{_id}:{version}"
reg = SchemaRegistration(
id=_id, version=version or 1, model=cls, retention=retention, streams=streams
)
if key in self._schemas:
raise SchemaConflictException(self._schemas[key], reg)
cls.__key__ = key # type: ignore
self._schemas[key] = reg
return cls
return inner
async def _get_producer(self) -> aiokafka.AIOKafkaProducer:
if self._producer is None:
self._producer = aiokafka.AIOKafkaProducer(
bootstrap_servers=cast(List[str], self._kafka_servers),
loop=asyncio.get_event_loop(),
api_version=self._kafka_api_version,
)
await self._producer.start()
return self._producer
async def initialize(self) -> None:
for reg in self._schemas.values():
# initialize topics for known streams
for stream_id in reg.streams or []:
topic_id = self.topic_mng.get_topic_id(stream_id)
async with self.get_lock(stream_id):
if not await self.topic_mng.topic_exists(topic_id):
await self.topic_mng.create_topic(
topic_id,
retention_ms=reg.retention * 1000
if reg.retention is not None
else None,
)
self._intialized = True
async def finalize(self) -> None:
await self._call_event_handlers("finalize")
if self._producer is not None:
await self._producer.flush()
await self._producer.stop()
if self._topic_mng is not None:
await self._topic_mng.finalize()
self._producer = None
self._intialized = False
self._topic_mng = None
self._intialized = False
async def __aenter__(self) -> "Application":
await self.initialize()
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
await self.finalize()
async def consume_for(self, num_messages: int, *, seconds: Optional[int] = None) -> None:
consumers = []
consumed = 0
for subscription in self._subscriptions:
async def on_message(record: aiokafka.structs.ConsumerRecord) -> None:
nonlocal consumed
consumed += 1
if consumed >= num_messages:
raise StopConsumer
consumer = SubscriptionConsumer(
self, subscription, event_handlers={"message": [on_message]}
)
consumers.append(consumer)
try:
futures = [asyncio.create_task(c()) for c in consumers]
future = asyncio.gather(*futures)
if seconds is not None:
future = asyncio.wait_for(future, seconds)
try:
await future
except asyncio.TimeoutError:
...
finally:
for fut in futures:
if not fut.done():
fut.cancel()
async def consume_forever(self) -> None:
consumers = []
for subscription in self._subscriptions:
consumer = SubscriptionConsumer(self, subscription)
consumers.append(consumer)
try:
futures = [asyncio.create_task(c()) for c in consumers]
await asyncio.gather(*futures)
finally:
for fut in futures:
if not fut.done():
fut.cancel()
class CustomConsumerRebalanceListener(aiokafka.ConsumerRebalanceListener):
def __init__(self, consumer: aiokafka.AIOKafkaConsumer, app: Application, group_id: str):
self.consumer = consumer
self.app = app
self.group_id = group_id
async def on_partitions_revoked(self, revoked: List[aiokafka.structs.TopicPartition]) -> None:
...
async def on_partitions_assigned(self, assigned: List[aiokafka.structs.TopicPartition]) -> None:
"""This method will be called after partition
re-assignment completes and before the consumer
starts fetching data again.
Arguments:
assigned {TopicPartition} -- List of topics and partitions assigned
to a given consumer.
"""
starting_pos = await self.app.topic_mng.list_consumer_group_offsets(
self.group_id, partitions=assigned
)
logger.info(f"Partitions assigned: {assigned}")
for tp in assigned:
if tp not in starting_pos or starting_pos[tp].offset == -1:
# detect if we've never consumed from this topic before
# decision right now is to go back to beginning
# and it's unclear if this is always right decision
await self.consumer.seek_to_beginning(tp)
# XXX go back one message
# unclear if this is what we want to do...
# try:
# position = await self.consumer.position(tp)
# offset = position - 1
# except aiokafka.errors.IllegalStateError:
# offset = -1
# if offset > 0:
# self.consumer.seek(tp, offset)
# else:
# await self.consumer.seek_to_beginning(tp)
cli_parser = argparse.ArgumentParser(description="Run kafkaesk worker.")
cli_parser.add_argument("app", help="Application object")
cli_parser.add_argument("--kafka-servers", help="Kafka servers")
cli_parser.add_argument("--kafka-settings", help="Kafka settings")
cli_parser.add_argument("--topic-prefix", help="Topic prefix")
cli_parser.add_argument("--api-version", help="Kafka API Version")
def _close_app(app: Application, fut: asyncio.Future) -> None:
if not fut.done():
logger.info("Cancelling consumer from signal")
fut.cancel()
async def run_app(app: Application) -> None:
async with app:
loop = asyncio.get_event_loop()
fut = asyncio.create_task(app.consume_forever())
for signame in {"SIGINT", "SIGTERM"}:
loop.add_signal_handler(getattr(signal, signame), partial(_close_app, app, fut))
await fut
logger.info("Exiting consumer")
def run(app: Optional[Application] = None) -> None:
if app is None:
opts = cli_parser.parse_args()
module_str, attr = opts.app.split(":")
module = resolve_dotted_name(module_str)
app = getattr(module, attr)
if callable(app):
app = app()
app = cast(Application, app)
if opts.kafka_servers:
app.configure(kafka_servers=opts.kafka_servers.split(","))
if opts.kafka_settings:
app.configure(kafka_settings=orjson.loads(opts.kafka_settings))
if opts.topic_prefix:
app.configure(topic_prefix=opts.topic_prefix)
if opts.api_version:
app.configure(api_version=opts.api_version)
try:
logger.info(f"Running kafkaesk consumer {app}")
asyncio.run(run_app(app))
except asyncio.CancelledError:
logger.info("Closing because task was exited")
| dmanchon/kafkaesk | kafkaesk/app.py | app.py | py | 17,955 | python | en | code | null | github-code | 13 |
9063398303 | import sys
input = sys.stdin.readline
from collections import deque
# 상하좌우
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# n, m을 입력받음
n, m = map(int, input().split())
# 미로정보를 입력받음
maze = []
for _ in range(n):
maze.append(list(input().rstrip()))
# bfs를 위한 visited 리스트 생성
visited = [[False] * m for _ in range(n)]
# 큐 생성하고 첫 노드를 넣음
q = deque()
q.append((0, 0, 1))
visited[0][0] = True
# bfs
while q:
# 큐에서 노드를 하나 꺼냄
x, y, t = q.popleft()
# 도착지에 도착했다면 반복종료
if x == n - 1 and y == m - 1:
break
# 상하좌우로 다음위치 탐색
for d in range(4):
# 다음위치
nx = x + dx[d]
ny = y + dy[d]
# 미로를 벗어난다면 통과
if nx < 0 or nx >= n or ny < 0 or ny >= m:
continue
# 이미 방문했다면 통과
if visited[nx][ny]:
continue
# 이동할 수 있는 칸이면 이동
if maze[nx][ny] == '1':
q.append((nx, ny, t + 1))
visited[nx][ny] = True
# 결과 출력
print(t)
| yudh1232/Baekjoon-Online-Judge-Algorithm | 2178 미로 탐색.py | 2178 미로 탐색.py | py | 1,173 | python | ko | code | 0 | github-code | 13 |
2292560709 | from test_class import TestClass
from test_sample import TestClass1
def main():
t = TestClass()
t.test_one()
t.test_two()
t = TestClass1()
t.test_one1()
t.test_two2()
if __name__ == "__main__":
main()
| sneha203406/pytestProject1 | tests/main.py | main.py | py | 235 | python | en | code | 0 | github-code | 13 |
43114260172 | import sys
import heapq
input = sys.stdin.readline
INF = int(1e9)
n, m = map(int, input().split())
start = int(input())
graph = [[] for _ in range(n + 1)] # 인접 노드 그래프
distance = [INF] * (n + 1) # 최소 거리 정보 (시작점에서부터 각 노드 까지)
for _ in range(m):
u, v, w = map(int, input().split())
graph[u].append((v, w)) # i[0]은 목적 노드, i[1]은 가중치
def dijkstra(start):
q = []
heapq.heappush(q, (0, start)) # 첫번째 인덱스(=가중치) 기준으로 정렬
distance[start] = 0 # 자기 자신까지의 거리는 0
while q:
dist, now = heapq.heappop(q) # (초기) 0 1
# 이미 처리된 노드 skip
if dist > distance[now]: # (초기) 0 > 0 => False
continue
# 인접 노드 탐색
for i in graph[now]:
cost = dist + i[1] # 인접 노드로 가는 "새로운 경로값"
if cost < distance[i[0]]: # 인접 노드로 가는 기존 경로값보다 "새로운 경로값"이 작으면 갱신
distance[i[0]] = cost
heapq.heappush(q, (cost, i[0]))
dijkstra(start)
# 시작점에서부터 각 정점으로까지의 최단 경로 값 출력
for i in range(1, n+1):
if distance[i] == INF:
print("INF")
else:
print(distance[i]) | jinhyungrhee/Problem-Solving | BOJ/BOJ_1753_최단경로.py | BOJ_1753_최단경로.py | py | 1,251 | python | ko | code | 0 | github-code | 13 |
10409651744 | import torch
import torch.nn as nn
class TimeDistributed(nn.Module):
"""
A layer that could be nested to apply sub operation to every timestep of sequence input.
"""
def __init__(self, module, batch_first=True):
super(TimeDistributed, self).__init__()
self.module = module
self.batch_first = batch_first
def forward(self, x):
if len(x.size()) <= 2:
return self.module(x)
# Squash samples and timesteps into a single axis
# (samples * timesteps, input_size)
if self.batch_first:
batch = x.size(0)
timesteps = x.size(1)
else:
batch = x.size(1)
timesteps = x.size(0)
x_reshape = x.contiguous().view((-1,) + tuple(x.size()[2:]))
y = self.module(x_reshape)
# We have to reshape Y
if self.batch_first:
# (samples, timesteps, output_size)
y = y.contiguous().view((batch, timesteps) + tuple(y.size()[1:]))
else:
# (timesteps, samples, output_size)
y = y.contiguous().view((timesteps, batch) + tuple(y.size()[1:]))
return y
if __name__=='__main__':
fc = nn.Linear(10,20)
fc = TimeDistributed(fc)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '4,5'
a = torch.zeros((32, 10, 10))
fc.cuda()
a = a.cuda()
b = fc(a) | Adamink/EventBasedAction | src/model/utils.py | utils.py | py | 1,390 | python | en | code | 0 | github-code | 13 |
73469392656 | import torch
from torch.autograd import Variable
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv2d, MaxPool2d, Module, Softmax, BatchNorm2d, Dropout
from torch.optim import Adam, SGD
from load_data import mask
from torch.utils.data import DataLoader
import csv
import pandas as pd
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from tqdm import tqdm
import torch
from torch import nn
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, input):
residual = input
x = self.conv1(input)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
if self.downsample:
residual = self.downsample(residual)
x += residual
x = self.relu(x)
return x
class BottleNeck(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(BottleNeck, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, 1, bias=False)
self.bn3 = nn.BatchNorm2d(out_channels*self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, input):
residual = input
x = self.conv1(input)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.conv3(x)
x = self.bn3(x)
if self.downsample:
residual = self.downsample(residual)
x += residual
x = self.relu(x)
return x
class Resnet(nn.Module):
# 224*224
def __init__(self, block, num_layer, n_classes=2, input_channels=3):
super(Resnet, self).__init__()
self.in_channels = 64
self.conv1 = nn.Conv2d(input_channels, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 64, num_layer[0])
self.layer2 = self._make_layer(block, 128, num_layer[1], 2)
self.layer3 = self._make_layer(block, 256, num_layer[2], 2)
self.layer4 = self._make_layer(block, 512, num_layer[3], 2)
self.avgpool = nn.AvgPool2d(kernel_size=7, stride=1)
self.fc1 = nn.Linear(block.expansion * 512, block.expansion * 128)
self.fc2 = nn.Linear(block.expansion * 128, block.expansion * 16)
self.fc3 = nn.Linear(block.expansion * 16, n_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1.0)
nn.init.constant_(m.bias, 0.0)
def _make_layer(self, block, out_channels, num_block, stride=1):
downsample = None
if stride != 1 or self.in_channels != out_channels * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.in_channels, out_channels * block.expansion, 1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels * block.expansion)
)
layers = []
layers.append(block(self.in_channels, out_channels, stride, downsample))
self.in_channels = out_channels * block.expansion
for _ in range(1, num_block):
layers.append(block(self.in_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, input):
x = self.conv1(input)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
def resnet18(pretrained=False, **kwargs):
model = Resnet(BasicBlock, [2, 2, 2, 2], **kwargs)
return model
test_db = mask('/home/xiejun/mask_PUF/data/demo_test/final/bot', 224)
batchsz = 1000
test_loader = DataLoader(test_db, batch_size=batchsz, num_workers=0, shuffle=False)
device = torch.device('cpu')
outputpath = 'demo_final_bot.csv'
model = resnet18().to(device)
model.load_state_dict(torch.load('./best_2bot.mdl'))
print(model)
def evalute(model, loader, outputpath):
model.eval()
correct = 0
total = len(loader.dataset)
for step, (x, y) in enumerate(loader):
# if step>=1:
# break
x, y = x.to(device), y.to(device)
with torch.no_grad(): #不需要计算梯度,所以加上不求导,验证集一定要加上这几句话
logits = model(x)
pred = logits.argmax(dim=1)
with open(outputpath, 'a+') as f:
csv_write = csv.writer(f)
write = [logits.detach().numpy(), y.detach().numpy()]
csv_write.writerows([write[0][:,0],write[1]])
correct += torch.eq(pred, y).sum().float().item()
return correct / total
test_acc = evalute(model, test_loader, outputpath)
| AugustusXie-rgb/mask_PUF | Resnet_prediction.py | Resnet_prediction.py | py | 6,023 | python | en | code | 0 | github-code | 13 |
72320803537 | from .cloud import S3 , GS
from .db import DB
import time
import sys
bucket_name = "towercrane-projects"
class Config():
def __init__(self):
self.db = DB()
self.db.setupDB()
self.mother_config = self.db.get_mother_config()
self.set_mother_config = self.db.set_mother_config
def config_towercrane(self):
"""
Pormpt for setting up TowerCrane
It asks for your cloud of choice
and if you have already done the authentication.
... Other Questions To Be Added
"""
cloudtype = ""
while cloudtype not in ["aws","gcloud"]:
cloudtype = input("what is your choice for cloud storage? aws or gcloud: ") or "aws"
self.set_mother_config("cloudtype",cloudtype)
auth_done = input(f"Have you authenticated your {cloudtype}? (y/n): ") or "n"
if auth_done in ["n","N","no","NO"] :
print("AWS Authentication: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config")
print("Google Cloud Authentication: https://cloud.google.com/docs/authentication/getting-started")
elif auth_done in ["y","Y","yes","YES"] :
print(f"Start with 'towercrane scan' ")
"""
Reading Config Table
and getting cloud and DB clients based on the configs.
get_cloud_client: returns either the s3 or gcloud
get_db_client: returns db client
"""
def get_cloud_client(self):
# first read from DB and see what cloud to use
cloudtype = self.mother_config["cloudtype"]
if cloudtype == "notset" :
sys.exit('Cloud is not configured in towercrane.\nplease use "towercrane config" first. ')
elif cloudtype == "aws" :
cloud_client = S3()
cloud_projects = cloud_client.list_cloud_projects()
if bucket_name not in cloud_projects:
print("There is no towercrane-projects bucket on AWS, creating one ...")
cloud_client.create_cloud_project(bucket_name)
print("created: ",bucket_name)
return cloud_client
elif cloudtype == "gcloud" :
cloud_client = GS()
cloud_projects = cloud_client.list_cloud_projects()
if bucket_name not in cloud_projects:
print("There is no towercrane-projects bucket on GCP, creating one ...")
cloud_client.create_cloud_project(bucket_name)
print("created: ",bucket_name)
return cloud_client
def get_db_client(self):
# we can run our db test here
return self.db
| ashtianicode/towercrane | towercrane/config.py | config.py | py | 2,827 | python | en | code | 0 | github-code | 13 |
12946655299 | def jiujiu():
xx = 9
for i in range(1, xx + 1):
for j in range(1, i + 1):
print('%d*%d=%d' % (i, j, i * j), end='\t')
print()
jiujiu()
def xiaoxiao():
print('luoluo')
xiaoxiao()
print(xiaoxiao()) #没有返回值默认返回None
def fib():
a = [0, 1]
b = 8
for i in range(b-2):
a.append(a[-2]+a[-1])
return a
dib = fib()
alist = [i * 2 for i in dib]
print(alist)
def fib(n):
a = [0, 1]
for i in range(n-2):
a.append(a[-2]+a[-1])
return a
a = fib(5)
print(fib(10))
n = int(input('input your number:'))
import sys
print(sys.argv)
| HLQ1102/MyPython | base-python/py03/hanshu.py | hanshu.py | py | 618 | python | en | code | 0 | github-code | 13 |
72995643219 | #!/usr/bin/python3
from sys import argv
if __name__ == "__main__":
length = len(argv)
if length < 2:
print('0 arguments.')
elif length == 2:
print('1 argument:')
else:
print('{:d} arguments:'.format(length - 1))
for i in range(1, length):
print('{:d}: {}'.format(i, argv[i]))
| HeimerR/holbertonschool-higher_level_programming | 0x02-python-import_modules/2-args.py | 2-args.py | py | 328 | python | en | code | 1 | github-code | 13 |
43147099696 | """
Traffic Light >> YOLOv5m
Stop Line and Lane line >> TwinLite
模型串行
"""
import os
import sys
from collections import deque
from pathlib import Path
import cv2
import numpy as np
import tritonclient.grpc as grpcclient
import torch
from sklearn.cluster import DBSCAN
from models import TwinLite as net
from models.common import DetectMultiBackend
from utils.general import check_img_size, Profile, non_max_suppression, scale_boxes
from utils.torch_utils import select_device
from utils.augmentations import letterbox
# utils
def get_traffic_light_color(im0, x1, y1, x2, y2):
"""
:param im0: image
:param x1: left top x
:param y1: left top y
:param x2: right bottom x
:param y2: right bottom y
:return: traffic light color
"""
traffic_light = im0[int(y1):int(y2), int(x1):int(x2)]
hsv = cv2.cvtColor(traffic_light, cv2.COLOR_BGR2HSV)
# Red color
low_red = np.array([161, 155, 84])
low_red_2 = np.array([0, 155, 84])
high_red = np.array([179, 255, 255])
high_red_2 = np.array([10, 255, 255])
red_mask = cv2.inRange(hsv, low_red, high_red)
red_mask_2 = cv2.inRange(hsv, low_red_2, high_red_2)
red = cv2.bitwise_and(traffic_light, traffic_light, mask=red_mask)
red_2 = cv2.bitwise_and(traffic_light, traffic_light, mask=red_mask_2)
# Green color
low_green = np.array([25, 52, 72])
high_green = np.array([102, 255, 255])
green_mask = cv2.inRange(hsv, low_green, high_green)
green = cv2.bitwise_and(traffic_light, traffic_light, mask=green_mask)
# Yellow color
low_yellow = np.array([20, 100, 100])
high_yellow = np.array([30, 255, 255])
yellow_mask = cv2.inRange(hsv, low_yellow, high_yellow)
yellow = cv2.bitwise_and(traffic_light, traffic_light, mask=yellow_mask)
if red.any() or yellow.any():
traffic_light_color = 'red'
elif green.any():
traffic_light_color = 'green'
else:
traffic_light_color = 'unknown'
return traffic_light_color
def get_color_queue(max_len, fault_value='unknown'):
"""
:param max_len: max length
:param fault_value: fault value
:return: color queue
"""
color_queue = deque(maxlen=max_len)
for i in range(max_len):
color_queue.append(fault_value)
return color_queue
def get_queue_color(color_queue):
"""
:param color_queue: color queue
:return: color
"""
if color_queue.count('red') > 1:
color = 'red'
elif color_queue.count('green') > 3:
color = 'green'
else:
color = 'unknown'
return color
def yolo_predict(triton_client, input_images, input_name="images", output_name="output0", fp="FP16"):
inputs = []
outputs = []
inputs.append(grpcclient.InferInput(input_name, [*input_images.shape], fp))
# data initialize
inputs[-1].set_data_from_numpy(input_images)
outputs.append(grpcclient.InferRequestedOutput(output_name))
results = triton_client.infer(model_name="yolov5", inputs=inputs, outputs=outputs)
return results.as_numpy(output_name)
def detect_traffic_light(triton_server, image_0, imgsz, stride, conf_thres=0.25, iou_thres=0.45, max_det=1000,
classes=[0, 1, 2, 3, 5, 7, 9, 10], agnostic_nms=False, augment=False):
"""
:param model: yolo model
:param image_0: image :param imgsz: size
:param stride: stride
:param conf_thres: confidence threshold
:param iou_thres: iou threshold
:param max_det: max detection
:param classes: classes
:param agnostic_nms: agnostic nms
:param augment: augment
:return: x1, y1, x2, y2, color, conf
"""
frame = image_0.copy()
im = letterbox(frame, imgsz, stride, auto=True)[0] # padded resize
im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
im = np.ascontiguousarray(im) # contiguous
# dt = (Profile(), Profile(), Profile())
# with dt[0]:
# im = torch.from_numpy(im).to(model.device)
# im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
# im /= 255
# if len(im.shape) == 3:
# im = im[None] # expand for batch dim
# with dt[1]:
# pred = model(im, augment=augment, visualize=False)
# with dt[2]:
# pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
pred = yolo_predict(triton_server, im)
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
for i, det in enumerate(pred): # per image
im0 = frame.copy()
if len(det):
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
for *xyxy, conf, cls in reversed(det):
c = int(cls) # integer class
if c == 9:
x1, y1, x2, y2 = [coord.item() for coord in xyxy]
color = get_traffic_light_color(im0, x1, y1, x2, y2)
return x1, y1, x2, y2, color
return f"unknown"
def lane_element_detect(model, img0, Matrix, prev_points_for_fit_0, prev_points_for_fit_1, roi=None):
img = img0.copy()
if roi is not None:
img = cv2.resize(img, (640, 360))
mask = np.zeros_like(img)
cv2.fillPoly(mask, [roi], (255, 255, 255))
img = cv2.bitwise_and(img, mask)
img_rs = img.copy()
else:
img = cv2.resize(img, (640, 360))
img_rs = img.copy()
img = img[:, :, ::-1].transpose([2, 0, 1])
img = np.ascontiguousarray(img)
img = torch.from_numpy(img)
img = torch.unsqueeze(img, 0) # add a batch dimension
img = img.cuda().float() / 255.0
img = img.cuda()
with torch.no_grad():
img_out = model(img)
# x0 = img_out[0]
x1 = img_out[1]
# _, da_predict = torch.max(x0, 1)
_, ll_predict = torch.max(x1, 1)
# DA = da_predict.byte().cpu().data.numpy()[0] * 255
LL = ll_predict.byte().cpu().data.numpy()[0] * 255
# 对DA进行腐蚀和膨胀以及边缘平滑处理,降低锯齿
# DA = post_process(DA, size_e=3, size_g=5, size_ed=5)
# cv2.warpPerspective的flags有INTER_NEAREST、INTER_LINEAR、INTER_AREA、INTER_CUBIC、INTER_LANCZOS4
flag = cv2.INTER_LINEAR
# DA_ipm = cv2.warpPerspective(DA, Matrix, (640, 360), flags=flag)
LL_ipm = cv2.warpPerspective(LL, Matrix, (640, 360), flags=flag)
# 对DA进行腐蚀和膨胀以及边缘平滑处理,降低锯齿
# DA_ipm = post_process(DA_ipm, size_e=7, size_g=5, size_ed=3)
# 对LL_ipm的每一行像素值为255的点进行计数,若当前行的像素值为255的点数大于阈值200,则将当前行的所有点的像素信息存入stop中,
# 否则,将当前点的像素信息存入stop中之后全部置零
stop = []
threshold_s = 120
# threshold_l = 35
for i in range(360):
if np.sum(LL_ipm[i] == 255) > threshold_s:
stop.append(LL_ipm[i])
else:
stop.append(np.zeros(640))
stop = np.array(stop)
# 构建一个矩形区域,此区域包含stop的所有像素点,且每个方向上都有一定的余量
# 获取stop中所有点坐标x和y的最大值和最小值,以此构建矩形区域
indices = np.where(stop == 255)
boarder = 30
if np.any(indices):
stop_x_min = np.min(np.where(stop == 255)[1])
stop_x_max = np.max(np.where(stop == 255)[1])
stop_y_min = np.min(np.where(stop == 255)[0])
stop_y_max = np.max(np.where(stop == 255)[0])
left_top = (max(stop_x_min - boarder, 0), max(stop_y_min - boarder, 0))
right_bottom = (min(stop_x_max + boarder, 640), min(stop_y_max + boarder, 360))
stop_left_end, stop_right_end = get_start_end_point(stop_x_min, stop_x_max, stop_y_min, stop_y_max)
else:
left_top = (0, 0)
right_bottom = (0, 0)
stop_left_end, stop_right_end = (0, 0), (0, 0)
trans_ratio = 0.031
bias = 2.1
dist_SL = -300
for i in range(359, -1, -1):
if np.sum(stop[i] == 255) > 0:
dist_SL = 359 - i
break
dist = dist_SL * trans_ratio + bias
img_rs_ipm = cv2.warpPerspective(img_rs, Matrix, (640, 360), flags=flag)
# DA_ipm[LL_ipm == 255] = 0
# img_rs_ipm[DA_ipm > 100] = [0, 0, 255]
img_rs_ipm[stop == 255] = [255, 0, 0]
# lane定义为LL_ipm中stop_area区域置零后的图像
lane = LL_ipm.copy()
lane = pixel_set_zero(left_top, right_bottom, lane)
# Get coordinates of non-zero pixels in the lane
coords = np.column_stack(np.nonzero(lane))
down_sample = 5
coords = coords[::down_sample]
if len(coords) <= 40 // down_sample:
return img_rs_ipm, dist_SL
db = DBSCAN(eps=9, min_samples=3).fit(coords)
lanes = [coords[db.labels_ == i] for i in range(max(db.labels_) + 1)]
# Get the number of points in each lane
num_points = np.array([len(lane) for lane in lanes])
# Get the mean number of points in a lane
mean_num_points = num_points.mean()
# Loop over each lane and remove it if it has less than mean_num_points * factor
factor = 0.4
lanes = np.array(lanes, dtype=object)[num_points > mean_num_points * factor].tolist()
# get mid lanes
mid_lanes = get_mid_lane(lanes)
# get the side lanes
if not mid_lanes:
side_lanes = lanes
else:
side_lanes = [lane for lane in lanes if not any(np.array_equal(lane, mid_lane) for mid_lane in mid_lanes)]
# Define colors for lanes
center_color = (0, 0, 255)
mid_color = (255, 0, 0)
side_color = (0, 255, 0)
# Display lanes with different colors
if mid_lanes:
points_for_fit_0, points_for_fit_1 = get_points_for_fit(mid_lanes)
if not points_for_fit_0 or not points_for_fit_1 or len(points_for_fit_0) < 10 or len(points_for_fit_1) < 10:
points_for_fit_0 = points_for_fit_modify(points_for_fit_0, prev_points_for_fit_0)
points_for_fit_1 = points_for_fit_modify(points_for_fit_1, prev_points_for_fit_1)
else:
points_for_fit_0 = points_for_fit_modify(None, prev_points_for_fit_0)
points_for_fit_1 = points_for_fit_modify(None, prev_points_for_fit_1)
# calculate center points of mid-lanes
center_points = []
for i in range(len(points_for_fit_0)):
center_points.append([(points_for_fit_0[i][0] + points_for_fit_1[i][0]) / 2,
(points_for_fit_0[i][1] + points_for_fit_1[i][1]) / 2])
draw_fitted_lane(img_rs_ipm, points_for_fit_0, color=mid_color)
draw_fitted_lane(img_rs_ipm, points_for_fit_1, color=mid_color)
draw_fitted_lane(img_rs_ipm, center_points, color=center_color)
# draw circles for points for fit
for point in points_for_fit_0:
cv2.circle(img_rs_ipm, (int(point[1]), int(point[0])), 3, (0, 0, 255), -1)
for point in points_for_fit_1:
cv2.circle(img_rs_ipm, (int(point[1]), int(point[0])), 3, (0, 0, 255), -1)
for point in center_points:
cv2.circle(img_rs_ipm, (int(point[1]), int(point[0])), 3, (0, 255, 0), -1)
if mid_lanes:
for i, lane in enumerate(mid_lanes):
lane = np.array(lane)
img_rs_ipm[lane[:, 0], lane[:, 1]] = mid_color
if side_lanes:
for i, lane in enumerate(side_lanes):
lane = np.array(lane)
img_rs_ipm[lane[:, 0], lane[:, 1]] = side_color
return img_rs_ipm, dist, stop_left_end, stop_right_end, points_for_fit_0, points_for_fit_1
def get_start_end_point(stop_x_min, stop_x_max, left_top_y, right_bottom_y):
"""
:param stop_x_min: stop x min
:param stop_x_max: stop x max
:param left_top_y: left top y
:param right_bottom_y: right bottom y
:return: left end point, right end point
"""
left_end_point = (stop_x_min, int((left_top_y + right_bottom_y) / 2))
right_end_point = (stop_x_max, int((left_top_y + right_bottom_y) / 2))
return left_end_point, right_end_point
def get_mid_lane(lanes, window_mid=320):
"""
:param lanes: points set of each lane
:param window_mid: the x-coordinate of the window center
:return: mid-lane
"""
if len(lanes) < 2:
return None
lanes.sort(key=lambda x: x[0][0])
left_lanes = [lane for lane in lanes if lane[:, 1].min() <= window_mid]
right_lanes = [lane for lane in lanes if lane[:, 1].min() > window_mid]
if not left_lanes or not right_lanes:
return None
left_lane = min(left_lanes, key=lambda lane: window_mid - lane[:, 1].min())
right_lane = min(right_lanes, key=lambda lane: lane[:, 1].min() - window_mid)
return [left_lane, right_lane]
def get_points_for_fit(mid_lanes, points_used=10):
"""
:param mid_lanes: mid-lanes
:param points_used: num of points used for fit
:return: points for fit
"""
points_for_fit_0, points_for_fit_1 = [], []
height_0 = mid_lanes[0][:, 0].max() - mid_lanes[0][:, 0].min()
height_1 = mid_lanes[1][:, 0].max() - mid_lanes[1][:, 0].min()
per_height_0 = int(height_0 / points_used)
per_height_1 = int(height_1 / points_used)
thresh_height = 60
if per_height_0 < thresh_height / points_used or per_height_1 < thresh_height / points_used:
return None, None
for i in range(points_used):
height_range_0 = [per_height_0 * i, per_height_0 * (i + 1)]
height_range_1 = [per_height_1 * i, per_height_1 * (i + 1)]
point_list_0 = [point for point in mid_lanes[0] if height_range_0[0] <= point[0] <= height_range_0[1]]
point_list_1 = [point for point in mid_lanes[1] if height_range_1[0] <= point[0] <= height_range_1[1]]
if len(point_list_0) == 0 or len(point_list_1) == 0:
continue
point_0 = np.mean(point_list_0, axis=0)
point_1 = np.mean(point_list_1, axis=0)
points_for_fit_0.append(point_0)
points_for_fit_1.append(point_1)
return points_for_fit_0, points_for_fit_1
def points_for_fit_modify(points_for_fit, prev_points_for_fit):
if not points_for_fit or len(points_for_fit) < 8:
points_for_fit = []
if prev_points_for_fit[0] and prev_points_for_fit[1] and prev_points_for_fit[2]:
for i in range(len(prev_points_for_fit[0])):
point = prev_points_for_fit[0][i]
points_for_fit.append(point)
print("points_for_fit_modify")
elif prev_points_for_fit[0]:
points_for_fit = prev_points_for_fit[0]
return points_for_fit
def points_check(lane_points, thresh=10):
"""
:param lane_points: points of lane
:param thresh: threshold
:return: True or False
"""
return True if lane_points and len(lane_points) >= thresh else False
def get_lane_fit_coefficients(points, deg=2):
"""
:param points: points
:param deg: degree
:return: coefficients
"""
# if not points_check(points):
# return None
x = [point[0] for point in points]
y = [point[1] for point in points]
coefficients = np.polyfit(x, y, deg)
return coefficients
def get_fitted_lane_point(y, coefficients):
"""
:param y: y
:param coefficients: coefficients
:return: fitted lane point location
"""
return [int(sum(coefficient * y ** i for i, coefficient in enumerate(coefficients[::-1]))), y]
def is_point_in_img(point):
"""
:param point: point
:return: True or False
"""
return True if 0 <= point[0] < 640 and 0 <= point[1] < 360 else False
def draw_fitted_lane(img, lane_points_for_fit, color):
"""
:param img: image
:param lane_points_for_fit: points for fit
:param color: color
"""
coefficients = get_lane_fit_coefficients(lane_points_for_fit)
if coefficients is not None:
for y in range(10, 350):
point = get_fitted_lane_point(y, coefficients)
if is_point_in_img(point):
img[point[1], point[0]] = color
def post_process(src, size_e, size_g, size_ed):
"""
:param src: source image
:param size_e: erode kernel size
:param size_g: gaussian kernel size
:param size_ed: dilate kernel size
:return: processed image
"""
kernel_e = np.ones((size_e, size_e), np.uint8) if size_e and size_e != 0 else None
kernel_ed = np.ones((size_ed, size_ed), np.uint8) if size_ed and size_ed != 0 else None
if kernel_e is not None:
src = cv2.erode(src, kernel_e, iterations=1)
if size_g and size_g != 0:
src = cv2.GaussianBlur(src, (size_g, size_g), 0)
if kernel_ed is not None:
src = cv2.erode(src, kernel_ed, iterations=1)
src = cv2.dilate(src, kernel_ed, iterations=1)
return src
def pixel_set_zero(left_top, right_bottom, src_bin):
"""
:param left_top: left top point
:param right_bottom: right bottom point
:param src_bin: source binary image
:return: processed source binary image
"""
if left_top == (0, 0) and right_bottom == (0, 0):
return src_bin
for i in range(left_top[1], right_bottom[1]):
for j in range(left_top[0], right_bottom[0]):
src_bin[i][j] = 0
return src_bin
def perception_preparation():
"""
:return: yolo model, twinlite model, image size, stride, M, roi
"""
# dir prepare
# FILE = Path(__file__).resolve()
# ROOT = FILE.parents[0] # YOLOv5 root directory
# if str(ROOT) not in sys.path:
# sys.path.append(str(ROOT)) # add ROOT to PATH
# ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
# twinlite model prepares
model_twinlite = net.TwinLiteNet()
model_twinlite = torch.nn.DataParallel(model_twinlite)
model_twinlite = model_twinlite.cuda()
model_twinlite.load_state_dict(torch.load('twinlite.pth'))
model_twinlite.eval()
# print("twinlite model loaded" if model_twinlite else "twinlite model load failed")
# twinlite data prepare
input_pts = np.float32([[100, 200], [540, 200], [540, 360], [100, 360]])
output_pts = np.float32([[0, 0], [640, 0], [360, 360], [280, 360]])
M = cv2.getPerspectiveTransform(input_pts, output_pts)
roi = np.array([[[80, 185], [540, 185], [560, 360], [100, 360]]], dtype=np.int32)
# yolo model prepares
# device = select_device('')
# weights = ROOT / 'yolov5m.pt'
# data = ROOT / 'data/coco128.yaml'
# model_yolo = DetectMultiBackend(weights, device=device, dnn=False, data=data, fp16=True)
# stride, pt = model_yolo.stride, model_yolo.pt
# imgsz = (1080, 1920)
# imgsz = check_img_size(imgsz, s=stride) # check image size
# bs = 1 # batch_size
# model_yolo.warmup(imgsz=(1 if pt or model_yolo.triton else bs, 3, *imgsz))
# print("yolo model loaded" if model_yolo else "yolo model load failed")
# triton server connection
try:
triton_client = grpcclient.InferenceServerClient(url="localhost:8001")
except Exception as e:
print("context creation failed: " + str(e))
sys.exit()
return triton_client, model_twinlite, M, roi
def perception_out(frame, triton_server, model_twinlite, M, prev_points_for_fit_0, prev_points_for_fit_1, roi=None):
traffic_light = detect_traffic_light(triton_server, frame)
lane_elements = lane_element_detect(model_twinlite, frame, M, prev_points_for_fit_0, prev_points_for_fit_1, roi)
return traffic_light, lane_elements
def put_text(frame, texts):
"""
:param frame: image
:param texts: texts
:return: image with texts
"""
position = (20, 40)
for i, text in enumerate(texts):
cv2.putText(frame, text, (position[0], position[1] + 30 * i), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 1,
cv2.LINE_AA)
return
| bg-szy/iav | Perception_with_TritonServer.py | Perception_with_TritonServer.py | py | 20,201 | python | en | code | 0 | github-code | 13 |
33089224766 | # from botXsrc.botXexport import botXexport
from botXsrc.peanut_arm_api.arm_component import ArmComponent
"""
botXexport is a dictionary containing all the reusable components you
developed for the project, and you will use them in the main program.
"""
def main():
print('starting app ...')
ac = ArmComponent()
ac.setup()
my_pose = dict()
my_pose['position'] = {'x': 0.2, 'y': -0.27, 'z': 0.48}
my_pose['orientation'] = {'x': 0.67, 'y': -0.15, 'z': -0.69, 'w': 0.17}
try:
ac.move_to(my_pose)
except ValueError as e:
print(e)
print('all tasks finished')
"""
This is the only script that should be running from terminal so that the
program can gather modules correctly, so we need to specify main as entry point.
"""
if __name__ == '__main__':
main()
| superbotx/PeanutHacks | botXapp.py | botXapp.py | py | 810 | python | en | code | 0 | github-code | 13 |
17048749474 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ApprovedInfo(object):
def __init__(self):
self._application_no = None
self._approval_letter_url = None
self._imm_code = None
self._imm_fullname = None
self._imm_position = None
self._note = None
self._payment_confirm_url = None
self._receipt_url = None
self._remark = None
self._status = None
self._status_date_time = None
self._tm_6_url = None
self._tm_88_url = None
@property
def application_no(self):
return self._application_no
@application_no.setter
def application_no(self, value):
self._application_no = value
@property
def approval_letter_url(self):
return self._approval_letter_url
@approval_letter_url.setter
def approval_letter_url(self, value):
self._approval_letter_url = value
@property
def imm_code(self):
return self._imm_code
@imm_code.setter
def imm_code(self, value):
self._imm_code = value
@property
def imm_fullname(self):
return self._imm_fullname
@imm_fullname.setter
def imm_fullname(self, value):
self._imm_fullname = value
@property
def imm_position(self):
return self._imm_position
@imm_position.setter
def imm_position(self, value):
self._imm_position = value
@property
def note(self):
return self._note
@note.setter
def note(self, value):
self._note = value
@property
def payment_confirm_url(self):
return self._payment_confirm_url
@payment_confirm_url.setter
def payment_confirm_url(self, value):
self._payment_confirm_url = value
@property
def receipt_url(self):
return self._receipt_url
@receipt_url.setter
def receipt_url(self, value):
self._receipt_url = value
@property
def remark(self):
return self._remark
@remark.setter
def remark(self, value):
self._remark = value
@property
def status(self):
return self._status
@status.setter
def status(self, value):
self._status = value
@property
def status_date_time(self):
return self._status_date_time
@status_date_time.setter
def status_date_time(self, value):
self._status_date_time = value
@property
def tm_6_url(self):
return self._tm_6_url
@tm_6_url.setter
def tm_6_url(self, value):
self._tm_6_url = value
@property
def tm_88_url(self):
return self._tm_88_url
@tm_88_url.setter
def tm_88_url(self, value):
self._tm_88_url = value
def to_alipay_dict(self):
params = dict()
if self.application_no:
if hasattr(self.application_no, 'to_alipay_dict'):
params['application_no'] = self.application_no.to_alipay_dict()
else:
params['application_no'] = self.application_no
if self.approval_letter_url:
if hasattr(self.approval_letter_url, 'to_alipay_dict'):
params['approval_letter_url'] = self.approval_letter_url.to_alipay_dict()
else:
params['approval_letter_url'] = self.approval_letter_url
if self.imm_code:
if hasattr(self.imm_code, 'to_alipay_dict'):
params['imm_code'] = self.imm_code.to_alipay_dict()
else:
params['imm_code'] = self.imm_code
if self.imm_fullname:
if hasattr(self.imm_fullname, 'to_alipay_dict'):
params['imm_fullname'] = self.imm_fullname.to_alipay_dict()
else:
params['imm_fullname'] = self.imm_fullname
if self.imm_position:
if hasattr(self.imm_position, 'to_alipay_dict'):
params['imm_position'] = self.imm_position.to_alipay_dict()
else:
params['imm_position'] = self.imm_position
if self.note:
if hasattr(self.note, 'to_alipay_dict'):
params['note'] = self.note.to_alipay_dict()
else:
params['note'] = self.note
if self.payment_confirm_url:
if hasattr(self.payment_confirm_url, 'to_alipay_dict'):
params['payment_confirm_url'] = self.payment_confirm_url.to_alipay_dict()
else:
params['payment_confirm_url'] = self.payment_confirm_url
if self.receipt_url:
if hasattr(self.receipt_url, 'to_alipay_dict'):
params['receipt_url'] = self.receipt_url.to_alipay_dict()
else:
params['receipt_url'] = self.receipt_url
if self.remark:
if hasattr(self.remark, 'to_alipay_dict'):
params['remark'] = self.remark.to_alipay_dict()
else:
params['remark'] = self.remark
if self.status:
if hasattr(self.status, 'to_alipay_dict'):
params['status'] = self.status.to_alipay_dict()
else:
params['status'] = self.status
if self.status_date_time:
if hasattr(self.status_date_time, 'to_alipay_dict'):
params['status_date_time'] = self.status_date_time.to_alipay_dict()
else:
params['status_date_time'] = self.status_date_time
if self.tm_6_url:
if hasattr(self.tm_6_url, 'to_alipay_dict'):
params['tm_6_url'] = self.tm_6_url.to_alipay_dict()
else:
params['tm_6_url'] = self.tm_6_url
if self.tm_88_url:
if hasattr(self.tm_88_url, 'to_alipay_dict'):
params['tm_88_url'] = self.tm_88_url.to_alipay_dict()
else:
params['tm_88_url'] = self.tm_88_url
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = ApprovedInfo()
if 'application_no' in d:
o.application_no = d['application_no']
if 'approval_letter_url' in d:
o.approval_letter_url = d['approval_letter_url']
if 'imm_code' in d:
o.imm_code = d['imm_code']
if 'imm_fullname' in d:
o.imm_fullname = d['imm_fullname']
if 'imm_position' in d:
o.imm_position = d['imm_position']
if 'note' in d:
o.note = d['note']
if 'payment_confirm_url' in d:
o.payment_confirm_url = d['payment_confirm_url']
if 'receipt_url' in d:
o.receipt_url = d['receipt_url']
if 'remark' in d:
o.remark = d['remark']
if 'status' in d:
o.status = d['status']
if 'status_date_time' in d:
o.status_date_time = d['status_date_time']
if 'tm_6_url' in d:
o.tm_6_url = d['tm_6_url']
if 'tm_88_url' in d:
o.tm_88_url = d['tm_88_url']
return o
| alipay/alipay-sdk-python-all | alipay/aop/api/domain/ApprovedInfo.py | ApprovedInfo.py | py | 7,079 | python | en | code | 241 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.