blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
b588f2c1ecc3daa6991eab8af144bceb73afd1cb
7d75f44a9486b6e2bb0e58c72d22be436cc308af
/EventSelector/scripts/wq2-ls
4d93419f50c4dcd2e7f4cd550c4c53f5c8220804
[]
no_license
zinon/RawData
f95dbef4c12eb9db73adbae8e94c031781bc3bef
38743ed4d52f532a03e53dfee774abfa49e82988
refs/heads/master
2021-01-19T20:18:15.971916
2015-02-25T11:30:18
2015-02-25T11:30:18
31,310,618
0
0
null
null
null
null
UTF-8
Python
false
false
1,520
#! /usr/bin/env python """ Module createContainer improved dq2-ls splits up unique and duplicated datasets """ import optparse import subprocess import os import re from DQ2Tool import DQ2Tool ## Configuration ############################################################ def main(): # Load Parser usage = "usage: %prog [options] SEARCH_STRING" parser = optparse.OptionParser(usage=usage) # Set Options parser.add_option("-c", "--contents", dest="contents", action="store_true", default=False, help="display the contents of any container" ) # Set Defaults #parser.set_defaults( checking = False ) # Parse Args (options,args) = parser.parse_args() # Check for search string if len(args) < 1 : print "ERROR - Must provide search string" parser.print_help() exit(1) ## Load dq2 tool dq2 = DQ2Tool() ## Run ######################################################## input_containers = dq2.lsArray( args ) overlap, unique, junk = dq2.getOverlappingDatasets( input_containers ) if options.contents: unique = dq2.getContainerArrayContents(unique) # Summaries datasets print print '# Unique datasets:' for dataset_name in unique: print dataset_name print print '# Overlapping datasets:' for entry in overlap: print '#%s:'%entry for dataset_name in overlap[entry]: print ' ',dataset_name print print '# Junk datasets:' for dataset_name in junk: print dataset_name if __name__ == '__main__': main()
[ "zinon123@gmail.com" ]
zinon123@gmail.com
d1456bb6326f302fbb94ad3ef15d4303f90f97cc
9f6691c51f5ee58d19caa5c9e4cb82ddbd917ec0
/V2RaycSpider1225/src/BusinessLogicLayer/utils/staff_mining/support/staff_collector.py
51704a1ff91c67c352648a349fe62e6638fb4d65
[ "MIT" ]
permissive
TOBICHI-Origami/V2RSS
2bef6e1e48942cf21023a3c91eefeecb42ddfe3e
a5dc1478b0229d87881c53095366f692ddeac04a
refs/heads/master
2023-09-05T07:55:45.082232
2021-10-19T15:35:25
2021-10-19T15:35:25
420,401,126
0
1
null
null
null
null
UTF-8
Python
false
false
8,741
py
__all__ = ["StaffCollector"] import random import sys import time from selenium.common.exceptions import NoSuchElementException, WebDriverException from selenium.webdriver import Chrome, ChromeOptions from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from tqdm import tqdm from ..common.exceptions import CollectorSwitchError class StaffCollector: def __init__( self, cache_path: str, chromedriver_path: str, silence: bool = True, debug: bool = False, ): """ :param cache_path: :param silence: :param debug: :param chromedriver_path: """ self.GOOGLE_SEARCH_API = "https://www.google.com.hk" # self.SEARCH_QUERY = '"特此免费授予任何获得副本的人这个软件和相关的文档文件"' self.SEARCH_QUERY = '"由 @editXY 修改适配。"' self.CHROMEDRIVER_PATH = chromedriver_path self.cache_path = cache_path self.debug = debug self.silence = silence @staticmethod def _down_to_api(api: Chrome, search_query: str): """键入并跳转至相关页面""" while True: try: input_tag = api.find_element_by_xpath("//input[@name='q']") input_tag.click() input_tag.clear() input_tag.send_keys(search_query) input_tag.send_keys(Keys.ENTER) break except NoSuchElementException: time.sleep(0.5) continue @staticmethod def _page_switcher(api: Chrome, is_home_page: bool = False): start_time = time.time() # 首页 -> 第二页 if is_home_page: while True: try: ActionChains(api).send_keys(Keys.END).perform() time.sleep(0.5) api.find_element_by_xpath("//a[@id='pnnext']").click() break except NoSuchElementException: # 检测到到流量拦截 主动抛出异常并采取备用方案 if "sorry" in api.current_url: raise CollectorSwitchError time.sleep(0.5) api.refresh() continue # 第二页 -> 第N页 else: while True: try: ActionChains(api).send_keys(Keys.END).perform() time.sleep(0.5) page_switchers = api.find_elements_by_xpath("//a[@id='pnnext']") next_page_bottom = page_switchers[-1] next_page_bottom.click() break except (NoSuchElementException, IndexError): time.sleep(0.5) # 检测到到流量拦截 主动抛出异常并采取备用方案 if "sorry" in api.current_url: raise CollectorSwitchError # 最后一页 if time.time() - start_time > 5: break continue def _capture_host(self, api: Chrome): time.sleep(1) # hosts = api.find_elements_by_xpath("//span[@class='qXLe6d dXDvrc']//span[@class='fYyStc']") hosts = api.find_elements_by_xpath( "//div[contains(@class,'NJjxre')]//cite[@class='iUh30 Zu0yb qLRx3b tjvcx']" ) with open(self.cache_path, "a", encoding="utf8") as f: for host in hosts: f.write(f"{host.text.split(' ')[0].strip()}/auth/register\n") def set_spider_options(self) -> Chrome: # 实例化Chrome可选参数 options = ChromeOptions() # 最高权限运行 options.add_argument("--no-sandbox") # 隐身模式 options.add_argument("-incognito") # 无缓存加载 options.add_argument("--disk-cache-") # 设置中文 options.add_argument("lang=zh_CN.UTF-8") # 禁用 DevTools listening options.add_experimental_option("excludeSwitches", ["enable-logging"]) options.add_argument("--log-level=3") # 更换头部 options.add_argument( "user-agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78'" ) # 静默启动 if self.silence is True: options.add_argument("--headless") options.add_argument("--disable-gpu") options.add_argument("--disable-software-rasterizer") # 抑制自动化控制特征 options.add_argument("--disable-blink-features=AutomationControlled") options.add_experimental_option("useAutomationExtension", False) options.add_experimental_option("excludeSwitches", ["enable-automation"]) try: _api = Chrome(options=options, executable_path=self.CHROMEDRIVER_PATH) _api.execute_cdp_cmd( "Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }, ) return _api except WebDriverException as e: if "chromedriver" in str(e): print(f">>> 指定目录下缺少chromedriver {self.CHROMEDRIVER_PATH}") sys.exit() @staticmethod def get_page_num(api: Chrome): try: result = api.find_element_by_xpath("//div[@id='result-stats']") tag_num = result.text.strip().split(" ")[1] print(tag_num) except NoSuchElementException: return None def run(self, page_num: int = 26, sleep_node: int = 5): # API 实例化 api = self.set_spider_options() # 进度条 初始化 loop_progress = tqdm( total=page_num, desc="STAFF COLLECTOR", ncols=150, unit="piece", dynamic_ncols=False, leave=True, ) loop_progress.set_postfix({"status": "__initialize__"}) try: # 根据关键词 去首页 api.get(self.GOOGLE_SEARCH_API) self._down_to_api(api=api, search_query=self.SEARCH_QUERY) self.get_page_num(api) # 获取page_num页的注册链接 # 正常情况一页10个链接 既共获取page_num * 10个链接 for x in range(page_num): # ============================================================== # 采集器 # ============================================================== # 萃取注册链接并保存 self._capture_host(api=api) loop_progress.set_postfix({"status": "__collect__"}) loop_progress.update(1) # self._debugger(message=f"Successfully collected the staff-hosts from page {x + 1}", level="info") # print(f"<StaffCollector> Successfully collected the staff-hosts [{x + 1}/{page_num}]") # ============================================================== # 翻页控制器 # ============================================================== # 第1页 -> 第2页 if x == 0: self._page_switcher(api=api, is_home_page=True) # 第2页-> 第N页 self._page_switcher(api=api, is_home_page=False) # ============================================================== # 休眠控制器 # ============================================================== # 每sleep_node页进行一次随机时长的休眠 if x % sleep_node == 0: tax_ = random.uniform(3, 5) # self._debugger(message=f"Tactical sleep! The mission will continue in {round(tax_, 3)} seconds", # level="debug") # print(f"<StaffCollector> Tactical sleep! The mission will continue in {round(tax_, 3)} seconds") loop_progress.set_postfix({"status": "__sleep__"}) time.sleep(tax_) finally: api.quit() # self._debugger(message="Mission completed", level="info") # self._debugger(message=f"the cache file address is {self.cache_path}", level="info")
[ "62018067+QIN2DIM@users.noreply.github.com" ]
62018067+QIN2DIM@users.noreply.github.com
dc27dc63f6a3b9d4bd00afcbc7b4639d4e1533d0
993f7b85a9c4d69d91c100b22aba2f14b638fc81
/swea-5656.py
b3c3a1d27380c90f74ffdb1dc8c05350b1e22d44
[]
no_license
bearics/coding-test
2a5eca9d12eb6051e5fd14646fee719ba328f962
ffe7a602e088245cd931f0d078dbd2e8dad83254
refs/heads/master
2020-07-20T18:33:23.187916
2019-09-06T02:24:35
2019-09-06T02:24:35
206,692,398
0
0
null
null
null
null
UTF-8
Python
false
false
2,533
py
dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]] # R D L U, [X, Y] def sol(n): # global debugggg # debugggg += 1 # print(debugggg) global base_map # if debugggg == 28: # print("stop") if len(n) >= N: count = 0 global min_count for rr in range(H): for cc in range(W): if base_map[rr][cc] != 0: count += 1 min_count = min(min_count, count) # if n[0] == 2 and n[1] ==2 and n[2] == 6: # print("here!!") # print(n) # for _r in base_map: # print(*_r) return # print(n, end=" ") for c in range(W): # 부술 벽돌이 있는지 확인 have_brick = False broken_bricks = [] for r in range(H): if base_map[r][c] != 0: broken_bricks.append([r, c]) break prev_map = [row[:] for row in base_map] # c열에는 벽돌이 없어서 끝 if len(broken_bricks) == 0: continue # c열에 깰 벽돌이 있음 broken_map = [[0] * W for _ in range(H)] while broken_bricks: br, bc = broken_bricks.pop(0) count = base_map[br][bc] for dx, dy in dirs: broken_map[br][bc] = 1 base_map[br][bc] = -1 if count == 1: break for idx in range(1, count): if ((br + (idx * dy)) < 0 or (br + (idx * dy)) >= H) or ((bc + (idx * dx)) < 0 or (bc + (idx * dx)) >= W): continue else: if base_map[br + (idx * dy)][bc + (idx * dx)] > 0 and broken_map[br + (idx * dy)][bc + (idx * dx)] == 0: broken_bricks.append([br + (idx * dy), bc + (idx * dx)]) broken_map[br + (idx * dy)][bc + (idx * dx)] = 1 # 벽돌 제거 for rr in range(H): for cc in range(W): if broken_map[rr][cc] == 1: base_map[rr][cc] = 0 # 벽돌 정리 for cc in range(W): temp = [] for rr in range(H): if base_map[rr][cc] != 0: temp.append(base_map[rr][cc]) base_map[rr][cc] = 0 for r_idx in range(len(temp)): base_map[H - r_idx - 1][cc] = temp[len(temp) - r_idx - 1] # print("n:{} c:{}".format(n, c), end=' ') n.append(c) sol(n) n.pop() base_map = [_[:] for _ in prev_map] T = int(input()) for case_idx in range(T): N, W, H = map(int, input().split()) # print(N, W, H) base_map = [] for row in range(H): base_map.append(list(map(int, input().split()))) min_count = 999999 debugggg = 0 sol([]) if min_count is 999999: min_count = 0 print("#{} {}".format(case_idx + 1, min_count))
[ "bearics@gmail.com" ]
bearics@gmail.com
39a6558bfc2c2ddd777939bce2b4f90f80b198ee
8901d53969eb840338fb3b66895d199e4c82aad7
/vantage_media_player/bin/django-admin
66b2baa559b0508aad95a980ef2638ff3144b892
[]
no_license
SaundersB/web-media-player
26438614685ba6d065d5d64c61468862cf4535cd
3b3690a6860a4d815542f0fdfa524b3ba0222fcc
refs/heads/master
2021-05-31T22:27:28.969328
2016-07-19T20:29:27
2016-07-19T20:29:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
317
#!/home/brandons/src/Web_Media_Player/vantage_media_player/bin/python # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
[ "speakeasys@gmail.com" ]
speakeasys@gmail.com
7b1d8bb258a7103c7da00088999d4559fef09750
ec8d24cab32a821338055654e51589307d363d86
/linked/linked/pipelines.py
f065f97abef8391e9b5328856dadafb106afd6e1
[]
no_license
caiprozect/crawl
ce64c765469baf64e09dae4229d9387512302a45
43b75aca258830c44628e3efc33aabce9d4957e7
refs/heads/master
2021-01-24T09:45:33.061037
2016-10-05T12:00:08
2016-10-05T12:00:08
69,521,875
0
0
null
null
null
null
UTF-8
Python
false
false
286
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class LinkedPipeline(object): def process_item(self, item, spider): return item
[ "caiprozect@gmail.com" ]
caiprozect@gmail.com
e6963b1f1c20af3ad100d73cbd2a60ebafed797b
afe177633a6af170d6a2f56660aafb7cef388daa
/sprites/ground.py
87e71d59839583697b126e1acb0ab513302bd842
[ "MIT" ]
permissive
sdcpku/FlappyBirdAI
5f25c61bcbf7c6b68c82be653946b24dfda0b42d
945f42a6a5f83facf69f314f40af9612638467e9
refs/heads/master
2021-01-12T14:19:42.875747
2014-06-20T06:02:42
2014-06-20T06:02:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
860
py
import cocos import cocos.euclid import cocos.collision_model import setting class Ground(cocos.sprite.Sprite): def __init__(self, y): super(Ground, self).__init__(image="resources/ground.png") position = (setting.GAME_WIDTH - self.width / 2, y) self.position = position self.cshape = cocos.collision_model.AARectShape(cocos.euclid.Vector2(*position), self.width / 2, self.height / 2) ground_action = cocos.actions.Repeat( cocos.actions.MoveTo((setting.GAME_WIDTH / 2, y), duration=(self.width - setting.GAME_WIDTH) / 2.0 / setting.SPEED) + cocos.actions.Place((setting.GAME_WIDTH - self.width / 2, y)) ) self.do(ground_action) def update_cshape(self): pass
[ "xianyubo@qq.com" ]
xianyubo@qq.com
aca671cbd29112f2e6668647ab92fe0be17afbb2
60c6f68000fe9440948f91b493d15e96c2159373
/python/index-gsoc-searcher-data.py
21b0674d84288efb1850321cec4495f20140c197
[]
no_license
dbpedia-spotlight/gsoc-searcher
a0a288686089c0bb89c05d4d5b55a7f16925b25c
a75c4c3177e30273995e38c9a924ae835e2247ad
HEAD
2016-09-01T23:08:53.629598
2013-06-11T10:08:44
2013-06-11T10:08:44
9,697,566
3
1
null
null
null
null
UTF-8
Python
false
false
3,490
py
""" Requires an ElasticSearch server to be running. python index-gsoc-search-data.py <dataDir> <elasticSearchUrl> """ import sys import os import urllib2 import re INDEX_ID = "gsoc2013" TYPE_ID = "d" MAPPING = """{ "d" : { "properties" : { "ideas" : { "type" : "string", "store" : "yes" }, "linkId" : { "type" : "string", "store" : "yes" }, "name" : { "type" : "string", "store" : "yes" }, "tagged" : { "type" : "string", "store" : "yes" }, "taggedString" : { "type" : "string", "store" : "yes" }, "textTagged" : { "type" : "string", "store" : "yes" } } } }""" class RequestWithMethod(urllib2.Request): """Hack for forcing the method in a request - allows PUT and DELETE Ack: Eric S. Raymond http://benjamin.smedbergs.us/blog/2008-10-21/putting-and-deleteing-in-python-urllib2/#comment-430392 """ def __init__(self, method, *args, **kwargs): # This assignment works directly in older Python versions self._method = method urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): # This method works in newer Pythons (2.6.5, possibly earlier). if self._method: return self._method elif self.has_data(): return 'POST' else: return 'GET' def analyzeKey(k): return k.replace("/", "_") def iterOrgData(dataDir): d = {} # group org data for fileName in [fn for fn in os.listdir(dataDir) if not fn.endswith(".text")]: fullPath = os.path.join(dataDir, fileName) with open(fullPath) as f: for line in f: key, prop, val = line.strip().split("\t") d.setdefault(key, []).append((prop, val)) for k, vals in d.iteritems(): yield k, vals def wipeIndex(elasticSearchUrl): print "Wiping index %s" % elasticSearchUrl url = "%s/%s" % (elasticSearchUrl, INDEX_ID) try: print urllib2.urlopen(RequestWithMethod('DELETE', url)).read() except urllib2.HTTPError, err: if err.code != 404: raise # none existed urllib2.urlopen(RequestWithMethod('PUT', url)).read() def setMapping(elasticSearchUrl): url = "%s/%s/%s/_mapping" % (elasticSearchUrl, INDEX_ID, TYPE_ID) print urllib2.urlopen(RequestWithMethod('PUT', url, data=MAPPING)).read() def indexOrgData(elasticSearchUrl, orgData): key, vals = orgData print "Indexing in %s: %s" % (elasticSearchUrl, key) url = "%s/%s/%s/%s" % (elasticSearchUrl, INDEX_ID, TYPE_ID, analyzeKey(key)) data = '{' + ",".join(['"%s":"%s"' % (prop, val) for prop, val in vals]) + '}' answerJson = urllib2.urlopen(RequestWithMethod('PUT', url, data=data)).read() if not '"ok":true' in answerJson: print url, data print orgData, "failed indexation" sys.exit(1) def flushIndex(elasticSearchUrl): url = "%s/_flush" % (elasticSearchUrl) print urllib2.urlopen(RequestWithMethod('POST', url)).read() if __name__ == "__main__": dataDir = sys.argv[1] elasticSearchUrl = "http://localhost:9200" if len(sys.argv) == 3: elasticSearchUrl = re.sub("/$", "", sys.argv[2]) wipeIndex(elasticSearchUrl) setMapping(elasticSearchUrl) for orgData in iterOrgData(dataDir): indexOrgData(elasticSearchUrl, orgData) flushIndex(elasticSearchUrl)
[ "max.jakob@gmail.com" ]
max.jakob@gmail.com
876a4e19c8e2c703b622a9bd2a112eb53263922f
cca746947ed7779c48dbca2bdd6398755445f801
/chapter13/decorate_demo.py
530e3e7f50f686fcd6730def079ee16e9c8d6ff5
[]
no_license
TangBean/AdvancePython
0081ce5afc434dd8ee10d3539df952d1845c8cff
6b29c3c271104fdc947522f26c9884c011147c86
refs/heads/master
2020-05-19T21:10:37.330795
2019-05-13T15:19:21
2019-05-13T15:19:21
185,217,792
2
1
null
null
null
null
UTF-8
Python
false
false
649
py
def log(func): def wrapper(*args, **kwargs): print("call %s():" % func.__name__) func(*args, **kwargs) print("call finish") return "returning" return wrapper # 在这里用 log 装饰 now 函数,相当于调用了 now = log(now),也就是说,now 函数现在是 wrapper 函数 # 然后调用 now("hello") == wrapper("hello") # 在 wrapper 中调用 func(*args, **kwargs) 相当于调用 now("hello") 本身,我们可以在这个函数调用前后加逻辑装饰它 @log def now(msg): print(msg) res = now("hello") print(res) print(now) # <function log.<locals>.wrapper at 0x000001E5CAD73598>
[ "984354469@qq.com" ]
984354469@qq.com
cc253dd395f7b5886f218c25e5d30b74c5670852
91afa6d9e893b6b6586226acaca684ab8bbfb5e9
/plaining/migrations/0003_person_sexe.py
9f72632904fd8a0ac8a753d9b054704119a77521
[]
no_license
elmehdiLAM/frontend
4a71604d9cb75511d98d17acebb44bcf9db8ad4c
e469cf7d01665065309d620bc55867949020d2ab
refs/heads/master
2023-03-08T12:33:10.055991
2021-02-21T17:02:49
2021-02-21T17:02:49
340,951,522
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
# Generated by Django 3.1.4 on 2021-01-02 22:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('plaining', '0002_auto_20210102_1516'), ] operations = [ migrations.AddField( model_name='person', name='sexe', field=models.CharField(choices=[('MAS', 'Masculin'), ('FEM', 'Feminin')], default='', max_length=10), ), ]
[ "elmehdi.lamsyah@fsr.ac.ma" ]
elmehdi.lamsyah@fsr.ac.ma
126797cd83a42c98ec04cdb75a1bd48f2f88afc4
ea3063b9559046fdd53e9ceff8839adcb04671d5
/nn/data/augmentation_preprocessing.py
3a227a3c7e986d64a1a3eeccd882202b57fe6302
[]
no_license
Juravlik/diploma_1
a4f2631c588841139a13db917326f137e741ea08
07d95db3b0df529d3bce37de81b96aa75ad5a3e4
refs/heads/main
2023-05-04T07:08:23.746603
2021-05-27T01:40:25
2021-05-27T01:40:25
370,557,047
0
0
null
null
null
null
UTF-8
Python
false
false
2,116
py
import albumentations as A import torch import random import numpy as np import cv2 IMAGE_SIZE = 256 def lock_deterministic(seed=42): np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True def add_padding_to_square(x, **kwargs): max_side = max(x.shape) return A.PadIfNeeded( min_height=max_side, min_width=max_side, always_apply=True, border_mode=cv2.BORDER_CONSTANT )(image=x)['image'] def _get_validation_augmentation(): transforms = [ A.Lambda(image=add_padding_to_square, mask=add_padding_to_square, always_apply=True), A.Resize(height=IMAGE_SIZE, width=IMAGE_SIZE, always_apply=True), ] return A.Compose(transforms) def _get_training_augmentation(): transforms = [ A.Blur(blur_limit=(3, 3), p=0.05), A.Cutout(num_holes=6, max_h_size=12, max_w_size=12, fill_value=0, p=0.07), A.OneOf( [ A.ISONoise(color_shift=(0.05, 0.01), intensity=(0.1, 0.5), p=0.1), A.IAAAdditiveGaussianNoise(p=0.1), A.IAAPerspective(p=0.1), ], p=0.3 ), A.RandomBrightnessContrast(p=0.1), A.RandomShadow(num_shadows_upper=3, p=0.05), A.Flip(p=0.25), A.ShiftScaleRotate(border_mode=cv2.BORDER_CONSTANT, p=0.2), _get_validation_augmentation(), ] return A.Compose(transforms) def get_train_aug_preproc(preprocessing_fn): return A.Compose([*_get_training_augmentation()] + [*_get_preprocessing(preprocessing_fn)]) def get_valid_aug_preproc(preprocessing_fn): return A.Compose([*_get_validation_augmentation()] + [*_get_preprocessing(preprocessing_fn)]) def to_tensor(x, **kwargs): return torch.from_numpy(x.transpose(2, 0, 1).astype('float32')) def _get_preprocessing(preprocessing_fn): _transform = [ A.Lambda(image=preprocessing_fn), A.Lambda(image=to_tensor), ] return A.Compose(_transform)
[ "temelyanov@griddynamics.com" ]
temelyanov@griddynamics.com
2a99b3bb613dba1885dc7a069898c4d69a501f7e
833b43575815ce6c5fa8cbac2628cb774331eda7
/chap20_p371_code3.py
dcda8aea075beb81ff7c9027d10c117c90dfe210
[]
no_license
ai-times/infinitybook_python
d9529dfe7d486bf5c713d52b530915a23cbf1812
1c011c31994d07fe959bba9b519c4365f5f40e7f
refs/heads/main
2023-03-01T12:18:20.695888
2021-02-14T04:22:40
2021-02-14T04:22:40
338,578,047
0
0
null
null
null
null
UTF-8
Python
false
false
124
py
from datetime import datetime birth = datetime(2002, 6, 30, 10, 15, 3, 56765) now = datetime.now( ) print( now - birth )
[ "wskim092@gmail.com" ]
wskim092@gmail.com
d2f174d698d8c02ec6ecce24ca62979fbca72999
0397efdc80bae46a9057b80d98f281dfad421abf
/monitorize/wsgi.py
0bddf78b1d1db059f733bb50f77e5fc47114029b
[]
no_license
sungpia/Monitorize
4751b608d4284cc148cc6b106ae31033b1117761
b472a74c0145995f4bc51e2cc271ee86dd9ce9a9
refs/heads/master
2020-05-26T15:48:39.961287
2019-05-24T21:35:35
2019-05-24T21:35:35
188,293,260
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
""" WSGI config for monitorize project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "monitorize.settings") application = get_wsgi_application()
[ "sungpia@me.com" ]
sungpia@me.com
89e36ad6da49de830237eae3d65f2168dc4709bc
bd23d83683c9b6ef9e440b751b0b9f3a6daab126
/src/djangodbu/sql.py
e545e4d65a26b9a77491e38dccee5f6168bad92b
[ "MIT" ]
permissive
mulderns/djangodbu
08cf83a3edccc84bc9b9fd8517b876b4bb595fdc
25c212986776a1bac63efed2040fd555f1d20f40
refs/heads/master
2023-03-11T20:38:39.870146
2023-03-02T11:31:10
2023-03-02T11:31:10
95,750,999
1
0
null
null
null
null
UTF-8
Python
false
false
9,332
py
# -*- coding: utf-8 -*- ''' For debugging SQL queries, (SOME ASSEMBLY REQUIRED!) You need to: - add a line to django.db.backends.utils.py, see details in stack_position - configure excluded paths for stack traces to get cleaner output ''' import logging import re import os import traceback from math import log as ln from collections import defaultdict import sqlparse from sqlparse import keywords # SQL keywords for colorization KEYS = list(keywords.KEYWORDS.keys()) KEYS.extend(list(keywords.KEYWORDS_COMMON.keys())) log = logging.getLogger(__name__) _MINIBARS = [ '\033[1;32m|', '\033[0;32m|', '\033[0;33m|', '\033[1;33m|', '\033[1;31m|', '\033[0;31m|', ] _RESET = '\033[0m' def _minilogbars(time): bars = max(0, min(5, int(round(ln(time*100)))) if time != 0 else 0) pad = ' ' * max(0, 5 - bars) return '{bars}{reset}{pad}'.format(bars=''.join(_MINIBARS[:bars]), reset=_RESET, pad=pad) #colorize_sql_regexp = re.compile(r"([^.])`([^`]*)`\.", re.IGNORECASE) # `(table)`.`...` #colorize_sql_regexp_2 = re.compile(r"\.`([^`]*)`", re.IGNORECASE) # `table.`(field)` colorize_sql_regexp_1_2 = re.compile(r"`([^`]*)`\.`([^`]*)`", re.IGNORECASE) # `(table)`.`(field)` colorize_sql_regexp_3 = re.compile(r" `([^`]*)`[^.]", re.IGNORECASE) # `(table)` colorize_sql_regexp_4 = re.compile(r'('+'[^A-Z]|'.join(KEYS)+r')') # KEYWORDS colorize_sql_regexp_5 = re.compile(r'( [=<>] )') # comparators def colorize_sql(sql): #sql = colorize_sql_regexp.sub(r'\1\033[1;30m\2\033[0m.', sql) #sql = colorize_sql_regexp_2.sub(r'.\033[0;34m\1\033[0m', sql) sql = colorize_sql_regexp_1_2.sub(r'\033[1;30m\1\033[0m.\033[0;34m\2\033[0m', sql) sql = colorize_sql_regexp_3.sub(r' \033[0;35m\1\033[0m ', sql) sql = colorize_sql_regexp_4.sub(r'\033[0;33m\1\033[0m', sql) sql = colorize_sql_regexp_5.sub(r'\033[0;31m\1\033[0m', sql) return sql def format_sql(sql): return sqlparse.format(sql, reindent=True) def print_query(query): from .utils import uni sqlstring = uni(query.__str__()) print(colorize_sql(format_sql(sqlstring))) def sqlprint(data, filtering=True, tb=False): ''' "Print SQL queries": { "prefix": "dbusql", "body": [ "from django.db import connection; # TODO: remove this debug\nfrom dbu import sql; sql.sqlprint(connection.queries) # TODO: remove this debug" ], "description": "list sql queries" } also "Reset SQL queries": { "prefix": "dbusqlr", "body": [ "from django.db import reset_queries; reset_queries() # TODO: remove this debug" ], "description": "reset sql queries list" } ''' for row in data: #row['sql'] = colorize_sql(row['sql']) if filtering and float(row['time']) < 0.0001: log.info("{} :".format(row['time'])) continue location = '-' if 'tb' in row: location = _get_location(row['tb']) sql = format_sql(row['sql']) sql = colorize_sql(sql) log.info("{time} {loc}\n{sql}\n".format(time=row['time'], loc=location, sql=sql)) new_line_replace = re.compile(r'(\n)') def _indent_newlines(data, indentation=4): sub_space = '\n' + (' ' * indentation) return new_line_replace.sub(sub_space, data) trace_exclude_paths = re.compile(r'/System|site-packages|wsgi\.py') def __format_traceback_debug(tb): for frame in tb: if trace_exclude_paths.search(frame[0]): continue simple_file = os.path.basename(frame[0]) #print "<{f}:{l}:{m}> {t}".format(f=simple_file, l=frame[1], m=frame[2], t=frame[3]) print("{f}:{m}:{l:<4} > {t} \t ".format(f=frame[0], fs=simple_file, l=frame[1], m=frame[2], t=frame[3])) print("") def _format_traceback(tb): #return '\n \033[0;35m>\033[0m '.join("\033[0;34m{file}\033[1;30m:\033[0;36m{module}\033[1;30m:\033[0;37m{linenum:<3}\033[0;35m :\033[0m {text}".format(file=os.path.basename(frame[0]), linenum=frame[1], module=frame[2], text=frame[3]) for frame in tb if not trace_exclude_paths.search(frame[0])) #return '\n \033[0;35m>\033[0m '.join("\033[0;34m{file}\033[1;30m:\033[0;37m{linenum:<3}\033[1;30m:\033[0;36m{module}\033[0;35m :\033[0m {text}".format(file=os.path.basename(frame[0]), linenum=frame[1], module=frame[2], text=frame[3]) for frame in tb if not trace_exclude_paths.search(frame[0])) #return '\n \033[0;35m>\033[0m '.join("\033[0;34m{file}\033[1;30m:\033[0;37m{linenum:<3} \033[0;36m{module}\033[0;35m:\033[0m {text}".format(file=os.path.basename(frame[0]), linenum=frame[1], module=frame[2], text=frame[3]) for frame in tb if not trace_exclude_paths.search(frame[0])) return '\n \033[0;35m>\033[0m '.join("\033[0;34m{file}\033[1;30m:\033[0;37m{linenum:<3} \033[0;36m{module}\033[0m {text}".format(file=os.path.basename(frame[0]), linenum=frame[1], module=frame[2], text=frame[3]) for frame in tb if not trace_exclude_paths.search(frame[0])) def _format_traceback2(tb, exclude=True): # filea:123 ... # filea:123 > 223 > fileb:323 .... # filec:123 > filed:232 ... # frame > frame > frame # filter frames if exclude: filtered_tb = [frame for frame in tb if not trace_exclude_paths.search(frame[0])] else: filtered_tb = tb last_index = len(filtered_tb) - 1 output_frames = [] prev_file = None for i, frame in enumerate(filtered_tb): output = '' simple_file = os.path.basename(frame[0]) if simple_file != prev_file: output = "\033[0;34m{file}\033[1;30m:\033[0;37m{linenum:<3}".format(file=os.path.basename(frame[0]), linenum=frame[1]) prev_file = simple_file else: output = "\033[0;37m{linenum:<3}".format(linenum=frame[1]) if i == last_index: output += " \033[0;36m{module}\033[0m {text}".format(module=frame[2], text=frame[3]) output_frames.append(output) return ' \033[0;35m>\033[0m '.join(output_frames) def _get_location(tb): relevant_frames = [frame for frame in tb if not trace_exclude_paths.search(frame[0])] if len(relevant_frames) == 0: return "." frame = relevant_frames[-1] return "\033[0;36m{module}(\033[1;30m…\033[0;36m) \033[1;30m[\033[0;34m{file}\033[1;30m:\033[0;37m{linenum:<3}\033[1;30m] \033[0m{text}".format(file=os.path.basename(frame[0]), linenum=frame[1], module=frame[2], text=frame[3]) _SQL_ID_PATTERN = re.compile(r'=\s*\d+') def sqlcount(data, filtersmall=False, include_sql=False): ''' "Count SQL queries": { "prefix": "dbusqlcount", "body": [ "from django.db import connection; # TODO: remove this debug\nfrom dbu import sql; sql.sqlcount(connection.queries) # TODO: remove this debug" ], "description": "count number and total time of sql queries, show originating lines" } ''' counts = defaultdict(lambda: {'count':0.0, 'time':0.0, 'location': set()}) for row in data: key = _SQL_ID_PATTERN.sub('= ?', row['sql']) counts[key]['count'] += 1.0 time = float(row['time']) if time == 0.001: time = 0.0007 elif time == 0.000: time = 0.0004 counts[key]['time'] += time if 'trace' in row: counts[key]['location'].add(_format_traceback2(row['trace'])) elif 'tb' in row: counts[key]['location'].add(_format_traceback2(row['tb'])) results = [(val['count'], val['time'], val['location'], key) for key, val in list(counts.items()) if val['time'] > 0.01 or not filtersmall] results.sort(key=lambda x: (x[0], x[1]), reverse=True) total_count = 0 total_time = 0 out = '' for count, time, location, sql in results: if '' in location: location.remove('') out += "{: 4} / {:05.3f} [{}]: {}\n".format(int(count), time, _minilogbars(time), _indent_newlines('\n'.join(location), 22)) total_count += int(count) total_time += time if include_sql: out += "{}\n\n".format(colorize_sql(sql)) out += "{: 4} / {:05.3f} [{}] Total".format(total_count, total_time, _minilogbars(total_time)) log.info('counts: \n{}'.format(out)) def stack_position(): return ' > '.join([f[2] for f in traceback.extract_stack()]) # ADD THIS TO django > db > backends > utils.py > CursorDebugWrapper # self.db.queries_log.append({ # 'sql': sql, # 'time': "%.3f" % duration, # 'trace': stack_position(), # <-- THIS # }) # # def stack_position(): # import traceback # return traceback.extract_stack()# ' > '.join([f[2] for f in traceback.extract_stack()]) # STACK def format_stack(): # file, ln, function, text for frame in traceback.extract_stack(): simple_file = os.path.basename(frame[0]) print("{m:>20.20}:{l:<4} > {t}".format(f=frame[0], fs=simple_file, l=frame[1], m=frame[2], t=frame[3])) def format_stack2(): # file, ln, function, text prev_file = None for frame in traceback.extract_stack(): simple_file = os.path.basename(frame[0]) if simple_file == prev_file: print("{l:<4} > {t}".format(f=frame[0], fs=simple_file, l=frame[1], m=frame[2], t=frame[3])) else: print("{m:>20.20}:{l:<4} > {t}".format(f=frame[0], fs=simple_file, l=frame[1], m=frame[2], t=frame[3])) prev_file = simple_file
[ "mulderns@iki.fi" ]
mulderns@iki.fi
d018dae1106391a3d078188de5671e9268624e32
7dd3f071766dbac0fccaffa68644d86a1831e764
/chapter_1/p1_7.py
033399a950c867cd50ac57483f0f5d046e9cafd5
[]
no_license
gaokang9009/CTCI_python
22eb223d698e33b306bb21e16095d408363c3b2f
e28399c3b133af9913d0228c400aa67e4b113150
refs/heads/master
2023-01-04T13:44:51.936748
2020-09-23T21:09:57
2020-09-23T21:09:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
972
py
from typing import List def rotate(arr: List[List[int]]) -> List[List[int]]: rot_help(arr, 0, len(arr[0])-1, 0, len(arr)-1) return arr def rot_help(arr, xl, xh, yl, yh): if xl >= xh and yl >= yh: print(f"Shorting 0 or 1 wide at {xl} to {xh}") return else: rot_help(arr, xl+1, xh-1, yl+1, yh-1) side = xh-xl for i in range(side): print(f"{i} of {side} side, w/ x:{xl}-{xh} y:{yl}-{yh}") temp = arr[yl][xl+i] # Top left segment arr[yl][xl+i] = arr[yh-i][xl] # Trasition 1 arr[yh-i][xl] = arr[yh][xh-i] # Transition 2 arr[yh][xh-i] = arr[yl+i][xh] # Transition 3 arr[yl+i][xh] = temp # Top right end if __name__ == "__main__": ex1 = [[1, 2, 3], [8, 0, 4], [7, 6, 5]] rotate(ex1) for line in ex1: print(line) ex2 = [[1, 2], [3, 4]] rotate(ex2) for line in ex2: print(line)
[ "bogdan.stoicescu17@imperial.ac.uk" ]
bogdan.stoicescu17@imperial.ac.uk
812740cc28468da5b0b2168e7b0073a2145eca87
fb8c088fb460fdb31f766044883c752b6315c93e
/daily14/test_ratings_key.py
125bd7a5199bc706348c00b292f215c0ab33f117
[]
no_license
gjakubik/paradigmsCollaboration
9a3797e8dc73cef62995f7bb0677856be699f180
0e75c006e71e37c5f7e287d9d43e8f246f79857e
refs/heads/master
2023-01-02T17:25:46.272412
2020-10-26T18:32:56
2020-10-26T18:32:56
300,013,084
0
0
null
null
null
null
UTF-8
Python
false
false
1,082
py
import unittest import requests import json class TestRatings(unittest.TestCase): SITE_URL = 'http://localhost:51068' # replace with your port id print("Testing for server: " + SITE_URL) RATINGS_URL = SITE_URL + '/ratings/' RESET_URL = SITE_URL + '/reset/' def reset_data(self): m = {} r = requests.put(self.RESET_URL) def is_json(self, resp): try: json.loads(resp) return True except ValueError: return False def test_ratings_get_key(self): self.reset_data() movie_id = 32 r = requests.get(self.RATINGS_URL + str(movie_id)) #print("response is " + str(r.content.decode())) #debug self.assertTrue(self.is_json(r.content.decode())) resp = json.loads(r.content.decode()) self.assertEqual(resp['rating'], 3.945731303772336) # this is the value when user data is also considered #self.assertEqual(resp['rating'], 0.0) self.assertEqual(resp['movie_id'], movie_id) if __name__ == "__main__": unittest.main()
[ "gjakubik@nd.edu" ]
gjakubik@nd.edu
8df8770f43395ac195c0de00375b8098830b1db6
7670598360cdd28a75c17cbdc74eedcd2bcd916c
/driver/world.py
80934c961a8e764d2d7b47851cda81b2b2fc0046
[]
no_license
jordan-schneider/driver-env
d5663edffebd1acb4b53b81bff43a8a416152fa0
45a1c3ef478826ed33298f53bfa6d57d825b9e43
refs/heads/main
2023-06-05T01:06:34.891257
2021-06-17T01:40:42
2021-06-17T01:40:42
342,935,967
0
0
null
null
null
null
UTF-8
Python
false
false
7,876
py
"""Base class for driving scenarios.""" from typing import Any, Dict, Iterable, List, Optional, Tuple import numpy as np import tensorflow as tf from car.fixed_plan_car import FixedPlanCar, LegacyPlanCar # type: ignore from driver.car import Car class CarWorld: """ Contains the objects in a driving scenario - cars, lanes, obstacles, etc. In addition, contains a step() function that increments the state of the environment over time. Finally, this class provides visualizations for the environment. """ def __init__( self, dt: float = 0.1, lanes: Optional[List] = None, obstacles: Optional[List] = None, visualizer_args: Optional[Dict] = None, **kwargs ): """ Initializes this CarWorld. Note: the visualizer is *not* initialized until the first render() call. Args: dt: the time increment per tick of simulation. lanes: a list of lanes this world should contain. obstacles: a list of obstacles this world should contain. visualizer_args: a dict of arguments for the visualizer. **kwargs: """ self.cars: List[Car] = [] self.dt = dt if lanes is None: self.lanes = [] else: self.lanes = lanes if obstacles is None: self.obstacles = [] else: self.obstacles = obstacles if visualizer_args is None: self.visualizer_args = dict() else: self.visualizer_args = visualizer_args self.visualizer: Optional[Any] = None def add_car(self, car): car.index = len(self.cars) self.cars.append(car) def add_cars(self, cars: Iterable): for car in cars: self.add_car(car) @property def state(self): return [c.state for c in self.cars] @state.setter def state(self, new_state: Iterable): for c, x in zip(self.cars, new_state): c.state = x def reset(self): for car in self.cars: car.reset() if self.visualizer is not None: self.visualizer.reset() def step( self, dt: Optional[float] = None ) -> Tuple[List[tf.Tensor], List[tf.Tensor], List[tf.Tensor]]: """ Asks all cars to generate plans, and then updates the world state based on those plans We need to split the plan generation and car state updating because all the cars act at once (in the simulation) Args: dt: the amount of time to increment the simulation forward by. Returns: past_state: the previous state of the world, before this tick. controls: the controls applied to all the cars in this timestep. state: the current state of the world. """ past_state = self.state if dt is None: dt = self.dt for car in self.cars: if not car.control_already_determined_for_current_step: car.set_next_control() for car in self.cars: car.step(dt) return past_state, [c.control for c in self.cars], self.state def render(self, mode: str = "human", heatmap_show=False) -> Optional[np.ndarray]: """ Renders the state of this car world. If mode="human", we display it using the visualizer. If mode="rgb_array", we return a np.array with shape (x, y, 3) representing RGB values, useful for making gifs and videos. Note: we currently assume that the main car is the first car in self.cars. Args: mode: One of ["human", "rgb_array"]. Returns: rgb_representation: if str="rgb_array", we return an np.array of shape (x, y, 3), representing the rendered image. TODO(chanlaw): add support for terminal visualization """ if self.visualizer is None: from driver.visualizer import CarVisualizer self.visualizer = CarVisualizer(world=self, **self.visualizer_args) self.visualizer.set_main_car(index=0) if mode == "human": self.visualizer.render(display=True, return_rgb=False, heatmap_show=heatmap_show) return None elif mode == "rgb_array": return self.visualizer.render(display=False, return_rgb=True, heatmap_show=heatmap_show) else: raise ValueError("Mode must be either `human` or `rgb_array`.") class ThreeLaneCarWorld(CarWorld): """ A car world initialized with three straight lanes that extend for a long while in either direction. """ def __init__(self, dt=0.1, **kwargs): self.lane_width = 0.17 lane = StraightLane((0.0, -5.0), (0.0, 10.0), self.lane_width) lanes = [lane.shifted(1), lane, lane.shifted(-1)] super().__init__(dt=dt, lanes=lanes, **kwargs) class TwoTrajectoryWorld(ThreeLaneCarWorld): def __init__(self, dt, good_plan, bad_plan, **kwargs): super().__init__( dt=dt, visualizer_args={"legacy_state": True, "follow_main_car": True}, **kwargs ) # state = [x, y, angel, vel] self.good_car = FixedPlanCar( env=self, init_state=[0.0, -0.3, np.pi / 2.0, 0.4], plan=good_plan, color="blue", legacy_state=True, ) self.bad_car = FixedPlanCar( env=self, init_state=[0.0, -0.3, np.pi / 2.0, 0.4], plan=bad_plan, color="red", legacy_state=True, ) self.other_car = LegacyPlanCar(env=self) self.add_cars([self.good_car, self.bad_car, self.other_car]) class TwoLaneCarWorld(CarWorld): def __init__(self, dt=0.1, **kwargs): lane = StraightLane((-0.05, -5.0), (-0.05, 10.0), 0.1) lanes = [lane, lane.shifted(-1)] super().__init__(dt=dt, lanes=lanes, **kwargs) class StraightLane(object): """ Defines a lane with median defined by the line segment between points p and q, and width w. TODO(chanlaw): need to implement roads that aren't line segments """ def __init__(self, p: Tuple[float, float], q: Tuple[float, float], w: float): """ Initializes the straight lane. Args: p: the x,y coordinates of the start point for the center of the lane q: the x,y coordinates of the end point for the center of the lane w: the width of the lane """ self.p = np.asarray(p) self.q = np.asarray(q) self.w = w self.m = (self.q - self.p) / np.linalg.norm( self.q - self.p ) # unit vector in direction of lane self.n = np.asarray([-self.m[1], self.m[0]]) # normal vector to the lane def shifted(self, n_lanes: int): """ Returns a lane that is shifted n_lanes in the direction of self.n. When n_lanes < 0, this is shifted in the other direction instead. Args: n_lanes: number of lanes to shift Returns: (StraightLane): a straight lane shifted in the appropriate way. """ return StraightLane( self.p + self.n * self.w * n_lanes, self.q + self.n * self.w * n_lanes, self.w ) def dist2median(self, point: Tuple[float, float]): """ Returns the squared distance of a point to the median of the lane. Args: point: the x,y coordinates of the point. Returns: (float): the distance to the median of this lane """ r = (point[0] - self.p[0]) * self.n[0] + (point[1] - self.p[1]) * self.n[1] return r ** 2 def on_road(self, point): raise NotImplementedError
[ "jordan.jack.schneider@gmail.com" ]
jordan.jack.schneider@gmail.com
895889f61a87b66537421257604f1a6e97cb00b0
91ff50a612aaa081ed89dc6ce529ddcac3a054cb
/scripts/cluster_init.py
4e9c3384aca2a6ada678726a1fd31535f34b4539
[]
no_license
wgantt/event_type_induction
85f13715a39683015670d290196cedd0e46dd394
52959012756efb5a1bd328e35ff4094a2722a555
refs/heads/master
2023-08-04T06:51:19.273433
2021-09-12T19:36:37
2021-09-12T19:52:42
286,784,794
7
0
null
null
null
null
UTF-8
Python
false
false
38,703
py
# Package external imports import argparse from decomp import UDSCorpus import numpy as np import random from sklearn.mixture import GaussianMixture import torch from torch.nn import Parameter, ParameterDict, Module from typing import List # Package internal imports from event_type_induction.constants import * from event_type_induction.modules.vectorized_likelihood import * from scripts.setup_logging import setup_logging from event_type_induction.utils import * LOG = setup_logging() class GMM: def __init__( self, uds: UDSCorpus, random_seed: int = 42, use_ordinal: bool = False, device: str = "cpu", ): """Gaussian mixture model over UDS properties Parameters ---------- uds the UDSCorpus random_seed optional random seed to use for the mixture model use_ordinal determines whether ordinal properties should actually be represented as scalar interval values or as categorical ones device the device on which data tensors are to be created """ self.uds = uds self.s_metadata = self.uds.metadata.sentence_metadata self.d_metadata = self.uds.metadata.document_metadata self.random_seed = random_seed self.use_ordinal = use_ordinal self.device = device self.str_to_category = { cat: idx for idx, cat in enumerate( self.uds.metadata.sentence_metadata["time"]["duration"].value.categories ) } self.annotation_func_by_type = { Type.EVENT: self.get_event_annotations, Type.PARTICIPANT: self.get_participant_annotations, Type.ROLE: self.get_role_annotations, Type.RELATION: self.get_relation_annotations, } def get_annotations( self, t: Type, data: List[str], confidences: Dict[str, Dict[int, float]], property_means: Dict[str, np.ndarray], device: str = "cpu", ): """Retrieves annotations from a UDSCorpus for a specified type Should definitely be factored out into utils or something; I just haven't taken the time yet. Parameters ---------- t the type for which annotations should be retrieved data a list of identifiers for UDSSentenceGraphs, for which the annotations are to be retrieved confidences ridit-scored confidence values for each annotator, keyed on annotator name. Nested dict property_means pre-computed mean values for each property; these are used to impute missing annotations for each item device the device on which all the tensors are to be created """ # Averaged annotations for each item all_annotations = [] # Maps properties to a range of indices in the annotation vector # for each item properties_to_indices = {} # All (raw) annotations, grouped by property annotations_by_property = DefaultOrderedDict(list) # Annotators corresponding to each annotation in annotations_by_property annotators_by_property = DefaultOrderedDict(list) # Confidence scores for each annotation in annotations_by_property confidences_by_property = DefaultOrderedDict(list) # Item IDs corresponding to each annotation in annotations_by_property items_by_property = DefaultOrderedDict(list) # Maps integer IDs to UDS node/edge names idx_to_item = DefaultOrderedDict(str) # Unique annotators for each property unique_annotators_by_property = DefaultOrderedDict(set) # The length of a full annotation vector anno_vec_len = 0 # Counts total nodes or edges item_ctr = 0 for name in data: graph = self.uds[name] for item, anno in get_item_iter(graph, t): anno_vec = [] annotation_found = False if t == Type.ROLE and ( ("protoroles" not in anno) or ("distributivity" not in anno) ): # We subset to only those edges annotated for both # protoroles and distributivity to avoid having to # do heavy imputation continue for subspace in sorted(SUBSPACES_BY_TYPE[t]): for p in sorted(self.s_metadata.properties(subspace)): prop_dim = get_prop_dim( self.s_metadata, subspace, p, use_ordinal=self.use_ordinal ) vec = np.zeros(prop_dim) # The genericity subspace includes properties associated # with both events and participants. We need to mask the # ones that aren't relevant in each case if (t == Type.EVENT and "arg" in p) or ( t == Type.PARTICIPANT and "pred" in p ): continue # The distributive property is listed under the event_structure # subspace, but is not relevant to event types if t == Type.EVENT and p == "distributive": continue # Associate the current property with a range of indices # in the annotation vector if p not in properties_to_indices: properties_to_indices[p] = np.array( [anno_vec_len, anno_vec_len + prop_dim] ) anno_vec_len += prop_dim # Process annotations for this item only if they actually exist n_annos = 0 # number of annotations for this item if subspace in anno and p in anno[subspace]: annotation_found = True for a, value in anno[subspace][p]["value"].items(): # Confidence for current annotation # --------------------------------- conf = anno[subspace][p]["confidence"][a] ridit_conf = confidences[a] if ( ridit_conf is None or ridit_conf.get(conf) is None or ridit_conf[conf] < 0 ): # invalid confidence values; default to 1 ridit_conf = 1 else: ridit_conf = ridit_conf.get(conf, 1) # Value for current annotation # ---------------------------- # Special case 1: None values (i.e. property was annotated as "doesn't apply") if value is None: # This should only be true of conditional properties assert ( p in CONDITIONAL_PROPERTIES ), f"unexpected None value for property {p}" # If this is an ordinal property, and we're treating ordinal variables # as such, we set the "does not apply" value to the mean ordinal value if ( self.use_ordinal and self.s_metadata[subspace][ p ].value.is_ordered_categorical ): val = np.nan # Otherwise, the "does not apply" case corresponds to the last category # when treating ordinal variables nominally. else: val = prop_dim - 1 # Special case 2: String values (should only be duration annotations) elif isinstance(value, str): assert ( p == "duration" ), f"unexpected string value for property {p}" val = self.str_to_category[value] # Special case 3: Protoroles properties elif subspace == "protoroles": if conf == 0: if self.use_ordinal: val = np.nan ridit_conf = conf else: val = prop_dim - 1 ridit_conf = 1 else: val = value ridit_conf = 1 # Default case: all other properties else: val = value if prop_dim == 1: # binary or ordinal if not self.s_metadata[subspace][ p ].value.is_ordered_categorical: assert ( val == 0 or val == 1 ), f"non-binary value for binary property {p}" if not np.isnan(val): vec[0] += val else: # categorical vec[val] += 1 # Raw annotations and confidences by property annotations_by_property[p].append(val) items_by_property[p].append(item_ctr) idx_to_item[item_ctr] = item annotator_num = int(a.split("-")[-1]) annotators_by_property[p].append(annotator_num) unique_annotators_by_property[p].add(annotator_num) confidences_by_property[p].append(ridit_conf) if not np.isnan(val): n_annos += 1 else: # No annotation for this property, so just use the mean vec = property_means[p] # Compute average annotation for this item; for all # train data, there will be only one annotation """ assert ( n_annos <= 3 ), f"{n_annos} annotations found for property {p} on item {item}" """ anno_vec.append(vec / max(n_annos, 1)) # Append current annotation vector to list of all # annotation vectors (but only if we actually found # relevant annotations) if annotation_found: all_annotations.append(np.concatenate(anno_vec)) item_ctr += 1 return ( np.stack(all_annotations), properties_to_indices, { p: torch.FloatTensor(np.stack(v)).to(device) for p, v in annotations_by_property.items() }, { p: torch.LongTensor(np.array(v)).to(device) for p, v in items_by_property.items() }, idx_to_item, { p: torch.FloatTensor(np.array(v)).to(device) for p, v in confidences_by_property.items() }, { p: torch.LongTensor(np.array(v)).to(device) for p, v in annotators_by_property.items() }, unique_annotators_by_property, ) def get_event_annotations( self, data: List[str], confidences: Dict[str, Dict[int, float]], property_means: Dict[str, np.ndarray], device: str = "cpu", ): return self.get_annotations( Type.EVENT, data, confidences, property_means, device ) def get_participant_annotations( self, data: List[str], confidences: Dict[str, Dict[int, float]], property_means: Dict[str, np.ndarray], device: str = "cpu", ): return self.get_annotations( Type.PARTICIPANT, data, confidences, property_means, device ) def get_role_annotations( self, data: List[str], confidences: Dict[str, Dict[int, float]], property_means: Dict[str, np.ndarray], device: str = "cpu", ): return self.get_annotations( Type.ROLE, data, confidences, property_means, device ) def get_relation_annotations( self, data: List[str], confidences: Dict[str, Dict[int, float]], property_means: Dict[str, np.ndarray], device: str = "cpu", ): all_annotations = [] annotations_by_property = DefaultOrderedDict(list) items_by_property = DefaultOrderedDict(list) idx_to_item = DefaultOrderedDict(str) annotators_by_property = DefaultOrderedDict(list) unique_annotators_by_property = DefaultOrderedDict(set) confidences_by_property = DefaultOrderedDict(list) properties_to_indices = {} anno_vec_len = 0 item_ctr = 0 for dname in data: graph = self.uds.documents[dname].document_graph for edge, anno in sorted(graph.edges.items()): anno_vec = [] if "mereology" in anno and "time" not in anno: continue for subspace in sorted(SUBSPACES_BY_TYPE[Type.RELATION]): for p in sorted(self.d_metadata.properties(subspace)): vec = np.zeros(1) n_annos = 0 # Associate this property with a range of indices in the type vector if p not in properties_to_indices: properties_to_indices[p] = np.array( [anno_vec_len, anno_vec_len + 1] ) anno_vec_len += 1 # Collect annotation and confidence if subspace in anno and p in anno[subspace]: for a, value in sorted(anno[subspace][p]["value"].items()): # Get confidence for this annotation conf = anno[subspace][p]["confidence"][a] ridit_conf = confidences[a].get(conf, 1) # Get value vec += value # Bookkeeping n_annos += 1 annotations_by_property[p].append(value) items_by_property[p].append(item_ctr) idx_to_item[item_ctr] = edge annotator_num = int(a.split("-")[-1]) annotators_by_property[p].append(annotator_num) unique_annotators_by_property[p].add(annotator_num) confidences_by_property[p].append(ridit_conf) else: # Since mereology annotations were conditioned on # temporal containment, if they don't occur in a # given annotation, there cannot be mereological # containment, so we default to zero. assert subspace == "mereology" vec = torch.zeros(1) # Average annotation for this item anno_vec.append(vec / max(n_annos, 1)) all_annotations.append(np.concatenate(anno_vec)) item_ctr += 1 return ( np.stack(all_annotations), properties_to_indices, { p: torch.FloatTensor(np.stack(v)).to(device) for p, v in annotations_by_property.items() }, { p: torch.LongTensor(np.array(v)).to(device) for p, v in items_by_property.items() }, idx_to_item, { p: torch.FloatTensor(np.array(v)).to(device) for p, v in confidences_by_property.items() }, { p: torch.LongTensor(np.array(v)).to(device) for p, v in annotators_by_property.items() }, unique_annotators_by_property, ) def fit( self, data: List[str], t: Type, n_components: int, confidences: Dict[str, Dict[int, float]], ) -> GaussianMixture: gmm = GaussianMixture(n_components, random_state=self.random_seed) if t == Type.RELATION: property_means = None else: property_means = get_sentence_property_means( self.uds, data, t, use_ordinal=self.use_ordinal ) ( average_annotations, properties_to_indices, annotations_by_property, items_by_property, idx_to_item, confidences_by_property, annotators_by_property, unique_annotators_by_property, ) = self.annotation_func_by_type[t]( data, confidences, property_means, self.device ) gmm = gmm.fit(average_annotations) LOG.info( f"GMM average train LL for {n_components} components: {gmm.score(average_annotations)}" ) # Probably shouldn't be returning all these things from a call to # "fit", but didn't want to have to separately call the annotation # getter function again return ( gmm, average_annotations, properties_to_indices, annotations_by_property, items_by_property, idx_to_item, confidences_by_property, annotators_by_property, unique_annotators_by_property, ) class MultiviewMixtureModel(Module): def __init__( self, uds: UDSCorpus, random_seed: int = 42, use_ordinal: bool = False, device: str = "cpu", ): super(MultiviewMixtureModel, self).__init__() self.uds = uds self.random_seed = random_seed self.s_metadata = self.uds.metadata.sentence_metadata self.d_metadata = self.uds.metadata.document_metadata self.type_to_likelihood = { Type.EVENT: PredicateNodeAnnotationLikelihood, Type.PARTICIPANT: ArgumentNodeAnnotationLikelihood, Type.ROLE: SemanticsEdgeAnnotationLikelihood, Type.RELATION: DocumentEdgeAnnotationLikelihood, } self.type_to_annotator_ids = { Type.EVENT: load_pred_node_annotator_ids, Type.PARTICIPANT: load_arg_node_annotator_ids, Type.ROLE: load_sem_edge_annotator_ids, Type.RELATION: load_doc_edge_annotator_ids, } self.mus = None self.component_weights = None self.random_effects = None self.final_train_posteriors = None self.final_dev_posteriors = None self.train_idx_to_item = None self.dev_idx_to_item = None self.use_ordinal = use_ordinal self.device = device def _init_mus( self, t: Type, gmm_means: np.ndarray, props_to_indices: Dict[str, np.ndarray], n_components: int, ) -> None: mu_dict = {} if t == Type.RELATION: metadata = self.d_metadata else: metadata = self.s_metadata for subspace in SUBSPACES_BY_TYPE[t]: for p in metadata.properties(subspace): # Random effects for relation types handled below if "rel-" in p: continue # Restrict genericity to either argument or predicate # depending on the type we're clustering on if (t == Type.EVENT and "arg" in p) or ( t == Type.PARTICIPANT and "pred" in p ): continue # Most means for the mixture model are set based on # the GMM means start, end = props_to_indices[p] mu = torch.FloatTensor(gmm_means[:, start:end]) min_mean = torch.ones(mu.shape) * MIN_MEAN mu = torch.where(mu > MIN_MEAN, mu, min_mean) # We apply different mean initialization strategies based on # property type is_ordinal = metadata[subspace][p].value.is_ordered_categorical if self.use_ordinal and is_ordinal: # Ordinal conditional properties are modeled using a hurdle # model, so we initialize a mean for the Bernoullis that # indicate whether the property applies or not. if p in CONDITIONAL_PROPERTIES: mu_applies = Parameter(logit(torch.ones(n_components) * 0.5)) mu_dict[p.replace(".", "-") + "-applies"] = mu_applies # For all ordinal properties, we subtract off the median # of the ordinal scale (this is 2 for protoroles) if subspace == "protoroles": median = 2 else: median = len(metadata[subspace][p].value.categories) // 2 mu -= median # For binary properties, we apply a logit to the GMM mean elif mu.shape[-1] == 1: mu = logit(mu) # All other means are stored in log form else: mu = torch.log(mu) mu_dict[p.replace(".", "-")] = Parameter(mu) if t == Type.RELATION: # Randomly initialize probabilities that # 1. The events' start points are locked to 0. # 2. The events' end points are locked to 100. # 3. The events' midpoints are locked to each other. # Note: I tried an initialization based on the GMM clusters, # but this led to radical overfitting. # The three dimensions of these distributions correspond # to the probabilities that 1) both points are locked; 2) only # e1's point is locked; 3) only e2's point is locked mu_dict["time-lock_start_mu"] = Parameter( torch.log(torch.softmax(torch.randn((n_components, 3)), -1)) ) mu_dict["time-lock_end_mu"] = Parameter( torch.log(torch.softmax(torch.randn((n_components, 3)), -1)) ) # The three dimensions of these distributions correspond to # the probabailities that 1) e1's midpoint equals e2's midpoint; # 2) e1's midpoint comes before e2's; 3) e2's comes before e1's. mu_dict["time-lock_mid_mu"] = Parameter( torch.log(torch.softmax(torch.randn((n_components, 3)), -1)) ) self.mus = ParameterDict(mu_dict).to(self.device) def _get_annotator_ridits( self, data: List[str], t: Type ) -> Dict[str, Dict[int, float]]: annotator_ids = self.type_to_annotator_ids[t](self.uds) if t == Type.RELATION: ridits = ridit_score_confidence(self.uds, sents=data) else: ridits = ridit_score_confidence(self.uds, docs=data) return {a: ridits.get(a) for a in annotator_ids} def fit( self, data: Dict[str, List[str]], t: Type, n_components: int, iterations: int = 10000, lr: float = 0.001, clip_min_ll=False, confidence_weighting=False, patience: int = 1, verbosity: int = 10, ) -> "MultiviewMixtureModel": random.seed(self.random_seed) torch.manual_seed(self.random_seed) LOG.info( f"Fitting model on type {t.name} using {n_components} components on device {self.device}" ) LOG.info("Fitting GMM...") train_confidences = self._get_annotator_ridits(data["train"], t) train_gmm = GMM(self.uds, use_ordinal=self.use_ordinal, device=self.device) ( gmm, train_avg_annotations, train_properties_to_indices, train_annotations_by_property, train_items_by_property, self.train_idx_to_item, train_confidences_by_property, train_annotators_by_property, train_unique_annotators_by_property, ) = train_gmm.fit(data["train"], t, n_components, train_confidences) LOG.info("...GMM fitting complete") LOG.info("Loading dev data...") dev_confidences = self._get_annotator_ridits(data["dev"], t) # Determine the total number of train items annotated across all properties train_items = set() for train_item in train_items_by_property.values(): train_items |= set(train_item.tolist()) total_train_items = len(train_items) train_items = torch.LongTensor(list(train_items)).to(self.device) if t == Type.RELATION: dev_property_means = None else: dev_property_means = get_sentence_property_means( self.uds, data["dev"], t, self.use_ordinal ) ( dev_avg_annotations, dev_properties_to_indices, dev_annotations_by_property, dev_items_by_property, self.dev_idx_to_item, dev_confidences_by_property, dev_annotators_by_property, dev_unique_annotators_by_property, ) = train_gmm.annotation_func_by_type[t]( data["dev"], dev_confidences, dev_property_means, device=self.device ) # Determine the total number of dev items annotated across all properties dev_items = set() for dev_item in dev_items_by_property.values(): dev_items |= set(dev_item.tolist()) total_dev_items = len(dev_items) dev_items = torch.LongTensor(list(dev_items)).to(self.device) LOG.info("...Complete.") LOG.info(f"total train items: {total_train_items}") LOG.info(f"total dev items: {total_dev_items}") # verify that annotations and confidence values are as expected assert ( train_annotations_by_property.keys() == train_confidences_by_property.keys() ) for p in train_annotations_by_property: anno_len = len(train_annotations_by_property[p]) conf_len = len(train_confidences_by_property[p]) num_annotators = len(train_annotators_by_property[p]) assert ( anno_len == conf_len ), f"mismatched annotation and confidence lengths ({anno_len} and {conf_len}) for property {p}" assert ( num_annotators == anno_len ), f"mismatched annotation and annotator lengths ({anno_len} and {num_annotators})" # Determine which annotators in dev are also in train # This is necessary for determining the appropriate random # effects for each annotator dev_annotators_in_train = {} for p, dev_annos in dev_annotators_by_property.items(): new_dev = len( dev_unique_annotators_by_property[p] - train_unique_annotators_by_property[p] ) train_annos = train_unique_annotators_by_property[p] dev_annotators_in_train[p] = torch.BoolTensor( [a.item() in train_annos for a in dev_annos] ) train_unique_annotators_by_property[p] = torch.LongTensor( list(train_unique_annotators_by_property[p]) ) # Get the right type of property metadata (document metadata for # relation types; sentence metadata for everything else) if t == Type.RELATION: metadata = self.d_metadata else: metadata = self.s_metadata # Initialize Likelihood module, property means, # annotator random effects, and component weights ll = self.type_to_likelihood[t]( train_confidences, metadata, n_components, use_ordinal=self.use_ordinal, clip_min_ll=clip_min_ll, confidence_weighting=confidence_weighting, device=self.device, ) self._init_mus(t, gmm.means_, train_properties_to_indices, n_components) self.random_effects = ll.random_effects self.component_weights = Parameter( torch.log(torch.FloatTensor(gmm.weights_)).to(self.device) ) optimizer = torch.optim.Adam(self.parameters(), lr=lr) min_train_fixed_loss = float("inf") min_dev_fixed_loss = float("inf") iters_without_improvement = 0 LOG.info(f"Beginning training for {iterations} epochs") for i in range(iterations): # training _, train_ll = ll( self.mus, train_annotations_by_property, train_items_by_property, train_annotators_by_property, train_confidences_by_property, ) # per-type likelihoods for all items train_fixed_loss = train_ll # add in prior over components prior = exp_normalize(self.component_weights)[:, None] train_posteriors = train_fixed_loss[:, train_items] + prior # logsumexp over all components to get log-evidence for each item train_fixed_loss = ( -torch.logsumexp(train_posteriors, 0).sum() / total_train_items ) # add in random loss, backprop, and take gradient step train_random_loss = ll.random_loss() train_loss = train_fixed_loss + train_random_loss train_loss.backward() optimizer.step() # train logging if i % verbosity == 0: LOG.info( f"component weights: {torch.exp(exp_normalize(self.component_weights))}" ) LOG.info(f"Epoch {i} train log prior: {self.component_weights.data}") LOG.info(f"Epoch {i} train log likelihood: {train_ll.mean(-1)}") LOG.info( f"Epoch {i} train fixed loss: {np.round(train_fixed_loss.item(), 5)}" ) LOG.info( f"Epoch {i} train random loss: {np.round(train_random_loss.item(), 5)}" ) # eval with torch.no_grad(): _, dev_ll = ll( self.mus, dev_annotations_by_property, dev_items_by_property, dev_annotators_by_property, dev_confidences_by_property, train_unique_annotators_by_property, dev_annotators_in_train, ) # dev fixed loss computed the same way as train dev_fixed_loss = dev_ll dev_posteriors = dev_fixed_loss[:, dev_items] + prior dev_fixed_loss = ( -torch.logsumexp(dev_posteriors, 0).sum() / total_dev_items ) if i % verbosity == 0: LOG.info( f"Epoch {i} dev fixed loss: {np.round(dev_fixed_loss.item(), 5)}" ) # stop early if no improvement in dev if dev_fixed_loss < min_dev_fixed_loss: min_dev_fixed_loss = dev_fixed_loss iters_without_improvement = 0 else: iters_without_improvement += 1 # since we're doing full GD, there's no real sense in setting # patience to anything other than 1 if iters_without_improvement == patience: self.final_train_posteriors = train_posteriors self.final_dev_posteriors = dev_posteriors LOG.info( f"No improvement in dev LL for model with {n_components} components after {patience} iterations. Stopping early." ) LOG.info( f"Final component weights (epoch {i}): {torch.exp(exp_normalize(self.component_weights))}" ) LOG.info( f"Final train fixed loss (epoch {i}): {np.round(train_fixed_loss.item(), 5)}" ) LOG.info( f"Final dev fixed loss (epoch {i}): {np.round(dev_fixed_loss.item(), 5)}" ) return self.eval() LOG.info(f"Max iterations reached") LOG.info( f"Final component weights (epoch {i}): {torch.exp(exp_normalize(self.component_weights))}" ) LOG.info( f"Final train fixed loss (epoch {i}): {np.round(train_fixed_loss.item(), 5)}" ) LOG.info( f"Final dev fixed loss (epoch {i}): {np.round(dev_fixed_loss.item(), 5)}" ) self.final_train_posteriors = train_posteriors self.final_dev_posteriors = dev_posteriors return self.eval() def main(args): assert ( args.min_types <= args.max_types ), f"min types must be less than or equal to max!" # Load UDS and initialize the mixture model uds = UDSCorpus(version="2.0", annotation_format="raw") load_event_structure_annotations(uds) # Define train and dev splits t = STR_TO_TYPE[args.type.upper()] if t == Type.RELATION: train = sorted( set([graph.document_id for name, graph in uds.items() if "train" in name]) ) dev = sorted( set([graph.document_id for name, graph in uds.items() if "dev" in name]) ) else: train = [s for s in uds if "train" in s] dev = [s for s in uds if "dev" in s] data = {"train": train, "dev": dev} LOG.info( f"Fitting mixture model with all types in range {args.min_types} to {args.max_types}, inclusive" ) model_root = args.model_name if args.model_name is not None else t.name for n_components in range(args.min_types, args.max_types + 1): # Initialize and fit the model mmm = MultiviewMixtureModel(uds, use_ordinal=True, device=args.device) model_name = model_root + "-" + str(n_components) + ".pt" mmm = mmm.fit( data, t, n_components, clip_min_ll=args.clip_min_ll, confidence_weighting=args.weight_by_confidence, patience=args.patience, ) # Save it save_model(mmm.state_dict(), args.model_dir, model_name) # Dump property means to file if args.dump_means: means_file = "-".join([model_root, str(n_components), "means"]) + ".csv" means_file = os.path.join(args.model_dir, means_file) dump_params(means_file, mmm.mus) # Dump per-item posteriors to file if args.dump_posteriors: posteriors_file = ( "-".join([model_root, str(n_components), "posteriors"]) + ".csv" ) posteriors_file = os.path.join(args.model_dir, posteriors_file) dump_mmm_posteriors( posteriors_file, mmm.final_train_posteriors, mmm.train_idx_to_item, mmm.final_dev_posteriors, mmm.dev_idx_to_item, ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("type", type=str, help="the type to cluster on") parser.add_argument( "min_types", type=int, help="minimum of range of numbers of types to try" ) parser.add_argument( "max_types", type=int, help="maximum of range of numbers of types to try" ) parser.add_argument( "--model_name", type=str, help="name for model checkpoint files" ) parser.add_argument( "--model_dir", type=str, default="/data/wgantt/event_type_induction/checkpoints/", help="path to directory where checkpoint files are to be saved", ) parser.add_argument( "--dump_means", action="store_true", help="dump MMM property means to file", ) parser.add_argument( "--dump_posteriors", action="store_true", help="dump per-item MMM (log) posteriors to file", ) parser.add_argument( "--clip_min_ll", action="store_true", help="clip all likelihoods to a minimum value", ) parser.add_argument( "--weight_by_confidence", action="store_true", help="weight likelihoods by annotator confidence", ) parser.add_argument( "--patience", type=int, default=1, help="number of epochs tolerated without dev improvement", ) parser.add_argument("--device", type=str, default="cpu") args = parser.parse_args() main(args)
[ "wgantt.iv@gmail.com" ]
wgantt.iv@gmail.com
e47e26a1d21f99e42e90ad7c55badcdb1476659d
cbfb8897956669c1b3d12df21b98e32b4eedb74a
/api/app/models/base_model.py
533e43772754174f31143bd563a16122deea19b5
[]
no_license
jorgi710/PruebaAndres
1c449b61079b7a4239b66a19a3a66479561518cd
849d80a231ca210df3c7740a90180656d31fefb9
refs/heads/master
2023-08-24T04:50:40.374300
2021-10-30T17:08:15
2021-10-30T17:08:15
422,941,450
0
0
null
null
null
null
UTF-8
Python
false
false
1,449
py
# -*- coding: utf-8 -*- ######################################################### from datetime import datetime from app import db from app.exception import InternalServerError class BaseModel(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True, nullable=False) create_date = db.Column(db.DateTime, default=db.func.now(), comment='Fecha de creación') update_date = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now(), comment='Fecha de Actualización') def delete(self): try: db.session.delete(self) db.session.commit() except Exception as e: print(e) db.session.rollback() raise InternalServerError(e) def save(self): try: self.create_date = datetime.now() self.update_date = datetime.now() db.session.add(self) db.session.flush() db.session.commit() return self except Exception as e: print(e) db.session.rollback() raise InternalServerError(e) def update(self): try: self.update_date = datetime.now() db.session.add(self) db.session.flush() db.session.commit() return self except Exception as e: print(e) db.session.rollback() raise InternalServerError(e)
[ "jorgi710@hotmail.com" ]
jorgi710@hotmail.com
6a58e63d91a21db344180ef94deea98046c9a6e6
b27e4c2f80f306fe758d77a03a9d626e5eea77cc
/zuri_one.py
ec60691af1f5a6acdbc6ace6b21860a76a05b56c
[]
no_license
Fredricknjeri/zuri_atm
8e4919c2580486f661531620b46ec1d3f9098582
fc6da81986083cfae33330e4ac3bf786248c9169
refs/heads/main
2023-04-18T16:07:05.404796
2021-04-24T13:25:09
2021-04-24T13:25:09
361,167,429
0
0
null
null
null
null
UTF-8
Python
false
false
2,287
py
from datetime import datetime import time import sys username = input('What is your name?\n') allowed_users = ['Fred', 'Monic', 'Tony','Mary'] passwords = ['fredpass','monicpass','tonypass','marypass'] amount = [50000,40000,100000,80000] #progressbar def update_progress(progress): print('Processing...') for i in range(progress +1): time.sleep(0.01) sys.stdout.write("\r%d%%" % i) sys.stdout.flush() print('') def goodbye(): print('Thank you for your time, Goodbye!') if(username in allowed_users): auth = input('Please enter your password:\n') userId = allowed_users.index(username) if( auth == passwords[userId]): print('Welcome', username) print('These are the available of options:') print('1. Withdraw') print('2. Deposit') print('3. Complaint') #task 1 timenow = datetime.now() now = timenow.strftime("%d/%m/%Y %H:%M:%S") print(now) selectedOption = int(input('Please select an option:\n')) if(selectedOption == 1) : print('You selected %s' %selectedOption) withdraw_amount= int(input('How much do you want to withdraw:\n')) update_progress(100) print('take your cash') currentbalance = amount[userId] - withdraw_amount print('Your current balance:%d' %currentbalance) time.sleep(1) goodbye() elif(selectedOption == 2): print('You selected %s' %selectedOption) deposit_amount = int(input('How much would you like to deposit?\n')) update_progress(100) time.sleep(1) currentbalance = amount[userId] + deposit_amount print('Current balance: %d' %currentbalance) goodbye() elif(selectedOption == 3): print('You selected %s' %selectedOption) report = input('What issue will you like to report?\n') time.sleep(2) print('Thank you for contacting us') else: print('Invalid option, Try again') else: print('Enter correct password!') else: print("You are not allowed to user the system!")
[ "fredricknjeri@Fredricks-MacBook-Pro.local" ]
fredricknjeri@Fredricks-MacBook-Pro.local
786b1d757a1cff4c034b72055eedc3bf6af0e80e
95842c10eebe5cfb3e97bbe13134517180367bea
/venv/Scripts/pip3-script.py
ac080d5977424b134355c53cd6c27f1c0f045566
[]
no_license
linaGitHub1/PyCharmProjects
0fd2c0ebe3a2db9a0256d492364ea5b021686494
e3953413b97f14abeb979baf8b9b801a9ac6ccd9
refs/heads/master
2021-01-04T06:00:42.300307
2020-02-14T06:56:41
2020-02-14T06:56:41
240,420,145
0
0
null
null
null
null
UTF-8
Python
false
false
406
py
#!D:\PyCharm\Lina\PyCharmProjects\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')() )
[ "lina_lemon@163.com" ]
lina_lemon@163.com
29689d82e65139fffd325b2517ea32a511041d38
9734c93c86c982b1ce046340bac9e53645b261b8
/tests/formatters/yaml_formatters_file.py
f69655c1080aa94b6d70e50bbc0002921e12694b
[ "Apache-2.0" ]
permissive
log2timeline/plaso
cd72dd407d6c5627506c14f58cb8f6a6926aa808
d6022f8cfebfddf2d08ab2d300a41b61f3349933
refs/heads/main
2023-09-02T08:43:48.241198
2023-08-19T07:28:12
2023-08-19T07:28:12
23,812,315
1,506
421
Apache-2.0
2023-09-04T08:24:53
2014-09-08T23:29:28
Python
UTF-8
Python
false
false
3,363
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the YAML-based formatters file.""" import io import unittest from plaso.formatters import yaml_formatters_file from plaso.lib import errors from tests import test_lib as shared_test_lib class YAMLFormattersFileTest(shared_test_lib.BaseTestCase): """Tests for the YAML-based formatters file.""" # pylint: disable=protected-access _FORMATTERS_YAML = { 'type': 'conditional', 'data_type': 'test:fs:stat', 'message': [ '{display_name}', 'Type: {file_entry_type}', '({unallocated})'], 'short_message': [ '{filename}'], 'short_source': 'SOURCE', 'source': 'My Custom Log Source'} def testReadFormatterDefinition(self): """Tests the _ReadFormatterDefinition function.""" test_formatters_file = yaml_formatters_file.YAMLFormattersFile() formatter = test_formatters_file._ReadFormatterDefinition( self._FORMATTERS_YAML) self.assertIsNotNone(formatter) self.assertEqual(formatter.data_type, 'test:fs:stat') with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({'type': 'bogus'}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({'type': 'conditional'}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({ 'type': 'conditional', 'data_type': 'test:fs:stat'}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({ 'type': 'conditional', 'data_type': 'test:fs:stat', 'message': [ '{display_name}', 'Type: {file_entry_type}', '({unallocated})']}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({ 'type': 'conditional', 'data_type': 'test:fs:stat', 'message': [ '{display_name}', 'Type: {file_entry_type}', '({unallocated})']}) with self.assertRaises(errors.ParseError): test_formatters_file._ReadFormatterDefinition({'bogus': 'error'}) def testReadFromFileObject(self): """Tests the _ReadFromFileObject function.""" test_file_path = self._GetTestFilePath(['formatters', 'format_test.yaml']) self._SkipIfPathNotExists(test_file_path) test_formatters_file = yaml_formatters_file.YAMLFormattersFile() with io.open(test_file_path, 'r', encoding='utf-8') as file_object: formatters = list(test_formatters_file._ReadFromFileObject(file_object)) self.assertEqual(len(formatters), 2) def testReadFromFile(self): """Tests the ReadFromFile function.""" test_file_path = self._GetTestFilePath(['formatters', 'format_test.yaml']) self._SkipIfPathNotExists(test_file_path) test_formatters_file = yaml_formatters_file.YAMLFormattersFile() formatters = list(test_formatters_file.ReadFromFile(test_file_path)) self.assertEqual(len(formatters), 2) self.assertEqual(formatters[0].data_type, 'test:event') self.assertEqual(formatters[1].data_type, 'test:fs:stat') if __name__ == '__main__': unittest.main()
[ "noreply@github.com" ]
noreply@github.com
08283262024ac11a678bf93a86fc13799fde7db9
c7231df2a4740dde9e19d4db174d3fbc3d617033
/test/build/exe.win-amd64-3.5/PyQt5/_QOpenGLFunctions_2_1.pyi
c121336e38ab0a6ab5822ff9a0159402b3f3476d
[]
no_license
wangzhibinjunhua/python_test
c05c1b250dbabe13243c3e46af13efb25f0bd298
ddd812e81e1ba1d82fdc525aff3e8b3a935b6f70
refs/heads/master
2021-10-03T10:54:23.561997
2018-12-03T01:33:11
2018-12-03T01:33:11
103,799,043
0
0
null
null
null
null
UTF-8
Python
false
false
43,729
pyi
# The PEP 484 type hints stub file for the _QOpenGLFunctions_2_1 module. # # Generated by SIP 4.18 # # Copyright (c) 2016 Riverbank Computing Limited <info@riverbankcomputing.com> # # This file is part of PyQt5. # # This file may be used under the terms of the GNU General Public License # version 3.0 as published by the Free Software Foundation and appearing in # the file LICENSE included in the packaging of this file. Please review the # following information to ensure the GNU General Public License version 3.0 # requirements will be met: http://www.gnu.org/copyleft/gpl.html. # # If you do not wish to use this file under the terms of the GPL version 3.0 # then you may purchase a commercial license. For more information contact # info@riverbankcomputing.com. # # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. import typing import sip from PyQt5 import QtGui # Support for QDate, QDateTime and QTime. import datetime # Convenient type aliases. PYQT_SIGNAL = typing.Union[QtCore.pyqtSignal, QtCore.pyqtBoundSignal] PYQT_SLOT = typing.Union[typing.Callable[..., None], QtCore.pyqtBoundSignal] # Convenient aliases for complicated OpenGL types. PYQT_OPENGL_ARRAY = typing.Union[typing.Sequence[int], typing.Sequence[float], sip.Buffer, None] PYQT_OPENGL_BOUND_ARRAY = typing.Union[typing.Sequence[int], typing.Sequence[float], sip.Buffer, int, None] class QOpenGLFunctions_2_1(QtGui.QAbstractOpenGLFunctions): def __init__(self) -> None: ... def glVertexAttrib1d(self, index: int, x: float) -> None: ... def glVertexAttrib1dv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib1f(self, index: int, x: float) -> None: ... def glVertexAttrib1fv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib1s(self, index: int, x: int) -> None: ... def glVertexAttrib1sv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib2d(self, index: int, x: float, y: float) -> None: ... def glVertexAttrib2dv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib2f(self, index: int, x: float, y: float) -> None: ... def glVertexAttrib2fv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib2s(self, index: int, x: int, y: int) -> None: ... def glVertexAttrib2sv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib3d(self, index: int, x: float, y: float, z: float) -> None: ... def glVertexAttrib3dv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib3f(self, index: int, x: float, y: float, z: float) -> None: ... def glVertexAttrib3fv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib3s(self, index: int, x: int, y: int, z: int) -> None: ... def glVertexAttrib3sv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Nbv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Niv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Nsv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Nub(self, index: int, x: int, y: int, z: int, w: int) -> None: ... def glVertexAttrib4Nubv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Nuiv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4Nusv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4bv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4d(self, index: int, x: float, y: float, z: float, w: float) -> None: ... def glVertexAttrib4dv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4f(self, index: int, x: float, y: float, z: float, w: float) -> None: ... def glVertexAttrib4fv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4iv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4s(self, index: int, x: int, y: int, z: int, w: int) -> None: ... def glVertexAttrib4sv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4ubv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4uiv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertexAttrib4usv(self, index: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glFogCoordf(self, coord: float) -> None: ... def glFogCoordfv(self, coord: PYQT_OPENGL_ARRAY) -> None: ... def glFogCoordd(self, coord: float) -> None: ... def glFogCoorddv(self, coord: PYQT_OPENGL_ARRAY) -> None: ... def glFogCoordPointer(self, type: int, stride: int, pointer: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3b(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3bv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3d(self, red: float, green: float, blue: float) -> None: ... def glSecondaryColor3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3f(self, red: float, green: float, blue: float) -> None: ... def glSecondaryColor3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3i(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3s(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3ub(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3ubv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3ui(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3uiv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColor3us(self, red: int, green: int, blue: int) -> None: ... def glSecondaryColor3usv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glSecondaryColorPointer(self, size: int, type: int, stride: int, pointer: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos2d(self, x: float, y: float) -> None: ... def glWindowPos2dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos2f(self, x: float, y: float) -> None: ... def glWindowPos2fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos2i(self, x: int, y: int) -> None: ... def glWindowPos2iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos2s(self, x: int, y: int) -> None: ... def glWindowPos2sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos3d(self, x: float, y: float, z: float) -> None: ... def glWindowPos3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos3f(self, x: float, y: float, z: float) -> None: ... def glWindowPos3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos3i(self, x: int, y: int, z: int) -> None: ... def glWindowPos3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glWindowPos3s(self, x: int, y: int, z: int) -> None: ... def glWindowPos3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glClientActiveTexture(self, texture: int) -> None: ... def glMultiTexCoord1d(self, target: int, s: float) -> None: ... def glMultiTexCoord1dv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord1f(self, target: int, s: float) -> None: ... def glMultiTexCoord1fv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord1i(self, target: int, s: int) -> None: ... def glMultiTexCoord1iv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord1s(self, target: int, s: int) -> None: ... def glMultiTexCoord1sv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord2d(self, target: int, s: float, t: float) -> None: ... def glMultiTexCoord2dv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord2f(self, target: int, s: float, t: float) -> None: ... def glMultiTexCoord2fv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord2i(self, target: int, s: int, t: int) -> None: ... def glMultiTexCoord2iv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord2s(self, target: int, s: int, t: int) -> None: ... def glMultiTexCoord2sv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord3d(self, target: int, s: float, t: float, r: float) -> None: ... def glMultiTexCoord3dv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord3f(self, target: int, s: float, t: float, r: float) -> None: ... def glMultiTexCoord3fv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord3i(self, target: int, s: int, t: int, r: int) -> None: ... def glMultiTexCoord3iv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord3s(self, target: int, s: int, t: int, r: int) -> None: ... def glMultiTexCoord3sv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord4d(self, target: int, s: float, t: float, r: float, q: float) -> None: ... def glMultiTexCoord4dv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord4f(self, target: int, s: float, t: float, r: float, q: float) -> None: ... def glMultiTexCoord4fv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord4i(self, target: int, s: int, t: int, r: int, q: int) -> None: ... def glMultiTexCoord4iv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glMultiTexCoord4s(self, target: int, s: int, t: int, r: int, q: int) -> None: ... def glMultiTexCoord4sv(self, target: int, v: PYQT_OPENGL_ARRAY) -> None: ... def glLoadTransposeMatrixf(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glLoadTransposeMatrixd(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glMultTransposeMatrixf(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glMultTransposeMatrixd(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glColorTable(self, target: int, internalformat: int, width: int, format: int, type: int, table: PYQT_OPENGL_ARRAY) -> None: ... def glColorTableParameterfv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glColorTableParameteriv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glCopyColorTable(self, target: int, internalformat: int, x: int, y: int, width: int) -> None: ... def glGetColorTableParameterfv(self, target: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetColorTableParameteriv(self, target: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glColorSubTable(self, target: int, start: int, count: int, format: int, type: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCopyColorSubTable(self, target: int, start: int, x: int, y: int, width: int) -> None: ... def glConvolutionFilter1D(self, target: int, internalformat: int, width: int, format: int, type: int, image: PYQT_OPENGL_ARRAY) -> None: ... def glConvolutionFilter2D(self, target: int, internalformat: int, width: int, height: int, format: int, type: int, image: PYQT_OPENGL_ARRAY) -> None: ... def glConvolutionParameterf(self, target: int, pname: int, params: float) -> None: ... def glConvolutionParameterfv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glConvolutionParameteri(self, target: int, pname: int, params: int) -> None: ... def glConvolutionParameteriv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glCopyConvolutionFilter1D(self, target: int, internalformat: int, x: int, y: int, width: int) -> None: ... def glCopyConvolutionFilter2D(self, target: int, internalformat: int, x: int, y: int, width: int, height: int) -> None: ... def glGetConvolutionParameterfv(self, target: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetConvolutionParameteriv(self, target: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glHistogram(self, target: int, width: int, internalformat: int, sink: int) -> None: ... def glMinmax(self, target: int, internalformat: int, sink: int) -> None: ... def glResetHistogram(self, target: int) -> None: ... def glResetMinmax(self, target: int) -> None: ... def glArrayElement(self, i: int) -> None: ... def glColorPointer(self, size: int, type: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glDisableClientState(self, array: int) -> None: ... def glEdgeFlagPointer(self, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glEnableClientState(self, array: int) -> None: ... def glIndexPointer(self, type: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glNormalPointer(self, type: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glTexCoordPointer(self, size: int, type: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glVertexPointer(self, size: int, type: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glPopClientAttrib(self) -> None: ... def glPushClientAttrib(self, mask: int) -> None: ... def glNewList(self, list: int, mode: int) -> None: ... def glEndList(self) -> None: ... def glCallList(self, list: int) -> None: ... def glDeleteLists(self, list: int, range: int) -> None: ... def glGenLists(self, range: int) -> int: ... def glListBase(self, base: int) -> None: ... def glBegin(self, mode: int) -> None: ... def glBitmap(self, width: int, height: int, xorig: float, yorig: float, xmove: float, ymove: float, bitmap: PYQT_OPENGL_ARRAY) -> None: ... def glColor3b(self, red: int, green: int, blue: int) -> None: ... def glColor3bv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3d(self, red: float, green: float, blue: float) -> None: ... def glColor3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3f(self, red: float, green: float, blue: float) -> None: ... def glColor3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3i(self, red: int, green: int, blue: int) -> None: ... def glColor3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3s(self, red: int, green: int, blue: int) -> None: ... def glColor3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3ub(self, red: int, green: int, blue: int) -> None: ... def glColor3ubv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3ui(self, red: int, green: int, blue: int) -> None: ... def glColor3uiv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor3us(self, red: int, green: int, blue: int) -> None: ... def glColor3usv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4b(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4bv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4d(self, red: float, green: float, blue: float, alpha: float) -> None: ... def glColor4dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4f(self, red: float, green: float, blue: float, alpha: float) -> None: ... def glColor4fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4i(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4s(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4ub(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4ubv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4ui(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4uiv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glColor4us(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glColor4usv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glEdgeFlag(self, flag: int) -> None: ... def glEdgeFlagv(self, flag: PYQT_OPENGL_ARRAY) -> None: ... def glEnd(self) -> None: ... def glIndexd(self, c: float) -> None: ... def glIndexdv(self, c: PYQT_OPENGL_ARRAY) -> None: ... def glIndexf(self, c: float) -> None: ... def glIndexfv(self, c: PYQT_OPENGL_ARRAY) -> None: ... def glIndexi(self, c: int) -> None: ... def glIndexiv(self, c: PYQT_OPENGL_ARRAY) -> None: ... def glIndexs(self, c: int) -> None: ... def glIndexsv(self, c: PYQT_OPENGL_ARRAY) -> None: ... def glNormal3b(self, nx: int, ny: int, nz: int) -> None: ... def glNormal3bv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glNormal3d(self, nx: float, ny: float, nz: float) -> None: ... def glNormal3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glNormal3f(self, nx: float, ny: float, nz: float) -> None: ... def glNormal3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glNormal3i(self, nx: int, ny: int, nz: int) -> None: ... def glNormal3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glNormal3s(self, nx: int, ny: int, nz: int) -> None: ... def glNormal3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos2d(self, x: float, y: float) -> None: ... def glRasterPos2dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos2f(self, x: float, y: float) -> None: ... def glRasterPos2fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos2i(self, x: int, y: int) -> None: ... def glRasterPos2iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos2s(self, x: int, y: int) -> None: ... def glRasterPos2sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos3d(self, x: float, y: float, z: float) -> None: ... def glRasterPos3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos3f(self, x: float, y: float, z: float) -> None: ... def glRasterPos3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos3i(self, x: int, y: int, z: int) -> None: ... def glRasterPos3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos3s(self, x: int, y: int, z: int) -> None: ... def glRasterPos3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos4d(self, x: float, y: float, z: float, w: float) -> None: ... def glRasterPos4dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos4f(self, x: float, y: float, z: float, w: float) -> None: ... def glRasterPos4fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos4i(self, x: int, y: int, z: int, w: int) -> None: ... def glRasterPos4iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRasterPos4s(self, x: int, y: int, z: int, w: int) -> None: ... def glRasterPos4sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glRectd(self, x1: float, y1: float, x2: float, y2: float) -> None: ... def glRectf(self, x1: float, y1: float, x2: float, y2: float) -> None: ... def glRecti(self, x1: int, y1: int, x2: int, y2: int) -> None: ... def glRects(self, x1: int, y1: int, x2: int, y2: int) -> None: ... def glTexCoord1d(self, s: float) -> None: ... def glTexCoord1dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord1f(self, s: float) -> None: ... def glTexCoord1fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord1i(self, s: int) -> None: ... def glTexCoord1iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord1s(self, s: int) -> None: ... def glTexCoord1sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord2d(self, s: float, t: float) -> None: ... def glTexCoord2dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord2f(self, s: float, t: float) -> None: ... def glTexCoord2fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord2i(self, s: int, t: int) -> None: ... def glTexCoord2iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord2s(self, s: int, t: int) -> None: ... def glTexCoord2sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord3d(self, s: float, t: float, r: float) -> None: ... def glTexCoord3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord3f(self, s: float, t: float, r: float) -> None: ... def glTexCoord3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord3i(self, s: int, t: int, r: int) -> None: ... def glTexCoord3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord3s(self, s: int, t: int, r: int) -> None: ... def glTexCoord3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord4d(self, s: float, t: float, r: float, q: float) -> None: ... def glTexCoord4dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord4f(self, s: float, t: float, r: float, q: float) -> None: ... def glTexCoord4fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord4i(self, s: int, t: int, r: int, q: int) -> None: ... def glTexCoord4iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glTexCoord4s(self, s: int, t: int, r: int, q: int) -> None: ... def glTexCoord4sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex2d(self, x: float, y: float) -> None: ... def glVertex2dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex2f(self, x: float, y: float) -> None: ... def glVertex2fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex2i(self, x: int, y: int) -> None: ... def glVertex2iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex2s(self, x: int, y: int) -> None: ... def glVertex2sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex3d(self, x: float, y: float, z: float) -> None: ... def glVertex3dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex3f(self, x: float, y: float, z: float) -> None: ... def glVertex3fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex3i(self, x: int, y: int, z: int) -> None: ... def glVertex3iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex3s(self, x: int, y: int, z: int) -> None: ... def glVertex3sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex4d(self, x: float, y: float, z: float, w: float) -> None: ... def glVertex4dv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex4f(self, x: float, y: float, z: float, w: float) -> None: ... def glVertex4fv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex4i(self, x: int, y: int, z: int, w: int) -> None: ... def glVertex4iv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glVertex4s(self, x: int, y: int, z: int, w: int) -> None: ... def glVertex4sv(self, v: PYQT_OPENGL_ARRAY) -> None: ... def glClipPlane(self, plane: int, equation: PYQT_OPENGL_ARRAY) -> None: ... def glColorMaterial(self, face: int, mode: int) -> None: ... def glFogf(self, pname: int, param: float) -> None: ... def glFogfv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glFogi(self, pname: int, param: int) -> None: ... def glFogiv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glLightf(self, light: int, pname: int, param: float) -> None: ... def glLightfv(self, light: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glLighti(self, light: int, pname: int, param: int) -> None: ... def glLightiv(self, light: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glLightModelf(self, pname: int, param: float) -> None: ... def glLightModelfv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glLightModeli(self, pname: int, param: int) -> None: ... def glLightModeliv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glLineStipple(self, factor: int, pattern: int) -> None: ... def glMaterialf(self, face: int, pname: int, param: float) -> None: ... def glMaterialfv(self, face: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glMateriali(self, face: int, pname: int, param: int) -> None: ... def glMaterialiv(self, face: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glPolygonStipple(self, mask: PYQT_OPENGL_ARRAY) -> None: ... def glShadeModel(self, mode: int) -> None: ... def glTexEnvf(self, target: int, pname: int, param: float) -> None: ... def glTexEnvfv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexEnvi(self, target: int, pname: int, param: int) -> None: ... def glTexEnviv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexGend(self, coord: int, pname: int, param: float) -> None: ... def glTexGendv(self, coord: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexGenf(self, coord: int, pname: int, param: float) -> None: ... def glTexGenfv(self, coord: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexGeni(self, coord: int, pname: int, param: int) -> None: ... def glTexGeniv(self, coord: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glRenderMode(self, mode: int) -> int: ... def glInitNames(self) -> None: ... def glLoadName(self, name: int) -> None: ... def glPassThrough(self, token: float) -> None: ... def glPopName(self) -> None: ... def glPushName(self, name: int) -> None: ... def glClearAccum(self, red: float, green: float, blue: float, alpha: float) -> None: ... def glClearIndex(self, c: float) -> None: ... def glIndexMask(self, mask: int) -> None: ... def glAccum(self, op: int, value: float) -> None: ... def glPopAttrib(self) -> None: ... def glPushAttrib(self, mask: int) -> None: ... def glMap1d(self, target: int, u1: float, u2: float, stride: int, order: int, points: PYQT_OPENGL_ARRAY) -> None: ... def glMap1f(self, target: int, u1: float, u2: float, stride: int, order: int, points: PYQT_OPENGL_ARRAY) -> None: ... def glMap2d(self, target: int, u1: float, u2: float, ustride: int, uorder: int, v1: float, v2: float, vstride: int, vorder: int, points: PYQT_OPENGL_ARRAY) -> None: ... def glMap2f(self, target: int, u1: float, u2: float, ustride: int, uorder: int, v1: float, v2: float, vstride: int, vorder: int, points: PYQT_OPENGL_ARRAY) -> None: ... def glMapGrid1d(self, un: int, u1: float, u2: float) -> None: ... def glMapGrid1f(self, un: int, u1: float, u2: float) -> None: ... def glMapGrid2d(self, un: int, u1: float, u2: float, vn: int, v1: float, v2: float) -> None: ... def glMapGrid2f(self, un: int, u1: float, u2: float, vn: int, v1: float, v2: float) -> None: ... def glEvalCoord1d(self, u: float) -> None: ... def glEvalCoord1dv(self, u: PYQT_OPENGL_ARRAY) -> None: ... def glEvalCoord1f(self, u: float) -> None: ... def glEvalCoord1fv(self, u: PYQT_OPENGL_ARRAY) -> None: ... def glEvalCoord2d(self, u: float, v: float) -> None: ... def glEvalCoord2dv(self, u: PYQT_OPENGL_ARRAY) -> None: ... def glEvalCoord2f(self, u: float, v: float) -> None: ... def glEvalCoord2fv(self, u: PYQT_OPENGL_ARRAY) -> None: ... def glEvalMesh1(self, mode: int, i1: int, i2: int) -> None: ... def glEvalPoint1(self, i: int) -> None: ... def glEvalMesh2(self, mode: int, i1: int, i2: int, j1: int, j2: int) -> None: ... def glEvalPoint2(self, i: int, j: int) -> None: ... def glAlphaFunc(self, func: int, ref: float) -> None: ... def glPixelZoom(self, xfactor: float, yfactor: float) -> None: ... def glPixelTransferf(self, pname: int, param: float) -> None: ... def glPixelTransferi(self, pname: int, param: int) -> None: ... def glPixelMapfv(self, map: int, mapsize: int, values: PYQT_OPENGL_ARRAY) -> None: ... def glPixelMapuiv(self, map: int, mapsize: int, values: PYQT_OPENGL_ARRAY) -> None: ... def glPixelMapusv(self, map: int, mapsize: int, values: PYQT_OPENGL_ARRAY) -> None: ... def glCopyPixels(self, x: int, y: int, width: int, height: int, type: int) -> None: ... def glDrawPixels(self, width: int, height: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glGetClipPlane(self, plane: int) -> typing.Tuple[float, float, float, float]: ... def glGetLightfv(self, light: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float], typing.Tuple[float, float, float, float]]: ... def glGetLightiv(self, light: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int], typing.Tuple[int, int, int, int]]: ... def glGetMaterialfv(self, face: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float], typing.Tuple[float, float, float, float]]: ... def glGetMaterialiv(self, face: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int], typing.Tuple[int, int, int, int]]: ... def glGetTexEnvfv(self, target: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetTexEnviv(self, target: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glGetTexGendv(self, coord: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetTexGenfv(self, coord: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetTexGeniv(self, coord: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glIsList(self, list: int) -> int: ... def glFrustum(self, left: float, right: float, bottom: float, top: float, zNear: float, zFar: float) -> None: ... def glLoadIdentity(self) -> None: ... def glLoadMatrixf(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glLoadMatrixd(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glMatrixMode(self, mode: int) -> None: ... def glMultMatrixf(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glMultMatrixd(self, m: PYQT_OPENGL_ARRAY) -> None: ... def glOrtho(self, left: float, right: float, bottom: float, top: float, zNear: float, zFar: float) -> None: ... def glPopMatrix(self) -> None: ... def glPushMatrix(self) -> None: ... def glRotated(self, angle: float, x: float, y: float, z: float) -> None: ... def glRotatef(self, angle: float, x: float, y: float, z: float) -> None: ... def glScaled(self, x: float, y: float, z: float) -> None: ... def glScalef(self, x: float, y: float, z: float) -> None: ... def glTranslated(self, x: float, y: float, z: float) -> None: ... def glTranslatef(self, x: float, y: float, z: float) -> None: ... def glBlendEquationSeparate(self, modeRGB: int, modeAlpha: int) -> None: ... def glDrawBuffers(self, n: int, bufs: PYQT_OPENGL_ARRAY) -> None: ... def glStencilOpSeparate(self, face: int, sfail: int, dpfail: int, dppass: int) -> None: ... def glStencilFuncSeparate(self, face: int, func: int, ref: int, mask: int) -> None: ... def glStencilMaskSeparate(self, face: int, mask: int) -> None: ... def glAttachShader(self, program: int, shader: int) -> None: ... def glBindAttribLocation(self, program: int, index: int, name: str) -> None: ... def glCompileShader(self, shader: int) -> None: ... def glCreateProgram(self) -> int: ... def glCreateShader(self, type: int) -> int: ... def glDeleteProgram(self, program: int) -> None: ... def glDeleteShader(self, shader: int) -> None: ... def glDetachShader(self, program: int, shader: int) -> None: ... def glDisableVertexAttribArray(self, index: int) -> None: ... def glEnableVertexAttribArray(self, index: int) -> None: ... def glGetActiveAttrib(self, program: int, index: int) -> typing.Tuple[str, int, int]: ... def glGetActiveUniform(self, program: int, index: int) -> typing.Tuple[str, int, int]: ... def glGetAttachedShaders(self, program: int) -> typing.Tuple[int, ...]: ... def glGetAttribLocation(self, program: int, name: str) -> int: ... def glGetProgramiv(self, program: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int]]: ... def glGetProgramInfoLog(self, program: int) -> bytes: ... def glGetShaderiv(self, shader: int, pname: int) -> int: ... def glGetShaderInfoLog(self, shader: int) -> bytes: ... def glGetShaderSource(self, shader: int) -> bytes: ... def glGetUniformLocation(self, program: int, name: str) -> int: ... def glGetVertexAttribdv(self, index: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetVertexAttribfv(self, index: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetVertexAttribiv(self, index: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glIsProgram(self, program: int) -> int: ... def glIsShader(self, shader: int) -> int: ... def glLinkProgram(self, program: int) -> None: ... def glUseProgram(self, program: int) -> None: ... def glUniform1f(self, location: int, v0: float) -> None: ... def glUniform2f(self, location: int, v0: float, v1: float) -> None: ... def glUniform3f(self, location: int, v0: float, v1: float, v2: float) -> None: ... def glUniform4f(self, location: int, v0: float, v1: float, v2: float, v3: float) -> None: ... def glUniform1i(self, location: int, v0: int) -> None: ... def glUniform2i(self, location: int, v0: int, v1: int) -> None: ... def glUniform3i(self, location: int, v0: int, v1: int, v2: int) -> None: ... def glUniform4i(self, location: int, v0: int, v1: int, v2: int, v3: int) -> None: ... def glUniform1fv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform2fv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform3fv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform4fv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform1iv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform2iv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform3iv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniform4iv(self, location: int, count: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniformMatrix2fv(self, location: int, count: int, transpose: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniformMatrix3fv(self, location: int, count: int, transpose: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glUniformMatrix4fv(self, location: int, count: int, transpose: int, value: PYQT_OPENGL_ARRAY) -> None: ... def glValidateProgram(self, program: int) -> None: ... def glVertexAttribPointer(self, index: int, size: int, type: int, normalized: int, stride: int, pointer: PYQT_OPENGL_BOUND_ARRAY) -> None: ... def glGenQueries(self, n: int) -> typing.Union[int, typing.Tuple[int, ...]]: ... def glDeleteQueries(self, n: int, ids: PYQT_OPENGL_ARRAY) -> None: ... def glIsQuery(self, id: int) -> int: ... def glBeginQuery(self, target: int, id: int) -> None: ... def glEndQuery(self, target: int) -> None: ... def glGetQueryiv(self, target: int, pname: int) -> int: ... def glBindBuffer(self, target: int, buffer: int) -> None: ... def glDeleteBuffers(self, n: int, buffers: PYQT_OPENGL_ARRAY) -> None: ... def glGenBuffers(self, n: int) -> typing.Union[int, typing.Tuple[int, ...]]: ... def glIsBuffer(self, buffer: int) -> int: ... def glBufferData(self, target: int, size: int, data: PYQT_OPENGL_ARRAY, usage: int) -> None: ... def glBufferSubData(self, target: int, offset: int, size: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glUnmapBuffer(self, target: int) -> int: ... def glGetBufferParameteriv(self, target: int, pname: int) -> int: ... def glBlendFuncSeparate(self, sfactorRGB: int, dfactorRGB: int, sfactorAlpha: int, dfactorAlpha: int) -> None: ... def glPointParameterf(self, pname: int, param: float) -> None: ... def glPointParameterfv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glPointParameteri(self, pname: int, param: int) -> None: ... def glPointParameteriv(self, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glActiveTexture(self, texture: int) -> None: ... def glSampleCoverage(self, value: float, invert: int) -> None: ... def glCompressedTexImage3D(self, target: int, level: int, internalformat: int, width: int, height: int, depth: int, border: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCompressedTexImage2D(self, target: int, level: int, internalformat: int, width: int, height: int, border: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCompressedTexImage1D(self, target: int, level: int, internalformat: int, width: int, border: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCompressedTexSubImage3D(self, target: int, level: int, xoffset: int, yoffset: int, zoffset: int, width: int, height: int, depth: int, format: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCompressedTexSubImage2D(self, target: int, level: int, xoffset: int, yoffset: int, width: int, height: int, format: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glCompressedTexSubImage1D(self, target: int, level: int, xoffset: int, width: int, format: int, imageSize: int, data: PYQT_OPENGL_ARRAY) -> None: ... def glBlendColor(self, red: float, green: float, blue: float, alpha: float) -> None: ... def glBlendEquation(self, mode: int) -> None: ... def glDrawRangeElements(self, mode: int, start: int, end: int, count: int, type: int, indices: PYQT_OPENGL_ARRAY) -> None: ... def glTexImage3D(self, target: int, level: int, internalformat: int, width: int, height: int, depth: int, border: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glTexSubImage3D(self, target: int, level: int, xoffset: int, yoffset: int, zoffset: int, width: int, height: int, depth: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glCopyTexSubImage3D(self, target: int, level: int, xoffset: int, yoffset: int, zoffset: int, x: int, y: int, width: int, height: int) -> None: ... def glDrawArrays(self, mode: int, first: int, count: int) -> None: ... def glDrawElements(self, mode: int, count: int, type: int, indices: PYQT_OPENGL_ARRAY) -> None: ... def glPolygonOffset(self, factor: float, units: float) -> None: ... def glCopyTexImage1D(self, target: int, level: int, internalformat: int, x: int, y: int, width: int, border: int) -> None: ... def glCopyTexImage2D(self, target: int, level: int, internalformat: int, x: int, y: int, width: int, height: int, border: int) -> None: ... def glCopyTexSubImage1D(self, target: int, level: int, xoffset: int, x: int, y: int, width: int) -> None: ... def glCopyTexSubImage2D(self, target: int, level: int, xoffset: int, yoffset: int, x: int, y: int, width: int, height: int) -> None: ... def glTexSubImage1D(self, target: int, level: int, xoffset: int, width: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glTexSubImage2D(self, target: int, level: int, xoffset: int, yoffset: int, width: int, height: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glBindTexture(self, target: int, texture: int) -> None: ... def glDeleteTextures(self, n: int, textures: PYQT_OPENGL_ARRAY) -> None: ... def glGenTextures(self, n: int) -> typing.Union[int, typing.Tuple[int, ...]]: ... def glIsTexture(self, texture: int) -> int: ... def glIndexub(self, c: int) -> None: ... def glIndexubv(self, c: PYQT_OPENGL_ARRAY) -> None: ... def glCullFace(self, mode: int) -> None: ... def glFrontFace(self, mode: int) -> None: ... def glHint(self, target: int, mode: int) -> None: ... def glLineWidth(self, width: float) -> None: ... def glPointSize(self, size: float) -> None: ... def glPolygonMode(self, face: int, mode: int) -> None: ... def glScissor(self, x: int, y: int, width: int, height: int) -> None: ... def glTexParameterf(self, target: int, pname: int, param: float) -> None: ... def glTexParameterfv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexParameteri(self, target: int, pname: int, param: int) -> None: ... def glTexParameteriv(self, target: int, pname: int, params: PYQT_OPENGL_ARRAY) -> None: ... def glTexImage1D(self, target: int, level: int, internalformat: int, width: int, border: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glTexImage2D(self, target: int, level: int, internalformat: int, width: int, height: int, border: int, format: int, type: int, pixels: PYQT_OPENGL_ARRAY) -> None: ... def glDrawBuffer(self, mode: int) -> None: ... def glClear(self, mask: int) -> None: ... def glClearColor(self, red: float, green: float, blue: float, alpha: float) -> None: ... def glClearStencil(self, s: int) -> None: ... def glClearDepth(self, depth: float) -> None: ... def glStencilMask(self, mask: int) -> None: ... def glColorMask(self, red: int, green: int, blue: int, alpha: int) -> None: ... def glDepthMask(self, flag: int) -> None: ... def glDisable(self, cap: int) -> None: ... def glEnable(self, cap: int) -> None: ... def glFinish(self) -> None: ... def glFlush(self) -> None: ... def glBlendFunc(self, sfactor: int, dfactor: int) -> None: ... def glLogicOp(self, opcode: int) -> None: ... def glStencilFunc(self, func: int, ref: int, mask: int) -> None: ... def glStencilOp(self, fail: int, zfail: int, zpass: int) -> None: ... def glDepthFunc(self, func: int) -> None: ... def glPixelStoref(self, pname: int, param: float) -> None: ... def glPixelStorei(self, pname: int, param: int) -> None: ... def glReadBuffer(self, mode: int) -> None: ... def glGetBooleanv(self, pname: int) -> typing.Union[bool, typing.Tuple[bool, ...]]: ... def glGetDoublev(self, pname: int) -> typing.Union[float, typing.Tuple[float, ...]]: ... def glGetError(self) -> int: ... def glGetFloatv(self, pname: int) -> typing.Union[float, typing.Tuple[float, ...]]: ... def glGetIntegerv(self, pname: int) -> typing.Union[int, typing.Tuple[int, ...]]: ... def glGetString(self, name: int) -> str: ... def glGetTexParameterfv(self, target: int, pname: int) -> typing.Union[float, typing.Tuple[float, float, float, float]]: ... def glGetTexParameteriv(self, target: int, pname: int) -> typing.Union[int, typing.Tuple[int, int, int, int]]: ... def glGetTexLevelParameterfv(self, target: int, level: int, pname: int) -> float: ... def glGetTexLevelParameteriv(self, target: int, level: int, pname: int) -> int: ... def glIsEnabled(self, cap: int) -> int: ... def glDepthRange(self, nearVal: float, farVal: float) -> None: ... def glViewport(self, x: int, y: int, width: int, height: int) -> None: ... def initializeOpenGLFunctions(self) -> bool: ...
[ "wangzhibin_x@foxmail.com" ]
wangzhibin_x@foxmail.com
5d54d9806081b5a4bfe7026d4711ef3642d29885
0bfb74494054dc9e0774618687b5d234e6db6a92
/ch11/progress_queue.py
400bf69717d73d7b1dbf7bc59cba559aad28aa52
[]
no_license
FSSlc/AdvancePython
dddee32524cf1071a36eb4316efc2b53185645e3
61ed98f951fc877cc01e43a50488fc91b775c0f0
refs/heads/master
2022-11-06T10:53:07.812770
2020-06-25T23:43:24
2020-06-25T23:43:24
273,885,468
0
0
null
null
null
null
UTF-8
Python
false
false
2,069
py
#!/usr/bin/env python # coding: utf-8 """ 通过 Queue 来进行进程间通信 共享全局变量不能适用于多进程编程,可以适用于多线程编程 multiprocessing 中的 Queue 不能用于 pool 线程池 pool 中的进程间通信需要使用 manager 中的 Queue 还可以使用管道 pipe 来进行进程间通信 """ import multiprocessing import time from multiprocessing import Process, Queue, Manager, Pipe def producer(queue): queue.put('a') time.sleep(2) def consumer(queue): time.sleep(2) data = queue.get() print(data) def producer_pipe(pipe): pipe.send('user') def consumer_pipe(pipe): print(pipe.recv()) def add_data(p_dict, key, value): p_dict[key] = value if __name__ == '__main__': queue = Queue(10) my_producer = Process(target=producer, args=(queue,)) my_consumer = Process(target=consumer, args=(queue,)) my_producer.start() my_consumer.start() my_producer.join() my_consumer.join() # 使用线程池 # 使用 Manager 实例化的 Queue 来通信 queue = Manager().Queue(10) with multiprocessing.Pool(multiprocessing.cpu_count()) as pool: pool.apply_async(producer, args=(queue,)) pool.apply_async(consumer, args=(queue,)) pool.join() # 使用 Pipe 来通信 # Pipe 只能适合于 2 个进程 # Pipe 的性能比较高 receive_pipe, send_pipe = Pipe() my_producer = Process(target=producer_pipe, args=(send_pipe,)) my_consumer = Process(target=consumer_pipe, args=(receive_pipe,)) my_producer.start() my_consumer.start() my_producer.join() my_consumer.join() # Manager 中包含了常见的通信方式和数据结构例如 dict Array Condition 等 process_dict = Manager().dict() first_progress = Process(target=add_data, args=(process_dict, 'user1', 22)) second_progress = Process(target=add_data, args=(process_dict, 'user2', 23)) first_progress.start() second_progress.start() first_progress.join() second_progress.join() print(process_dict)
[ "fsslc235@gmail.com" ]
fsslc235@gmail.com
da6268d37a31875a6f3720c7b2592c435e43bc0f
0b01f92e125c27ceaf7586645f72dd5234e6841f
/Pages/product_details_page.py
14698824353ac81b2aa33a4eb20094f8e7cce642
[ "MIT" ]
permissive
gykudo/sauce_demo
40789ee7b55b36e37bd77752f5a55a00890409ca
313b4bd956cad4807d225b0a7ed98ca0be9f3371
refs/heads/main
2023-01-11T16:08:37.710841
2020-11-14T13:26:09
2020-11-14T13:26:09
305,707,742
0
0
null
null
null
null
UTF-8
Python
false
false
1,341
py
from Objects.product import Product from Pages.base_page_object import BasePage from Locators.product_detail_page_locator import ProductDetailPageLocator class ProductsDetailsPage(BasePage): def __init__(self, driver): super().__init__(driver) def get_product_badge(self): total = 0 try: total = self.get_text(ProductDetailPageLocator.SHOPPING_CART_LABEL) except Exception: pass return int(total) def get_product_info(self): name = self.get_text(ProductDetailPageLocator.PRODUCT_NAME_LABEL) desc = self.get_text(ProductDetailPageLocator.PRODUCT_DESC_LABEL) price = self.get_text(ProductDetailPageLocator.PRODUCT_PRICE_LABEL) return Product(name, desc, price) def add_product_to_cart(self): self.click(ProductDetailPageLocator.PRODUCT_ADD_BUTTON) def does_add_button_exist(self): return self.is_visible(ProductDetailPageLocator.PRODUCT_ADD_BUTTON) def remove_product_from_cart(self): self.click(ProductDetailPageLocator.PRODUCT_REMOVE_BUTTON) def does_remove_button_exist(self): return self.is_visible(ProductDetailPageLocator.PRODUCT_REMOVE_BUTTON) def is_product_badge_invisible(self): return self.is_invisible(ProductDetailPageLocator.SHOPPING_CART_LABEL) def back_to_product_page(self): self.click(ProductDetailPageLocator.BACK_BUTTON)
[ "tukimtuan@gmail.com" ]
tukimtuan@gmail.com
3ebe01d084af1e6585aa032e0a4d15ab6c775bfd
0a3eada15be160f13642afc357b74dd8c2095710
/2017/python/14-disk-defragmentation/main.py
3cf0e0206fedac1fc80c289314d3589ad87f2cfb
[]
no_license
cj1128/advent-of-code
af8edfa0e1479ed1221c07eb28eab193877a66d6
273eeaf97204ca1755006b7c4b61ac3609124f79
refs/heads/master
2022-11-28T18:58:32.087955
2020-08-09T13:57:40
2020-08-09T13:57:40
113,849,897
0
0
null
null
null
null
UTF-8
Python
false
false
1,556
py
import binascii import numpy import sys sys.path.append("..") from utils import know_hash input = "hwlqcszp" part1_test = ("flqrgnkx", 8108) def solve_part1(input): used = 0 for i in range(128): hash = know_hash(f"{input}-{i}") bits = format(int(hash, 16), "08b") used += bits.count("1") return used # print(solve_part1(part1_test[0]) == part1_test[1]) # print(solve_part1(input)) # 8304 part2_test = ("flqrgnkx", 1242) def get_adjacent(row, col, dimension): result = [] # top if row > 0: result.append((row - 1, col)) # down if row < dimension - 1: result.append((row + 1, col)) # left if col > 0: result.append((row, col - 1)) # right if col < dimension - 1: result.append((row, col + 1)) return result def mark_group(row, col, result, disk, group): result[(row, col)] = group for row, col in get_adjacent(row, col, 128): if disk[row][col] == 1 and (row, col) not in result: mark_group(row, col, result, disk, group) def solve_part2(input): disk = [] for i in range(128): hash = know_hash(f"{input}-{i}") bits = "".join([format(b, "08b") for b in binascii.unhexlify(hash)]) disk.append([int(b) for b in bits]) result = dict() group = 1 for row in range(128): for col in range(128): if disk[row][col] == 0: continue if (row, col) in result: continue mark_group(row, col, result, disk, group) group += 1 return max(result.values()) # print(solve_part2(part2_test[0]) == part2_test[1]) print(solve_part2(input))
[ "fatelovely1128@gmail.com" ]
fatelovely1128@gmail.com
106f45f4de87ee679c33655383f062436ab7d436
e928be64f52609ac4be5cb0a4c2d8571d999bb2d
/JapaneseTools/Conversion/k.py
e938a9f155b61fb276531464e2f97f93460a400f
[]
no_license
youkaicountry/JapaneseTools
ac19bd6e9202f5e474b74649032cd87ad7017863
20fcec03c0e24bbb65a2846cdeae81f9f86ccb99
refs/heads/master
2021-05-26T18:45:35.305598
2011-12-10T04:32:38
2011-12-10T04:32:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,382
py
# -*- coding: utf-8 -*- def toIF(kana): #step 1: basic processing t = [] for x in kana: t.append(__getRomaji(x)) t2 = [] #step 2: process special characters t2pos = 0 for i in range(len(t)): if i > 0 and t[i-1][0] == ">": continue if t[i][0] == "<": if i > 0: t2.append(__getSpecial((t[i-1], t[i]))) t2.pop(t2pos-1) elif t[i][0] == ">": if i < len(t)-1: t2.append(t[i+1][0] + t[i+1]) t2.append(__getSpecial((t[i], t[i+1]))) else: t2.append(t[i]) t2pos += 1 return t2 def __getRomaji(kana): try: ret = ktor[kana] except KeyError: ret = "" return ret def __getSpecial(rom): try: ret = special[rom] except KeyError: ret = "" return ret ktor = {} ktor["あ"] = "a" ktor["ア"] = "A" ktor["い"] = "i" ktor["イ"] = "I" ktor["う"] = "u" ktor["ウ"] = "U" ktor["え"] = "e" ktor["エ"] = "E" ktor["お"] = "o" ktor["オ"] = "O" ktor["か"] = "ka" ktor["カ"] = "KA" ktor["き"] = "ki" ktor["キ"] = "KI" ktor["く"] = "ku" ktor["ク"] = "KU" ktor["け"] = "ke" ktor["ケ"] = "KE" ktor["こ"] = "ko" ktor["コ"] = "KO" ktor["さ"] = "sa" ktor["サ"] = "SA" ktor["し"] = "shi" ktor["シ"] = "SHI" ktor["す"] = "su" ktor["ス"] = "SU" ktor["せ"] = "se" ktor["セ"] = "SE" ktor["そ"] = "so" ktor["ソ"] = "SO" ktor["た"] = "ta" ktor["タ"] = "TA" ktor["ち"] = "chi" ktor["チ"] = "CHI" ktor["つ"] = "tsu" ktor["ツ"] = "TSU" ktor["て"] = "te" ktor["テ"] = "TE" ktor["と"] = "to" ktor["ト"] = "TO" ktor["な"] = "na" ktor["ナ"] = "NA" ktor["に"] = "ni" ktor["ニ"] = "NI" ktor["ぬ"] = "nu" ktor["ヌ"] = "NU" ktor["ね"] = "ne" ktor["ネ"] = "NE" ktor["の"] = "no" ktor["ノ"] = "NO" ktor["は"] = "ha" ktor["ハ"] = "HA" ktor["ひ"] = "hi" ktor["ヒ"] = "HI" ktor["ふ"] = "fu" ktor["フ"] = "FU" ktor["へ"] = "he" ktor["ヘ"] = "HE" ktor["ほ"] = "ho" ktor["ホ"] = "HO" ktor["ま"] = "ma" ktor["マ"] = "MA" ktor["み"] = "mi" ktor["ミ"] = "MI" ktor["む"] = "mu" ktor["ム"] = "MU" ktor["め"] = "me" ktor["メ"] = "ME" ktor["も"] = "mo" ktor["モ"] = "MO" ktor["や"] = "ya" ktor["ヤ"] = "YA" ktor["ゆ"] = "yu" ktor["ユ"] = "YU" ktor["よ"] = "yo" ktor["ヨ"] = "YO" ktor["ら"] = "ra" ktor["ラ"] = "RA" ktor["り"] = "ri" ktor["リ"] = "RI" ktor["る"] = "ru" ktor["ル"] = "RU" ktor["れ"] = "re" ktor["レ"] = "RE" ktor["ろ"] = "ro" ktor["ロ"] = "RO" ktor["わ"] = "wa" ktor["ワ"] = "WA" ktor["を"] = "wo" ktor["ヲ"] = "WO" ktor["が"] = "ga" ktor["ガ"] = "GA" ktor["ぎ"] = "gi" ktor["ギ"] = "GI" ktor["ぐ"] = "gu" ktor["グ"] = "GU" ktor["げ"] = "ge" ktor["ゲ"] = "GE" ktor["ご"] = "go" ktor["ゴ"] = "GO" ktor["ざ"] = "za" ktor["ザ"] = "ZA" ktor["じ"] = "ji" ktor["ジ"] = "JI" ktor["ず"] = "zu" ktor["ズ"] = "ZU" ktor["ぜ"] = "ze" ktor["ゼ"] = "ZE" ktor["ぞ"] = "zo" ktor["ゾ"] = "ZO" ktor["だ"] = "da" ktor["ダ"] = "DA" ktor["ぢ"] = "di" ktor["ヂ"] = "DI" ktor["づ"] = "du" ktor["ヅ"] = "DU" ktor["で"] = "de" ktor["デ"] = "DE" ktor["ど"] = "do" ktor["ド"] = "DO" ktor["ば"] = "ba" ktor["バ"] = "BA" ktor["び"] = "bi" ktor["ビ"] = "BI" ktor["ぶ"] = "bu" ktor["ブ"] = "BU" ktor["べ"] = "be" ktor["ベ"] = "BE" ktor["ぼ"] = "bo" ktor["ボ"] = "BO" ktor["ぱ"] = "pa" ktor["パ"] = "PA" ktor["ぴ"] = "pi" ktor["ピ"] = "PI" ktor["ぷ"] = "pu" ktor["プ"] = "PU" ktor["ぺ"] = "pe" ktor["ペ"] = "PE" ktor["ぽ"] = "po" ktor["ポ"] = "PO" ktor["ー"] = "-" ktor["。"] = "." ktor["?"] = "?" ktor["!"] = "!" ktor["、"] = "," ktor[" "] = "_" ktor["("] = "[" ktor[")"] = "]" ktor["〜"] = "~" ktor["ゃ"] = "<ya" ktor["ャ"] = "<YA" ktor["ゅ"] = "<yu" ktor["ュ"] = "<YU" ktor["ょ"] = "<yo" ktor["ョ"] = "<YO" ktor["ん"] = "n" ktor["ン"] = "N" ktor["っ"] = ">tsu" ktor["ッ"] = ">TSU" ktor["「"] = "'" ktor["」"] = "'" ktor["ゐ"] = "wi" ktor["ヰ"] = "WI" special = {} special[("ni","<ya")] = "nya" special[("NI","<YA")] = "NYA" special[("ni","<yu")] = "nyu" special[("NI","<YU")] = "NYU" special[("ni","<yo")] = "nyo" special[("NI","<YO")] = "NYO" special[("ki","<ya")] = "kya" special[("KI","<YA")] = "KYA" special[("ki","<yu")] = "kyu" special[("KI","<YU")] = "KYU" special[("ki","<yo")] = "kyo" special[("KI","<YO")] = "KYO" special[("shi","<ya")] = "sha" special[("SHI","<YA")] = "SHA" special[("shi","<yu")] = "shu" special[("SHI","<YU")] = "SHU" special[("shi","<yo")] = "sho" special[("SHI","<YO")] = "SHO" special[("chi","<ya")] = "cha" special[("CHI","<YA")] = "CHA" special[("chi","<yu")] = "chu" special[("CHI","<YU")] = "CHU" special[("chi","<yo")] = "cho" special[("CHI","<YO")] = "CHO" special[("hi","<ya")] = "hya" special[("HI","<YA")] = "HYA" special[("hi","<yu")] = "hyu" special[("HI","<YU")] = "HYU" special[("hi","<yo")] = "hyo" special[("HI","<YO")] = "HYO" special[("mi","<ya")] = "mya" special[("MI","<YA")] = "MYA" special[("mi","<yu")] = "myu" special[("MI","<YU")] = "MYU" special[("mi","<yo")] = "myo" special[("MI","<YO")] = "MYO" special[("ri","<ya")] = "rya" special[("RI","<YA")] = "RYA" special[("ri","<yu")] = "ryu" special[("RI","<YU")] = "RYU" special[("ri","<yo")] = "ryo" special[("RI","<YO")] = "RYO" special[("gi","<ya")] = "gya" special[("GI","<YA")] = "GYA" special[("gi","<yu")] = "gyu" special[("GI","<YU")] = "GYU" special[("gi","<yo")] = "gyo" special[("GI","<YO")] = "GYO" special[("ji","<ya")] = "ja" special[("JI","<YA")] = "JA" special[("ji","<yu")] = "ju" special[("JI","<YU")] = "JU" special[("ji","<yo")] = "jo" special[("JI","<YO")] = "JO" special[("bi","<ya")] = "bya" special[("BI","<YA")] = "BYA" special[("bi","<yu")] = "byu" special[("BI","<YU")] = "BYU" special[("bi","<yo")] = "byo" special[("BI","<YO")] = "BYO" special[("pi","<ya")] = "pya" special[("PI","<YA")] = "PYA" special[("pi","<yu")] = "pyu" special[("PI","<YU")] = "PYU" special[("pi","<yo")] = "pyo" special[("PI","<YO")] = "PYO" special[("di","<ya")] = "dya" special[("DI","<YA")] = "DYA" special[("di","<yu")] = "dyu" special[("DI","<YU")] = "DYU" special[("di","<yo")] = "dyo" special[("DI","<YO")] = "DYO"
[ "nbcwell@gmail.com" ]
nbcwell@gmail.com
82fe4e45ff38d5287f5bdbc7456289d0b5be9b04
4befe5b55c189da9e3f73e9c372ad2effec8ffcb
/tests/features/steps/models_repo/test_models_delete.py
29db060d9337e515002fd6978d3f44a36542eec5
[ "Apache-2.0" ]
permissive
mohamedgaliaa/dtlpy
da68abc0c03a23efb103c4a8dc50e8cfd6909800
502a51881bd41497c8b5d9096e8478fd13f3f174
refs/heads/master
2023-04-03T17:10:37.249161
2021-04-07T12:44:54
2021-04-07T12:44:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
706
py
import behave @behave.when(u'I delete the model that was created by name') def step_impl(context): context.project.models.delete(model_name=context.model.name) @behave.when(u'I delete the model that was created by id') def step_impl(context): context.project.models.delete(model_id=context.model.id) @behave.when(u'I try to delete a model by the name of "{model_name}"') def step_impl(context, model_name): try: context.project.models.delete(model_name=model_name) context.error = None except Exception as e: context.error = e @behave.then(u'No model was deleted') def step_impl(context): assert len(context.project.models.list()) == context.model_count
[ "micha@dataloop.ai" ]
micha@dataloop.ai
cb2e1a3938df6ebe22a28a25c29f67bdea6afc60
b44234267386b8d162bafec0a3cd2d718eb3afde
/code/simplemooc/simplemooc/courses/forms.py
e69256612c19f5811fb128f19e0799137ac59d3a
[]
no_license
PuckmanXY/Simple_MOOC
afb6efaa6d23c362d438fda004c79e94bfa11e5e
afe01970ecb131b2e517b9520b158a70728507ce
refs/heads/master
2021-04-29T12:03:18.547459
2018-04-21T00:29:20
2018-04-21T00:29:20
121,720,417
0
0
null
null
null
null
UTF-8
Python
false
false
808
py
from django import forms from django.core.mail import send_mail from django.conf import settings from simplemooc.core.mail import send_mail_template class ContactCourse(forms.Form): name = forms.CharField(label = 'Nome', max_length = 100) email = forms.EmailField(label = 'E-mail') message = forms.CharField( label = 'Mensagem/Dúvida', widget = forms.Textarea ) def send_mail(self, course): subject = '[%s] Contato' % course context = { 'name': self.cleaned_data['name'], 'email': self.cleaned_data['email'], 'message': self.cleaned_data['message'], } template_name = 'courses/contact_email.html' send_mail_template( subject, template_name, context, [settings.CONTACT_EMAIL] )
[ "kayoanderson0403@gmail.com" ]
kayoanderson0403@gmail.com
40c87866e4260e92c9b0ecbd0776992362a3c7fa
ed36b3f1a953545e0f4d90d3d716e07d5d1900cd
/src/ARIMA-Future.py
81776f2324397777b963c2c5877c5bb6927c863b
[]
no_license
Sprea22/CS_Bachelor_Thesis___Python_Data_Analysis
ab0c2a840277511577e5c2d7c723a8dbe9840683
f0a06db61809f08d491a342b976acd7202fa3a83
refs/heads/master
2021-06-16T18:23:36.984031
2017-06-01T09:44:06
2017-06-01T09:44:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,192
py
import os import csv import sys import warnings import numpy as np import pandas as pd from pandas import Series from matplotlib import pyplot from statsmodels.tsa.arima_model import ARIMA pyplot.style.use('ggplot') #------------------------------------------------------------------------------------------- #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # CALCULATED MAPE BETWEEN PREDICTIONS AND REAL VALUES# #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% def mean_absolute_percentage_error(y_true, y_pred): try: rng = len(y_true) diff = [] for i in range(0,rng): diff.append(y_true[i] - y_pred[i]) diff[i] = diff[i] / y_true[i] abs = np.abs(diff) mn = np.mean(abs) percentageError = mn * 100 except: rng = 0 abs = np.abs((y_true-y_pred)/y_true) percentageError = abs * 100 return percentageError #------------------------------------------------------------------------------------------- # Load current dataset input series = pd.read_csv("Datasets/"+sys.argv[1]+".csv", usecols=[sys.argv[2]]) yearInput = pd.read_csv("Datasets/" + sys.argv[1]+".csv", usecols=[0]) # Reading the real future values realValues = pd.read_csv("Results_Forecast/"+sys.argv[1]+"/"+sys.argv[1]+"_"+sys.argv[2]+"_2015.csv", usecols=[0,1,"feedConsumption"]) # Initial datasets configurations. realValuesData = realValues[sys.argv[2]].values realValuesData = realValuesData.astype('float32') dataset = series.values dataset = dataset.astype('float32') # Evaluate model with order (p_values, d_values, q_values) p_values = int(sys.argv[4]) d_values = int(sys.argv[5]) q_values = int(sys.argv[6]) order = (p_values, d_values, q_values) warnings.filterwarnings("ignore") ################################## # PREDICTION ABOUT FUTURE VALUES # ################################## # Making the ARIMA Model with the current Dataset and Order previously chosen model = ARIMA(dataset, order=order) model_fit = model.fit(disp=0) # Filling the list "forecast" with the predictions results values forecast = model_fit.forecast(int(sys.argv[3]))[0] # Preparing the data that are going to be written in the output document that contains the results. index = [] for i in range(1,int(sys.argv[3])+1): index.append(len(dataset) +i) mape_list = [] for i in range(0,len(forecast)): mape_list.append(mean_absolute_percentage_error(realValuesData[i], forecast[i])) # Writing the predictions results values inside an output document rows = zip(index, realValuesData, forecast, mape_list) f = open("Results_Forecast/"+sys.argv[1]+"/"+sys.argv[1]+"_"+sys.argv[2]+"_futurePred.csv", 'w') csv.writer(f).writerows(rows) f.close() # Reading the real future values from the reported document realValues= pd.read_csv("Results_Forecast/"+sys.argv[1]+"/"+sys.argv[1]+"_"+sys.argv[2]+"_futurePred.csv", index_col=[0], usecols=[0,1]) # Reading the predicted future values from the reported document predFuture = pd.read_csv("Results_Forecast/"+sys.argv[1]+"/"+sys.argv[1]+"_"+sys.argv[2]+"_futurePred.csv", index_col=[0], usecols=[0,2]) # Initializing output graphic pyplot.figure() ax = pyplot.subplot(111) pyplot.tight_layout() # Displaying the real future values plot, green color. ax.plot(realValues, "g", label='Real 2015 Values', linewidth=2) # Displaying the predicted future values plot, red color. ax.plot(predFuture, "r", label='Predicted 2015 Values', linewidth=2) # Displaying the historic values plot, blue color. ax.plot(series, "b", label='Historic Values', linewidth=2) # Graphic legend settings ax.legend(loc='lower right', ncol=1, fancybox=True, shadow=True, fontsize=20) # Displaying current years on the xlabel. years = [] j = 0 for i in range(len(yearInput)): if j==11: years.append(yearInput.values[i][0]) j=0 else: j=j+1 x = range(0, len(yearInput.values)) pyplot.title(sys.argv[1] + " - " + sys.argv[2] + " | ARIMA order: " + str(order), fontsize=20) pyplot.xticks(np.arange(min(x), max(x)+1, 12.0), years) pyplot.xlabel("Years") pyplot.ylabel(sys.argv[2]+" in "+sys.argv[1], fontsize=20) # Display final graphic in full screen mode manager = pyplot.get_current_fig_manager() manager.resize(*manager.window.maxsize()) pyplot.show()
[ "asp005@post.uit.no" ]
asp005@post.uit.no
541be20181d90c2f788955ed7c94c8e307b6d08e
a7da58ad91b007b3650003708eb91928f1e3684a
/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_payment_workflow/scripts/validateCounter.py
1259c1c7a0143dad30f158e310e8328d81adaa3d
[]
no_license
jgpjuniorj/j
042d1bd7710fa2830355d4312a6b76103e29639d
dc02bfa887ffab9841abebc3f5c16d874388cef5
refs/heads/master
2021-01-01T09:26:36.121339
2020-01-31T10:34:17
2020-02-07T04:39:18
239,214,398
1
0
null
null
null
null
UTF-8
Python
false
false
1,447
py
from Products.DCWorkflow.DCWorkflow import ValidationFailed from Products.ERP5Type.Message import Message transaction = state_change['object'] date = transaction.getStartDate() source = transaction.getSource(None) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=source, date=transaction.getStartDate()) # check again that the counter is open context.Baobab_checkCounterOpened(source) if transaction.getPaymentType() in (None, ""): msg = Message(domain="ui", message="No payment type defined.") raise ValidationFailed, (msg,) #test if the source or the destination is correct transaction.Base_checkBaobabSourceAndDestination() # Get price and total_price. amount = transaction.getSourceTotalAssetPrice() total_price = transaction.getTotalPrice(portal_type=('Cash Delivery Line','Cash Delivery Cell'), fast=0) if amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") raise ValidationFailed, (msg,) if source is None: msg = Message(domain='ui', message='No counter defined.') raise ValidationFailed, (msg,) site = transaction.getSourceValue() vault = transaction.getBaobabSource() resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Delivery Line',same_source=1) #context.log('resource',resource) if resource == 2: msg = Message(domain="ui", message="No Resource.") raise ValidationFailed, (msg,)
[ "georgios.dagkakis@nexedi.com" ]
georgios.dagkakis@nexedi.com
cccfd301348060e0bbbb8535705d6e1069d6c44a
4341fa31ee6a6f964c4545b648eedfdda4192b3a
/contentFeatures.py
43b97a25a578d7e3f4e5a40a2db11fc6c74e705a
[]
no_license
Asmita-Ranashinge/Data-Analytics
60715ec65b423fb0ee16e9753b52682abc31a305
0fadc0ad3ada90b0a641cc7c7ece0623de5a8cad
refs/heads/master
2020-06-12T22:11:56.531414
2019-06-29T19:55:02
2019-06-29T19:55:02
194,443,447
1
0
null
null
null
null
UTF-8
Python
false
false
1,028
py
import string import nltk from collections import Counter from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.porter import * def get_tokens(): with open('Phishing_Content.txt', 'r') as shakes: #load text file text = shakes.read() lowers = text.lower() tokenizer = RegexpTokenizer(r'\w\D\w+') #remove digit and punctuation tokens = tokenizer.tokenize(lowers) #convert all the letters into lowercase return tokens tokens = get_tokens() count = Counter(tokens) filtered = [w for w in tokens if not w in stopwords.words('english')] #remove all the stopwords such as 'the', 'in', 'at' etc. count = Counter(filtered) print (count.most_common(50)) #stemming: to remove derived words def stem_tokens(tokens, stemmer): stemmed = [] for item in tokens: stemmed.append(stemmer.stem(item)) return stemmed stemmer = PorterStemmer() stemmed = stem_tokens(filtered, stemmer) count = Counter(stemmed) print (count.most_common(50))
[ "asmita.ranashinge@gmail.com" ]
asmita.ranashinge@gmail.com
0e1cdca49f5eeb7315a63e0091ae55029d0eece7
32c56293475f49c6dd1b0f1334756b5ad8763da9
/google-cloud-sdk/lib/third_party/kubernetes/client/models/v1_watch_event.py
eeac0514753ca0d2cfe0c9ba717f53e73fabf2aa
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
bopopescu/socialliteapp
b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494
85bb264e273568b5a0408f733b403c56373e2508
refs/heads/master
2022-11-20T03:01:47.654498
2020-02-01T20:29:43
2020-02-01T20:29:43
282,403,750
0
0
MIT
2020-07-25T08:31:59
2020-07-25T08:31:59
null
UTF-8
Python
false
false
3,880
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1WatchEvent(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ 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 = {'object': 'RuntimeRawExtension', 'type': 'str'} attribute_map = {'object': 'object', 'type': 'type'} def __init__(self, object=None, type=None): """ V1WatchEvent - a model defined in Swagger """ self._object = None self._type = None self.discriminator = None self.object = object self.type = type @property def object(self): """ Gets the object of this V1WatchEvent. Object is: * If Type is Added or Modified: the new state of the object. * If Type is Deleted: the state of the object immediately before deletion. * If Type is Error: *Status is recommended; other types may make sense depending on context. :return: The object of this V1WatchEvent. :rtype: RuntimeRawExtension """ return self._object @object.setter def object(self, object): """ Sets the object of this V1WatchEvent. Object is: * If Type is Added or Modified: the new state of the object. * If Type is Deleted: the state of the object immediately before deletion. * If Type is Error: *Status is recommended; other types may make sense depending on context. :param object: The object of this V1WatchEvent. :type: RuntimeRawExtension """ if object is None: raise ValueError('Invalid value for `object`, must not be `None`') self._object = object @property def type(self): """ Gets the type of this V1WatchEvent. :return: The type of this V1WatchEvent. :rtype: str """ return self._type @type.setter def type(self, type): """ Sets the type of this V1WatchEvent. :param type: The type of this V1WatchEvent. :type: str """ if type is None: raise ValueError('Invalid value for `type`, must not be `None`') self._type = type def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): 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 return result def to_str(self): """ Returns the string representation of the model """ return 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, V1WatchEvent): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "jonathang132298@gmail.com" ]
jonathang132298@gmail.com
b6329d939728790bcea89156b8375bc4669e816f
67a7bf852f9284f59b0b3e604572524ae6f02cf2
/mergesort.py
30724c7c8d469fe44d7dc7741d37e51d472e5da5
[]
no_license
sheetaljantikar/python-codes
6745cfda23f47e387a5954e2c9bcc739164e0803
f0a27c3159aafd97f9d66f192d8cdc48fe51bca5
refs/heads/master
2020-12-25T13:45:48.132779
2016-06-28T04:22:32
2016-06-28T04:22:32
62,109,677
0
0
null
null
null
null
UTF-8
Python
false
false
764
py
def merge(left,right,list): nl=len(left) nR=len(right) i=0 j=0 k=0 while(i<nl and j<nR): if (left[i]<right[j]): list[k]=left[i] k=k+1 i=i+1 else: list[k]=right[j] k=k+1 j=j+1 while (i<nl): list[k]=left[i] i=i+1 k=k+1 while(j<nR): list[k]=right[j] j=j+1 k=k+1 return list def mergesort(list): if len(list)<2: return else: mid=len(list)//2 left=list[0:mid] right=list[mid:] mergesort(left) mergesort(right) merge(left,right,list) return list a=[3,7,4,1,8,2] b=mergesort(a)
[ "noreply@github.com" ]
noreply@github.com
3d648307ee324055cbbbdd9c14e4bd57f785a79d
c9704cb6f799620090f0e8e3ec3fbcb720e032e6
/grunge/tests/test_tracks.py
6819feb99e77906a25683263e96cb52de27f31c3
[]
no_license
LiveLike/grunge
afceb90c96bce73311e41c2f2d69091808fa84ea
8ac296099b7e579147e7f6b2685cfd788650c0b8
refs/heads/main
2023-02-23T13:59:13.148883
2021-01-26T17:58:31
2021-01-26T17:58:31
333,166,387
0
3
null
2021-01-26T19:10:35
2021-01-26T17:43:37
Python
UTF-8
Python
false
false
1,404
py
from uuid import UUID from furl import furl from rest_framework import status from rest_framework.reverse import reverse as drf_reverse from . import BaseAPITestCase class TrackTests(BaseAPITestCase): def setUp(self): self.track_name = "Last Exit" self.track_uuid = UUID("b3083319-47a9-40ed-a4e0-a79d050d9df7") self.album_uuid = UUID("b4fee0db-0c93-4470-96b3-cebd158033a0") def test_list_tracks(self): url = drf_reverse("track-list", kwargs={"version": self.version}) r = self.client.get(url) self.assertEqual(r.status_code, status.HTTP_200_OK) self.assertEqual(r.data["count"], 3695) def test_search_tracks(self): url = drf_reverse("track-list", kwargs={"version": self.version}) url = furl(url).set({"name": self.track_name}).url r = self.client.get(url) self.assertEqual(r.status_code, status.HTTP_200_OK) self.assertEqual(r.data["count"], 4) self.assertEqual(r.data["results"][0]["uuid"], self.track_uuid) def test_get_track(self): url = drf_reverse( "track-detail", kwargs={"version": self.version, "uuid": self.track_uuid} ) r = self.client.get(url) self.assertEqual(r.status_code, status.HTTP_200_OK) self.assertEqual(r.data["name"], self.track_name) self.assertEqual(r.data["album"]["uuid"], self.album_uuid)
[ "benwilber@gmail.com" ]
benwilber@gmail.com
8cc5c311344282da37caf398197d8929dffbdf8f
a5b235e3b6d263c3ea6e820154454b703148181b
/tool/begin.py
9d71c390e3c45732370f694e39e7bf748c0ac346
[]
no_license
shiyuyuanyue/stat
9ad343e97c1d29dfb795dc88cc83372afbc5edd8
a24ed90c6b08d1e548ed7fb589b9587d1c3dfd14
refs/heads/master
2021-01-13T23:53:44.418934
2020-02-23T15:27:32
2020-02-23T15:27:32
242,534,266
1
0
null
null
null
null
UTF-8
Python
false
false
29
py
data = {} print(bool([data]))
[ "776977960@qq.com" ]
776977960@qq.com
cd3b8b16eeef7fca013cfb2b4744d00d3610f92f
21587c0e6c0b71cd8db7f8592b75e661388a53d3
/run.py
b761ad01e77e0726a97e17318efe25513ad6ef17
[]
no_license
Junwu302/ResistoMap
63999f99fd2ae3fbfd815e993cd90ad61225eca5
48da878eb6927d15c14733f9eeeb155fafbe616b
refs/heads/master
2020-06-14T00:22:09.591337
2017-01-16T16:38:45
2017-01-16T16:38:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
888
py
from src.main import main import argparse import os SCRIPTDIR = os.path.dirname(os.path.realpath(__file__)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('read_file', metavar='read_file', type=str, nargs='+', help='input read files') parser.add_argument('-n', '--n_threads', type=int, help='number of bowtie/diamond threads (default: 1)', default=1) parser.add_argument('-o', '--output_folder', type=str, help='output folder path (default: current dir)', default=os.getcwd()) args = vars(parser.parse_args()) read_files_pathes = [os.path.abspath(read_file) for read_file in args['read_file']] n_threads = args['n_threads'] output_folder = os.path.abspath(args['output_folder']) main(read_files_pathes, n_threads, output_folder, SCRIPTDIR)
[ "yarygin@phystech.edu" ]
yarygin@phystech.edu
e168642194f6d7a4aef859071a5f60aaa48f573d
327112e61d08ff89a6609d3a9e7d091c72718c44
/tutorial/settings.py
cec40f80ab040d2a77bc4a1aff2c407a1b128742
[]
no_license
bridgecrew-perf7/tutorial
1149698870b619c61be7d31ec5cf3df59d9bfefa
456a27fde546b431cb039545cc4af51fdab2a7e6
refs/heads/master
2023-05-08T14:29:15.907222
2021-05-29T19:36:05
2021-05-29T19:36:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,225
py
""" Django settings for tutorial project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import datetime from dotenv import load_dotenv load_dotenv() # 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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'imn@d&n&d-1r1uo8w5dd*x76f7jwx9o(g@#!)m@!+uq3bguo)l' # SECURITY WARNING: don't run with debug turned on in production! PRODUCTION = os.environ.get("PRODUCTION", False) == "true" DEBUG = not PRODUCTION ALLOWED_HOSTS = [ "localhost", "127.0.0.1", "ptibem.cs.ui.ac.id" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django_cas_ng', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'corsheaders', 'app_auth', 'app_profile', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'app_auth.sso_backends.SSOCASBackend', # Dari app_auth ) ROOT_URLCONF = 'tutorial.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 = 'tutorial.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases if PRODUCTION: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DATABASE_NAME"), "USER": os.environ.get("DATABASE_USER"), "PASSWORD": os.environ.get("DATABASE_PASSWORD"), "HOST": os.environ.get("DATABASE_HOST"), "PORT": os.environ.get("DATABASE_PORT"), } } else: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ), "DEFAULT_AUTHENTICATION_CLASSES": ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } # JWT config JWT_AUTH = { 'JWT_SECRET_KEY': 'SECRET_KEY', 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', # Handler dari app_auth 'JWT_RESPONSE_PAYLOAD_HANDLER': 'app_auth.sso_jwt.jwt_response_payload_handler', 'JWT_PAYLOAD_HANDLER': 'app_auth.sso_jwt.jwt_payload_handler', } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_USER_MODEL = 'app_auth.User' 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.0/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.0/howto/static-files/ STATIC_URL = '/static/' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ "https://bemapps.cs.ui.ac.id", "https://ptibem.cs.ui.ac.id", "http://localhost:3000", ] URL_PREFIX = os.environ.get("URL_PREFIX", "") MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = f'{URL_PREFIX}/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Django CAS-NG configuration CAS_SERVER = os.environ.get("CAS_SERVER", 'CAS 2') CAS_SERVER_URL = os.environ.get("CAS_SERVER_URL", 'https://sso.ui.ac.id/cas2/') CAS_POPUP_LOGIN = os.environ.get("CAS_POPUP_LOGIN", False) CAS_FORCE_CHANGE_USERNAME_CASE = 'lower' CAS_LOGOUT_COMPLETELY = True CAS_CREATE_USER = True CAS_APPLY_ATTRIBUTES_TO_USER = True # Where to send a user after logging in or out if there is no referrer and no next page set. CAS_REDIRECT_URL = os.environ.get("CAS_REDIRECT_URL", 'https://www.google.com/') CLIENT_HOST = os.environ.get("CLIENT_HOST", 'https://www.google.com/')
[ "agenganugrah@gmail.com" ]
agenganugrah@gmail.com
119662e1432ab732091a253b070a031ee6566b6d
9490e6f64e8824f15384d8f740fe136f31cec1b5
/venv/bin/ipython
5262c7d3931f5ba0f150a72e2986e01884b7f486
[]
no_license
AmoCook/GUI_pj
cc3b49d8fb6244e1c33163812cb1835b8d18b960
729bed91a96d7366401b82dd7cfc2cbc4ff59997
refs/heads/master
2020-04-16T13:23:58.449573
2019-01-14T09:22:11
2019-01-14T09:22:11
165,625,589
0
0
null
null
null
null
UTF-8
Python
false
false
261
#!/Users/amo/PycharmProjects/test_1/venv/bin/python # -*- coding: utf-8 -*- import re import sys from IPython import start_ipython if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(start_ipython())
[ "amo9502@stumail.nwu.edu.cn" ]
amo9502@stumail.nwu.edu.cn
410dc874ff5b29dbc7227b95c1a8c1894533a7aa
6113017bfaec2c2f0e5919b41bb78a5336722303
/luminartechnolabproject/dictionary/word_count.py
e25d3bcb5e42bd4cd5f5f0acda8fe740556e45d1
[]
no_license
prince2255/python
2affcf998dcf1e756fe36c0e8ee5f70ccc226cb6
b0ad2e5a62ac0d6251ceefdc1909f294e9d9ac69
refs/heads/master
2020-12-11T00:42:49.680357
2020-01-28T05:54:32
2020-01-28T05:54:32
233,756,640
0
0
null
null
null
null
UTF-8
Python
false
false
216
py
line="hai hello hai how" words=line.split(" ") dict={} for word in words: if(word not in dict): dict[word]=1 else: dict[word]+=1 for item in dict: print(item,end=" ") print(dict[item])
[ "75prince76@gmail.com" ]
75prince76@gmail.com
c4167281b5e6283bb6cd67dd447b40152c61100c
f36fc94a1ac5ffbfb6d2a78807992347a7e9f6e2
/assignment1/cs231n/classifiers/linear_classifier.py
844826318d20b5e2114d43a0cfb20aa6ca31046a
[]
no_license
Dipeshtamboli/CS231n-Assignments
d2f60504410499aed96da9f988fc69c239096abe
146b3ce885867c81dd609abdbaedabeafa23f7b7
refs/heads/master
2020-04-11T09:10:45.563002
2019-01-01T20:56:18
2019-01-01T20:56:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,966
py
from __future__ import print_function import numpy as np from cs231n.classifiers.linear_svm import * from cs231n.classifiers.softmax import * class LinearClassifier(object): def __init__(self): self.W = None def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100, batch_size=200, verbose=False): """ Train this linear classifier using stochastic gradient descent. Inputs: - X: A numpy array of shape (N, D) containing training data; there are N training samples each of dimension D. - y: A numpy array of shape (N,) containing training labels; y[i] = c means that X[i] has label 0 <= c < C for C classes. - learning_rate: (float) learning rate for optimization. - reg: (float) regularization strength. - num_iters: (integer) number of steps to take when optimizing - batch_size: (integer) number of training examples to use at each step. - verbose: (boolean) If true, print progress during optimization. Outputs: A list containing the value of the loss function at each training iteration. """ num_train, dim = X.shape num_classes = np.max(y) + 1 # assume y takes values 0...K-1 where K is number of classes if self.W is None: # lazily initialize W self.W = 0.001 * np.random.randn(dim, num_classes) # Run stochastic gradient descent to optimize W loss_history = [] for it in range(num_iters): X_batch = None y_batch = None ######################################################################### # TODO: # # Sample batch_size elements from the training data and their # # corresponding labels to use in this round of gradient descent. # # Store the data in X_batch and their corresponding labels in # # y_batch; after sampling X_batch should have shape (dim, batch_size) # @@ X_batch should have shape (batch_size,dim) # and y_batch should have shape (batch_size,) # @@ instead of (dim,batch_size) # # # Hint: Use np.random.choice to generate indices. Sampling with # # replacement is faster than sampling without replacement. # ######################################################################### ####### #CODE ####### ids=np.arange(batch_size) ids=np.random.choice(ids,batch_size,replace=True) X_batch=X[ids] y_batch=y[ids] ####### pass ######################################################################### # END OF YOUR CODE # ######################################################################### # evaluate loss and gradient loss, grad = self.loss(X_batch, y_batch, reg) loss_history.append(loss) # perform parameter update ######################################################################### # TODO: # # Update the weights using the gradient and the learning rate. # ######################################################################### ####### #CODE ####### self.W-=learning_rate*grad ####### pass ######################################################################### # END OF YOUR CODE # ######################################################################### if verbose and it % 100 == 0: print('iteration %d / %d: loss %f' % (it, num_iters, loss)) return loss_history def predict(self, X): """ Use the trained weights of this linear classifier to predict labels for data points. Inputs: - X: A numpy array of shape (N, D) containing training data; there are N training samples each of dimension D. Returns: - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional array of length N, and each element is an integer giving the predicted class. """ y_pred = np.zeros(X.shape[0]) ########################################################################### # TODO: # # Implement this method. Store the predicted labels in y_pred. # ########################################################################### ####### #CODE ####### score=X.dot(self.W) y_pred=np.argmax(score,axis=1) ####### pass ########################################################################### # END OF YOUR CODE # ########################################################################### return y_pred def loss(self, X_batch, y_batch, reg): """ Compute the loss function and its derivative. Subclasses will override this. Inputs: - X_batch: A numpy array of shape (N, D) containing a minibatch of N data points; each point has dimension D. - y_batch: A numpy array of shape (N,) containing labels for the minibatch. - reg: (float) regularization strength. Returns: A tuple containing: - loss as a single float - gradient with respect to self.W; an array of the same shape as W """ pass class LinearSVM(LinearClassifier): """ A subclass that uses the Multiclass SVM loss function """ def loss(self, X_batch, y_batch, reg): return svm_loss_vectorized(self.W, X_batch, y_batch, reg) class Softmax(LinearClassifier): """ A subclass that uses the Softmax + Cross-entropy loss function """ def loss(self, X_batch, y_batch, reg): return softmax_loss_vectorized(self.W, X_batch, y_batch, reg)
[ "dipeshtamboli@gmail.com" ]
dipeshtamboli@gmail.com
d243c506f63f7cc1780806923f5d78de5943116b
08ee36e0bb1c250f7f2dfda12c1a73d1984cd2bc
/src/mnistk/networks/linearrelu_5.py
efcfbec738c0a5f4fad45d439a1de52528caf7c2
[]
no_license
ahgamut/mnistk
58dadffad204602d425b18549e9b3d245dbf5486
19a661185e6d82996624fc6fcc03de7ad9213eb0
refs/heads/master
2021-11-04T07:36:07.394100
2021-10-27T18:37:12
2021-10-27T18:37:12
227,103,881
2
1
null
2020-02-19T22:07:24
2019-12-10T11:33:09
Python
UTF-8
Python
false
false
675
py
# -*- coding: utf-8 -*- """ linearrelu_5.py :copyright: (c) 2019 by Gautham Venkatasubramanian. :license: MIT """ import torch from torch import nn class LinearReLU_5(nn.Module): def __init__(self): nn.Module.__init__(self) self.f0 = nn.Linear(in_features=784, out_features=70, bias=True) self.f1 = nn.ReLU(inplace=False) self.f2 = nn.Linear(in_features=70, out_features=10, bias=False) self.f3 = nn.LogSoftmax(dim=1) def forward(self, *inputs): x = inputs[0] x = x.view(x.shape[0],784) x = self.f0(x) x = self.f1(x) x = self.f2(x) x = self.f3(x) return x
[ "41098605+ahgamut@users.noreply.github.com" ]
41098605+ahgamut@users.noreply.github.com
9928a8ad26f248afae38d0f90a41c40115d927dc
3865d338db6caedff9cce9c0ca2ac4b5929ac2d1
/nanjiang/misc/uniprottrembldat2table.py
d042cb83f1815e6a9de9844a6060620eeda49a66
[]
no_license
vam-sin/bioinfo-toolbox
fc90b347da7d733a2e5732b7352f1e8cdbf5b164
79f52038b7eb20337508ee49a87d2677a8ffad9c
refs/heads/master
2022-12-09T18:39:18.743490
2020-08-26T14:14:58
2020-08-26T14:14:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,325
py
#!/usr/bin/env python # Description: Extract data from uniprot_trembl.dat # ChangeLog 2014-08-28 # add options # -keep_no_genename Keep proteins without gene name # -keep_non_refpro Keep protein not in reference proteome # -keep_isoform Keep proteins in isoforms # ChangeLog 2014-08-29 # taxonomic_class "Bacteria." is considered as "Bacteria", for e.g. O34002, # P07472, Q54506 # import os import sys import myfunc usage = """ usage: uniprottrembldat2table.py -i uniprot_trembl.dat [-o OUTFILE] Description: Extract data from uniprot_trembl.dat and output table with the format # AC Length GN OS OC tab delimited Options: -q Quiet mode -oc STR Restrict to taxonomic_class -keep_no_genename Keep proteins without gene name -keep_non_refpro Keep protein not in reference proteome -keep_isoform Keep proteins in isoforms -h, --help Print this help message and exit Created 2012-06-01, updated 2014-08-29, Nanjiang Shu """ def PrintHelp(): print usage def FilterRecord(recordList, restrictOCList):#{{{ # Filter records # 1. without gene name # 2. without keyword "reference proteome" (KW) # 3. filter out isoforms (those with ID-names ended with -INT) if len(recordList) <= 0: return [] newList = [] isRestrictOC = False if len(restrictOCList) > 0 and restrictOCList[0].lower() != "all": isRestrictOC = True for rd in recordList: if g_params['filter_no_genename'] and rd['genename'] == "" : print >> sys.stderr, "%s NO genaname, ignored" % (rd['accession']) continue if g_params['filter_non_refpro'] and not rd['isRefPro']: print >> sys.stderr, "%s not reference proteome, ignored" % (rd['accession']) continue if g_params['filter_isoform'] and rd['accession'].find("-") != -1: print >> sys.stderr, "%s with isoforms, ignored" % (rd['accession']) continue if isRestrictOC and (rd['taxonomic_class'] not in restrictOCList): print >> sys.stderr, (rd['accession'], "not in", restrictOCList, "ignored.") continue newList.append(rd) return newList #}}} def WriteRecord(recordList, fpout):#{{{ for rd in recordList: fpout.write("%s\t%d\t%s\t%s\t%s\t%s\t%d\n"%( rd['accession'], rd['length'], rd['genename'], rd['organism'], rd['taxonomic_class'], ";".join(rd['pfamidList']), rd['isRefPro'] )) #}}} def ExtractFromUniprotTremblRecord(recordContent):#{{{ record = {} lines = recordContent.split("\n") numLine = len(lines) i = 0 # AC can be multiple lines str_accession = "" # AC str_genename = "" # GN str_organism = "" # OS pfamidList = [] # str_keyword = "" length = 0 # from ID record str_taxonomic_class = "" # OC, e.g. Archaes, Becteria for line in lines: if len(line) > 2: tag = line[0:2] if tag == "ID": strs = line[5:].split() nstrs = len(strs) length = int (strs[nstrs-2]) elif tag == "AC": str_accession += line[5:] elif tag == "GN": str_genename += line[5:] elif tag == "OS": str_organism += line[5:] elif tag == "OC": str_taxonomic_class += line[5:] elif tag == "KW": str_keyword += line[5:] elif tag == "DR": if line[5:].find("Pfam") == 0: strs = line[5:].split(";") pfamidList.append(strs[1].strip()) elif tag == "SQ": break #accession accessionList = str_accession.split(";") accessionList = filter(None, accessionList) accessionList = [x.strip() for x in accessionList] accession = ";".join(accessionList) # genename: strs = str_genename.split(";") strs = filter(None, strs) li = [] for ss in strs: sp1 = ss.split("=") if len(sp1) == 1: ac = sp1[0].strip() else: ac = sp1[1].strip() li.append(ac) genename = ";".join(li) # organism organism = str_organism.rstrip(".") # taxonomic_class taxonomic_class = str_taxonomic_class.split(";")[0] taxonomic_class = taxonomic_class.strip(".") # added 2014-08-29, this solved Bacteria. for P07472. isRefPro = False if str_keyword.find("Reference proteome") != -1: isRefPro = True else: isRefPro = False if accession != "": record['accession'] = accession record['length'] = length record['genename'] = genename record['organism'] = organism record['taxonomic_class'] = taxonomic_class record['isRefPro'] = isRefPro record['pfamidList'] = pfamidList return record else: return {} #}}} def Read_UniprotTremblData_from_buffer(buff, recordList, isEOFreached):#{{{ if not buff: return "" unprocessedBuffer = "" beg = 0 end = 0 while 1: beg=buff.find("ID ",beg) if beg >= 0: end=buff.find("\n//",beg+1) if end >= 0: recordContent = buff[beg:end] record = ExtractFromUniprotTremblRecord(recordContent) if record != {}: recordList.append(record) beg = end else: unprocessedBuffer = buff[beg:] break else: unprocessedBuffer = buff[end:] break if isEOFreached and unprocessedBuffer: recordContent = unprocessedBuffer record = ExtractFromUniprotTremblRecord(recordContent) if record != {}: recordList.append(record) unprocessedBuffer = "" return unprocessedBuffer #}}} def UniprotTremblData2Table(datafile, restrictOCList, fpout):#{{{ try: fpout.write("#AC\tLength\tGN\tOS\tOC\tPfamID\tisRefPro\n") fpin = open(datafile, "r") unprocessedBuffer="" isEOFreached = False while 1: buff = fpin.read(BLOCK_SIZE) if len(buff) < BLOCK_SIZE: isEOFreached = True buff = unprocessedBuffer + buff recordList = [] unprocessedBuffer = Read_UniprotTremblData_from_buffer( buff, recordList, isEOFreached) if len(recordList) > 0: filteredRecordList = FilterRecord(recordList, restrictOCList) if len(filteredRecordList) > 0: WriteRecord(filteredRecordList, fpout) if isEOFreached == True: break fpin.close() except IOError: print >> sys.stderr, "Failed to read datafile ", datafile return 1 #}}} def main(g_params):#{{{ argv = sys.argv numArgv = len(argv) if numArgv < 2: PrintHelp() return 1 outfile = "" datafile = "" restrictOCList = [] i = 1 isNonOptionArg=False while i < numArgv: if isNonOptionArg == True: datafile = argv[i] isNonOptionArg = False i += 1 elif argv[i] == "--": isNonOptionArg = True i += 1 elif argv[i][0] == "-": if argv[i] in ["-h", "--help"]: PrintHelp() return 1 elif argv[i] in ["-o", "--o", "-outfile", "--outfile"]: outfile = argv[i+1] i += 2 elif argv[i] in ["-i", "--i"] : datafile = argv[i+1] i += 2 elif argv[i] in ["-keep_isoform", "--keep_isoform"] : g_params['filter_isoform'] = False i += 1 elif argv[i] in ["-keep_non_refpro", "--keep_non_refpro"] : g_params['filter_non_refpro'] = False i += 1 elif argv[i] in ["-keep_no_genename", "--keep_no_genename"] : g_params['filter_no_genename'] = False i += 1 elif argv[i] in ["-oc", "--oc"] : restrictOCList.append(argv[i+1]) i += 2 elif argv[i] in ["-q"]: g_params['isQuiet'] = True i += 1 else: print >> sys.stderr, "Error! Wrong argument:", argv[i] return 1 else: datafile = argv[i] i += 1 if not os.path.exists(datafile): print >> sys.stderr, "datafile %s not set or not exists. Exit" %(datafile) return 1 fpout = myfunc.myopen(outfile, sys.stdout, "w", False) UniprotTremblData2Table(datafile, restrictOCList, fpout) myfunc.myclose(fpout) return 0 #}}} def InitGlobalParameter():#{{{ g_params = {} g_params['isQuiet'] = True g_params['filter_no_genename'] = True g_params['filter_non_refpro'] = True g_params['filter_isoform'] = True return g_params #}}} if __name__ == '__main__' : BLOCK_SIZE=100000 g_params = InitGlobalParameter() sys.exit(main(g_params))
[ "nanjiang.shu@bils.se" ]
nanjiang.shu@bils.se
8e65f1218388ca45500e4bd62348647c2fbb7197
344e2956b4e2a30a8ef7532d951f96d995d1dd1e
/21_maskrcnn/lib/cfgs/cascade_mask_rcnn_r101_64x4d_fpn_coco.py
d43096d1dc7c09bd4ed5fbb76ee8a9fbe1c09e25
[ "Apache-2.0", "LGPL-3.0-only", "MIT", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "GPL-3.0-only" ]
permissive
karndeepsingh/Monk_Object_Detection
e64199705326e4cd65e4b29946cae210a4ef9649
425fa50a3236cb9097389646275da06bf9185f6b
refs/heads/master
2022-12-22T18:26:53.933397
2020-09-28T12:49:50
2020-09-28T12:49:50
299,307,843
1
1
Apache-2.0
2020-09-28T12:52:18
2020-09-28T12:52:17
null
UTF-8
Python
false
false
9,156
py
# model settings model = dict( type='CascadeRCNN', pretrained='torchvision://resnext101_64x4d', backbone=dict( type='ResNeXt', depth=101, groups=64, base_width=4, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)), roi_head=dict( type='CascadeRoIHead', num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)))) # model training and testing settings train_cfg = dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=0, pos_weight=-1, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=2000, max_num=2000, nms_thr=0.7, min_bbox_size=0), rcnn=[ dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.6, neg_iou_thr=0.6, min_pos_iou=0.6, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False), dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.7, min_pos_iou=0.7, match_low_quality=False, ignore_iof_thr=-1), sampler=dict( type='RandomSampler', num=512, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False) ]) test_cfg = dict( rpn=dict( nms_across_levels=False, nms_pre=1000, nms_post=1000, max_num=1000, nms_thr=0.7, min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, mask_thr_binary=0.5)) #Dataset Settings dataset_type = 'CocoDataset' data_root = '' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( samples_per_gpu=, #change1 workers_per_gpu=, #change2 train=dict( type=dataset_type, classes=, #change3 ann_file=, #change4 img_prefix=, #change5 pipeline=train_pipeline), val=dict( type=dataset_type, classes=, #change6 ann_file=, #change7 img_prefix=, #change8 pipeline=test_pipeline), test=dict( type=dataset_type, classes=, #change9 ann_file=, #change10 img_prefix=, #change11 pipeline=test_pipeline)) evaluation = dict(interval=, metric='bbox') #change9 # Schedule Settings optimizer = dict(type='SGD', lr=, momentum=, weight_decay=) #change12 optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=) #change13 total_epochs = #change14 # Runtime Dataset checkpoint_config = dict(interval=) #change15 # yapf:disable log_config = dict( interval=50, #change16 hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable dist_params = dict(backend='nccl') log_level = 'INFO' load_from = #change17 resume_from = None workflow = [('train', 1)] gpu_ids = None #change18
[ "abhishek4273@gmail.com" ]
abhishek4273@gmail.com
ba5bb91ca511973700ab76b1f0f7a7bd8c5fc7f0
d8bc78d7bf99ad456920740e93db5428093dcb45
/usuario/models.py
27473f1074764cbbd65d9bdb9a33d6ad0e6d8699
[ "MIT" ]
permissive
ongame-entretenimento/cadastro
d698adce23eccf066c8da2504d25c7a93a072f46
8c9de028088a96ad2e761156ee597cb56456b376
refs/heads/master
2021-03-12T20:13:24.737376
2014-09-10T20:45:35
2014-09-10T20:45:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,810
py
# -*- coding: utf-8 -*- from django.db import models class Estado(models.Model): nome = models.CharField(max_length=100) def __unicode__(self): return self.nome class Cidade(models.Model): nome = models.CharField(max_length=100) estado = models.ForeignKey(Estado) def __unicode__(self): return self.nome class Usuario(models.Model): SEXO = ( (0, 'Masculino'), (1, 'Feminino'), ) usuario = models.CharField(max_length=16, unique=True) senha = models.CharField(max_length=32) email = models.EmailField(max_length=40, unique=True) data_nascimento = models.DateField('Data de Nascimento') sexo = models.IntegerField(default=0, choices=SEXO) cidade = models.ForeignKey(Cidade) confirmado = models.BooleanField(default=0) hash = models.CharField(max_length=32) data_cadastro = models.DateTimeField('Data de Cadastro') def __unicode__(self): return self.usuario class Meta: verbose_name = 'Usuário' verbose_name_plural = 'Usuários' class UsuarioPendente(models.Model): SEXO = ( (0, 'Masculino'), (1, 'Feminino'), ) usuario = models.CharField(max_length=16, unique=True) senha = models.CharField(max_length=32) email = models.EmailField(max_length=40, unique=True) data_nascimento = models.DateField('Data de Nascimento') sexo = models.IntegerField(default=0, choices=SEXO) cidade = models.ForeignKey(Cidade) confirmado = models.BooleanField(default=0) hash = models.CharField(max_length=32) data_cadastro = models.DateTimeField('Data de Cadastro') def __unicode__(self): return self.usuario class Meta: verbose_name = 'Usuário Pendente' verbose_name_plural = 'Usuários Pendentes'
[ "ti@ti-netbook.(none)" ]
ti@ti-netbook.(none)
8154743effc63d1f2a7c401f9819631fb1bc162c
a20e686d8e176cd30e157bf55f219b1738b204b7
/lambda/lambda_comprehend.py
44030402bbbac2107844a532e3e5b17c385263fd
[ "MIT" ]
permissive
Veryinheart/aws-tutorial-code
5e61465571f305e75f1905fa26aab0e8dadf3168
6b2a88340d8a94e51bf5c2935704edb9a78c4244
refs/heads/master
2022-07-07T14:15:35.018888
2020-05-13T18:32:22
2020-05-13T18:32:22
267,770,685
1
0
MIT
2020-05-29T05:12:37
2020-05-29T05:12:37
null
UTF-8
Python
false
false
927
py
""" -*- coding: utf-8 -*- ======================== AWS Lambda ======================== Contributor: Chirag Rathod (Srce Cde) ======================== """ import boto3 from pprint import pprint def lambda_handler(event, context): s3 = boto3.client("s3") bucket = "bucket-name" key = "filename.txt" file = s3.get_object(Bucket = bucket, Key = key) paragraph = str(file['Body'].read()) comprehend = boto3.client("comprehend") #Extracting sentiments using comprehend sentiment = comprehend.detect_sentiment(Text = paragraph, LanguageCode = "en") print(sentiment) #Extracting entities using comprehend entities = comprehend.detect_entities(Text = paragraph, LanguageCode = "en") pprint(entities) #Extracting keyphrase using comprehend keyphrase = comprehend.detect_key_phrases(Text = paragraph, LanguageCode = "en") pprint(keyphrase) return 'Thanks'
[ "chiragr83@gmail.com" ]
chiragr83@gmail.com
3603592a43f6cb57493b90f261bc46ecb00ef171
1f936103af336af6bbd335f45d6baa55c426922b
/monatbx/generate_random_image_list.py
8a9ca4dabc8f05852c8bdb56a7c99cb54b3732fe
[]
no_license
monarin/monatbx
2ec342d67f1fbccb82656218ffd136f2eb7d96ab
43f56974f811e5b2b0dcc428d4f9b36043ed9d04
refs/heads/master
2020-06-18T13:08:58.893701
2016-11-30T00:58:18
2016-11-30T00:58:18
75,136,381
0
0
null
null
null
null
UTF-8
Python
false
false
510
py
import os import sys import random p = sys.argv[1] n_images = int(sys.argv[2]) frame_files = [] if os.path.isdir(p): for pickle_filename in os.listdir(p): if pickle_filename.endswith('.pickle'): frame_files.append(p+'/'+pickle_filename) i_rand = random.sample(range(len(frame_files)),n_images) frame_files_sel = [frame_files[i] for i in i_rand] txt_out = '' for frame in frame_files_sel: txt_out += frame + '\n' f = open('frame_rand_'+str(n_images)+'.lst', 'w') f.write(txt_out) f.close()
[ "monarin@gmail.com" ]
monarin@gmail.com
4eb2b48de24e83967dcf33b509a946a81d00451d
d03ef3eac49ccae08fe33a1ecf874d11fa86e635
/dozo/commands/extend.py
a19374c1461cdc71c2d61c29a28cf1088143d55f
[]
no_license
johnmontero/dozo
5ddd2801f8fc919443faffde68fad5ff3f0be8aa
abc3377e3ee32ac21735bd22a7fd41b7d9c881d3
refs/heads/master
2021-01-10T21:08:56.890991
2012-05-15T06:47:15
2012-05-15T06:47:15
2,735,707
0
0
null
null
null
null
UTF-8
Python
false
false
5,931
py
from os import path from os import mkdir import pystache import envoy from tambo import Transport from dozo.config import db from dozo.config import get_config_value from dozo.commands import CommandError TEMPLATE_OPTION_COMMAND = '''# -*- coding: utf-8-*- from tambo import Transport from dozo.config import db from dozo.config import get_config_value class Command(object): """ {{name}} related actions: --h, --help, help Prints this help text and exits. print Print description of the {{name}} """ help = "Commands associated with {{name}}" def __init__(self, argv, conf=None): self.argv = argv self.config = conf or db.stored_config() self.actions = { 'print' : self.{{name}}_print } def {{name}}_print(self): print "Print {{name}}" def parse_args(self): transport = Transport(self.argv, check_help=False) transport.catch_help = self.__doc__ if len(self.argv) <= 1: transport.print_help() transport.parse_args() for action in self.actions: if transport.has(action): return self.actions.get(action)() # If nothing matches, print the help transport.print_help() ''' class Command(object): """ Command Extend related actions: -h, --help, help Prints this help text and exits. create Create subcommand edit Edit subcommand path Path to extend subcommands """ help = "Commands associated with this commands extend's Dozo" def __init__(self, argv, conf=None): self.argv = argv self.config = conf or db.stored_config() self.actions = { 'create' : self.cmd_create, 'edit' : self.cmd_edit, 'path' : self.cmd_path_extend } def cmd_create(self): """ """ if len(self.argv) < 3: value = None else: value = self.argv[2] if value is not None: if value.endswith('.py'): raise CommandError("\nNot include '.py'\n") path_extend = get_config_value('path-extend') if path_extend is None: print "Path extend is not define." print "Use:\n dozo extend path /path/to/extend" return path_to_file = "{0}/commands/{1}.py".format(path_extend,value) if path.isfile(path_to_file): print "\nOption command '{0}' exist.\n".format(value) filename = '%s/commands/%s.py' % ( path_extend, value ) f = open(filename,'w+') f.write(pystache.render(TEMPLATE_OPTION_COMMAND, {'name':value})) f.close() def cmd_edit(self): """ """ try: extend_command = self.argv[2] except: extend_command = None if extend_command is None: #print "Please use option:" #print " dozo %s" % self.usage return text_editor = get_config_value('text-editor') if text_editor is None: print "\n Text editor is not define.\n" print "Use:\n dozo config add text-editor=vim\n" return path_extend = get_config_value('path-extend') if path_extend is None: print('''\n Path extend is not define.\n Use:\n dozo config path-extend /opt/dozo/dozo_extend''') return filename = '{0}/commands/{1}.py'.format(path_extend, extend_command) if not path.isfile(filename): print('\n{0}: Extend command not exist.\n'.format( extend_command)) return cmd = '{0} {1}'.format(text_editor, filename) r = envoy.run(cmd) if r is not 0: print('\n{0}\n'.format(r.std_err)) def cmd_values(self): """ """ try: for i in self.config.items(): print "%-15s= %-4s" % (i[0], i[1]) print '' except Exception, error: raise CommandError("Could not complete command: %s" % error) def cmd_path_extend(self): """ """ try: path_extend = self.argv[2] except: path_extend = None if path_extend is None: try: del self.config['path-extend'] except KeyError: pass else: if '-' in '/'.join(path_extend.split('/')[-1:]): raise CommandError("\nIs not character valid '-'.\n") if not path.isdir(path_extend): mkdir(path_extend) path_to_file = '%s/__init__.py' % path_extend if not path.isfile(path_to_file): f = open(path_to_file,'w+') f.write('__name__="path-extend"\n') f.close() path_command = '%s/commands' % path_extend if not path.isdir(path_command): mkdir(path_command) path_to_file = '%s/__init__.py' % path_command if not path.isfile(path_to_file): f = open(path_to_file,'w+') f.write('__name__="commands"\n') f.close() self.config['path-extend'] = path_extend def parse_args(self): transport = Transport(self.argv, check_help=False) transport.catch_help = self.__doc__ if len(self.argv) <= 1: transport.print_help() transport.parse_args() for action in self.actions: if transport.has(action): return self.actions.get(action)() # If nothing matches, print the help transport.print_help()
[ "jmonteroc@gmail.com" ]
jmonteroc@gmail.com
575a9eb27903aa702c0a9262637736f7f935d21b
0be37def5e61f61858b9a3c9cbac55cad53224ec
/finchcollector/finchcollector/settings.py
6949914a0d45e62392c2202a1714bbbddc5e4294
[]
no_license
crystallynnv/finchcollector
177b6c23db3175f9f66c0295d455bfff7dc16daa
9937ec6d0ca6f2b53b2bb7eb5ccac1ecf2a3186a
refs/heads/master
2021-03-31T06:03:18.088621
2020-03-21T16:41:10
2020-03-21T16:41:10
248,083,778
0
0
null
null
null
null
UTF-8
Python
false
false
3,172
py
""" Django settings for finchcollector project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6axj657e7l7gj193##i6ovpb#kbba@em-j$k4d1dd$jcgf3ou%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'main_app', '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 = 'finchcollector.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 = 'finchcollector.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'finchcollector', } } # Password validation # https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/ STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/finches/' LOGOUT_REDIRECT_URL = '/'
[ "home@homes-mbp.lan" ]
home@homes-mbp.lan
947dced367bd8dde73a91f39443a0f7b80bda3a8
86319aad3690906f614ac1af28b8843529e9e0da
/thwackbin/data/__init__.py
a156485bd18d0e80a766cdfa5aabbee5f290dab9
[]
no_license
sohgoh/thwackbin
b5828783a6179e96784bed0bdb894b179e3bea07
ba9fedc4bcec598f367aa6d4f2567d1840c65c51
refs/heads/master
2021-01-21T03:14:08.261732
2014-04-16T03:53:51
2014-04-16T04:02:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
410
py
""" thwackbin.data ~~~~~~~~~~~~~~ Package which contains mock results data stored on the file system. """ __author__ = 'Andrew Hawker <andrew@appthwack.com>' import json import os RESULTS = None ROOT = os.path.dirname(__file__) def init(): """ Load and cache our results.json data on startup. """ global RESULTS RESULTS = json.load(open(os.path.join(ROOT, 'results.json')))
[ "andrew.r.hawker@gmail.com" ]
andrew.r.hawker@gmail.com
0ebcc3529c3a8cb45cbce6983629d8612e22f559
4857bf63cfc7a500cfa1f476e05399a82d43a461
/Hex/play.py
e50b5e733778ad8a59d5df88a013082728e6f692
[]
no_license
askbk/IT3105-AI-Programming
fe862d85499be0df7a26adbddc7dc050232acc1a
b3543b21fba878f402fd932665473a7f2765cde2
refs/heads/master
2023-04-04T19:06:00.102865
2021-04-19T08:32:20
2021-04-19T08:32:20
328,206,521
0
0
null
null
null
null
UTF-8
Python
false
false
496
py
import json from Hex.Game import Board from Hex.Player import Player if __name__ == "__main__": with open("./config.json", mode="r") as f: config = json.loads(f.read()) play_config = config.get("simple_playthrough") Player.from_config( config, game=Board(size=play_config.get("board_size")) ).play_episodes( play_config.get("episodes"), display_board=play_config.get("display_board"), time_interval=play_config.get("time_interval"), )
[ "askbk@protonmail.com" ]
askbk@protonmail.com
4325da0054b8ecb4e522b27b733ba8e35f54ecc8
0cb76eb5d69972c6da2b7fe6011d6bd5e694eee4
/setup.py
8cc5d30ce029ce325d8ec2e7730928559d145ac3
[]
no_license
xfenix/django-xflatpages
990d58e9bd3b536c6f65240ce9c4c6e7344a6ddf
763f8898100081a9798d6b25324150a5c08f3737
refs/heads/master
2020-05-18T00:50:33.529864
2014-12-16T23:56:20
2014-12-16T23:56:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
445
py
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages from xflatpages import __version__ # readme descr = 'Simple flatpages app' setup( name='django-xflatpages', version=__version__, description=descr, long_description=descr, author='Xfenix', author_email='ad@xfenix.ru', packages=find_packages(), include_package_data=True, install_requires=[ 'django-cache-utils', ] )
[ "ad@xfenix.ru" ]
ad@xfenix.ru
26733fb81cb6083b579420deb5cc816fb49e12d9
c1b1967be7dde14f434703922768f4379334e2f7
/angr_platforms/msp430/arch_msp430.py
2b193654051a08c8bd5c73575dc91e00935e1d83
[ "BSD-2-Clause" ]
permissive
grant-h/angr-platforms
aecd0bcc18be870416f508f3ef4f769ffc9878c7
b0e4648d3ea00fef5c05e4bd1fa9c59c6c4440bb
refs/heads/master
2021-07-03T19:43:39.324945
2017-09-08T22:43:35
2017-09-08T22:43:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,037
py
from archinfo.arch import register_arch, Arch class ArchMSP430(Arch): def __init__(self, endness="Iend_LE"): super(ArchMSP430, self).__init__(endness) # TODO: Define function prologs # ip_offset = 136 # sp_offset = 124 # bp_offset = 128 # ret_offset = 16 # lr_offset = 132 # syscall_num_offset = 16 # call_pushes_ret = False # stack_change = -4 # branch_delay_slot = True sizeof = {'short': 16, 'int': 16, 'long': 32, 'long long': 64} function_prologs = {} function_epilogs = {} qemu_name = 'msp430' bits = 16 name = "MSP430" ida_processor = 'msp430' max_inst_bytes = 6 ret_instruction = "\x98\x00" nop_instruction = "" instruction_alignment = 1 persistent_regs = [] default_register_values = [ ( 'sp', Arch.initial_sp, True, 'global' ), # the stack ] entry_register_values = { } default_symbolic_registers = [] class Mode: REGISTER_MODE = 0 INDEXED_MODE = 1 INDIRECT_REGISTER_MODE = 2 INDIRECT_AUTOINCREMENT_MODE = 3 SYMBOLIC_MODE = 4 ABSOLUTE_MODE = 5 IMMEDIATE_MODE = 6 CONSTANT_MODE0 = 7 CONSTANT_MODE1 = 8 CONSTANT_MODE2 = 9 CONSTANT_MODE4 = 10 CONSTANT_MODE8 = 11 CONSTANT_MODE_NEG1 = 12 OFFSET = 13 register_index = [ 'pc', 'sp', 'sr', 'cg', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15' ] register_names = { 0: 'pc', 2: 'sp', 4: 'sr', 6: 'zero', 8: 'r4', 10: 'r5', 12: 'r6', 14: 'r7', 16: 'r8', 18: 'r9', 20: 'r10', 22: 'r11', 24: 'r12', 26: 'r13', 28: 'r14', 39: 'r15' } registers = { 'r0': (0, 2), 'pc': (0, 2), 'ip': (0, 2), 'r1': (2, 2), 'sp': (2, 2), 'r2': (4, 2), 'sr': (4, 2), 'r3': (6, 2), 'zero': (6, 2), 'cg': (6, 2), 'r4': (8, 2), 'r5': (10, 2), 'r6': (12, 2), 'r7': (14, 2), 'r8': (16, 2), 'r9': (18, 2), 'r10': (20, 2), 'r11': (22, 2), 'r12': (24, 2), 'r13': (26, 2), 'r14': (28, 2), 'r15': (30, 2) } argument_registers = { registers['r4'][0], registers['r5'][0], registers['r6'][0], registers['r7'][0], registers['r8'][0], registers['r9'][0], registers['r10'][0], registers['r11'][0], registers['r12'][0], registers['r13'][0], registers['r14'][0], registers['r15'][0], } # EDG: Can you even use PIC here? I don't think so dynamic_tag_translation = {} register_arch([r'msp|msp430|em_msp430'], 32, 'Iend_LE' , ArchMSP430)
[ "edg@cs.ucsb.edu" ]
edg@cs.ucsb.edu
6f4f86844af5579493a6f13c1a0dcd95fafe0bd1
c79e7e691c9fa5cc05bd227209762f735e6263e7
/pyy1/.pycharm_helpers/python_stubs/-1550516950/apt_pkg/Hashes.py
92a3d2de462fdebf1fdaf1414141fd87e81bd746
[ "Apache-2.0" ]
permissive
pyy1988/pyy_test1
27fd5fbd41935ba907e26f4f4d2546ca502f29a6
6bea878409e658aa87441384419be51aaab061e7
refs/heads/master
2020-04-05T07:01:58.745653
2018-11-08T12:51:00
2018-11-08T12:51:00
156,660,893
0
0
null
null
null
null
UTF-8
Python
false
false
1,555
py
# encoding: utf-8 # module apt_pkg # from /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 """ Classes and functions wrapping the apt-pkg library. The apt_pkg module provides several classes and functions for accessing the functionality provided by the apt-pkg library. Typical uses might include reading APT index files and configuration files and installing or removing packages. """ # no imports from .object import object class Hashes(object): """ Hashes([object: (bytes, file)]) Calculate hashes for the given object. It can be used to create all supported hashes for a file. The parameter 'object' can be a bytestring, an object providing the fileno() method, or an integer describing a file descriptor. """ def __init__(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass md5 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """The MD5Sum of the file as a string.""" sha1 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """The SHA1Sum of the file as a string.""" sha256 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """The SHA256Sum of the file as a string."""
[ "347003917@qq.com" ]
347003917@qq.com
bae0c8adce6d3a4872acaeed60d8daa4b5c24172
3357d08b91a61bbfb653f5506e63aa77caf60868
/message.py
9cf75cf1ba3b0fd0cc47c238619a77bfbaa7290e
[]
no_license
saivishwakgangam/error-detection_crc
2f121553c6381ff790ed2f410e4f95c38d377c52
143b50864a741ae6b6a8e47226d632d14c841e48
refs/heads/main
2023-03-24T23:06:06.626384
2021-03-22T19:00:30
2021-03-22T19:00:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
207
py
class Message: def __init__(self,send_matrix,crc_code): self.send_matrix=send_matrix self.crc_code=crc_code def empty(self): self.send_matrix=[] self.crc_code=b''
[ "noreply@github.com" ]
noreply@github.com
57b977f2ae53db87282b285aa878effd453face0
2a46ad4e83dcd903451fb5fba8d04da266dbd49e
/Algorithm/Leetcode/Codes/ConstructBinaryTreeFromInorderAndPostorderTraversal.py
769cc7114912f93e7e81cf26965025c23ac1cdbd
[]
no_license
chloeeekim/TIL
e248801508340cb2eb9f3cfddc486b7dd7250386
c5a94e81aa2f2dfcc626820205ca9feaad069fad
refs/heads/master
2022-03-02T04:05:24.439271
2022-02-22T01:25:14
2022-02-22T01:25:14
190,150,063
8
1
null
null
null
null
UTF-8
Python
false
false
1,522
py
""" 106. Construct Binary Tree from Inorder and Postorder Traversal : https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ 어떤 트리의 inorder, postorder traversal 결과가 리스트로 주어졌을 때, 트리를 복원하는 문제 - 트리 내에 중복된 값은 없다고 가정한다 Example: - Input : inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] - Output : [3,9,20,null,null,15,7] Note: recursive하게 해결 inorder와 preorder로 트리를 복원하는 문제에서 약간만 변형 postorder 리스트의 마지막 값이 root가 되고, inorder 리스트에서 root 값을 기준으로 left children과 right children으로 구분된다 위 조건이 모든 subtree에 대해서도 만족 preorder에서는 left children을 먼저 구하고, right children을 구하는 순서였으나, postorder에서는 반대로 right children을 먼저 구하고, left children을 구하는 순서 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: if inorder: rootval = postorder.pop(-1) root = TreeNode(rootval) idx = inorder.index(rootval) root.right = self.buildTree(inorder[idx+1:], postorder) root.left = self.buildTree(inorder[:idx], postorder) return root
[ "hiyaku0317@gmail.com" ]
hiyaku0317@gmail.com
31137672e5dfb8c23d9a8d755c634681497e7e42
609bf65158e80d7f11dce7406b1075be83688949
/trials.py
c9084b4ff11931e66a38e94033f658cded27492e
[]
no_license
jacquetta/js-trials1
ac4f674b6f650514da5f3d752f13aa5cfede9af7
137555766561327fc3aa51e2bd9dc6a719902315
refs/heads/main
2023-08-19T06:17:31.200662
2021-10-18T21:27:27
2021-10-18T21:27:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,802
py
"""Python functions for JavaScript Trials 1.""" group = ['item1', 'item2', 'item3'] nums_all = [1, 2, 4, 5, 7, 8,] def output_all_items(items): pass for item in items: # print(item) return items output_all_items(group) def get_all_evens(nums): pass even_nums = [] for num in nums: if num % 2 == 0: even_nums.append(num) # print(even_nums) return even_nums get_all_evens([7, 8, 10, 1, 2, 2]) def get_odd_indices(items): pass # TODO: replace this line with your code result = [] for i in range(len(items)): if i % 2 != 0: result.append(items[i]) # print(result) return result get_odd_indices([1, 'hello', True, 500]) def print_as_numbered_list(items): pass i = 1 for item in items: # print(f'{i}. {item}') i += 1 print_as_numbered_list([1, 'hello', True]) def get_range(start, stop): pass nums = [] i = start for i in range(stop): nums.append(i) # print(nums) get_range(0, 5) def censor_vowels(word): pass chars = [] for letter in word: if letter in "aeiou": chars.append("*") else: chars.append(letter) return ''.join(chars) censor_vowels('hello world') def snake_to_camel(string): pass camel_case = [] word = string.split("_") print(word) # camel_case.append(upper(word)) snake_to_camel('hello_world') def longest_word_length(words): pass # TODO: replace this line with your code def truncate(string): pass # TODO: replace this line with your code def has_balanced_parens(string): pass # TODO: replace this line with your code def compress(string): pass # TODO: replace this line with your code
[ "jacquettavb@hotmail.com" ]
jacquettavb@hotmail.com
cd04b6a0b795d69ec92e5523eb52cd2095f05e08
06c9fa55c525a89c48991f699b3b14099fcefd84
/parallax/parallax/examples/nmt/inference_test.py
7c342f9f976885e9c242f7cec36a709a949d8aea
[ "Apache-2.0" ]
permissive
snuspl/parallax
ec21997f17b74ed16484d8fe854001c3c0540f51
351a913877df3ae03f1b1b52320ee4536b17a667
refs/heads/master
2022-03-13T20:40:08.823881
2022-02-21T08:12:43
2022-02-21T08:12:43
142,282,082
133
33
Apache-2.0
2019-07-09T03:46:02
2018-07-25T10:01:57
Python
UTF-8
Python
false
false
8,018
py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for model inference.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow as tf from . import attention_model from . import model_helper from . import model as nmt_model from . import gnmt_model from . import inference from .utils import common_test_utils float32 = np.float32 int32 = np.int32 array = np.array class InferenceTest(tf.test.TestCase): def _createTestInferCheckpoint(self, hparams, out_dir): if not hparams.attention: model_creator = nmt_model.Model elif hparams.attention_architecture == "standard": model_creator = attention_model.AttentionModel elif hparams.attention_architecture in ["gnmt", "gnmt_v2"]: model_creator = gnmt_model.GNMTModel else: raise ValueError("Unknown model architecture") infer_model = model_helper.create_infer_model(model_creator, hparams) with self.test_session(graph=infer_model.graph) as sess: loaded_model, global_step = model_helper.create_or_load_model( infer_model.model, out_dir, sess, "infer_name") ckpt = loaded_model.saver.save( sess, os.path.join(out_dir, "translate.ckpt"), global_step=global_step) return ckpt def testBasicModel(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=1, attention="", attention_architecture="", use_residual=False,) vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "basic_infer") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference(ckpt, infer_file, output_infer, hparams) with open(output_infer) as f: self.assertEqual(5, len(list(f))) def testBasicModelWithMultipleTranslations(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=1, attention="", attention_architecture="", use_residual=False, num_translations_per_input=2, beam_width=2, ) vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "multi_basic_infer") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference(ckpt, infer_file, output_infer, hparams) with open(output_infer) as f: self.assertEqual(10, len(list(f))) def testAttentionModel(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=1, attention="scaled_luong", attention_architecture="standard", use_residual=False,) vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "attention_infer") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference(ckpt, infer_file, output_infer, hparams) with open(output_infer) as f: self.assertEqual(5, len(list(f))) def testMultiWorkers(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=2, attention="scaled_luong", attention_architecture="standard", use_residual=False,) vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "multi_worker_infer") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") num_workers = 3 # There are 5 examples, make batch_size=3 makes job0 has 3 examples, job1 # has 2 examples, and job2 has 0 example. This helps testing some edge # cases. hparams.batch_size = 3 ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference( ckpt, infer_file, output_infer, hparams, num_workers, jobid=1) inference.inference( ckpt, infer_file, output_infer, hparams, num_workers, jobid=2) # Note: Need to start job 0 at the end; otherwise, it will block the testing # thread. inference.inference( ckpt, infer_file, output_infer, hparams, num_workers, jobid=0) with open(output_infer) as f: self.assertEqual(5, len(list(f))) def testBasicModelWithInferIndices(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=1, attention="", attention_architecture="", use_residual=False, inference_indices=[0]) vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "basic_infer_with_indices") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference(ckpt, infer_file, output_infer, hparams) with open(output_infer) as f: self.assertEqual(1, len(list(f))) def testAttentionModelWithInferIndices(self): hparams = common_test_utils.create_test_hparams( encoder_type="uni", num_layers=1, attention="scaled_luong", attention_architecture="standard", use_residual=False, inference_indices=[1, 2]) # TODO(rzhao): Make infer indices support batch_size > 1. hparams.infer_batch_size = 1 vocab_prefix = "nmt/testdata/test_infer_vocab" hparams.src_vocab_file = vocab_prefix + "." + hparams.src hparams.tgt_vocab_file = vocab_prefix + "." + hparams.tgt infer_file = "nmt/testdata/test_infer_file" out_dir = os.path.join(tf.test.get_temp_dir(), "attention_infer_with_indices") hparams.out_dir = out_dir os.makedirs(out_dir) output_infer = os.path.join(out_dir, "output_infer") ckpt = self._createTestInferCheckpoint(hparams, out_dir) inference.inference(ckpt, infer_file, output_infer, hparams) with open(output_infer) as f: self.assertEqual(2, len(list(f))) self.assertTrue(os.path.exists(output_infer+str(1)+".png")) self.assertTrue(os.path.exists(output_infer+str(2)+".png")) if __name__ == "__main__": tf.test.main()
[ "pigbug419@gmail.com" ]
pigbug419@gmail.com
892e33c12c641e469991e444dcd7b42bcc2337f4
3f77f05c6a664555d5a99896597ebb447be3fbe4
/src/main/python/gui.py
482411caa50ef232aa15c4b256af23addc0f240d
[]
no_license
JettChenT/echat-client
9d090462580191c250a619739e5a21442b0e8094
b1f33a30e38421832e63e3c1e3c6e0e1dc32ce1f
refs/heads/master
2023-03-01T09:00:44.364691
2021-02-01T02:56:46
2021-02-01T02:56:46
334,071,457
0
0
null
null
null
null
UTF-8
Python
false
false
13,201
py
from executer import Executer from PyQt5.QtWidgets import * from PyQt5.QtCore import * from threading import Thread from time import sleep import json from passwordStrength import PasswordStrengthChecker import sys import faulthandler import atexit from fbs_runtime.application_context.PyQt5 import ApplicationContext faulthandler.enable() class LoginForm(QWidget): def __init__(self, server_exec): super(LoginForm,self).__init__() self.pwc = PasswordStrengthChecker(strict=False) self.setWindowFlags(Qt.WindowStaysOnTopHint) self.setFocusPolicy(Qt.StrongFocus) self.activateWindow() self.server_exec = server_exec self.setStyleSheet(open("style.qss", "r").read()) self.title = "Login/Register" self.layout = QGridLayout() # Reused widgets label_login_name = QLabel("<font size='4'> Username </font>") self.username = QLineEdit() self.username.setPlaceholderText("Please enter your username") self.layout.addWidget(label_login_name, 0, 0) self.layout.addWidget(self.username, 0, 1) label_login_password = QLabel("<font size='4'> Password </font>") self.password = QLineEdit() self.password.setPlaceholderText('Please enter your password') self.layout.addWidget(label_login_password, 1, 0) self.layout.addWidget(self.password, 1, 1) # tab 1 button_login = QPushButton('login') button_login.pressed.connect(self.login) button_register = QPushButton('register') button_register.pressed.connect(self.register) self.layout.addWidget(button_login,2,1) self.layout.addWidget(button_register,2,0) self.setLayout(self.layout) def login(self): while True: r = self.server_exec.exec_(f"login {self.username.text()} {self.password.text()}") if r == False: continue msg = QMessageBox(self) msg.setText(r) if r == "You're logged in!": msg.setIcon(QMessageBox.Information) msg.exec_() self.close() else: msg.setIcon(QMessageBox.Critical) msg.exec_() break def register(self): is_secure, rsp = self.pwc.is_secure(self.password.text()) if is_secure: r = self.server_exec.exec_(f"reg {self.username.text()} {self.password.text()}") msg = QMessageBox(self) msg.setText(r) msg.exec_() else: msg = QMessageBox(self) msg.setIcon(QMessageBox.Critical) msg.setText(rsp) msg.exec_() class ChatWindow(QWidget): def __init__(self, server_exec): super(ChatWindow, self).__init__() self.server_exec = server_exec self.last_sender = "" self.setWindowTitle("EncryptiiChat") self.setMinimumWidth(600) self.setMinimumHeight(500) self.loginWindow = LoginForm(self.server_exec) self.loginWindow.show() self.MQ = [] self.text_area = QTextEdit(self) self.text_area.setFocusPolicy(Qt.NoFocus) self.text_area.setReadOnly(True) self.text_area.setAcceptRichText(True) self.text_area.setAutoFormatting(QTextEdit.AutoAll) self.message = QLineEdit(self) self.message.setPlaceholderText("Enter your message") self.layout = QGridLayout(self) self.layout.addWidget(self.text_area,0,0,1,3) self.to_user = QComboBox(self) self.match_button = QPushButton("Match") self.match_button.pressed.connect(self.match) self.layout.addWidget(self.to_user,2,0) self.layout.addWidget(self.match_button,2,1) self.layout.addWidget(self.message,2,2) self.colors_layout = QHBoxLayout(self) self.yellow_button = QPushButton("") self.yellow_button.setStyleSheet("background-color:#FFCD48") self.orange_button = QPushButton("") self.orange_button.setStyleSheet("background-color:#F28437") self.red_button = QPushButton("") self.red_button.setStyleSheet("background-color:#DE4557") self.purple_button = QPushButton("") self.purple_button.setStyleSheet("background-color:#B940E5") self.blue_button = QPushButton("") self.blue_button.setStyleSheet("background-color:#55A5FD") self.light_blue_button = QPushButton("") self.light_blue_button.setStyleSheet("background-color:#1AD3FB") self.green_button = QPushButton("") self.green_button.setStyleSheet("background-color:#A4DB47") self.colors_layout.addWidget(self.yellow_button) self.colors_layout.addWidget(self.orange_button) self.colors_layout.addWidget(self.red_button) self.colors_layout.addWidget(self.purple_button) self.colors_layout.addWidget(self.blue_button) self.colors_layout.addWidget(self.light_blue_button) self.colors_layout.addWidget(self.green_button) self.init_colors() self.layout.addLayout(self.colors_layout,1,0,1,3) self.layout.setColumnStretch(2,4) self.layout.setColumnStretch(1,1) self.layout.setColumnStretch(0,2) self.setLayout(self.layout) self.message.returnPressed.connect(self.send_message_thread) self.thread = Thread(target=self.fetch_new_messages, daemon=True) self.thread.start() def init_colors(self): with open("colorsconfig.json","r") as f: color_data = json.load(f) self.yellow_button.setText(color_data["yellow"]["about"]) self.yellow_button.pressed.connect(lambda:self.send_color_thread("yellow")) self.orange_button.setText(color_data["orange"]["about"]) self.orange_button.pressed.connect(lambda:self.send_color_thread("orange")) self.red_button.setText(color_data["red"]["about"]) self.red_button.pressed.connect(lambda:self.send_color_thread("red")) self.blue_button.setText(color_data["blue"]["about"]) self.blue_button.pressed.connect(lambda:self.send_color_thread("blue")) self.light_blue_button.setText(color_data["light-blue"]["about"]) self.light_blue_button.pressed.connect(lambda:self.send_color_thread("light-blue")) self.green_button.setText(color_data["green"]["about"]) self.green_button.pressed.connect(lambda:self.send_color_thread("green")) self.purple_button.setText(color_data["purple"]["about"]) self.purple_button.pressed.connect(lambda:self.send_color_thread("purple")) self.color_data = color_data self.orig_color_data = color_data def send_message_thread(self): if self.server_exec.not_logged_in(): print("log in first!") self.not_logged_in_popup() self.loginWindow.show() return if self.to_user.count() == 0: self.not_matched_popup() return sendThread = Thread(target=self.send_message) sendThread.start() def match(self): while True: res = self.server_exec.exec_("match") if res!= False: target_alias, my_alias = res break self.to_user.addItem(target_alias) index = self.to_user.findText(target_alias,Qt.MatchFixedString) self.to_user.setCurrentIndex(index) def get_mg(self,color): return f"{self.color_data[color]['details']}" def suggest(self,msg): msg = msg.lower() for rsp in self.color_data['responses']: if rsp in msg: self.color_data['yellow']['details'] = self.color_data['responses'][rsp]['details'] self.yellow_button.setText(self.color_data['responses'][rsp]['about']) return self.color_data['responses'][rsp] return False def send_color_thread(self,color): if self.server_exec.not_logged_in(): print("log in first!") self.not_logged_in_popup() self.loginWindow.show() return if self.to_user.count() == 0: self.not_matched_popup() return sendThread = Thread(target=self.send_color(color)) sendThread.start() def send_color(self,color): html_resp = f"<span style=\"color:#ffffff\">[to <i>{self.to_user.currentText()}</i>]:{self.get_mg(color)}</span>" tc = self.text_area.textCursor() form = tc.charFormat() form.setForeground(Qt.green) tc.setCharFormat(form) tc.insertHtml(html_resp) self.text_area.append("") self.message.clear() while True: r = self.server_exec.exec_(f"send {self.to_user.currentText()} {self.get_mg(color)}") if not r: continue print(f"{self.server_exec.username}:sent!") sleep(0.1) break def send_message(self): html_resp = f"<span style=\"color:#ffffff\">[to <i>{self.to_user.currentText()}</i>]:{self.message.text()}</span>" tc = self.text_area.textCursor() form = tc.charFormat() form.setForeground(Qt.green) tc.setCharFormat(form) tc.insertHtml(html_resp) self.text_area.append("") send_msg = self.message.text() self.message.clear() self.message.setPlaceholderText("Sending...") self.message.setFocusPolicy(Qt.NoFocus) while True: r = self.server_exec.exec_(f"send {self.to_user.currentText()} {send_msg}") if r == False: continue self.message.setPlaceholderText("Enter your message") self.message.setFocusPolicy(Qt.ClickFocus) print(f"{self.server_exec.username}:sent:{send_msg}") sleep(0.1) break def not_logged_in_popup(self): msg = QMessageBox(self) msg.setWindowTitle("Not logged in!") msg.setText("Please log in to send a message") msg.setIcon(QMessageBox.Critical) x = msg.exec_() def not_matched_popup(self): msg = QMessageBox(self) msg.setWindowTitle("Matched") msg.setText("Please hit the match button to match with someone") msg.setIcon(QMessageBox.Critical) x = msg.exec_() def get_cur_sender(self,msg): for i in range(len(msg)): if msg[i:i+1] == ']': un = msg[1:i].split(":")[0] mg = msg[i+2:] break return un, mg def display_new_messages(self): while len(self.MQ): new_msg = self.MQ.pop(0) self.cur_sender,cur_msg = self.get_cur_sender(new_msg) index = self.to_user.findText(self.cur_sender) if index == -1: self.to_user.addItem(self.cur_sender) new_index = self.to_user.findText(self.cur_sender) self.to_user.setCurrentIndex(new_index) if self.last_sender != self.cur_sender: print(self.cur_sender) self.text_area.textCursor().insertHtml(f"<h3 style=\"color:#ffff00\">sender: {self.cur_sender}</h3>") self.text_area.append("") self.text_area.textCursor().insertHtml(f"<span style=\"color:#ffffff\">{cur_msg}</span>") self.suggest(cur_msg) self.text_area.append("") self.last_sender = self.cur_sender def fetch_new_messages(self): while True: if self.server_exec.not_logged_in(): sleep(0.5) continue try: new_message = self.server_exec.exec_("getMsg") if type(new_message) == list: for msg in new_message: decoded_msg = msg.decode() print(decoded_msg) self.MQ.append(decoded_msg) sleep(0.5) except: continue class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Chat application") with open("config.json") as f: cfg = json.load(f) server = cfg['server'] port = int(cfg['port']) print(server,port) self.server_exec = Executer((server, port)) atexit.register(self.server_exec.on_exit) self.setStyleSheet(open("style.qss", "r").read()) self.mainWidget = ChatWindow(self.server_exec) self.setCentralWidget(self.mainWidget) def closeEvent(self, event): print("close") while True: try: rsp = self.server_exec.exec_("offline") if rsp!=False: print(rsp) break except: continue def window(): appctxt = ApplicationContext() app = QApplication(sys.argv) win = MainWindow() win.show() timer = QTimer() timer.timeout.connect(win.mainWidget.display_new_messages) timer.start(1000) app.exec_() exit_code = appctxt.app.exec_() window()
[ "jettchen12345@gmail.com" ]
jettchen12345@gmail.com
2b880886119cd49ba10dd9ed027ea26772f13106
b1fe732c6abb51d44bd965cbbf259bb2d93e4514
/Day3/problemSet.py
14560c6d9c0b5f77cfebb8b4be2faea25056a2f5
[]
no_license
RahulSinghDhek/GettingStartedWithPython
04c85c2c370e7ea93b16dade44e5eea633ec284c
c655e3376707b8e4e14ed352a8bc07b010c31e12
refs/heads/master
2020-05-07T17:15:38.120491
2019-04-11T05:39:12
2019-04-11T05:39:12
180,721,799
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
__author__ = 'rdhek' a=[1,3,5,7] b=[1,2,3,4,5] x= set(a) y= set(b) print list(x.intersection(y)) print x.union(y) print x-y
[ "rdhek@qti.qualcomm.com" ]
rdhek@qti.qualcomm.com
7379c533b289f68343bc5cd1947b5877f809fbb7
044bb022c77c34a92492b800fc380bdead99be52
/Python-Codes/Test Codes/test.py
1c94df5885c60c7434578cc3e599d8a737f2b6c3
[]
no_license
sswisty/ROV-SIREN
4c7190d2f45685d87ef3b601b286a647055b9c7b
5f949d6c139eb44b636e34ba1373c397472b23d0
refs/heads/master
2020-04-06T07:04:16.101218
2016-10-05T20:44:43
2016-10-05T20:44:43
51,488,996
1
2
null
null
null
null
UTF-8
Python
false
false
60
py
# Adding this file to create a new folder x = 5 print x+3
[ "sswisty7@gmail.com" ]
sswisty7@gmail.com
165146e30d5f3fdf5a47e708760346f1f979c67f
1c0d4b9c57e3eb987cba4ba082e855b4444797a2
/fresh_launch.py
8ccf5cb88927ed18aed2cb80a0df5d7664992c7d
[ "MIT" ]
permissive
prasad223/CSE586
4b70e5aefc2254d89c343f1d0217210cbbf65ed1
dfd3bbaa8e1732cb1ae6909cc7e75cc84a912b01
refs/heads/master
2021-01-21T03:21:04.699400
2016-05-05T12:57:19
2016-05-05T12:57:19
54,043,773
0
1
null
null
null
null
UTF-8
Python
false
false
694
py
#!/usr/bin/env python import os from environment import * apk_path = os.path.join(WORKSPACE, PROJECT_NAME, 'app', 'build', 'outputs', 'apk', 'app-debug.apk') app_package = PREFIX + '.' + PROJECT_EXT for i in 5554, 5556, 5558, 5560, 5562: print "Fresh launch on emulator", i emu = "emulator-" + str(i) cmd = 'adb -s ' + emu #uninstall full_cmd = cmd + ' uninstall ' + app_package os.system(full_cmd) #install full_cmd = cmd + ' install ' + apk_path os.system(full_cmd) #unlock full_cmd = cmd + ' shell input keyevent 82' os.system(full_cmd) #launch full_cmd = cmd + ' shell am start -n ' + app_package + '/' + app_package + '.' + MAIN_ACTIVITY os.system(full_cmd)
[ "prasadsjcecs@gmail.com" ]
prasadsjcecs@gmail.com
796dd3e7354d66e1ca0d2af453460dcea123a126
7f5980bcd5bd0d9e049295e7cbf1c38df04fb36d
/deprecated/Automations.py
406838933ffbcf450754338c42de2199d32c73f7
[]
no_license
menahishayan/Automated-Oven
0d91f0e2b47b3656ec2822fe522ebdfcbeaa09e5
51470c6fceff57903f232422c342409b72d01c49
refs/heads/main
2023-05-31T12:17:58.785205
2021-07-04T13:31:36
2021-07-04T13:31:36
361,813,332
0
0
null
null
null
null
UTF-8
Python
false
false
122
py
import json class Automations: def __init__(self, dbPath='./db/AutomationsDB.json'): self.path = dbPath
[ "shayan1232001@yahoo.co.in" ]
shayan1232001@yahoo.co.in
9816169c3cf62624bac7d4238f5e8c78629beb72
2816fe989f78240e950554b4b1fe680ec62b306a
/crawl/guba/multi.py
c333873535ef956172a687984e6e7b72f7986e17
[]
no_license
stop1992/python-security
fb4219e4769459e07e51227ba3d47d0c9a88ee98
b022e73f1f105179136360601c4f5122e9bc4875
refs/heads/master
2021-01-20T05:59:47.264360
2016-08-02T13:59:46
2016-08-02T13:59:46
65,118,931
4
2
null
2016-08-07T06:18:41
2016-08-07T06:18:41
null
UTF-8
Python
false
false
4,298
py
#!/usr/bin/env python # encoding: utf-8 import multiprocessing import os from pymongo import MongoClient from redis import Redis import re import time from clear import drop_mongo # process_nums = multiprocessing.cpu_count() MONGO_SERVER = '192.168.1.108' MONGO_PORT = 27017 MONGO_DB_IN = 'guba_data' MONGO_DB_OUT = 'guba' REDIS_SERVER = '192.168.1.108' REDIS_PORT = 6379 # process_nums = cpus - 1 process_nums = multiprocessing.cpu_count() redis_client = Redis(REDIS_SERVER, REDIS_PORT) mongo_client = MongoClient(MONGO_SERVER, MONGO_PORT) mongo_db_in = mongo_client[MONGO_DB_IN] mongo_db_out = mongo_client[MONGO_DB_OUT] # strip, then unicode, then compile key_words = [ re.compile(unicode(key.strip(), 'utf-8')) for key in open('keywords.txt', 'r').readlines() ] redis_client.sadd('stocks', '000002') redis_client.sadd('stocks', '000866') def add(x, y): return x + y def store2mongo(stock_num, ask_time, key_words_accouts): post = mongo_db_out[stock_num] # first get key words, then plus them ,then store all_document = post.find_one({'ask_time':ask_time}) # exist ask_time data if all_document: key_words_accouts_before = all_document['key_words'] post_times = all_document['post_times'] # compute every day key words occur times key_words_accouts_after = map(add, key_words_accouts, key_words_accouts_before) # find key words, then update post.update_one({'ask_time':ask_time}, {'$set':{'key_words':key_words_accouts_after, \ 'post_times':post_times+1}}) else: # not exist ask_time data post.insert({'ask_time':ask_time, 'post_times':1, 'key_words':key_words_accouts}) # print stock_num, ask_time, ' data process successfully....' def handle_data(stock_num): # stock num represent a collection table = mongo_db_in[stock_num] if table: # print 'start to process data....' for post_day in table.find(): # get post ask time ask_time = post_day['ask_time'] # store key words occur times key_words_accouts = [] # this day present occur 1 time replys_data = post_day['replys_data'] for pattern in key_words: # initial find_count is 0 key_find_count = 0 for text in replys_data: result = pattern.findall(text) if result: key_find_count = len(result) key_words_accouts.append(key_find_count) # store2mongo(stock_num, ask_time, key_words_accouts) post = mongo_db_out[stock_num] # first get key words, then plus them ,then store all_document = post.find_one({'ask_time':ask_time}) # exist ask_time data if all_document: key_words_accouts_before = all_document['key_words'] post_times = all_document['post_times'] # compute every day key words occur times key_words_accouts_after = map(add, key_words_accouts, key_words_accouts_before) # find key words, then update post.update_one({'ask_time':ask_time}, {'$set':{'key_words':key_words_accouts_after, \ 'post_times':post_times+1}}) else: # not exist ask_time data post.insert({'ask_time':ask_time, 'post_times':1, 'key_words':key_words_accouts}) def handle(process_name): while redis_client.scard('stocks') > 0: # use a set to store stock nums stock_num = redis_client.spop('stocks') if stock_num: stock_num = 'db' + stock_num handle_data(stock_num) def main(): jobs = [] pools = multiprocessing.Pool() for i in xrange(process_nums - 1): process_name = 'process_' + str(i) pools.apply_async(handle, (process_name, )) pools.close() pools.join() if __name__ == '__main__': os.system('printf "\033c"') start = time.time() print 'start time: ', start main() end = time.time() print 'used time: ', end - start # drop_mongo() # test()
[ "daitaomail@gmail.com" ]
daitaomail@gmail.com
fdba2e38a7275b27bf739668f77984e9aad554b6
d5fd936e7346844a1b7c5ea81dfa9adf5bb647d0
/datasets/load_data.py
c547ebd91f699327cac78ca35d0dbe0f0094489e
[]
no_license
isaachenrion/graphs
098e7098a894a3d1d9d18cf0ce1054e5910afa15
2ba6d50a7f61233fa8cc92ba03256691abb889de
refs/heads/master
2021-01-02T09:10:49.686240
2017-09-11T19:52:48
2017-09-11T19:52:48
99,154,954
0
0
null
null
null
null
UTF-8
Python
false
false
1,013
py
import os import pickle from .datasets import BatchedFixedOrderGraphDataset, FixedOrderGraphDataset, GraphDataset, BatchedGraphDataset from .add_virtual_node import add_virtual_node, add_target_nodes from .path import DATA_DIR def load_from_path(data_path, args): with open(data_path, 'rb') as f: dataset = pickle.load(f) if isinstance(dataset, FixedOrderGraphDataset): dataset = BatchedFixedOrderGraphDataset(dataset, args.batch_size) elif isinstance(dataset, GraphDataset): dataset = BatchedGraphDataset(dataset, args.batch_size) if args.model == 'vcn': add_target_nodes(dataset) dataset = dataset.preprocess() return dataset def load_data(args): train_data_path = os.path.join(DATA_DIR, args.problem + '-train.pkl') eval_data_path = os.path.join(DATA_DIR, args.problem + '-eval.pkl') training_set = load_from_path(train_data_path, args) validation_set = load_from_path(eval_data_path, args) return training_set, validation_set
[ "isaachenrion@gmail.com" ]
isaachenrion@gmail.com
8e990b308f624c1525603f9ab92945fda7fb8ce2
5167f77d96d1dc5412a8a0a91c95e3086acd05dc
/test/functional/wallet_implicitsegwit.py
553ce7367502b4851bea035523dbb7026ed2072f
[ "MIT" ]
permissive
ocvcoin/ocvcoin
04fb0cea7c11bf52e07ea06ddf9df89631eced5f
79c3803e330f32ed50c02ae657ff9aded6297b9d
refs/heads/master
2023-04-30T10:42:05.457630
2023-04-15T11:49:40
2023-04-15T11:49:40
406,011,904
3
2
null
null
null
null
UTF-8
Python
false
false
2,424
py
#!/usr/bin/env python3 # Copyright (c) 2019 The Ocvcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet implicit segwit feature.""" import test_framework.address as address from test_framework.test_framework import OcvcoinTestFramework # TODO: Might be nice to test p2pk here too address_types = ('legacy', 'bech32', 'p2sh-segwit') def key_to_address(key, address_type): if address_type == 'legacy': return address.key_to_p2pkh(key) elif address_type == 'p2sh-segwit': return address.key_to_p2sh_p2wpkh(key) elif address_type == 'bech32': return address.key_to_p2wpkh(key) def send_a_to_b(receive_node, send_node): keys = {} for a in address_types: a_address = receive_node.getnewaddress(address_type=a) pubkey = receive_node.getaddressinfo(a_address)['pubkey'] keys[a] = pubkey for b in address_types: b_address = key_to_address(pubkey, b) send_node.sendtoaddress(address=b_address, amount=1) return keys def check_implicit_transactions(implicit_keys, implicit_node): # The implicit segwit node allows conversion all possible ways txs = implicit_node.listtransactions(None, 99999) for a in address_types: pubkey = implicit_keys[a] for b in address_types: b_address = key_to_address(pubkey, b) assert(('receive', b_address) in tuple((tx['category'], tx['address']) for tx in txs)) class ImplicitSegwitTest(OcvcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.supports_cli = False def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.log.info("Manipulating addresses and sending transactions to all variations") implicit_keys = send_a_to_b(self.nodes[0], self.nodes[1]) self.sync_all() self.log.info("Checking that transactions show up correctly without a restart") check_implicit_transactions(implicit_keys, self.nodes[0]) self.log.info("Checking that transactions still show up correctly after a restart") self.restart_node(0) self.restart_node(1) check_implicit_transactions(implicit_keys, self.nodes[0]) if __name__ == '__main__': ImplicitSegwitTest().main()
[ "contact@ocvcoin.com" ]
contact@ocvcoin.com
7abdb85b4f5ecf93d8696b1a86d6ce317207a57e
f71415d51b9257e4cf6562a6b3c5e7596ff76daf
/mysite/settings.py
4b6dea8414c93ebdf4cd133733447271f0478692
[]
no_license
myromeu/fantastic-fiesta
effabb2df4dc8db7c674142038ef6ddb6bc82270
46ca55d3ff03563f2786ac5b913e2f25b13cdb68
refs/heads/master
2021-01-10T06:56:33.130626
2016-01-26T20:52:46
2016-01-26T20:52:46
49,889,440
0
0
null
null
null
null
UTF-8
Python
false
false
2,706
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os 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.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=-5@mq*a%x1e4e#+6nu+box+fh!3ao@jw6g=j0!xkc60w)^u_p' # 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', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
[ "myromeu@ya.ru" ]
myromeu@ya.ru
955b93a0198bf45f36553fa170bdc6effb0bec4b
765b558714acf20438ff717e57beadd9890fe1be
/galcon/galcon/migrations/0012_auto__del_group.py
deba6a67510de5e53a6da62f87851a001cc0d21d
[]
no_license
marky1991/galcon_clone
279cf4ec6adb266f5afabc0a0a61435a52a60119
12923b001d593c75934e99ed201627d8767462c2
refs/heads/master
2020-06-06T20:24:03.684856
2013-09-06T15:52:45
2013-09-06T15:52:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,810
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Group' db.delete_table('galcon_group') # Removing M2M table for field admins on 'Group' db.delete_table(db.shorten_name('galcon_group_admins')) def backwards(self, orm): # Adding model 'Group' db.create_table('galcon_group', ( ('description', self.gf('django.db.models.fields.TextField')(max_length=65000)), ('join_requires_approval', self.gf('django.db.models.fields.BooleanField')(default=False)), ('hidden', self.gf('django.db.models.fields.BooleanField')(default=False)), ('creation_time', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)), ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('slug', self.gf('django.db.models.fields.SlugField')(max_length=100, blank=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=25)), )) db.send_create_signal('galcon', ['Group']) # Adding M2M table for field admins on 'Group' m2m_table_name = db.shorten_name('galcon_group_admins') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('group', models.ForeignKey(orm['galcon.group'], null=False)), ('player', models.ForeignKey(orm['galcon.player'], null=False)) )) db.create_unique(m2m_table_name, ['group_id', 'player_id']) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'galcon.friend_request': { 'Meta': {'object_name': 'Friend_Request'}, 'accepted': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sent_friend_requests'", 'to': "orm['galcon.Player']"}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'friend_requests'", 'to': "orm['galcon.Player']"}) }, 'galcon.join_group_request': { 'Meta': {'object_name': 'Join_Group_Request'}, 'accepted': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sent_join_group_requests'", 'to': "orm['galcon.Player']"}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'join_group_requests'", 'to': "orm['galcon.Player']"}) }, 'galcon.note': { 'Meta': {'object_name': 'Note'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '100'}) }, 'galcon.player': { 'Meta': {'object_name': 'Player'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'friends': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'friends_rel_+'", 'blank': 'True', 'to': "orm['galcon.Player']"}), 'get_newsletter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'groups'", 'blank': 'True', 'to': "orm['groups.Group']"}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'post_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'rank': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['galcon.Rank']", 'unique': 'True'}), 'registration_code': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}), 'registration_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "''", 'max_length': '100'}), 'trophies': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'players'", 'blank': 'True', 'to': "orm['galcon.Trophy']"}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'galcon.pm': { 'Meta': {'object_name': 'Pm'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'written_messages'", 'to': "orm['galcon.Player']"}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'post_date': ('django.db.models.fields.DateTimeField', [], {}), 'read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'recipient': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'recieved_messages'", 'to': "orm['galcon.Player']"}), 'sent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100'}), 'starred': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '65000'}), 'title': ('django.db.models.fields.CharField', [], {'default': "'(Blank)'", 'max_length': '100'}) }, 'galcon.post': { 'Meta': {'object_name': 'Post'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['galcon.Player']"}), 'flag_note': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['galcon.Note']", 'null': 'True', 'blank': 'True'}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_modification_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'to': "orm['galcon.Thread']"}), 'post_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "''", 'max_length': '100'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '65000'}), 'title': ('django.db.models.fields.TextField', [], {'max_length': '100'}) }, 'galcon.rank': { 'Meta': {'object_name': 'Rank'}, 'classic_rank': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'flash_rank': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'fusion_rank': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'iphone_rank': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'galcon.section': { 'Meta': {'object_name': 'Section'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "''", 'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}) }, 'galcon.subsection': { 'Meta': {'object_name': 'Subsection'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'to': "orm['galcon.Section']"}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "''", 'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}) }, 'galcon.thread': { 'Meta': {'object_name': 'Thread'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'threads'", 'to': "orm['galcon.Player']"}), 'close_note': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['galcon.Note']", 'null': 'True', 'blank': 'True'}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page_views': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'to': "orm['galcon.Subsection']"}), 'post_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'slug': ('django.db.models.fields.SlugField', [], {'default': "''", 'max_length': '100'}), 'sticky': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'galcon.trophy': { 'Meta': {'object_name': 'Trophy'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '100'}) }, 'groups.group': { 'Meta': {'object_name': 'Group'}, 'admins': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'admined_groups'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['galcon.Player']"}), 'creation_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '65000'}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'join_requires_approval': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '25'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'blank': 'True'}) } } complete_apps = ['galcon']
[ "marky1991@gmail.com" ]
marky1991@gmail.com
02af9acedfd8eb63a76f63c93c109e539acb1fa4
0f9f8e8478017da7c8d408058f78853d69ac0171
/python2/l0064_minimum_path_sum.py
e5eed8adafa9b21abd66ed0af9541fba57e42edd
[]
no_license
sprax/1337
dc38f1776959ec7965c33f060f4d43d939f19302
33b6b68a8136109d2aaa26bb8bf9e873f995d5ab
refs/heads/master
2022-09-06T18:43:54.850467
2020-06-04T17:19:51
2020-06-04T17:19:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
748
py
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid: return 0 m = len(grid) n = len(grid[0]) dp = [[0 for _ in range(n)] for _ in range(m)] # Initialize. dp[m-1][n-1] = grid[m-1][n-1] for i in range(m-2, -1, -1): dp[i][n-1] = grid[i][n-1] + dp[i+1][n-1] for j in range(n-2, -1, -1): dp[m-1][j] = grid[m-1][j] + dp[m-1][j+1] # Solve. for i in range(m-2, -1, -1): for j in range(n-2, -1, -1): dp[i][j] = min(dp[i+1][j], dp[i][j+1]) + grid[i][j] return dp[0][0]
[ "zhoulu312@gmail.com" ]
zhoulu312@gmail.com
a41ee74e0d74a2f619205675cb265d0c888b3d01
9645bdfbb15742e0d94e3327f94471663f32061a
/Python/235 - Lowest Common Ancestor of a Binary Search Tree/235_lowest-common-ancestor-of-a-binary-search-tree.py
863b29d2d3d70572b919bc045ab5e6b412efb394
[]
no_license
aptend/leetcode-rua
f81c080b2260adb2da677612e5c437eda256781d
80e44f4e9d3a5b592fdebe0bf16d1df54e99991e
refs/heads/master
2023-06-22T00:40:05.533424
2021-03-17T13:51:28
2021-03-17T13:51:28
186,434,133
2
0
null
2023-06-21T22:12:51
2019-05-13T14:17:27
HTML
UTF-8
Python
false
false
1,554
py
from leezy import Solution, solution from leezy.assists import TreeContext class Q235(Solution): @solution def lowestCommonAncestor(self, root, p, q): # 68ms if p < root.val > q: return self.lowestCommonAncestor(root.left, p, q) if p > root.val < q: return self.lowestCommonAncestor(root.right, p, q) return root @solution def lca_iter(self, root, p, q): # 76ms 40.62% while root: if root.val > p and root.val > q: root = root.left elif root.val < p and root.val < q: root = root.right else: return root def lca_dumb(self, root, p, q): ppath, qpath = [], [] self.search(root, p, ppath) self.search(root, q, qpath) prev = x = y = None for x, y in zip(ppath, qpath): if x.val != y.val: return prev prev = x return x def search(self, node, v, path): if node is None: path.clear() return if v == node.val: path.append(node) return path.append(node) if v > node.val: self.search(node.right, v, path) else: self.search(node.left, v, path) def main(): q = Q235() q.set_context(TreeContext) t1 = [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5] q.add_args(t1, 2, 8) q.add_args(t1, 2, 4) q.add_args(t1, 3, 7) q.run() if __name__ == "__main__": main()
[ "crescentwhale@hotmail.com" ]
crescentwhale@hotmail.com
dcbc15d24ae14bff864146e04855549fd69c3bd4
029529c28784dc73362dfb38d29d16cbbba3ac98
/odx_crm_lead/models/insurance_premium.py
8d33f341e78187ce5b465199992165476b8c3d84
[]
no_license
linux8a/odoo_13
4a99e3ccaf7956c33501e7c1be79e84f6d763f95
19bbcecee21bbd8b4298df899dc4f3f47dff63ea
refs/heads/master
2022-12-21T07:48:09.968327
2020-10-04T06:12:54
2020-10-04T06:12:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,007
py
# -*- coding: utf-8 -*- from odoo import fields, models, api class InsurancePremium(models.Model): _name = 'insurance.premium' name = fields.Char('Name') insurance_company_id = fields.Many2one('res.partner', 'Insurance Company', domain=[('is_insurance_comapny', '=', True)],required=True) insurence_category = fields.Selection( [('motor_insurance', 'Motor Insurance'), ('family_medical', 'Individual / Family Medical Insurance'), ('group_medical', 'Group Medical Insurance'), ('business', 'Business Insurance'), ('travel', 'Travel Insurance'), ('bike_insurance', 'Bike Insurance'), ('yacht_insurance', 'Yacht Insurance'), ('home_insurance', 'Home Insurance')], string='Insurance Category', required=True) insurance_premium = fields.Selection([('fullcover', 'Full Cover'), ('comprehensive', 'Comprehensive')], string="Insurance Premium") vehicle_type = fields.Selection([('saloon', 'Saloon'), ('4_4', '4*4'),('p_up', 'P/UP'), ('motor_cycle', 'Motor Cycle'), ('trailer_watertanker', 'Trailer & Water Tanker'), ('equipments', 'Equipments'),('bus', 'Bus'), ('van', 'Van')], string="Vehicle Type") brokarage = fields.Float('Brokarage %') premium_product = fields.Many2one('product.product',"Premium Product",required=True) premium = fields.Float('Premium') tax_id = fields.Many2one('account.tax',String='Tax') total = fields.Float("Total",compute="_compute_amount") tax_amount = fields.Float('Tax Amount ',compute="_compute_amount") car_value = fields.Float('Car value') excess = fields.Char('Excess / Deductible') repaire_rates = fields.Char('Repaire Rates') driver_age = fields.Selection([('18to25', 'Between 18 years to 25 years'), ('25_above', 'Above 25 years')], string="Driver Age ") date_of_first_registration = fields.Selection([('1st', '1st Year'), ('2nd', '2nd Year'),('3rd', '3rd Year'), ('4th', '4th Year'),('5th', '5th Year'), ('6th', '6th Year and above')], string="Date of first registration and use") # benifits loss_dammage = fields.Boolean("Loss or Damage Cover") repaire_type = fields.Selection( [('agency', 'Agency Repair'),('non_agency', 'Non Agency Repair')],string="Repaire Type") third_party_liability = fields.Float("Third Party Liability") blood_money = fields.Boolean("Blood Money") fire_theft = fields.Boolean("Fire And Cheft Cover") storm_flood = fields.Boolean("Storm,Flood") natural_perils = fields.Boolean("Natural Perils") riot_strike = fields.Boolean("Riot & Strike") emergency_medical_expenses = fields.Boolean("Emergency Medical Expenses") personal_belongigs = fields.Boolean("Personal Belongings") oman_cover = fields.Selection( [('orange_card', 'Covered with orange card'),('yes', 'Yes'),('no', 'No')],string="Oman Cover") p_off_road = fields.Boolean("P Off-Road Cover") road_side_assistance = fields.Boolean("Road Side Assistance") ambulance_cover = fields.Boolean("Ambulance Cover") aed_500 = fields.Boolean("None Up to AED 5,000") aed_3500 = fields.Boolean("None Up to AED 3,500") optional_cover = fields.Boolean("Optional Covers") driver_cover = fields.Boolean("Driver Cover") passanger_cover = fields.Boolean("Passengers Cover") rent_a_car = fields.Char("Rent A Car") period_of_13_months = fields.Boolean("Perod Of 13 Months") geographical_area = fields.Char("Geographical Area") guranteed_repairs = fields.Boolean("Guaranteed Repairs") accident_break_down = fields.Boolean("Accident And Breakdown Recovery") excess_for_windscreen = fields.Char("Excess For Windscreen Damage") emergency_road_assistance = fields.Char('Emergency Road Assistance') geographical_area_extension = fields.Char("Geographical Area Extension") replacement_vehcle = fields.Char("Replacement Vehcle") assist_america_for_individual = fields.Char('Assist America For Individual') no_of_cylinder = fields.Selection( [('4cyl', '4Cyl'),('6cyl', '6Cyl'),('8cyl', '8Cyl'),('12cyl', '12Cyl')],string="No Of Cylinder") private_commercial = fields.Selection( [('private', 'Private'), ('commercial', 'Commercial')], string="Private/Commercial") weight = fields.Selection( [('1tonne', '1 Tonne'),('2tonne', '2 Tonne'),('3tonne', '3 Tonne'),('7tonne', '7 Tonne')],string="Weight") engin = fields.Selection( [('upto200', 'Up To 200 CC'), ('above200', 'Above 200 CC')], string="Engin") gallons = fields.Selection( [('upto200', 'Up To 2000 Gallons'), ('upto5000', 'Up To 5000 Gallons')], string="Gallons") water_tanker = fields.Boolean('Water Tanker') tariler = fields.Boolean("Trailer") water_tanker_trailer = fields.Boolean("Water Tanker Trailer") light_equipments = fields.Selection( [('dumber_agriculture', 'Dumber & Agriculture'), ('forklift', 'Forklift')], string="Light Equipments") heavy = fields.Boolean('Heavy') no_of_passengers = fields.Selection( [('upto14', 'Up To 14 Passengers'),('upto26', 'Up To 26 Passengers'),('upto56', 'Up To 56 Passengers')],string="No Of Passengers") # indivisual package_name = fields.Char("Package Name") network = fields.Char("Network") additional_members_ids = fields.One2many('additional.members', 'insurance_premium_id', string='Additional Members') @api.depends('premium', 'tax_id.amount') def _compute_amount(self): for record in self: if record.tax_id: record.tax_amount = record.premium * (record.tax_id.amount/100) else: record.tax_amount = 0 record.total = record.premium + record.tax_amount
[ "ashifpk1@gmail.com" ]
ashifpk1@gmail.com
87da898bd08cdfef60ac23b93bfa4e87e4b7567d
4587c4b6e381f0ac97a15fbf8f163d1bd9dbca8d
/codes/utils.py
4c404d23805fd827f4b8294d3c1f5afe3e51ce5d
[]
no_license
shoukreytom/live-share-code
b514d2aadaa6716d5cbd7c6811823635102dc2f8
19f1b1cd1e93414a08bc47c5c141cbf34e65f8be
refs/heads/main
2023-07-29T00:03:49.026302
2021-09-28T20:59:55
2021-09-28T20:59:55
368,343,352
0
0
null
null
null
null
UTF-8
Python
false
false
141
py
from random import randint def generate_share_key(): code_list = [str(randint(0, 9)) for _ in range(6)] return "".join(code_list)
[ "shoukreytom01@gmail.com" ]
shoukreytom01@gmail.com
ed777a2b20b0c94e0469882347bedeaacedfd55e
876a1b7b7c898c826b94ff34f3d9a1d22ee5459b
/QUANTAXIS/QAUtil/QAWebutil.py
8a2a75459233fd85e3744b092b8ba3babacb56ca
[ "MIT" ]
permissive
pm58/QUANTAXIS
6db63c461d18f13f7340f7d46e42cde3bc3f40cb
03c526f640f48f4a153e9c4e0e27f74ccd18a345
refs/heads/master
2020-04-27T08:17:42.227150
2019-03-09T05:56:05
2019-03-09T05:56:05
174,165,118
5
0
MIT
2019-03-09T05:56:06
2019-03-06T14:55:39
Python
UTF-8
Python
false
false
1,967
py
# coding:utf-8 # # The MIT License (MIT) # # Copyright (c) 2016-2018 yutiansut/QUANTAXIS # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import datetime from subprocess import PIPE, Popen def QA_util_web_ping(url): ms_list = [] p = Popen(["ping", url], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out = p.stdout.read() list_ = str(out).split('=') # print(list) for item in list_: if 'ms' in item: ms_list.append(int(item.split('ms')[0])) if len(ms_list) < 1: # Bad Request: ms_list.append(9999999) return ms_list[-1] class QA_Util_web_pool(): def __init__(self): pass def hot_update(self): pass def dynamic_optimics(self): pass def task_queue(self): pass if __name__ == "__main__": print(datetime.datetime.now()) print(QA_util_web_ping('www.baidu.com')) print(datetime.datetime.now())
[ "yutiansut@qq.com" ]
yutiansut@qq.com
14bff795b6ed2d74c4775d4f3bc0e738dffaa06b
97eb29b4fbb55ca3c4b3f4ce6b5b9432eb73efdd
/DjangoEnv/bin/django-admin
6a8820ebbc2b8895471291d8eddffd3f81122a90
[]
no_license
Gephi-2017/ProjectDjango
ced8a5c8547b0366319b756def3ff7baa3c14226
33969fddf4abe2a19629ce1657d04e6cbdd82d74
refs/heads/master
2020-03-17T00:50:11.012635
2018-05-12T09:12:28
2018-05-12T09:12:28
133,131,612
0
0
null
null
null
null
UTF-8
Python
false
false
297
#!/home/shree/ProjectDjango/DjangoEnv/bin/python # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
[ "slshruthi17@gmail.com" ]
slshruthi17@gmail.com
bbc89e8e7645a694b405dccb4acd25b4f0cc9544
84cfe9b0ca7209487231e0725f7ad0d233f09544
/smv/views.py
e0abea56ca1a13c1798a6cffabfed45f0991342d
[]
no_license
archit-dwevedi/M4Plan
3eefc12ea447d624bae6f758c3648d7caf825c1a
d162592748ea37bc070b6217365e8601a6ccdd9a
refs/heads/master
2021-10-26T23:22:04.456014
2019-04-14T20:02:17
2019-04-14T20:02:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,397
py
from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib import messages from absenteeism.models import * from skill_matrix.models import * from leave_calendar.models import * from .forms import * from .models import * import datetime def smv(request): if(request.method=='POST'): form = Smv(request.POST) if form.is_valid(): form.save() return HttpResponse("<h1>SMV is submitted</h1>") else: messages.error(request,"Error") else: form = Smv() return render(request,'smv/smv.html',{'form':form}) def dashsmv(request): a=SMV.objects.all() return render(request,'smv/dash_smv.html',{'a':a}) def dashpfm(request): a=SMV.objects.all() sam=[] mcs=[] for i in a: #time=((i.pick_in_sec+i.main_Process_in_sec+i.turn_in_sec+i.dispose_in_sec)*i.s_P_I.s_p_i)/12 sam.append((((((((i.pick_in_sec+i.main_Process_in_sec+i.turn_in_sec+i.dispose_in_sec)/60)/12)*i.s_P_I.s_p_i)/20)*i.stitch_Length.stitch_length)*int(i.complexity.complx))*(1+int(i.personal_Allowance+i.fatigue_Allowance+i.delay_Allowance))*0.02*0.9) print(sam) for i in sam: mcs.append(560/(480/(i*0.85))) print(mcs) return render(request,'smv/dash_pfm.html',{'a':a,'sam':sam,'mcs':mcs}) def newdashpfm(request): a=PFM.objects.all() return render(request,'smv/new_dash_pfm.html',{'a':a}) def ob(request): if(request.method=='POST'): form=Pfm(request.POST) if(form.is_valid()): global a global d global s s=request.POST.get('section') a=PFM.objects.filter(sec__name=s) d=a return redirect('/newob') else: messages.error(request,"Error") else: form=Pfm() return render(request,'smv/ob.html',{'form':form}) def newob(request): if(request.method=='POST'): global d myself=Ob(request.POST,operation=d) if(myself.is_valid()): global get cat=myself.cleaned_data['category'] sub=myself.cleaned_data['subcategory'] get=myself.cleaned_data['Add Neccessary Operation'] print(get) print(cat,sub) return redirect('/dashob') else: messages.error(request,"Error") else: global a global s form = Ob(operation=a) return render(request,'smv/ob.html',{'form':form,'s':s}) def dashob(request): global get global q q=[] sam=[] for i in get: q.append(SMV.objects.get(operation=i)) for i in q: print(i.operation) print(i.s_P_I) sam.append((((((((i.pick_in_sec + i.main_Process_in_sec + i.turn_in_sec + i.dispose_in_sec) / 60) / 12) * i.s_P_I.s_p_i) / 20) * i.stitch_Length.stitch_length) * int(i.complexity.complx)) * ( 1 + int(i.personal_Allowance + i.fatigue_Allowance + i.delay_Allowance)) * 0.02 * 0.9) return render(request,'smv/dashob.html',{'a':q,'sam':sam}) def layout(request): global s global q return render(request,'smv/layout.html',{'a':s,'q':q}) def dashboard(request): global s global q global get ab=[] d=datetime.datetime.now().date() a=LeaveApplication.objects.all() for i in a: if(d<=i.end_date): ab.append(i.key.user) print(ab) b=Person.objects.all() ab2=[] for j in b: if(j.date==d): if(j.status=='Absent' or j.status=='Leave' or j.status==None): ab2.append(User.objects.get(username=j.name)) print(ab2) c=Scale.objects.all() #e=Employee.objects.all() ss=ab+ab2 for m in ss: for n in c: if(m==n.use): c=c.exclude(use=m) print(c) print(get) for i in get: for j in c: if(str(j.operation)==i): print(j.use,j.operation,j.level) ## m=lambda x:x==y ## for i in c: ## y=str(i.operation) ## print(list(map(m,get))) list=zip(c,q) return render(request,'smv/dashboard.html',{'a':s,'q':q,'c':c,'get':get,'list':list}) def desc(request): return render(request,'smv/desc.html')
[ "dwevediar@gmail.com" ]
dwevediar@gmail.com
b20b0b8aafd7085cbf29263b494a5e85bcf65b65
41d3442bed584a40dbff035ee808c844b0b47f3e
/scoring/evaluator_vocabulary.py
71429f34645ac0710eafa9fe5d7ea689451b19e4
[]
no_license
konstantinschulz/alpaca
8e55b9b24a4c7c5db9ecfb041488ee34c9a43bb8
baa500ebb1e7ce92fe34a7c0b7ea65479a510567
refs/heads/main
2023-08-25T05:26:09.271704
2021-10-27T13:57:39
2021-10-27T13:57:39
375,756,439
0
0
null
null
null
null
UTF-8
Python
false
false
5,386
py
import logging import re from collections import defaultdict from pathlib import Path import pandas as pd from testing import test from parsing.webpage_data import WebpageData # modify profanity score gradient given this upper limit MAX_PROFANITY = 3 # multiplier for emotion intensity per words ratio to modify final emotionality score EMOTION_INTENSITY_MULTIPLIER = 2 # boundary checks if MAX_PROFANITY <= 0 or EMOTION_INTENSITY_MULTIPLIER <= 0: raise ValueError("A constant for vacabulary evaluation is set incorrectly") logger = logging.getLogger("alpaca") def evaluate_profanity(data: WebpageData) -> float: """Evaluates webpage by checking for occurrences of profanity. Combines and checks webpage headline and text. Profanity score is linear from 0 occurrences (best score => 1) to *MAX_PROFANITY* occurrences (worst score => 0). :return: Value between 1 (low profanity) and 0 (high profanity). """ # file containing profanity/slurs, one entry per line profanity_list_path = "files/profanity.txt" filepath = (Path(__file__).parent / profanity_list_path).resolve() fulltext = data.headline.lower() + " " + data.text.lower() profanity_matches = defaultdict(int) with open(filepath, "r") as profanity_words: for line in profanity_words.readlines(): if match := re.findall(r"\b" + line.strip() + r"\b", fulltext): profanity_matches[match[0]] += len(match) if profanity_matches: logger.info("[Vocabulary] Profanity matches: {}" .format(["{} ({}x)".format(slur, occurrences) for slur, occurrences in profanity_matches.items()])) test.add_result(data.url, "profanity", sum(profanity_matches.values())) match_count = sum(profanity_matches.values()) score = match_count / MAX_PROFANITY return 1 - min(score, 1) def evaluate_emotional_words(data: WebpageData) -> float: """Evaluates the vocabulary used by the webpage for its emotionality. Compares all words in the headline and text against a list of emotional words with specified emotion intensity values. Sums up all intensity values for any matches, scales the total sum by word count. Final score is linear between 0 (worst score, words have on average at least 1 / *EMOTION_INTENSITY_MULTIPLIER* emotion intensity) and 1 (best score, words have 0 emotion intensity on average). :return: Value between 0 (high emotionality) and 1 (low emotionality). """ # TODO possibly limit scoring to some subset of emotions # file containing words & their degree of association with 8 emotions, one entry per line # using emotion intensity lexicon by Saif M. Mohammad https://saifmohammad.com/WebPages/AffectIntensity.htm emotion_list_path = "files/emotion_intensity_list.csv" filepath = (Path(__file__).parent / emotion_list_path).resolve() emotional_words = pd.read_csv(filepath, sep=";") df_size = len(emotional_words) fulltext = data.headline.lower() + " " + data.text.lower() word_count = 0 emotionality_results = {"anger": {"count": 0, "intensity": 0}, "anticipation": {"count": 0, "intensity": 0}, "disgust": {"count": 0, "intensity": 0}, "fear": {"count": 0, "intensity": 0}, "sadness": {"count": 0, "intensity": 0}, "joy": {"count": 0, "intensity": 0}, "surprise": {"count": 0, "intensity": 0}, "trust": {"count": 0, "intensity": 0}} # lookup all words from article in emotional words list for article_word in re.findall("[a-z]+", fulltext): word_count += 1 match = emotional_words["word"].searchsorted(article_word) if match < df_size and emotional_words.iat[match, 0] == article_word: # get emotion intensity data for a word match for emotion, emotion_intensity in emotional_words.iloc[match, 1:].items(): if emotion_intensity > 0: emotionality_results[emotion]["count"] += 1 emotionality_results[emotion]["intensity"] += emotion_intensity total_emotion_count = sum(emotion_stats["count"] for emotion_stats in emotionality_results.values()) total_emotion_intensity = sum(emotion_stats["intensity"] for emotion_stats in emotionality_results.values()) logger.debug("[Vocabulary] Emotionality results: {}".format( ["{}: {} words, {:.3f} intensity".format(emotion, emotion_stats["count"], emotion_stats["intensity"]) for emotion, emotion_stats in emotionality_results.items()])) logger.debug("[Vocabulary] Emotionality overall: {} words | {:.3f} intensity | {:.3f} intensity per word".format( total_emotion_count, total_emotion_intensity, total_emotion_intensity / word_count)) for emotion in emotionality_results.keys(): test.add_result(data.url, emotion + "_word_count", emotionality_results[emotion]["count"]) test.add_result(data.url, emotion + "_intensity", emotionality_results[emotion]["intensity"]) emotion_score = (total_emotion_intensity * EMOTION_INTENSITY_MULTIPLIER) / word_count return max(1 - emotion_score, 0)
[ "Konstantin.Schulz@dfki.de" ]
Konstantin.Schulz@dfki.de
42cc2d6e0d7d6b565e6ce9d80f133c7f719e9115
b05cbedbcda2efd5e3722a52f309e7987b618de0
/Logging.py
23054220361b751acad1e9d24757b7a8507dd4df
[ "MIT" ]
permissive
bwhetherington/Gompei-Bot
ef32100a690e1af9be94511b33373e56cf186f72
a6c03c7a5a190fc63a96d0e4ab2529c3ba484dcb
refs/heads/master
2023-06-30T03:11:23.221088
2020-07-29T05:33:08
2020-07-29T05:33:08
286,293,970
0
0
null
2020-08-09T18:26:09
2020-08-09T18:26:09
null
UTF-8
Python
false
false
15,221
py
# TODO: Implementation # IDEA: Track which invite a user joined off of import discord import json import os from datetime import datetime from discord.ext import commands def module_perms(ctx): return ctx.message.author.guild_permissions.administrator def parse_id(arg): """ Parses an ID from a discord mention :param arg: mention or ID passed :return: ID """ if "<" in arg: for i, c in enumerate(arg): if c.isdigit(): return int(arg[i:-1]) # Using ID else: return int(arg) class Logging(commands.Cog): def __init__(self, bot): self.bot = bot self.embed = discord.Embed() self.logs = None async def update_guilds(self): savedGuilds = [] for guildID in self.logs: savedGuilds.append(guildID) guilds = [] for guild in self.bot.guilds: guilds.append(str(guild.id)) addGuilds = [x for x in guilds if x not in savedGuilds] removeGuilds = [x for x in savedGuilds if x not in guilds] # Add new guilds for guildID in addGuilds: self.logs[str(guildID)] = {"channel": None} # Remove disconnected guilds for guildID in removeGuilds: self.logs.pop(str(guildID)) await self.update_state() @commands.Cog.listener() async def on_ready(self): await self.load_state() await self.update_guilds() @commands.command(pass_context=True, name="logging") @commands.check(module_perms) async def change_logging(self, ctx, arg1): """ Changes the channel that the bot sends logging messages in :param arg1: channel ID or mention """ channel = ctx.guild.get_channel(parse_id(arg1)) print(parse_id(arg1)) if self.logs[str(ctx.message.guild.id)]["channel"] != channel.id: self.logs[str(ctx.message.guild.id)]["channel"] = channel.id print("Updating guild " + str(ctx.message.guild.id) + " to use logging channel " + str(channel.id)) await self.update_state() print("Finished updating logging channel") await ctx.send("Successfully updated logging channel to <#" + str(channel.id) + ">") @change_logging.error async def change_logging_error(self, ctx, error): if isinstance(error, commands.CheckFailure): print("!ERROR! " + str(ctx.author.id) + " did not have permissions for change logging command") elif isinstance(error, commands.MissingRequiredArgument): await ctx.send("Command is missing arguments") else: print(error) async def load_state(self): with open(os.path.join("config", "logging.json"), "r+") as loggingFile: logs = loggingFile.read() self.logs = json.loads(logs) async def update_state(self): with open(os.path.join("config", "logging.json"), "r+") as loggingFile: loggingFile.truncate(0) loggingFile.seek(0) json.dump(self.logs, loggingFile, indent=4) @commands.Cog.listener() async def on_message_delete(self, message): """ Sends a logging message containing author, channel, content, and time of the deleted message :param message: message object deleted """ if not message.author.bot: if self.logs[str(message.guild.id)]["channel"] is not None: loggingChannel = message.guild.get_channel(int(self.logs[str(message.guild.id)]["channel"])) channel = message.channel self.embed = discord.Embed() self.embed.colour = discord.Colour(0xbe4041) self.embed.set_author(name=message.author.name + "#" + message.author.discriminator, icon_url=message.author.avatar_url) self.embed.title = "Message deleted in " + "#" + channel.name self.embed.description = message.content self.embed.set_footer(text="ID: " + str(message.author.id)) self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_raw_message_delete(self, payload): """ Sends a logging message containing location (channel), and ID of the message deleted :param payload: :return: """ guild = self.bot.get_guild(payload.guild_id) if self.logs[str(guild.id)]["channel"] is not None and payload.cached_message is None: loggingChannel = guild.get_channel(int(self.logs[str(guild.id)]["channel"])) channel = guild.get_channel(payload.channel_id) self.embed = discord.Embed() self.embed.colour = discord.Colour(0xbe4041) self.embed.title = "Message deleted in " + "#" + channel.name self.embed.set_footer(text="Uncached message: " + str(payload.message_id)) self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_raw_bulk_message_delete(self, payload): """ Sends a logging message containing author, location (channel and placement), content, and time of the deleted messages May be limited if message is not in the cache :param payload: """ guild = self.bot.get_guild(payload.guild_id) if self.logs[str(guild.id)]["channel"] is not None: loggingChannel = guild.get_channel(int(self.logs[str(guild.id)]["channel"])) channel = guild.get_channel(payload.channel_id) content = "" count = 0 for message in payload.cached_messages: count += 1 content += "[" + message.author.name + "#" + message.author.discriminator + "]: " + message.content + "\n" self.embed = discord.Embed() self.embed.colour = discord.Colour(0xbe4041) self.embed.title = str(count) + " Messages bulk deleted in " + "#" + channel.name self.embed.description = content self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_message_edit(self, before, after): """ Sends a logging message containing the content of the message before and after the edit :param before: message object before :param after: message object after """ if not before.author.bot: if self.logs[str(before.guild.id)]["channel"] is not None: if before.content is after.content: return loggingChannel = before.guild.get_channel(int(self.logs[str(before.guild.id)]["channel"])) channel = before.channel self.embed = discord.Embed(url=before.jump_url) self.embed.colour = discord.Colour(0x8899d4) self.embed.set_author(name=before.author.name + "#" + before.author.discriminator, icon_url=before.author.avatar_url) self.embed.title = "Message edited in #" + channel.name self.embed.description = "**Before:** " + before.content + "\n**+After:** " + after.content self.embed.set_footer(text="ID: " + str(before.author.id)) self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_raw_message_edit(self, payload): """ Sends a logging message containing the content of the message after the edit :param payload: :return: """ # FIXME: Cannot get guild from payload # guild = self.bot.get_guild(payload.guild_id) # # if self.logs[str(guild.id)]["channel"] is not None and payload.cached_message is None: # loggingChannel = guild.get_channel(int(self.logs[str(guild.id)]["channel"])) # channel = guild.get_channel(payload.channel_id) # message = channel.fetch_message(payload.message_id) # # self.embed = discord.Embed() # self.embed.colour = discord.Colour(0x8899d4) # self.embed.set_author(name=message.author.name + "#" + message.author.discriminator, icon_url=message.author.avatar_url) # self.embed.title = "Message edited in " + "#" + channel.name # self.embed.description = "\n**+After:** " + message.content # self.embed.set_footer(text="ID: " + str(message.author.id)) # self.embed.timestamp = datetime.utcnow() # # await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_guild_channel_create(self, channel): """ Sends a logging message containing the name, category, and permissions of the channel :param channel: """ if self.logs[str(channel.guild.id)]["channel"] is not None: loggingChannel = channel.guild.get_channel(int(self.logs[str(channel.guild.id)]["channel"])) self.embed = discord.Embed() self.embed.colour = discord.Colour(0x43b581) permissions = "" # If a Category if channel.type is discord.ChannelType.category: self.embed.title = "Category created" description = "**Name:** " + channel.name + "\n**Position:** " + str(channel.position) if len(channel.overwrites) > 0: for role in channel.overwrites: # If you have permission to read messages if channel.overwrites[role].pair()[0].read_messages is True: permissions += "**Read Text Channels & See Voice Channels:** :white_check_mark:\n" permissions += "**Connect:** :white_check_mark:" else: permissions += "**Read Text Channels & See Voice Channels:** :x:\n" permissions += "**Connect:** :x:" else: description = "**Name:** " + channel.name + "\n**Position:** " + str( channel.position) + "\n**Category:** " if channel.category is not None: description += channel.category.name else: description += "None" # If a text channel if channel.type is discord.ChannelType.text: self.embed.title = "Text channel created" if len(channel.overwrites) > 0: for role in channel.overwrites: if channel.overwrites[role].pair()[0].read_messages is True: permissions += "**Read messages:** :white_check_mark:" else: permissions += "**Read messages:** :x:" # If a VoiceChannel else: self.embed.title = "Voice channel created" if len(channel.overwrites) > 0: for role in channel.overwrites: permissions = "" if channel.overwrites[role].pair()[0].connect is True: permissions += "**Connect:** :white_check_mark:" else: permissions += "**Connect:** :x:" self.embed.add_field(name="Overwrites for " + str(role.name), value=permissions, inline=False) self.embed.description = description self.embed.set_footer(text="ID: " + str(channel.id)) self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_guild_channel_delete(self, channel): """ Sends a logging message containing the name, category, and permissions of the channel """ if self.logs[str(channel.guild.id)]["channel"] is not None: loggingChannel = channel.guild.get_channel(int(self.logs[str(channel.guild.id)]["channel"])) self.embed = discord.Embed() self.embed.colour = discord.Colour(0xbe4041) if channel.type is discord.ChannelType.category: self.embed.title = "Category deleted" description = "**Name:** " + channel.name else: if channel.type is discord.ChannelType.text: self.embed.title = "Text channel deleted" else: self.embed.title = "Voice channel deleted" description = "**Name:** " + channel.name + "\n**Category:** " if channel.category is not None: description += channel.category.name else: description += "None" self.embed.description = description await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_guild_channel_update(self, before, after): """ Sends a logging message containing the updated properties of the channel """ # Check name update if before.name != after.name: if before.type is discord.ChannelType.category: self.embed.title # Check position update # Check permission update # Slow mode # NSFW return @commands.Cog.listener() async def on_guild_channel_pins_update(self, channel, last_pin): """ Sends a logging message containing the name of the channel, the content of the pinned message, and a link to the message """ return @commands.Cog.listener() async def on_guild_integrations_update(self, guild): """ WTF are guild integrations??? """ return @commands.Cog.listener() async def on_webhooks_update(self, channel): """ WTF are webhooks??? """ return @commands.Cog.listener() async def on_member_join(self, member): """ Sends a logging message containing the name, avatar, id, join position, account age """ if self.logs[str(member.guild.id)]["channel"] is not None: loggingChannel = member.guild.get_channel(int(self.logs[str(member.guild.id)]["channel"])) ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n / 10 % 10 != 1) * (n % 10 < 4) * n % 10::4]) self.embed = discord.Embed() self.embed.colour = discord.Colour(0x43b581) self.embed.set_author(name=member.name + "#" + member.discriminator, icon_url=member.avatar_url) self.embed.title = "Member joined" creationDelta = datetime.now() - member.created_at count = 0 self.embed.description = "<@" + str(member.id) + "> " + ordinal(member.guild.member_count) + " to join\ncreated " self.embed.set_footer(text="ID: " + str(member.id)) self.embed.timestamp = datetime.utcnow() await loggingChannel.send(embed=self.embed) @commands.Cog.listener() async def on_member_remove(self, member): """ Sends a logging message containing the name, avatar, id, time spent on the server """ return @commands.Cog.listener() async def on_member_update(self, before, after): """ Sends a logging message containing the property of the member updated before and after """ return @commands.Cog.listener() async def on_user_update(self, before, after): """ Sends a logging message containing the property of the user updated before and after """ return @commands.Cog.listener() async def on_guild_update(self, before, after): """ Sends a logging message containing the property of the guild updated before and after """ return @commands.Cog.listener() async def on_guild_role_create(self, role): """ Sends a logging message containing the id, name, color, mentionable, and hoisted properties of the role """ return @commands.Cog.listener() async def on_guild_role_delete(self, role): """ Sends a logging message containing the id, name, color, mentionable, and hoisted properties of the role """ return @commands.Cog.listener() async def on_guild_role_update(self, before, after): """ Sends a logging message containing the property of the role updated before and after """ return @commands.Cog.listener() async def on_guild_emojis_update(self, guild, before, after): """ Sends a logging message containing the id, name, and picture of the emoji """ return @commands.Cog.listener() async def on_voice_state_update(self, member, before, after): """ Sends a logging message containing the id, name, and updated voice properties of the member """ return @commands.Cog.listener() async def on_member_ban(self, guild, user): """ Sends a logging message containing the id, name, and join date of the member """ return @commands.Cog.listener() async def on_member_unban(self, guild, user): """ Sends a logging message containing the id and name of the member """ return @commands.Cog.listener() async def on_invite_create(self, invite): """ Sends a logging message containing the invite code, inviter name, inviter id, expiration time """ return @commands.Cog.listener() async def on_invite_delete(self, invite): """ Sends a logging message containing the invite code, inviter name, and expiration time """ return
[ "samuelcurrid@gmail.com" ]
samuelcurrid@gmail.com
91b9e1b36fadf5d38e7788326e49195823ae4444
957563c6d08819967813063a193619b7df7f0050
/mbof/migrations/0010_auto_20160303_1142.py
5840ed33e44677751ee650c027ae7832c5cc6e5b
[]
no_license
jlost/hacks_mbof
0c44657448c58c35b2443f285e2e0aa107980431
9bfe464e2842a09d2974103b5e8b5be15bd5d1cc
refs/heads/master
2021-01-21T07:45:59.878779
2016-03-04T16:13:27
2016-03-04T16:13:27
53,062,453
0
0
null
2016-03-03T15:43:03
2016-03-03T15:43:03
null
UTF-8
Python
false
false
535
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-03-03 16:42 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mbof', '0009_auto_20160303_1131'), ] operations = [ migrations.AlterField( model_name='user', name='roles', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='mbof.Role'), ), ]
[ "its-jlost@adsroot.itcs.umich.edu" ]
its-jlost@adsroot.itcs.umich.edu
06229e6afb5087b342f48ced5e2d41a803b865c3
30b084acbe36d02e85d756e4580f0e845dab65c9
/setup.py
4f793631bb4105c6c26c9395bfc1f42ed30854ef
[]
no_license
JavanTang/py2aliyungdb
47757ae9aacd4496a4fd4dda2733fc11c0ac5548
c62b985d04e1cb00c8f63f881a4ade1d2ed0eaa6
refs/heads/master
2022-12-03T01:48:53.163098
2020-08-17T05:40:46
2020-08-17T05:40:46
288,082,092
3
0
null
null
null
null
UTF-8
Python
false
false
405
py
''' Author: JavanTang Data: Do not edit LastEditors: JavanTang LastEditTime: 2020-08-17 11:04:35 Description: ''' from setuptools import setup setup( name='py2aliyungdb', # 应用名 version='0.0.1', # 版本号 packages=['py2aliyungdb'], # 包括在安装包内的 Python 包 author='JavanTang', author_email='tzfjobmail@gmail.com', url='https://github.com/pypa/sampleproject' )
[ "tzfjobmail@gmail.com" ]
tzfjobmail@gmail.com
1922476617a16ac1492b7ae020e4478f854a244c
97db962c17f91f6ca5da71a5a301094277d26a8e
/setup.py
ddd05323c9f71b1b4c9a1e80868e6267655cee53
[]
no_license
citrix-openstack/osnotify
0a510457e3663092a6a6d8e575019a5052c896e5
2feca02a843fed93a9d36254d7e896ba95107a9c
refs/heads/master
2020-05-17T01:04:23.088988
2013-03-01T17:34:37
2013-03-01T17:34:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
576
py
from setuptools import setup setup( name="osnotify", version="0.0", packages=["osnotify"], entry_points={ 'console_scripts': [ 'osnotify-proxy = osnotify.scripts:proxy', 'osnotify-subscribe = osnotify.scripts:subscribe', 'osnotify-publish = osnotify.scripts:publish', 'osnotify-install-service = osnotify.scripts:install_service', 'osnotify-gerrit-to-githook = osnotify.scripts:gerrit_to_githook', 'generate-initscript = osnotify.scripts:generate_initscript', ] } )
[ "mate.lakat@citrix.com" ]
mate.lakat@citrix.com
1984950eeeabd376b7d534bbc788f09949c9ea71
f3416956f9bfc7af870867e2fe8644f08d513b23
/combine/contest_20150310a/data_prep/prepare_pgmodel.py
18a14ff2cbcfdb41cfe5e56133323bb4b304d6ed
[]
no_license
dsjoerg/blundercheck
a71012c0d3ded929599d191d4f73dcb14f94030a
04fb39ba0dd1591b387f573f767973518b688822
refs/heads/master
2021-01-18T18:35:21.992359
2015-03-24T18:11:11
2015-03-24T18:11:11
27,928,453
4
1
null
null
null
null
UTF-8
Python
false
false
8,108
py
#!/usr/bin/env python from pandas import * from numpy import * from djeval import * import csv, code import cPickle as pickle from sklearn.externals import joblib GAMELIMIT=60000 NUM_GAMES=100000 def shell(): vars = globals() vars.update(locals()) shell = code.InteractiveConsole(vars) shell.interact() msg("Hi! Reading eheaders") eheaders_filename = '/data/eheaders.p' eheaders_file = open(eheaders_filename, 'r') eheaders = pickle.load(eheaders_file) elos = eheaders['elos'] result = eheaders['result'] checkmate = eheaders['checkmate'] openings = eheaders['openings'] ocount = eheaders['opening_count'] msg("Hi! Reading crunched movescores from %s" % sys.argv[1]) crunched_path = sys.argv[1] crunched_df = read_csv(crunched_path, sep=',', engine='c', index_col=['gamenum', 'side']) msg("Hi! Reading GB scores from %s" % sys.argv[2]) gb_path = sys.argv[2] gb_df = read_csv(gb_path, sep=',', engine='c', index_col=['gamenum']) msg("Hi! Reading depthstats") depthstats_path = '/data/depthstats.csv' columns = [ 'gamenum', 'side', 'mean_depth', 'mean_seldepth', 'mean_depths_agreeing_ratio', 'mean_deepest_agree_ratio', 'pct_sanemoves', 'gamelength', 'mean_num_bestmoves', 'mean_num_bestmove_changes', 'mean_bestmove_depths_agreeing', 'mean_deepest_change', 'mean_deepest_change_ratio', ] depthstats_df = read_csv(depthstats_path, sep=' ', engine='c', header=None, names=columns, index_col=False) depthstats_df = depthstats_df.set_index(['gamenum', 'side']) # we have the gamelength column in another df, drop it here to avoid conflicts depthstats_df.drop('gamelength', axis=1, inplace=True) msg("Hi! Reading material") material_path = '/data/material.csv' columns = [ 'gamenum', 'material_break_0', 'material_break_1', 'material_break_2', 'material_break_3', 'material_break_4', 'opening_length', 'midgame_length', 'endgame_length', 'mean_acwsa', 'mean_acwsa_0', 'mean_acwsa_1', 'mean_acwsa_2', 'mean_acwsa_3', 'mean_acwsa_4', 'mean_acwsa_5', 'mean_acwsa_6', 'mean_acwsa_7', 'mean_acwsa_8', 'mean_acwsa_9', ] material_df = read_csv(material_path, sep=' ', engine='c', header=None, names=columns, index_col=False) material_df = material_df.set_index(['gamenum']) material_df = material_df.reindex(range(1, NUM_GAMES+1)) material_df = material_df.fillna(material_df.mean()) msg("Reading ELOscored data") eloscored_cols = [ 'gamenum', 'final_elo', 'final_ply', 'final_num_games', 'final_elo_stdev', 'elopath_min', 'elopath_max', ] eloscored_df = read_csv('/data/data.pgn.eloscored21', sep=',', engine='c', header=None, names=eloscored_cols, index_col=False) eloscored_df = eloscored_df.set_index(['gamenum']) msg("Reading ELOscored data 4") eloscored4_cols = [ 'gamenum', 'final_elo', 'final_ply', 'final_num_games', 'final_elo_stdev', ] eloscored4_cols[1:] = [x + '_elo4' for x in eloscored4_cols[1:]] eloscored4_df = read_csv('/data/data.pgn.eloscored4', sep=',', engine='c', header=None, names=eloscored4_cols, index_col=False) eloscored4_df = eloscored4_df.set_index(['gamenum']) msg("Reading ELOscored data 10") eloscored10_cols = [ 'gamenum', 'final_elo', 'final_ply', 'final_num_games', 'final_elo_stdev', ] eloscored10_cols[1:] = [x + '_elo10' for x in eloscored10_cols[1:]] eloscored10_df = read_csv('/data/data.pgn.eloscored10', sep=',', engine='c', header=None, names=eloscored10_cols, index_col=False) eloscored10_df = eloscored10_df.set_index(['gamenum']) msg("Hi! Reading moveaggs") move_aggs = joblib.load('/data/move_aggs.p') move_aggs.fillna(move_aggs.mean(), inplace=True) msg("Hi! Reading wmoveaggs") wmove_aggs = joblib.load('/data/wmove_aggs.p') wmove_aggs.fillna(wmove_aggs.mean(), inplace=True) wmove_aggs.rename(columns={'elo_pred': 'moveelo_weighted'}, inplace=True) do_elochunk = True if do_elochunk: ch_agg_df = joblib.load('/data/chunk_aggs.p') ch_agg_df.index = ch_agg_df.index.droplevel('elo') ch_agg_df.columns = ['elochunk_' + x for x in ch_agg_df.columns] msg("Hi! Setting up playergame rows") if do_elochunk: elorange_cols = list(ch_agg_df.columns.values) msg("elorange cols are %s" % elorange_cols) msg('Preparing ELO df') elo_rows = [[x[0][0], x[0][1], x[1]] for x in elos.items()] elo_df = DataFrame(elo_rows, columns=['gamenum','side','elo']) elo_df.set_index(['gamenum','side'], inplace=True) msg('Joining DFs') supplemental_dfs = [move_aggs[['mean', 'median', '25', '10', 'min', 'max', 'stdev']], wmove_aggs['moveelo_weighted'], depthstats_df, elo_df, crunched_df] if do_elochunk: supplemental_dfs.append(ch_agg_df) mega_df = concat(supplemental_dfs, axis=1) mega_df = mega_df.join(material_df, how='outer') mega_df = mega_df.join(eloscored_df, how='outer') mega_df = mega_df.join(eloscored4_df, how='outer') mega_df = mega_df.join(eloscored10_df, how='outer') mega_df = mega_df.join(gb_df, how='outer') yy_df = mega_df msg("hi, columns are %s" % yy_df.columns) # TODO confirm that all columns are there def opening_feature(opening): if ocount[opening] < 20: return 'rare' if ocount[opening] < 200: return 'uncommon' return opening msg("Hi! Computing additional features") yy_df['opening_feature'] = [opening_feature(openings[x]) for x in yy_df.index.get_level_values('gamenum')] yy_df['opening_count'] = [ocount[openings[x]] for x in yy_df.index.get_level_values('gamenum')] yy_df['any_grit'] = (yy_df['grit'] > 0) yy_df['major_grit'] = (yy_df['grit'] > 5) yy_df['nmerror'] = log((-1 * yy_df['meanerror']).clip(1,60)).clip(1,4) - 2.53 yy_df['premature_quit'] = (yy_df['gameoutcome'] == -1) & (yy_df['my_final_equity'] > -100) yy_df['drawn_game'] = (yy_df['gameoutcome'] == 0) yy_df['ended_by_checkmate'] = yy_df['won_by_checkmate'] | yy_df['lost_by_checkmate'] yy_df['noblunders'] = (yy_df['blunderrate'] == 0) yy_df['final_equity'] = yy_df['my_final_equity'].abs().clip(0,300) yy_df['early_lead'] = yy_df['early_lead'].clip(0,100) yy_df['mean_depth_clipped'] = yy_df['mean_depth'].clip(0,25) yy_df['gamelength_clipped'] = yy_df['gamelength'].clip(20,200) # prepare opponent_df with selected info about opponent opponent_columns = ['meanerror', 'blunderrate', 'perfectrate', 'grit', 'meanecho', 'mate_created', 'mate_destroyed', 'q_error_one', 'q_error_two', 'stdeverror', 'elo', 'any_grit', 'noblunders', 'nmerror', 'mean_depths_agreeing_ratio', 'mean_deepest_agree_ratio'] if do_elochunk: opponent_columns.extend(elorange_cols) opponent_df = yy_df[opponent_columns] opponent_df = opponent_df.reset_index() opponent_df['side'] = opponent_df['side'] * -1 opponent_df.set_index(['gamenum', 'side'], inplace=True) opponent_df.columns = ['opponent_' + x for x in opponent_df.columns] yy_df = concat([yy_df, opponent_df], axis=1) # more derived columns that use opponent comparisons yy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo']).clip(-500, 500) yy_df['max_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].max(axis=1) yy_df['min_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].min(axis=1) yy_df['max_meanecho'] = yy_df[['meanecho', 'opponent_meanecho']].max(axis=1) yy_df['elo_avg'] = (yy_df['elo'] + yy_df['opponent_elo'])/2.0 yy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo']) yy_df['winner_elo_advantage'] = yy_df['elo_advantage'] * yy_df['gameoutcome'] msg("Hi! Computing dummy variables") categorical_features = ['opening_feature'] dummies = get_dummies(yy_df[categorical_features]).astype(np.int8) yy_df = yy_df.join(dummies) # fill in missing values msg("Hi! Filling in missing values") full_index = pandas.MultiIndex.from_product([range(1,NUM_GAMES + 1), [1,-1]], names=['gamenum', 'side']) yy_df = yy_df.reindex(full_index) yy_elo = yy_df['elo'].copy(True) yy_df.fillna(yy_df.mean(numeric_only=True), inplace=True) yy_df.fillna(False, inplace=True) yy_df['elo'] = yy_elo # stupid patch for some stupid opening feature that got assigned to False by fillna ?!!?!?!? yy_df.loc[yy_df['opening_feature'] == False,'opening_feature'] = 'rare' msg("Hi! Writing yy_df to disk") yy_df.to_pickle(sys.argv[3]) msg("Column counts are:") counts = yy_df.count(axis=0) print counts
[ "dsjoerg@gmail.com" ]
dsjoerg@gmail.com
45b49213838540d4cfa9b40c36aa8caf8d58558d
38445323b49947266d72645ec973b02e96879eed
/harshad number.py
8a99c9850563a0ad3ee51f2ed7074159f804f964
[]
no_license
pooja-pichad/loop
2d9989b472a2fbacf0a85da06d869016b2d74083
47dafba1253da98f98c8fa389e13283ce1e14dee
refs/heads/main
2023-04-22T02:58:49.274211
2021-05-22T07:13:39
2021-05-22T07:13:39
369,741,349
0
0
null
null
null
null
UTF-8
Python
false
false
717
py
# harshad number : # it is take any number and add this two digit number and check the # addition value is divisible bye this two digit number then it is divisible then its harshad # number then it not divisiblr then it not harshad number # forEx; 43 # 4+3=7 # 7/43 # num=int(input("enter a number ")) # i=0 # while i<1: # a=num%10 # b=(num//10)%10 # c=(num//10)//10 # d=a+b+c # i=i+1 # if num%d==0: # print("harshad number") # else: # print("not harshad number") i=1 while i<1000: a=i%10 b=(i//10)%10 c=(i//10)//10 d=a+b+c i=i+1 if i%d==0: print("harshad number",i) else: print("not harshad number",i)
[ "noreply@github.com" ]
noreply@github.com
e0eb2aa256dc0a8e392bfc9cb168920d0555df1b
5f04fccd92eb698fa76ab972c01188d699125a50
/ourdesign/wsgi.py
3b753904a90607efbaaae48b7d70cb0ba37388e5
[]
no_license
ourdesignspvt/ourdesign
9dbc8b2b7e2dd7b3019b699a19cb6aa80c3a65a7
cf9d8a3115d024c251d91b421510e1c4b8682c8a
refs/heads/master
2020-04-05T17:16:37.610982
2018-11-11T06:20:49
2018-11-11T06:20:49
157,052,786
0
0
null
null
null
null
UTF-8
Python
false
false
396
py
""" WSGI config for ourdesign project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ourdesign.settings") application = get_wsgi_application()
[ "ourdesignspvt@gmail.com" ]
ourdesignspvt@gmail.com
fed90f6926dd100b6713610ba1b01e6bcdb8133f
c4caffea3c284a2d9454f373dc7c66903c431e42
/test/functional/test_framework/test_framework.py
319fd494a6dfefc8b9c9141b0329c53f64bdea0b
[ "MIT" ]
permissive
heliumchain/squorum
2c36fc2b5149b61054f9aa5c234588f01a3a5d29
2e57ca8e774ab4d75999636abfa870fb8000477d
refs/heads/master
2022-12-02T05:52:59.747926
2020-08-23T16:55:03
2020-08-23T16:55:03
138,344,695
4
2
NOASSERTION
2020-08-23T16:55:04
2018-06-22T20:18:03
C++
UTF-8
Python
false
false
20,380
py
#!/usr/bin/env python3 # Copyright (c) 2014-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. """Base class for RPC testing.""" from enum import Enum import logging import optparse import os import pdb import shutil import sys import tempfile import time from .authproxy import JSONRPCException from . import coverage from .test_node import TestNode from .util import ( MAX_NODES, PortSeed, assert_equal, check_json_precision, connect_nodes_bi, disconnect_nodes, get_datadir_path, initialize_datadir, p2p_port, set_node_times, sync_blocks, sync_mempools, ) class TestStatus(Enum): PASSED = 1 FAILED = 2 SKIPPED = 3 TEST_EXIT_PASSED = 0 TEST_EXIT_FAILED = 1 TEST_EXIT_SKIPPED = 77 class BitcoinTestFramework(): """Base class for a squorum test script. Individual squorum test scripts should subclass this class and override the set_test_params() and run_test() methods. Individual tests can also override the following methods to customize the test setup: - add_options() - setup_chain() - setup_network() - setup_nodes() The __init__() and main() methods should not be overridden. This class also contains various public and private helper methods.""" def __init__(self): """Sets test framework defaults. Do not override this method. Instead, override the set_test_params() method""" self.setup_clean_chain = False self.nodes = [] self.mocktime = 0 self.supports_cli = False self.set_test_params() assert hasattr(self, "num_nodes"), "Test must set self.num_nodes in set_test_params()" def main(self): """Main function. This should not be overridden by the subclass test scripts.""" parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true", help="Leave squorumds and test.* datadir on exit or error") parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true", help="Don't stop squorumds after the test execution") parser.add_option("--srcdir", dest="srcdir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__))+"/../../../src"), help="Source directory containing squorumd/squorum-cli (default: %default)") parser.add_option("--cachedir", dest="cachedir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../../cache"), help="Directory for caching pregenerated datadirs") parser.add_option("--tmpdir", dest="tmpdir", help="Root directory for datadirs") parser.add_option("-l", "--loglevel", dest="loglevel", default="INFO", help="log events at this level and higher to the console. Can be set to DEBUG, INFO, WARNING, ERROR or CRITICAL. Passing --loglevel DEBUG will output all logs to console. Note that logs at all levels are always written to the test_framework.log file in the temporary test directory.") parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true", help="Print out all RPC calls as they are made") parser.add_option("--portseed", dest="port_seed", default=os.getpid(), type='int', help="The seed to use for assigning port numbers (default: current process id)") parser.add_option("--coveragedir", dest="coveragedir", help="Write tested RPC commands into this directory") parser.add_option("--configfile", dest="configfile", help="Location of the test framework config file") parser.add_option("--pdbonfailure", dest="pdbonfailure", default=False, action="store_true", help="Attach a python debugger if test fails") parser.add_option("--usecli", dest="usecli", default=False, action="store_true", help="use bitcoin-cli instead of RPC for all commands") self.add_options(parser) (self.options, self.args) = parser.parse_args() PortSeed.n = self.options.port_seed os.environ['PATH'] = self.options.srcdir + ":" + self.options.srcdir + "/qt:" + os.environ['PATH'] check_json_precision() self.options.cachedir = os.path.abspath(self.options.cachedir) # Set up temp directory and start logging if self.options.tmpdir: self.options.tmpdir = os.path.abspath(self.options.tmpdir) os.makedirs(self.options.tmpdir, exist_ok=False) else: self.options.tmpdir = tempfile.mkdtemp(prefix="test") self._start_logging() success = TestStatus.FAILED try: if self.options.usecli and not self.supports_cli: raise SkipTest("--usecli specified but test does not support using CLI") self.setup_chain() self.setup_network() time.sleep(5) self.run_test() success = TestStatus.PASSED except JSONRPCException as e: self.log.exception("JSONRPC error") except SkipTest as e: self.log.warning("Test Skipped: %s" % e.message) success = TestStatus.SKIPPED except AssertionError as e: self.log.exception("Assertion failed") except KeyError as e: self.log.exception("Key error") except Exception as e: self.log.exception("Unexpected exception caught during testing") except KeyboardInterrupt as e: self.log.warning("Exiting after keyboard interrupt") if success == TestStatus.FAILED and self.options.pdbonfailure: print("Testcase failed. Attaching python debugger. Enter ? for help") pdb.set_trace() if not self.options.noshutdown: self.log.info("Stopping nodes") if self.nodes: self.stop_nodes() else: for node in self.nodes: node.cleanup_on_exit = False self.log.info("Note: squorumds were not stopped and may still be running") if not self.options.nocleanup and not self.options.noshutdown and success != TestStatus.FAILED: self.log.info("Cleaning up") shutil.rmtree(self.options.tmpdir) else: self.log.warning("Not cleaning up dir %s" % self.options.tmpdir) if success == TestStatus.PASSED: self.log.info("Tests successful") exit_code = TEST_EXIT_PASSED elif success == TestStatus.SKIPPED: self.log.info("Test skipped") exit_code = TEST_EXIT_SKIPPED else: self.log.error("Test failed. Test logging available at %s/test_framework.log", self.options.tmpdir) self.log.error("Hint: Call {} '{}' to consolidate all logs".format(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../combine_logs.py"), self.options.tmpdir)) exit_code = TEST_EXIT_FAILED logging.shutdown() sys.exit(exit_code) # Methods to override in subclass test scripts. def set_test_params(self): """Tests must this method to change default values for number of nodes, topology, etc""" raise NotImplementedError def add_options(self, parser): """Override this method to add command-line options to the test""" pass def setup_chain(self): """Override this method to customize blockchain setup""" self.log.info("Initializing test directory " + self.options.tmpdir) if self.setup_clean_chain: self._initialize_chain_clean() else: self._initialize_chain() def setup_network(self): """Override this method to customize test network topology""" self.setup_nodes() # Connect the nodes as a "chain". This allows us # to split the network between nodes 1 and 2 to get # two halves that can work on competing chains. for i in range(self.num_nodes - 1): connect_nodes_bi(self.nodes, i, i + 1) self.sync_all() def setup_nodes(self): """Override this method to customize test node setup""" extra_args = None if hasattr(self, "extra_args"): extra_args = self.extra_args self.add_nodes(self.num_nodes, extra_args) self.start_nodes() def run_test(self): """Tests must override this method to define test logic""" raise NotImplementedError # Public helper methods. These can be accessed by the subclass test scripts. def add_nodes(self, num_nodes, extra_args=None, rpchost=None, timewait=None, binary=None): """Instantiate TestNode objects""" if extra_args is None: extra_args = [[]] * num_nodes if binary is None: binary = [None] * num_nodes assert_equal(len(extra_args), num_nodes) assert_equal(len(binary), num_nodes) for i in range(num_nodes): self.nodes.append(TestNode(i, self.options.tmpdir, extra_args[i], rpchost, timewait=timewait, binary=binary[i], stderr=None, mocktime=self.mocktime, coverage_dir=self.options.coveragedir, use_cli=self.options.usecli)) def start_node(self, i, *args, **kwargs): """Start a squorumd""" node = self.nodes[i] node.start(*args, **kwargs) node.wait_for_rpc_connection() time.sleep(10) if self.options.coveragedir is not None: coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc) def start_nodes(self, extra_args=None, *args, **kwargs): """Start multiple squorumds""" if extra_args is None: extra_args = [None] * self.num_nodes assert_equal(len(extra_args), self.num_nodes) try: for i, node in enumerate(self.nodes): node.start(extra_args[i], *args, **kwargs) for node in self.nodes: node.wait_for_rpc_connection() except: # If one node failed to start, stop the others self.stop_nodes() raise time.sleep(10) if self.options.coveragedir is not None: for node in self.nodes: coverage.write_all_rpc_commands(self.options.coveragedir, node.rpc) def stop_node(self, i): """Stop a squorumd test node""" self.nodes[i].stop_node() self.nodes[i].wait_until_stopped() def stop_nodes(self): """Stop multiple squorumd test nodes""" for node in self.nodes: # Issue RPC to stop nodes node.stop_node() for node in self.nodes: # Wait for nodes to stop time.sleep(5) node.wait_until_stopped() def restart_node(self, i, extra_args=None): """Stop and start a test node""" self.stop_node(i) self.start_node(i, extra_args) def assert_start_raises_init_error(self, i, extra_args=None, expected_msg=None, *args, **kwargs): with tempfile.SpooledTemporaryFile(max_size=2**16) as log_stderr: try: self.start_node(i, extra_args, stderr=log_stderr, *args, **kwargs) self.stop_node(i) except Exception as e: assert 'squorumd exited' in str(e) # node must have shutdown self.nodes[i].running = False self.nodes[i].process = None if expected_msg is not None: log_stderr.seek(0) stderr = log_stderr.read().decode('utf-8') if expected_msg not in stderr: raise AssertionError("Expected error \"" + expected_msg + "\" not found in:\n" + stderr) else: if expected_msg is None: assert_msg = "squorumd should have exited with an error" else: assert_msg = "squorumd should have exited with expected error " + expected_msg raise AssertionError(assert_msg) def wait_for_node_exit(self, i, timeout): self.nodes[i].process.wait(timeout) def split_network(self): """ Split the network of four nodes into nodes 0/1 and 2/3. """ disconnect_nodes(self.nodes[1], 2) disconnect_nodes(self.nodes[2], 1) self.sync_all([self.nodes[:2], self.nodes[2:]]) def join_network(self): """ Join the (previously split) network halves together. """ connect_nodes_bi(self.nodes, 1, 2) self.sync_all() def sync_all(self, node_groups=None): if not node_groups: node_groups = [self.nodes] for group in node_groups: sync_blocks(group) sync_mempools(group) def enable_mocktime(self): """Enable mocktime for the script. mocktime may be needed for scripts that use the cached version of the blockchain. If the cached version of the blockchain is used without mocktime then the mempools will not sync due to IBD. For backwared compatibility of the python scripts with previous versions of the cache, this helper function sets mocktime to Jan 1, 2014 + (201 * 10 * 60)""" self.mocktime = 1454124732 + (201 * 10 * 60) def disable_mocktime(self): self.mocktime = 0 # Private helper methods. These should not be accessed by the subclass test scripts. def _start_logging(self): # Add logger and logging handlers self.log = logging.getLogger('TestFramework') self.log.setLevel(logging.DEBUG) # Create file handler to log all messages fh = logging.FileHandler(self.options.tmpdir + '/test_framework.log') fh.setLevel(logging.DEBUG) # Create console handler to log messages to stderr. By default this logs only error messages, but can be configured with --loglevel. ch = logging.StreamHandler(sys.stdout) # User can provide log level as a number or string (eg DEBUG). loglevel was caught as a string, so try to convert it to an int ll = int(self.options.loglevel) if self.options.loglevel.isdigit() else self.options.loglevel.upper() ch.setLevel(ll) # Format logs the same as squorumd's debug.log with microprecision (so log files can be concatenated and sorted) formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d000 %(name)s (%(levelname)s): %(message)s', datefmt='%Y-%m-%d %H:%M:%S') formatter.converter = time.gmtime fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger self.log.addHandler(fh) self.log.addHandler(ch) if self.options.trace_rpc: rpc_logger = logging.getLogger("BitcoinRPC") rpc_logger.setLevel(logging.DEBUG) rpc_handler = logging.StreamHandler(sys.stdout) rpc_handler.setLevel(logging.DEBUG) rpc_logger.addHandler(rpc_handler) def _initialize_chain(self): """Initialize a pre-mined blockchain for use by the test. Create a cache of a 200-block-long chain (with wallet) for MAX_NODES Afterward, create num_nodes copies from the cache.""" assert self.num_nodes <= MAX_NODES create_cache = False for i in range(MAX_NODES): if not os.path.isdir(get_datadir_path(self.options.cachedir, i)): create_cache = True break if create_cache: self.log.debug("Creating data directories from cached datadir") # find and delete old cache directories if any exist for i in range(MAX_NODES): if os.path.isdir(get_datadir_path(self.options.cachedir, i)): shutil.rmtree(get_datadir_path(self.options.cachedir, i)) # Create cache directories, run bitcoinds: for i in range(MAX_NODES): datadir = initialize_datadir(self.options.cachedir, i) args = [os.getenv("BITCOIND", "squorumd"), "-spendzeroconfchange=1", "-server", "-keypool=1", "-datadir=" + datadir, "-discover=0"] if i > 0: args.append("-connect=127.0.0.1:" + str(p2p_port(0))) self.nodes.append(TestNode(i, self.options.cachedir, extra_args=[], rpchost=None, timewait=None, binary=None, stderr=None, mocktime=self.mocktime, coverage_dir=None)) self.nodes[i].args = args self.start_node(i) # Wait for RPC connections to be ready for node in self.nodes: node.wait_for_rpc_connection() # Create a 200-block-long chain; each of the 4 first nodes # gets 25 mature blocks and 25 immature. # Note: To preserve compatibility with older versions of # initialize_chain, only 4 nodes will generate coins. # # blocks are created with timestamps 10 minutes apart # starting from 2010 minutes in the past self.enable_mocktime() block_time = self.mocktime - (201 * 60) for i in range(2): for peer in range(4): for j in range(25): set_node_times(self.nodes, block_time) self.nodes[peer].generate(1) block_time += 60 # Must sync before next peer starts generating blocks sync_blocks(self.nodes) # Shut them down, and clean up cache directories: self.stop_nodes() self.nodes = [] self.disable_mocktime() def cache_path(n, *paths): return os.path.join(get_datadir_path(self.options.cachedir, n), "regtest", *paths) for i in range(MAX_NODES): for entry in os.listdir(cache_path(i)): if entry not in ['wallet.dat', 'chainstate', 'blocks', 'sporks', 'zerocoin', 'backups']: os.remove(cache_path(i, entry)) for i in range(self.num_nodes): from_dir = get_datadir_path(self.options.cachedir, i) to_dir = get_datadir_path(self.options.tmpdir, i) shutil.copytree(from_dir, to_dir) initialize_datadir(self.options.tmpdir, i) # Overwrite port/rpcport in bitcoin.conf def _initialize_chain_clean(self): """Initialize empty blockchain for use by the test. Create an empty blockchain and num_nodes wallets. Useful if a test case wants complete control over initialization.""" for i in range(self.num_nodes): initialize_datadir(self.options.tmpdir, i) class ComparisonTestFramework(BitcoinTestFramework): """Test framework for doing p2p comparison testing Sets up some squorumd binaries: - 1 binary: test binary - 2 binaries: 1 test binary, 1 ref binary - n>2 binaries: 1 test binary, n-1 ref binaries""" def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True def add_options(self, parser): parser.add_option("--testbinary", dest="testbinary", default=os.getenv("BITCOIND", "squorumd"), help="squorumd binary to test") parser.add_option("--refbinary", dest="refbinary", default=os.getenv("BITCOIND", "squorumd"), help="squorumd binary to use for reference nodes (if any)") def setup_network(self): extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes if hasattr(self, "extra_args"): extra_args = self.extra_args self.add_nodes(self.num_nodes, extra_args, binary=[self.options.testbinary] + [self.options.refbinary] * (self.num_nodes - 1)) self.start_nodes() class SkipTest(Exception): """This exception is raised to skip a test""" def __init__(self, message): self.message = message
[ "tischenko_2006@ukr.net" ]
tischenko_2006@ukr.net
25c53610cddc7f13a5edb9ef2f6bd7a082359139
25b96157297c6ee9d1a7faf4b0e85051aaf11591
/preprocess/features/Interval.py
0c27eb3b7f36d772c935063ab3fe285700051d3c
[]
no_license
notem/reWeFDE
07ae4088d8d60bbd4a5fdde334cec9e0a4b7f0b0
6fe576db1c470f33ffd158c52cf1130c96351f8e
refs/heads/master
2023-01-02T18:05:06.907759
2020-10-30T15:31:32
2020-10-30T15:31:32
179,397,367
18
6
null
null
null
null
UTF-8
Python
false
false
2,677
py
# inflow interval (icics, knn) from features.common import X def IntervalFeature(times, sizes, features, Category): if Category == 'KNN': # a list of first 300 intervals (KNN) # incoming interval count = 0 prevloc = 0 for i in range(0, len(sizes)): if sizes[i] > 0: count += 1 features.append(i - prevloc) prevloc = i if count == 300: break for i in range(count, 300): features.append(X) # outgoing interval count = 0 prevloc = 0 for i in range(0, len(sizes)): if sizes[i] < 0: count += 1 features.append(i - prevloc) prevloc = i if count == 300: break for i in range(count, 300): features.append(X) if Category == "ICICS" or Category == "WPES11": MAX_INTERVAL = 300 # Distribution of the intervals # incoming interval count = 0 prevloc = 0 interval_freq_in = [0] * (MAX_INTERVAL + 1) for i in range(0, len(sizes)): if sizes[i] > 0: inv = i - prevloc - 1 prevloc = i # record the interval if inv > MAX_INTERVAL: inv = MAX_INTERVAL interval_freq_in[inv] += 1 # outgoing interval count = 0 prevloc = 0 interval_freq_out = [0] * (MAX_INTERVAL + 1) for i in range(0, len(sizes)): if sizes[i] < 0: inv = i - prevloc - 1 prevloc = i # record the interval if inv > MAX_INTERVAL: inv = MAX_INTERVAL interval_freq_out[inv] += 1 # ICICS: no grouping if Category == "ICICS": features.extend(interval_freq_in) features.extend(interval_freq_out) # WPES 11: 1, 2, 3-5, 6-8, 9-13, 14 (grouping) if Category == "WPES11": # incoming features.extend(interval_freq_in[0:3]) features.append(sum(interval_freq_in[3:6])) features.append(sum(interval_freq_in[6:9])) features.append(sum(interval_freq_in[9:14])) features.extend(interval_freq_in[14:]) # outgoing features.extend(interval_freq_out[0:3]) features.append(sum(interval_freq_out[3:6])) features.append(sum(interval_freq_out[6:9])) features.append(sum(interval_freq_out[9:14])) features.extend(interval_freq_out[14:])
[ "njm3308@rit.edu" ]
njm3308@rit.edu
3064cd6f1c55c75609f9e92b45a1a1caa35e25ed
4e3c8b2cd89828e5f8d902d9d731e81c6dd33d55
/2015-16/Meeting_1/Minecraft-master/pyglet/gl/cocoa.py
0e6ce34ee5ff2ff4e4b66fc6a25ca5c7a73492ca
[ "MIT" ]
permissive
momja/Code-Club
c2a2c670545a8a77913b0a15078848e3f520bfe1
410c5ffbdae48aa69a170e80642405928e9cb6d5
refs/heads/master
2020-09-25T23:45:16.805921
2017-10-03T22:05:13
2017-10-03T22:05:13
66,742,298
64
5
null
null
null
null
UTF-8
Python
false
false
6,931
py
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' from pyglet.gl.base import Config, CanvasConfig, Context from pyglet.gl import ContextException from pyglet.gl import gl from pyglet.gl import agl from pyglet.canvas.cocoa import CocoaCanvas from pyglet.libs.darwin.cocoapy import * NSOpenGLPixelFormat = ObjCClass('NSOpenGLPixelFormat') NSOpenGLContext = ObjCClass('NSOpenGLContext') # Valid names for GL attributes and their corresponding NSOpenGL constant. _gl_attributes = { 'double_buffer': NSOpenGLPFADoubleBuffer, 'stereo': NSOpenGLPFAStereo, 'buffer_size': NSOpenGLPFAColorSize, 'sample_buffers': NSOpenGLPFASampleBuffers, 'samples': NSOpenGLPFASamples, 'aux_buffers': NSOpenGLPFAAuxBuffers, 'alpha_size': NSOpenGLPFAAlphaSize, 'depth_size': NSOpenGLPFADepthSize, 'stencil_size': NSOpenGLPFAStencilSize, # Not exposed by pyglet API (set internally) 'all_renderers': NSOpenGLPFAAllRenderers, 'fullscreen': NSOpenGLPFAFullScreen, 'minimum_policy': NSOpenGLPFAMinimumPolicy, 'maximum_policy': NSOpenGLPFAMaximumPolicy, 'screen_mask' : NSOpenGLPFAScreenMask, # Not supported in current pyglet API 'color_float': NSOpenGLPFAColorFloat, 'offscreen': NSOpenGLPFAOffScreen, 'sample_alpha': NSOpenGLPFASampleAlpha, 'multisample': NSOpenGLPFAMultisample, 'supersample': NSOpenGLPFASupersample, } # NSOpenGL constants which do not require a value. _boolean_gl_attributes = frozenset([ NSOpenGLPFAAllRenderers, NSOpenGLPFADoubleBuffer, NSOpenGLPFAStereo, NSOpenGLPFAMinimumPolicy, NSOpenGLPFAMaximumPolicy, NSOpenGLPFAOffScreen, NSOpenGLPFAFullScreen, NSOpenGLPFAColorFloat, NSOpenGLPFAMultisample, NSOpenGLPFASupersample, NSOpenGLPFASampleAlpha, ]) # Attributes for which no NSOpenGLPixelFormatAttribute name exists. # We could probably compute actual values for these using # NSOpenGLPFAColorSize / 4 and NSOpenGLFAAccumSize / 4, but I'm not that # confident I know what I'm doing. _fake_gl_attributes = { 'red_size': 0, 'green_size': 0, 'blue_size': 0, 'accum_red_size': 0, 'accum_green_size': 0, 'accum_blue_size': 0, 'accum_alpha_size': 0 } class CocoaConfig(Config): def match(self, canvas): # Construct array of attributes for NSOpenGLPixelFormat attrs = [] for name, value in self.get_gl_attributes(): attr = _gl_attributes.get(name) if not attr or not value: continue attrs.append(attr) if attr not in _boolean_gl_attributes: attrs.append(int(value)) # Support for RAGE-II, which is not compliant. attrs.append(NSOpenGLPFAAllRenderers) # Force selection policy. attrs.append(NSOpenGLPFAMaximumPolicy) # NSOpenGLPFAFullScreen is always supplied so we can switch to and # from fullscreen without losing the context. Also must supply the # NSOpenGLPFAScreenMask attribute with appropriate display ID. # Note that these attributes aren't necessary to render in fullscreen # on Mac OS X 10.6, because there we are simply rendering into a # screen sized window. See: # http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_fullscreen/opengl_cgl.html%23//apple_ref/doc/uid/TP40001987-CH210-SW6 attrs.append(NSOpenGLPFAFullScreen) attrs.append(NSOpenGLPFAScreenMask) attrs.append(quartz.CGDisplayIDToOpenGLDisplayMask(quartz.CGMainDisplayID())) # Terminate the list. attrs.append(0) # Create the pixel format. attrsArrayType = c_uint32 * len(attrs) attrsArray = attrsArrayType(*attrs) pixel_format = NSOpenGLPixelFormat.alloc().initWithAttributes_(attrsArray) # Return the match list. if pixel_format is None: return [] else: return [CocoaCanvasConfig(canvas, self, pixel_format)] class CocoaCanvasConfig(CanvasConfig): def __init__(self, canvas, config, pixel_format): super(CocoaCanvasConfig, self).__init__(canvas, config) self._pixel_format = pixel_format # Query values for the attributes of the pixel format, and then set the # corresponding attributes of the canvas config. for name, attr in _gl_attributes.items(): vals = c_int() self._pixel_format.getValues_forAttribute_forVirtualScreen_(byref(vals), attr, 0) setattr(self, name, vals.value) # Set these attributes so that we can run pyglet.info. for name, value in _fake_gl_attributes.items(): setattr(self, name, value) def create_context(self, share): # Determine the shared NSOpenGLContext. if share: share_context = share._nscontext else: share_context = None # Create a new NSOpenGLContext. nscontext = NSOpenGLContext.alloc().initWithFormat_shareContext_( self._pixel_format, share_context) return CocoaContext(self, nscontext, share) def compatible(self, canvas): return isinstance(canvas, CocoaCanvas) class CocoaContext(Context): def __init__(self, config, nscontext, share): super(CocoaContext, self).__init__(config, share) self.config = config self._nscontext = nscontext def attach(self, canvas): super(CocoaContext, self).attach(canvas) # The NSView instance should be attached to a nondeferred window before calling # setView, otherwise you get an "invalid drawable" message. self._nscontext.setView_(canvas.nsview) self._nscontext.view().setWantsBestResolutionOpenGLSurface_(1) self.set_current() def detach(self): super(CocoaContext, self).detach() self._nscontext.clearDrawable() def set_current(self): self._nscontext.makeCurrentContext() super(CocoaContext, self).set_current() def update_geometry(self): # Need to call this method whenever the context drawable (an NSView) # changes size or location. self._nscontext.update() def set_full_screen(self): self._nscontext.makeCurrentContext() self._nscontext.setFullScreen() def destroy(self): super(CocoaContext, self).destroy() self._nscontext.release() self._nscontext = None def set_vsync(self, vsync=True): vals = c_int(vsync) self._nscontext.setValues_forParameter_(byref(vals), NSOpenGLCPSwapInterval) def get_vsync(self): vals = c_int() self._nscontext.getValues_forParameter_(byref(vals), NSOpenGLCPSwapInterval) return vals.value def flip(self): self._nscontext.flushBuffer()
[ "mjomdal@gmail.com" ]
mjomdal@gmail.com
0d3b899d072571d9b6f47263ee86838fd0b208a6
6ecc1d05bbd9ca2c1d21322faef076c1f28454db
/chrome/browser/ui/webui/chromeos/login/DEPS
52acfb6a38a1c062632e3dbccf09ecbcc162ff4b
[ "BSD-3-Clause" ]
permissive
pandareen/chromium
0e3a9fb92bb9ad027d5b3482a6b03d0bb51c16a1
3ea799335afb5178c519f9e12db8b31390375736
refs/heads/master
2023-03-14T05:47:29.433132
2018-06-27T07:21:08
2018-06-27T07:21:08
138,843,522
0
0
null
2018-06-27T07:09:52
2018-06-27T07:09:52
null
UTF-8
Python
false
false
863
specific_include_rules = { # TODO(mash): Fix. https://crbug.com/770866 "core_oobe_handler\.cc": [ "+ash/shell.h", ], "oobe_display_chooser\.cc": [ "+ash/display/window_tree_host_manager.h", "+ash/shell.h", ], # TODO(mash): Fix. https://crbug.com/678990 "signin_screen_handler\.cc": [ "+ash/detachable_base", "+ash/shell.h", ], "signin_screen_handler\.h": [ "+ash/detachable_base/detachable_base_observer.h", ], # Tests. "oobe_display_chooser_browsertest\.cc": [ "+ash/shell.h", ], "oobe_display_chooser_unittest.cc": [ "+ash/display/display_configuration_controller.h", "+ash/shell.h", "+ash/test/ash_test_base.h", # TODO(mash): Remove. http://crbug.com/720917. "+ui/events/devices/device_data_manager.h", ], "signin_userlist_unittest\.cc": [ "+ash/test/ash_test_base.h" ], }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9b27fd8e4dbd66e5d9c1bd4174439f8c73cf96dc
fc6909db970d6894e8e2a097e10e7c17ddbaece2
/tutorials/frontend/from_pytorch.py
503f64a4e7d90d3d7da7adecd125320c11a3b2aa
[ "Apache-2.0", "Zlib", "MIT", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-2-Clause" ]
permissive
yagnasrinath/incubator-tvm
e631f9b91943f6780082cebbbe2c26666c3abaf8
8b2476fa87cda205daf4bd17d7d58e07a259043c
refs/heads/master
2021-01-09T12:50:17.506603
2020-03-15T09:54:29
2020-03-15T09:54:29
242,306,771
0
0
Apache-2.0
2020-02-28T23:20:14
2020-02-22T08:29:20
Python
UTF-8
Python
false
false
5,825
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. """ Compile PyTorch Models ====================== **Author**: `Alex Wong <https://github.com/alexwong/>`_ This article is an introductory tutorial to deploy PyTorch models with Relay. For us to begin with, PyTorch should be installed. TorchVision is also required since we will be using it as our model zoo. A quick solution is to install via pip .. code-block:: bash pip install torch==1.4.0 pip install torchvision==0.5.0 or please refer to official site https://pytorch.org/get-started/locally/ PyTorch versions should be backwards compatible but should be used with the proper TorchVision version. Currently, TVM supports PyTorch 1.4, 1.3, and 1.2. Other versions may be unstable. """ import tvm from tvm import relay import numpy as np from tvm.contrib.download import download_testdata from tvm.relay.frontend.pytorch import get_graph_input_names # PyTorch imports import torch import torchvision ###################################################################### # Load a pretrained PyTorch model # ------------------------------- model_name = 'resnet18' model = getattr(torchvision.models, model_name)(pretrained=True) model = model.eval() # We grab the TorchScripted model via tracing input_shape = [1, 3, 224, 224] input_data = torch.randn(input_shape) scripted_model = torch.jit.trace(model, input_data).eval() ###################################################################### # Load a test image # ----------------- # Classic cat example! from PIL import Image img_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true' img_path = download_testdata(img_url, 'cat.png', module='data') img = Image.open(img_path).resize((224, 224)) # Preprocess the image and convert to tensor from torchvision import transforms my_preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = my_preprocess(img) img = np.expand_dims(img, 0) ###################################################################### # Import the graph to Relay # ------------------------- # Convert PyTorch graph to Relay graph. input_name = get_graph_input_names(scripted_model)[0] # only one input shape_dict = {input_name: img.shape} mod, params = relay.frontend.from_pytorch(scripted_model, shape_dict) ###################################################################### # Relay Build # ----------- # Compile the graph to llvm target with given input specification. target = 'llvm' target_host = 'llvm' ctx = tvm.cpu(0) with relay.build_config(opt_level=3): graph, lib, params = relay.build(mod, target=target, target_host=target_host, params=params) ###################################################################### # Execute the portable graph on TVM # --------------------------------- # Now we can try deploying the compiled model on target. from tvm.contrib import graph_runtime dtype = 'float32' m = graph_runtime.create(graph, lib, ctx) # Set inputs m.set_input(input_name, tvm.nd.array(img.astype(dtype))) m.set_input(**params) # Execute m.run() # Get outputs tvm_output = m.get_output(0) ##################################################################### # Look up synset name # ------------------- # Look up prediction top 1 index in 1000 class synset. synset_url = ''.join(['https://raw.githubusercontent.com/Cadene/', 'pretrained-models.pytorch/master/data/', 'imagenet_synsets.txt']) synset_name = 'imagenet_synsets.txt' synset_path = download_testdata(synset_url, synset_name, module='data') with open(synset_path) as f: synsets = f.readlines() synsets = [x.strip() for x in synsets] splits = [line.split(' ') for line in synsets] key_to_classname = {spl[0]:' '.join(spl[1:]) for spl in splits} class_url = ''.join(['https://raw.githubusercontent.com/Cadene/', 'pretrained-models.pytorch/master/data/', 'imagenet_classes.txt']) class_name = 'imagenet_classes.txt' class_path = download_testdata(class_url, class_name, module='data') with open(class_path) as f: class_id_to_key = f.readlines() class_id_to_key = [x.strip() for x in class_id_to_key] # Get top-1 result for TVM top1_tvm = np.argmax(tvm_output.asnumpy()[0]) tvm_class_key = class_id_to_key[top1_tvm] # Convert input to PyTorch variable and get PyTorch result for comparison with torch.no_grad(): torch_img = torch.from_numpy(img) output = model(torch_img) # Get top-1 result for PyTorch top1_torch = np.argmax(output.numpy()) torch_class_key = class_id_to_key[top1_torch] print('Relay top-1 id: {}, class name: {}'.format(top1_tvm, key_to_classname[tvm_class_key])) print('Torch top-1 id: {}, class name: {}'.format(top1_torch, key_to_classname[torch_class_key]))
[ "noreply@github.com" ]
noreply@github.com
307b39b476091ab984dde86e503be570839f4667
77a7508c3a647711191b924959db80fb6d2bd146
/src/gamesbyexample/countingquiz.py
8b3131533dd87c5a56493d1814d27b3cca90f27e
[ "MIT" ]
permissive
surlydev/PythonStdioGames
ff7edb4c8c57a5eb6e2036e2b6ebc7e23ec994e0
d54c2509c12a5b1858eda275fd07d0edd456f23f
refs/heads/master
2021-05-22T21:01:15.529159
2020-03-26T07:34:10
2020-03-26T07:34:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,345
py
"""Counting Quiz, by Al Sweigart al@inventwithpython.com Use multiplication and subtraction to count the number of stars shown as fast as possible. Tags: short, math""" import math, random, time def main(): print('''Counting Quiz, by Al Sweigart al@inventwithpython.com Use multiplication and subtraction to count the number of stars shown as fast as possible. The quiz is 60 seconds long. For example: * * * * * * * * * * * * * * * * This is a 6 x 3 star field with 2 missing stars. The answer is 6 x 3 - 2 = 16 ''') while True: input('Press Enter to begin...') runQuiz() print('Would you like to play again? Y/N') response = input().upper() if not response.startswith('Y'): print('Thanks for playing!') break def runQuiz(): correct = 0 startTime = time.time() while time.time() < startTime + 60: print('\n' * 40) # Clear the screen by printing several newlines. # Generate the problem and the star field to display: width = random.randint(1, 10) height = random.randint(1, 10) canvas = {} for x in range(width): for y in range(height): canvas[(x, y)] = '*' numMissing = random.randint(0, math.sqrt(width * height) // 2) for i in range(numMissing): while True: x = random.randint(0, width - 1) y = random.randint(0, height - 1) if canvas[(x, y)] == '*': break canvas[(x, y)] = ' ' answer = width * height - numMissing # Display the star field: for y in range(height): for x in range(width): print(canvas[(x, y)] + ' ', end='') print() # Print a newline. # Let the player answer and determine if they're right or wrong. response = input('Enter the number of stars. > ') if response.isdecimal() and int(response) == answer: correct += 1 else: print('Wrong:', answer) time.sleep(1) print('Time\'s up!') print('You were able to count', correct, 'star fields correctly.') print() # If the program is run (instead of imported), run the game: if __name__ == '__main__': main()
[ "asweigart@gmail.com" ]
asweigart@gmail.com
7365f9c8cd8272ff89d5a4395be8d501ab43d64b
514f11a1e5643459594a90485c93332a3a53a338
/barf/barf/analysis/basicblock/basicblock.py
a2460e0ef5f0d7dfa4ff9d3839b0abfb3a3e113a
[ "BSD-2-Clause" ]
permissive
ksmaheshkumar/barf-project
b17cdfb3bd9f7eaeabba69ddd1f048d90d3d43ef
f5a4e081b458987676e1abf1f5f54f0ff49133b1
refs/heads/master
2021-01-17T21:55:27.477007
2015-01-16T14:34:56
2015-01-16T14:34:56
31,496,855
1
0
null
2015-03-01T13:10:51
2015-03-01T13:10:50
Python
UTF-8
Python
false
false
18,362
py
import bisect import itertools import networkx from Queue import Queue from pydot import Dot from pydot import Edge from pydot import Node from barf.core.reil import DualInstruction from barf.core.reil import ReilMnemonic from barf.core.reil import ReilImmediateOperand # CFG recovery mode BARF_DISASM_LINEAR = 0 # linear sweep BARF_DISASM_RECURSIVE = 1 # recursive descent BARF_DISASM_MIXED = 2 # linear sweep + recursive descent verbose = False class BasicBlock(object): """Basic block representation. """ def __init__(self): # List of instruction within the basic block. Each instruction # is a 'dual' instruction, e.i. it pairs an assembler # instruction with its REIL translation. self._instrs = [] # Start address of the basic block. self._address = None # Taken branch address. If a basic block ends in a conditional # instruction, this field has the address of the taken branch # (condition equals True) self._taken_branch = None # Similar to taken branch but it holds the target address of # the jump when the condition is false. self._not_taken_branch = None # If a basic block ends in a direct jump or in an instruction # different from a conditional jump, this fields holds the # address of the jump or next instruction. self._direct_branch = None @property def instrs(self): """Get basic block instructions. """ return self._instrs @property def address(self): """Get basic block start address. """ if self._instrs == []: return None return self._instrs[0].address @property def start_address(self): """Get basic block start address. """ if self._instrs is []: return None return self._instrs[0].address @property def end_address(self): """Get basic block end address. """ if self._instrs is []: return None return self._instrs[-1].address + self._instrs[-1].asm_instr.size - 1 @property def size(self): """Get basic block size. """ if self._instrs is []: return None return sum([dinstr.asm_instr.size for dinstr in self._instrs]) @property def taken_branch(self): """Get basic block taken branch. """ return self._taken_branch @taken_branch.setter def taken_branch(self, value): """Set basic block taken branch. """ self._taken_branch = value @property def not_taken_branch(self): """Get basic block not taken branch. """ return self._not_taken_branch @not_taken_branch.setter def not_taken_branch(self, value): """Set basic block not taken branch. """ self._not_taken_branch = value @property def direct_branch(self): """Get basic block direct branch. """ return self._direct_branch @direct_branch.setter def direct_branch(self, value): """Set basic block direct branch. """ self._direct_branch = value @property def branches(self): """Get basic block branches. """ branches = [] if self._taken_branch: branches += [(self._taken_branch, 'taken')] if self._not_taken_branch: branches += [(self._not_taken_branch, 'not-taken')] if self._direct_branch: branches += [(self._direct_branch, 'direct')] return branches def contains(self, address): """Check if an address is within the range of a basic block. """ return address >= self.address and address <= self.end_address def empty(self): """Check if a basic block is empty. """ return len(self._instrs) == 0 def __str__(self): lines = ["Basic Block @ 0x%08x" % (self.address if self.address else 0)] for instr in self._instrs: lines += [" %s ; %s" % (str(instr.ir_instrs[0]).ljust(25), str(instr.asm_instr))] for ir_instr in instr.ir_instrs[1:]: lines += [" %s" % str(ir_instr)] return "\n".join(lines) def __eq__(self, other): # Assumes that you are comparing basic block from the same binary return self.address == other.address and self.end_address == other.end_address def __ne__(self, other): return not self.__eq__(other) class BasicBlockGraph(object): """Basic block graph representation. """ def __init__(self, basic_blocks): # List of basic blocks. self._basic_blocks = basic_blocks # Basic block accessed by address self._bb_by_addr = dict([(bb.address, bb) for bb in basic_blocks]) # Basic block graph self._graph = self._build_graph(basic_blocks) def all_simple_bb_paths(self, start_address, end_address): """Return a list of path between start and end address. """ bb_start = self._find_basic_block(start_address) bb_end = self._find_basic_block(end_address) paths = networkx.all_simple_paths(self._graph, \ source=bb_start.address, target=bb_end.address) return (map(lambda addr : self._bb_by_addr[addr], path) for path in paths) def save(self, filename, print_ir=False, format='dot'): """Save basic block graph into a file. """ node_format = { 'shape' : 'Mrecord', 'rankdir' : 'LR', 'fontname' : 'monospace', 'fontsize' : '9.0' } edge_format = { 'fontname' : 'monospace', 'fontsize' : '8.0' } edge_colors = { 'taken' : 'green', 'not-taken' : 'red', 'direct' : 'blue' } try: # for each conneted component for idx, gr in enumerate(networkx.connected_component_subgraphs(self._graph.to_undirected())): graph = Dot(graph_type="digraph", rankdir="TB") # add nodes nodes = {} for bb_addr in gr.node.keys(): dump = self._dump_bb(self._bb_by_addr[bb_addr], print_ir) label = "{<f0> 0x%08x | %s}" % (bb_addr, dump) # html-encode colon character label = label.replace(":", "&#58;") nodes[bb_addr] = Node(bb_addr, label=label, **node_format) graph.add_node(nodes[bb_addr]) # add edges for bb_src_addr in gr.node.keys(): for bb_dst_addr, branch_type in self._bb_by_addr[bb_src_addr].branches: graph.add_edge(Edge(nodes[bb_src_addr], nodes[bb_dst_addr], label=branch_type, \ color=edge_colors[branch_type], **edge_format)) graph.write("%s_%03d.%s" % (filename, idx, format), format=format) except Exception as err: import traceback import sys print("[E] Error loading BARF (%s:%d) : '%s'" % (__name__, sys.exc_traceback.tb_lineno, str(err))) print("") print(traceback.format_exc()) # Auxiliary functions # ======================================================================== # def _build_graph(self, basic_blocks): graph = networkx.DiGraph() # add nodes for bb_addr in self._bb_by_addr.keys(): graph.add_node(bb_addr, address=bb_addr) # add edges for bb_src_addr in self._bb_by_addr.keys(): for bb_dst_addr, branch_type in self._bb_by_addr[bb_src_addr].branches: graph.add_edge(bb_src_addr, bb_dst_addr, branch_type=branch_type) return graph def _find_basic_block(self, address): bb_rv = None for bb in self._basic_blocks: if address >= bb.address and address <= bb.end_address: bb_rv = bb break return bb_rv def _dump_bb(self, basic_block, print_ir=False): lines = [] base_addr = basic_block.instrs[0].address for instr in basic_block.instrs: lines += ["0x%08x (%2d) " % (instr.address, instr.asm_instr.size) + str(instr.asm_instr) + "\\l"] # lines += ["+%02x " % (instr.address - base_addr) + str(instr.asm_instr) + "\\l"] # lines += [str(instr.asm_instr) + "\\l"] if print_ir: for ir_instr in instr.ir_instrs: lines += [" " + str(ir_instr) + "\\l"] return "".join(lines) @property def basic_blocks(self): return self._basic_blocks class BasicBlockBuilder(object): """Basic block builder. """ def __init__(self, disassembler, memory, translator): # An instance of a disassembler. self._disasm = disassembler # And instance of a REIL translator. self._ir_trans = translator # Maximun number of bytes that gets from memory to disassemble. self._lookahead_max = 16 # Memory of the program being analyze. self._mem = memory def build(self, start_address, end_address): """Return the list of basic blocks. Linear Sweep Disassembly. @param start_address: Address of the first byte to start disassembling basic blocks. @param end_address: Address of the last byte (inclusive) to finish disassembling basic blocks. """ if verbose: print("[+] Recovering Basic Blocks :") if verbose: print(" Finding candidate BBs...") bbs = self._find_candidate_bbs(start_address, end_address) if verbose: print(" %d" % len(bbs)) # print " Number of instrs..." # asm_count = 0 # ir_count = 0 # for bb in bbs: # asm_count += len(bb.instrs) # ir_count += sum(map(lambda i : len(i.ir_instrs), bb.instrs)) # print " asm : %d" % asm_count # print " ir : %d" % ir_count if verbose: print(" Refining BBs...") bbs = self._refine_bbs(bbs) if verbose: print(" %d" % len(bbs)) # print " Checking gaps..." # for curr, next in zip(bbs[:-1], bbs[1:]): # if curr.address + curr.size != next.address: # print "gap found @ %s" % hex(curr.address + curr.size) if verbose: print(" Stripping BBs...") bbs = self._strip_bbs(bbs) if verbose: print(" %d" % len(bbs)) if verbose: print(" Updating branches...") self._update_branches(bbs) if verbose: print(" %d" % len(bbs)) return bbs def _find_candidate_bbs(self, start_address, end_address, mode=BARF_DISASM_MIXED): bbs = [] addrs_to_process = Queue() addrs_processed = set() addrs_to_process.put(start_address) while not addrs_to_process.empty(): curr_addr = addrs_to_process.get() # there no standard way to check if an item is in the queue # before pushing it in. So, it is necesary to check if the pop # address have already been processed. if curr_addr in addrs_processed: continue # print "curr_addr : ", hex(curr_addr) bb = self._disassemble_bb(curr_addr, end_address + 0x1) if bb.empty(): # print " empty bb" continue # print " valid bb" # add bb to the list bbs += [bb] addrs_processed.add(curr_addr) # linear sweep mode: add next addr to process queue if mode in [BARF_DISASM_LINEAR, BARF_DISASM_MIXED]: next_addr = bb.address + bb.size # print "next_addr : ", hex(next_addr) if next_addr < end_address and not next_addr in addrs_processed: addrs_to_process.put(next_addr) # recursive descent mode: add branches to process queue if mode in [BARF_DISASM_RECURSIVE, BARF_DISASM_MIXED]: for addr, branch_type in bb.branches: if not addr in addrs_processed: addrs_to_process.put(addr) return bbs def _refine_bbs(self, bbs): bbs.sort(key=lambda x : x.address) bbs_addrs = map(lambda x : x.address, bbs) bbs_new = [] for idx, bb1 in enumerate(bbs): # sys.stdout.write("\r Processing : %d/%d" % (idx, len(bbs))) # sys.stdout.flush() bb_divided = False lower = bisect.bisect_left(bbs_addrs, bb1.start_address) upper = bisect.bisect_right(bbs_addrs, bb1.end_address) for bb2 in bbs[lower:upper]: if bb1.contains(bb2.address) and bb1 != bb2: # print "split!!", hex(bb2.address) bba = self._divide_bb(bb1, bb2.address) if len(bba.instrs) > 0 and bba not in bbs_new: bbs_new += [bba] bb_divided = True break if not bb_divided: if bb1 not in bbs_new: bbs_new += [bb1] return bbs_new def _strip_bbs(self, bbs): return [bb for bb in map(self._strip_bb, bbs) if len(bb.instrs) > 0] def _update_branches(self, bbs): bb_addrs = [bb.address for bb in bbs] for bb in bbs: if not bb.taken_branch in bb_addrs: bb.taken_branch = None if not bb.not_taken_branch in bb_addrs: bb.not_taken_branch = None if not bb.direct_branch in bb_addrs: bb.direct_branch = None def _strip_bb(self, bb): # top while len(bb.instrs) > 0: if bb.instrs[0].ir_instrs[0].mnemonic == ReilMnemonic.NOP: del bb.instrs[0] else: break # bottom while len(bb.instrs) > 0: if bb.instrs[-1].ir_instrs[0].mnemonic == ReilMnemonic.NOP: del bb.instrs[-1] else: break return bb def _divide_bb(self, bb, address): bb_new = BasicBlock() for dinstr in bb.instrs: if dinstr.address == address: break bb_new.instrs.append(dinstr) bb_new.direct_branch = address return bb_new def _disassemble_bb(self, start_address, end_address): bb_current = BasicBlock() if start_address > end_address: return bb_current addr = start_address taken = None not_taken = None direct = None while addr < end_address: start, end = addr, min(addr + self._lookahead_max, end_address) asm, size = self._disasm.disassemble(self._mem[start:end], addr) if not asm: break ir = self._ir_trans.translate(asm) bb_current.instrs.append(DualInstruction(addr, asm, ir)) # if there is an 'end' instruction process it accordingly if ir[-1].mnemonic == ReilMnemonic.RET: break # TODO: Manage 'call' instruction properly (without # resorting to 'asm.mnemonic == "call"'). if ir[-1].mnemonic == ReilMnemonic.JCC and not asm.mnemonic == "call": taken, not_taken, direct = self._extract_branches(addr, asm, size, ir) break # if ir[-1].mnemonic == ReilMnemonic.JCC and asm.mnemonic == "call": # direct_branch = addr + size # break # update instruction pointer and iterate addr += size bb_current.taken_branch = taken bb_current.not_taken_branch = not_taken bb_current.direct_branch = direct # print "bb addr : ", hex(bb_current.address), " bb end addr : ", hex(bb_current.end_address) # print " taken :", hex(taken) if taken else "" # print " not_taken :", hex(not_taken) if not_taken else "" # print " direct :", hex(direct) if direct else "" return bb_current def _resolve_branch_address(self, jmp_instr, instrs): dst = jmp_instr.operands[2] if isinstance(dst, ReilImmediateOperand): # branch address is an immediate # Transform Reil address back to source arch address return dst.immediate >> 8 else: # try to resolve branch address for instr in instrs[::-1]: if instr.mnemonic == ReilMnemonic.STR and \ isinstance(instr.operands[0], ReilImmediateOperand) and \ instr.dst == dst: # Transform Reil address back to source arch address return instr.operands[0].immediate >> 8 def _extract_branches(self, addr, asm, size, ir): taken_branch = None not_taken_branch = None direct_branch = None instr_last = ir[-1] if instr_last.mnemonic == ReilMnemonic.JCC: cond = instr_last.operands[0] dst = instr_last.operands[2] branch_addr = self._resolve_branch_address(instr_last, ir) # set branch address according to its type if isinstance(cond, ReilImmediateOperand): if cond.immediate == 0x0: taken_branch = addr + size not_taken_branch = branch_addr if cond.immediate == 0x1 and asm.mnemonic == 'call': direct_branch = addr + size if cond.immediate == 0x1 and asm.mnemonic != 'call': direct_branch = branch_addr else: taken_branch = branch_addr not_taken_branch = addr + size return taken_branch, not_taken_branch, direct_branch
[ "cnheitman@fundacionsadosky.org.ar" ]
cnheitman@fundacionsadosky.org.ar
ed3a646a75a5bb898ae2f02208dd96258d05759e
da63ecb7ba6afc40731b3b4268f21ed03c882b1b
/src/main/java/jython/toolbar.py
6c8644b14d882416e83a6e22550ee55dfc5a6d9e
[]
no_license
neopsis/jython-interpreter
5622dfe58769a3abac6c87119e4f4b581701a03b
85e6e448acee46dc24deb775f232f8a5d30071a5
refs/heads/master
2021-01-09T19:03:00.943500
2020-02-22T23:04:38
2020-02-22T23:04:38
242,421,886
1
0
null
null
null
null
UTF-8
Python
false
false
1,491
py
""" toolbar.py Contains utility classes for toolbar construction author: Carlos Quiroz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from javax.swing import JToolBar, JButton from java.awt import Insets from org.gjt.sp.jedit import jEdit, GUIUtilities class ToolbarHandler(object): """ Utility class to simplify the toolbar creation process """ def __init__(self, actions = None): self.actions = actions def createToolbar(self): toolBar = JToolBar() margin = Insets(1,1,1,1) [self.createButton(toolBar, i, t ,f) for (i,t,f) in self.actions] return toolBar def createButton(self, toolBar, i, t, f): if i == "separator": toolBar.addSeparator() else: b = JButton(icon = GUIUtilities.loadIcon(i), \ toolTipText = jEdit.getProperty(t), actionPerformed = f) toolBar.add(b) # :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:
[ "robert@neopsis.com" ]
robert@neopsis.com
27a6f1c6036145a7c8adf46f99b0c810c9572c18
89ddb1c0bd5793964cde9cdf1bb7c622c0662f29
/strategies/betray.py
1bb7cbea0d23bc1d1fcf8ad76530b97136f8dbf8
[]
no_license
evelinag/iterated-prisoners-dilemma
c48958e2e3153f634137fbdca5a13c0ce7a2d664
b339d69923515cce1184fad7b83fde6a0c5f9f36
refs/heads/main
2023-02-27T13:18:53.725466
2021-02-11T08:59:14
2021-02-11T08:59:14
337,871,467
0
0
null
null
null
null
UTF-8
Python
false
false
147
py
#!/usr/bin/env python import sys while True: inputs = sys.stdin.readline() # Always betray the opponent print("B\n") sys.stdout.flush()
[ "evelina@evelinag.com" ]
evelina@evelinag.com
fdf19265fb0e3cb327ccb42c022c93c96051ef51
59db30b968d025fcdf2a01eaad0a93fc5477a5fe
/src/smads_core/interface/robot_sensor_interface.py
169f5182c24a6bc7086184020b58c5a3b4ae1305
[ "BSD-3-Clause" ]
permissive
UTSMADS/smads_core
e727b7ecb3d45b93c55eed2dabd82eacd6d952e1
546b6bf6d3e31f226664a25153a2a931ce4b5035
refs/heads/master
2023-02-19T02:30:31.693606
2021-01-15T19:07:12
2021-01-15T19:07:12
279,627,165
0
0
null
null
null
null
UTF-8
Python
false
false
1,406
py
#!/usr/bin/env python3 import rospy import sensor_msgs from nav_msgs.msg import Odometry from sensor_msgs.msg import LaserScan from smads_core.client import RobotClient class RobotSensorInterface: def __init__(self, client, mutex, poll_rate=10, robot_prefix="smads_platform"): self.client = client self.mutex = mutex self.poll_rate = poll_rate self.robot_prefix = robot_prefix self.odom_pub = None self.scan_pub = None odom_postfix = rospy.get_param("smads_output_odom_topic") scan_postfix = rospy.get_param("smads_output_scan_topic") self.odom_pub = rospy.Publisher(self.robot_prefix + odom_postfix, Odometry, queue_size=10) self.scan_pub = rospy.Publisher(self.robot_prefix + scan_postfix, LaserScan, queue_size=10) def poll(self): r = rospy.Rate(self.poll_rate) while not rospy.is_shutdown(): scan_data = LaserScan() odom_data = Odometry() with self.mutex: scan_data = self.client.get_laserscan() odom_data = self.client.get_odom() self.scan_pub.publish(scan_data) self.odom_pub.publish(odom_data) r.sleep() def start(self): rospy.loginfo("robot_sensor_interface active") self.poll() rospy.loginfo("Polling of Client sensor data stopped.")
[ "maxsvetlik@gmail.com" ]
maxsvetlik@gmail.com
d134d707422b4f7133ac34d32cd47be72a95a753
f0801ad1a4e4097a7026cca8767e88fe74036ea7
/main/migrations/0001_initial.py
d9a3a1b77e612221874098a8914764b504ec1400
[]
no_license
meadhikari/django-crm
4ca446e020f07c50286a4d6debb5ecbf275abb39
944319ed0ead8aa1911b8ba2d66b390411972f35
refs/heads/master
2021-01-19T13:42:17.014964
2017-02-18T19:32:39
2017-02-18T19:32:41
82,411,094
0
0
null
null
null
null
UTF-8
Python
false
false
3,907
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-18 09:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('internal_identification_number', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=100, verbose_name='\u0928\u093e\u092e')), ('address', models.CharField(max_length=250, verbose_name='\u0920\u0947\u0917\u093e\u0928\u093e')), ('margh', models.CharField(max_length=100, verbose_name='\u092e\u093e\u0930\u094d\u0917')), ('house_no', models.CharField(max_length=50, verbose_name='\u0918\u0930 \u0928.')), ('barga_fit', models.CharField(max_length=100, verbose_name='\u0935\u0930\u094d\u0917 \u092b\u093f\u091f')), ('land_kitta_number', models.CharField(max_length=100, verbose_name='\u091c\u0917\u094d\u0917\u093e \u0915\u093f. \u0928.')), ('land_area', models.CharField(max_length=100, verbose_name='\u091c\u0917\u094d\u0917\u093e\u0915\u094b \u091a\u0947\u0924\u094d\u0930\u092b\u0932')), ('monthly_fee', models.IntegerField(verbose_name='\u092e\u093e\u0938\u093f\u0915 \u0938\u0941\u0932\u094d\u0915')), ('chetra', models.CharField(choices=[(b'awasiya', '\u0906\u0935\u093e\u0938\u0940\u092f'), (b'angsik_bajar', '\u0905\u0928\u094d\u0917\u094d\u0938\u093f\u0915 \u092c\u091c\u093e\u0930'), (b'bajar', '\u092c\u091c\u093e\u0930'), (b'mukhya_bajar', '\u092e\u0941\u0916\u094d\u092f \u092c\u091c\u093e\u0930')], default=None, max_length=100, verbose_name=b'\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7\xe0\xa5\x87\xe0\xa4\xa4\xe0\xa5\x8d\xe0\xa4\xb0 ')), ('batoko_kisim', models.CharField(choices=[(b'kacchi', '\u0915\u091a\u094d\u091a\u0940'), (b'sahayek', '\u0938\u093e\u0939\u092f\u0947\u0915'), (b'pichbato', '\u092a\u0940\u091a\u092c\u093e\u091f\u094b'), (b'mukhya_pichbato', '\u092e\u0941\u0916\u094d\u092f \u092a\u093f\u091a\u092c\u093e\u091f\u094b')], default=None, max_length=100, verbose_name=b'\xe0\xa4\xac\xe0\xa4\xbe\xe0\xa4\x9f\xe0\xa5\x8b \xe0\xa4\x95\xe0\xa5\x8b \xe0\xa4\x95\xe0\xa4\xbf\xe0\xa4\xb8\xe0\xa4\xbf\xe0\xa4\xae')), ('ghar_ko_kisim', models.CharField(choices=[(b'kacchi', '\u0915\u091a\u094d\u091a\u0940'), (b'pakki', '\u092a\u0915\u094d\u0915\u093f')], default=None, max_length=100, verbose_name=b'\xe0\xa4\x98\xe0\xa4\xb0 \xe0\xa4\x95\xe0\xa5\x8b \xe0\xa4\x95\xe0\xa4\xbf\xe0\xa4\xb8\xe0\xa4\xbf\xe0\xa4\xae')), ], options={ 'verbose_name': '\u0917\u094d\u0930\u093e\u0939\u0915 \u092c\u093f\u0935\u0930\u0923', 'verbose_name_plural': '\u0917\u094d\u0930\u093e\u0939\u0915 \u092c\u093f\u0935\u0930\u0923', }, ), migrations.CreateModel( name='Payment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rasid_number', models.IntegerField(null=True, verbose_name='\u0930\u0938\u093f\u0926 \u0928.')), ('amount', models.IntegerField(verbose_name='\u0930\u0915\u092e')), ('remarks', models.CharField(max_length=300, verbose_name='\u091f\u093f\u092a\u094d\u092a\u0923\u0940')), ('customer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='main.Customer')), ], options={ 'verbose_name': '\u092d\u0941\u0915\u094d\u0924\u093e\u0928\u0940', 'verbose_name_plural': '\u092d\u0941\u0915\u094d\u0924\u093e\u0928\u0940', }, ), ]
[ "salik.adhikari@gmail.com" ]
salik.adhikari@gmail.com
dd921655e2403677d6faea4bd90156830e7665ee
1c49952502f7684b5692011b8d9cc4d57886953c
/src/svdslow.py
7fe28d82fb270d8fc713da9fd202b1298b77ee50
[]
no_license
mokayy/KDDCup2011
a5f027ec776aceaafb575076f3445956ed8c2484
7390b024d46b2bdb239189c1c9a0d0952915694b
refs/heads/master
2021-01-14T12:31:35.573557
2011-08-09T20:30:22
2011-08-09T20:30:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,359
py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # vim: ts=4 sts=4 sw=4 tw=79 sta et """%prog [options] Python source code - replace this with a description of the code and write the code below this text. """ __author__ = 'Patrick Butler' __email__ = 'pbutler@killertux.org' user_t = 'int, int' #ncount, sum track_t = 'int, int, int, float, float' #id, count, sum, avg, pavg rating_t = 'int,int,int,int' #user, movie, rating, cache import os import numpy as np import cPickle as pickle INIT = 0.1 class SVD(object): def __init__(self, dir, nFeatures = 10): self.dir = dir self.tmap = {} self.nFeatures = nFeatures stats = open(os.path.join(dir, "info.txt")).readlines() stats = [ x.strip().split("=") for x in stats] stats = dict( [ (k,int(v)) for k,v in stats] ) self.stats = stats self.users = np.ndarray(stats['nUsers'], dtype=user_t) self.tracks = np.ndarray(stats['nTracks'], dtype=track_t) trackFile = open(os.path.join(dir, "trackData1.txt")) tidx = 0 for line in trackFile: data = line.strip().split("|") t = int(data[0]) self.tracks[tidx]= (t, 0, 0, 0, 0) self.tmap[t] = tidx tidx += 1 trackFile.close() self.nratings = 0 self.ratings = np.ndarray(int(stats['nRatings']), dtype=rating_t) trainFile = open(os.path.join(dir, "trainIdx1.txt")) uidx = 0 ridx = 0 for line in trainFile: u, n = ( int(a) for a in line.split("|") ) print n a = 0 for i in range(n): line = trainFile.next() id, score, day, time = line.strip().split("\t") id = int(id) score = int(score) if id not in self.tmap: n -= 1 continue a += score id = self.tmap[id] self.ratings[ridx] = (uidx, id, score, -1) self.tracks[id][1] += 1 self.tracks[id][1] += score ridx += 1 if n == 0: continue self.users[uidx] = (n, a) uidx += 1 trainFile.close() self.users.resize(uidx) self.ratings.resize(ridx) for i in range(len(self.tracks)): n = float(self.tracks[i][1]) tot = float(self.tracks[i][2]) if n == 0: self.tracks[i][3] = 0 else: self.tracks[i][3] = tot / n self.tracks[i][4] = ( ( 50*25 + tot) / (25 + n)) self.initFeatures() self.save() def initFeatures(self, nFeatures): self.nFeatures = nFeatures nUsers = self.stats['nUsers'] nTracks = self.stats['nTracks'] self.userFeatures = np.zeros(shape=(nFeatures, nUsers), dtype=np.float) self.trackFeatures = np.zeros(shape=(nFeatures, nTracks), dtype=np.float) self.userFeatures += INIT self.trackFeatures += INIT def __getstate__(self): odict = self.__dict__.copy() del odict['ratings'] del odict['tracks'] del odict['users'] del odict['userFeatures'] del odict['trackFeatures'] self.ratings.flush() self.tracks.flush() self.users.flush() return odict def __setstate__(self, dict): self.__dict__.update(dict) def loadmmaps(self): self.users = np.memmap(os.path.join(self.dir, "user.mmap"), dtype=user_t) self.ratings = np.memmap(os.path.join(self.dir, "rating.mmap"), dtype=rating_t) self.tracks = np.memmap(os.path.join(self.dir, "track.mmap"), dtype=track_t) def save(self): mmap = np.memmap(os.path.join(self.dir, "rating.mmap"), dtype=rating_t, shape=self.ratings.shape, mode="w+") mmap[:] = self.ratings[:] self.ratings = mmap mmap = np.memmap(os.path.join(self.dir, "user.mmap"), dtype=user_t, shape=self.users.shape, mode="w+") mmap[:] = self.users[:] self.users = mmap mmap = np.memmap(os.path.join(self.dir, "track.mmap"), dtype=track_t, shape=self.tracks.shape, mode="w+") mmap[:] = self.tracks[:] self.tracks = mmap @classmethod def load(cls, dir, nFeatures = 10): pklfile = os.path.join(dir, "cache") svd = pickle.load(open(pklfile)) svd.dir = dir svd.loadmmaps() svd.initFeatures(nFeatures) return svd def dump(self, file): pickle.dump(self, open(os.path.join(self.dir, file), "w"), -1) def train_all(self, nepochs = 10): shortPredict = self.shortPredict ratings = self.ratings userFeatures = self.userFeatures trackFeatures = self.trackFeatures for f in range(self.nFeatures): print "Training Feature %d" % f for e in range(nepochs): sq = 0 for r in range(len(ratings)): u, t, s, c = ratings[r] p = shortPredict(u, t, f, c, True) err = s - p sq += err**2 uf = userFeatures[f, u] tf = trackFeatures[f, t] userFeatures[f, u] += .001*(err*tf - .015 * uf) trackFeatures[f, t] += .001*(err*uf - .015 * tf) print " epoch=%d RMSE=%f" % (e, (sq/len(ratings))**.5) for r in range(len(ratings)): u, t, s, c = ratings[r] ratings[r][3] = shortPredict(u,t, f, c, False) def shortPredict(self, user, track, f, cache, trailing): if f > 0: sum = cache else: sum = self.tracks[track][4] sum += self.userFeatures[f, user] * self.trackFeatures[f, track] if sum < 0: sum = 0 if sum > 100: sum = 100 if trailing: sum += INIT*INIT*(self.nFeatures-1-f) if sum < 0: sum = 0 if sum > 100: sum = 100 return sum def main(args): import optparse parser = optparse.OptionParser() parser.usage = __doc__ parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-l", "--load", action="store_true", dest="load", help="load from a cache file") parser.add_option("-f", "--features", action="store", type=int, dest="nFeatures", default=10, help="user nfeatures") parser.add_option("-e", "--epochs", action="store", type=int, dest="nepochs", default=10, help="train through nepochs") (options, args) = parser.parse_args() if len(args) < 1: parser.error("Not enough arguments given") if options.load: svd = SVD.load(args[0], options.nFeatures) else: svd = SVD(args[0], options.nFeatures) svd.dump("cache") svd.train_all(options.nepochs) return 0 if __name__ == "__main__": import sys sys.exit( main( sys.argv ) )
[ "pbutler@killertux.org" ]
pbutler@killertux.org
8e71cd84c2bbcff8e95707bae8659fcf81742ad1
9fccc0a13c381288d7e3df08a8cb628832e35564
/rmotr_todo/assignment_4/fixtures/url_overrides/test_able_to_add_items_to_existing_list.py
49419211e1aed89f402e64ffe713d4e4ef493d38
[]
no_license
ine-rmotr-projects/wdc-w1-todo-lists
aa2321879a44ed679f0141037c1744f5f130bdb3
d1a4c291368a7c0d5c9e7de0578705c75d50fea8
refs/heads/master
2021-06-18T07:41:06.156750
2018-04-06T18:15:14
2018-04-06T18:15:14
201,114,300
0
0
null
2021-04-20T18:41:26
2019-08-07T19:23:56
Python
UTF-8
Python
false
false
279
py
from django.urls import path from assignment_4.fixtures import views urlpatterns = [path('', views.home, name='home'), path('lists/new', views.new_list, name='new_list'), path('lists/<list_id>/', views.view_list_doesnt_add_items, name='view_list')]
[ "jason.symons@gmail.com" ]
jason.symons@gmail.com
40be0ddf55f39cfcc4482a4bd777e333af9190e2
8ef8e6818c977c26d937d09b46be0d748022ea09
/cv/distiller/CWD/pytorch/mmrazor/tests/test_models/test_losses/test_distillation_losses.py
77233b81fce0cffa1c0bce23a3ba60bdeed31133
[ "Apache-2.0" ]
permissive
Deep-Spark/DeepSparkHub
eb5996607e63ccd2c706789f64b3cc0070e7f8ef
9d643e88946fc4a24f2d4d073c08b05ea693f4c5
refs/heads/master
2023-09-01T11:26:49.648759
2023-08-25T01:50:18
2023-08-25T01:50:18
534,133,249
7
6
Apache-2.0
2023-03-28T02:54:59
2022-09-08T09:07:01
Python
UTF-8
Python
false
false
8,154
py
# Copyright (c) OpenMMLab. All rights reserved. from unittest import TestCase import torch from mmengine.structures import BaseDataElement from mmrazor import digit_version from mmrazor.models import (ABLoss, ActivationLoss, ATLoss, CRDLoss, DKDLoss, FBKDLoss, FTLoss, InformationEntropyLoss, KDSoftCELoss, MGDLoss, OFDLoss, OnehotLikeLoss, PKDLoss) class TestLosses(TestCase): @classmethod def setUpClass(cls): cls.feats_1d = torch.randn(5, 6) cls.feats_2d = torch.randn(5, 2, 3) cls.feats_3d = torch.randn(5, 2, 3, 3) num_classes = 6 cls.labels = torch.randint(0, num_classes, [5]) def test_ofd_loss(self): ofd_loss = OFDLoss() self.normal_test_1d(ofd_loss) self.normal_test_3d(ofd_loss) # test the calculation s_feat_0 = torch.Tensor([[1, 1], [2, 2], [3, 3]]) t_feat_0 = torch.Tensor([[0, 0], [1, 1], [2, 2]]) ofd_loss_num_0 = ofd_loss.forward(s_feat_0, t_feat_0) assert ofd_loss_num_0 != torch.tensor(0.0) s_feat_1 = torch.Tensor([[1, 1], [2, 2], [3, 3]]) t_feat_1 = torch.Tensor([[2, 2], [3, 3], [4, 4]]) ofd_loss_num_1 = ofd_loss.forward(s_feat_1, t_feat_1) assert ofd_loss_num_1 != torch.tensor(0.0) s_feat_2 = torch.Tensor([[-3, -3], [-2, -2], [-1, -1]]) t_feat_2 = torch.Tensor([[-2, -2], [-1, -1], [0, 0]]) ofd_loss_num_2 = ofd_loss.forward(s_feat_2, t_feat_2) assert ofd_loss_num_2 == torch.tensor(0.0) def normal_test_1d(self, loss_instance, labels=False): args = tuple([self.feats_1d, self.feats_1d]) if labels: args += (self.labels, ) loss_1d = loss_instance.forward(*args) self.assertTrue(loss_1d.numel() == 1) def normal_test_2d(self, loss_instance, labels=False): args = tuple([self.feats_2d, self.feats_2d]) if labels: args += (self.labels, ) loss_2d = loss_instance.forward(*args) self.assertTrue(loss_2d.numel() == 1) def normal_test_3d(self, loss_instance, labels=False): args = tuple([self.feats_3d, self.feats_3d]) if labels: args += (self.labels, ) loss_3d = loss_instance.forward(*args) self.assertTrue(loss_3d.numel() == 1) def test_ab_loss(self): ab_loss_cfg = dict(loss_weight=1.0, margin=1.0) ab_loss = ABLoss(**ab_loss_cfg) self.normal_test_1d(ab_loss) self.normal_test_2d(ab_loss) self.normal_test_3d(ab_loss) def _mock_crd_data_sample(self, sample_idx_list): data_samples = [] for _idx in sample_idx_list: data_sample = BaseDataElement() data_sample.set_data(dict(sample_idx=_idx)) data_samples.append(data_sample) return data_samples def test_crd_loss(self): crd_loss = CRDLoss(**dict(neg_num=5, sample_n=10, dim_out=6)) sample_idx_list = torch.tensor(list(range(5))) data_samples = self._mock_crd_data_sample(sample_idx_list) loss = crd_loss.forward(self.feats_1d, self.feats_1d, data_samples) self.assertTrue(loss.numel() == 1) # test the calculation s_feat_0 = torch.randn((5, 6)) t_feat_0 = torch.randn((5, 6)) crd_loss_num_0 = crd_loss.forward(s_feat_0, t_feat_0, data_samples) assert crd_loss_num_0 != torch.tensor(0.0) s_feat_1 = torch.randn((5, 6)) t_feat_1 = torch.rand((5, 6)) sample_idx_list_1 = torch.tensor(list(range(5))) data_samples_1 = self._mock_crd_data_sample(sample_idx_list_1) crd_loss_num_1 = crd_loss.forward(s_feat_1, t_feat_1, data_samples_1) assert crd_loss_num_1 != torch.tensor(0.0) def test_dkd_loss(self): dkd_loss_cfg = dict(loss_weight=1.0) dkd_loss = DKDLoss(**dkd_loss_cfg) # dkd requires label logits self.normal_test_1d(dkd_loss, labels=True) def test_ft_loss(self): ft_loss_cfg = dict(loss_weight=1.0) ft_loss = FTLoss(**ft_loss_cfg) assert ft_loss.loss_weight == 1.0 self.normal_test_1d(ft_loss) self.normal_test_2d(ft_loss) self.normal_test_3d(ft_loss) def test_dafl_loss(self): dafl_loss_cfg = dict(loss_weight=1.0) ac_loss = ActivationLoss(**dafl_loss_cfg, norm_type='abs') oh_loss = OnehotLikeLoss(**dafl_loss_cfg) ie_loss = InformationEntropyLoss(**dafl_loss_cfg, gather=False) # normal test with only one input loss_ac = ac_loss.forward(self.feats_1d) self.assertTrue(loss_ac.numel() == 1) loss_oh = oh_loss.forward(self.feats_1d) self.assertTrue(loss_oh.numel() == 1) loss_ie = ie_loss.forward(self.feats_1d) self.assertTrue(loss_ie.numel() == 1) with self.assertRaisesRegex(AssertionError, '"norm_type" must be "norm" or "abs"'): _ = ActivationLoss(**dafl_loss_cfg, norm_type='random') # test gather_tensors ie_loss = InformationEntropyLoss(**dafl_loss_cfg, gather=True) ie_loss.world_size = 2 if digit_version(torch.__version__) >= digit_version('1.8.0'): with self.assertRaisesRegex( RuntimeError, 'Default process group has not been initialized'): loss_ie = ie_loss.forward(self.feats_1d) else: with self.assertRaisesRegex( AssertionError, 'Default process group is not initialized'): loss_ie = ie_loss.forward(self.feats_1d) def test_kdSoftce_loss(self): kdSoftce_loss_cfg = dict(loss_weight=1.0) kdSoftce_loss = KDSoftCELoss(**kdSoftce_loss_cfg) # kd soft ce loss requires label logits self.normal_test_1d(kdSoftce_loss, labels=True) def test_at_loss(self): at_loss_cfg = dict(loss_weight=1.0) at_loss = ATLoss(**at_loss_cfg) assert at_loss.loss_weight == 1.0 self.normal_test_1d(at_loss) self.normal_test_2d(at_loss) self.normal_test_3d(at_loss) def test_fbkdloss(self): fbkdloss_cfg = dict(loss_weight=1.0) fbkdloss = FBKDLoss(**fbkdloss_cfg) spatial_mask = torch.randn(1, 1, 3, 3) channel_mask = torch.randn(1, 4, 1, 1) channel_pool_adapt = torch.randn(1, 4) relation_adpt = torch.randn(1, 4, 3, 3) s_input = (spatial_mask, channel_mask, channel_pool_adapt, spatial_mask, channel_mask, relation_adpt) t_input = (spatial_mask, channel_mask, spatial_mask, channel_mask, relation_adpt) fbkd_loss = fbkdloss(s_input, t_input) self.assertTrue(fbkd_loss.numel() == 1) def test_pkdloss(self): pkd_loss = PKDLoss(loss_weight=1.0) feats_S, feats_T = torch.rand(2, 256, 4, 4), torch.rand(2, 256, 4, 4) loss = pkd_loss(feats_S, feats_T) self.assertTrue(loss.numel() == 1) self.assertTrue(0. <= loss <= 1.) num_stages = 4 feats_S = (torch.rand(2, 256, 4, 4) for _ in range(num_stages)) feats_T = (torch.rand(2, 256, 4, 4) for _ in range(num_stages)) loss = pkd_loss(feats_S, feats_T) self.assertTrue(loss.numel() == 1) self.assertTrue(0. <= loss <= num_stages * 1.) feats_S, feats_T = torch.rand(2, 256, 2, 2), torch.rand(2, 256, 4, 4) loss = pkd_loss(feats_S, feats_T) self.assertTrue(loss.numel() == 1) self.assertTrue(0. <= loss <= 1.) pkd_loss = PKDLoss(loss_weight=1.0, resize_stu=False) feats_S, feats_T = torch.rand(2, 256, 2, 2), torch.rand(2, 256, 4, 4) loss = pkd_loss(feats_S, feats_T) self.assertTrue(loss.numel() == 1) self.assertTrue(0. <= loss <= 1.) def test_mgd_loss(self): mgd_loss = MGDLoss(alpha_mgd=0.00002) feats_S, feats_T = torch.rand(2, 256, 4, 4), torch.rand(2, 256, 4, 4) loss = mgd_loss(feats_S, feats_T) self.assertTrue(loss.numel() == 1)
[ "mingjiang.li@iluvatar.ai" ]
mingjiang.li@iluvatar.ai
1b4a03e0afdaba82763c5ba5b2a63532512388f7
f38dbe8bcfea76701a6e2759f47b74df07d89a38
/제01일차/operatorTest01.py
0aed32af7552d9df0245cce0943e667d632a4751
[]
no_license
wooowsol/start-Python
1cd742114d18a2a6639d26d4588f8b64eb40b378
8129d85b20dd48ed35f3e3e048f3af8664124e55
refs/heads/master
2023-01-23T11:21:02.495162
2020-11-22T14:48:23
2020-11-22T14:48:23
312,837,137
0
0
null
null
null
null
UTF-8
Python
false
false
963
py
# operatorTest01.py # + = * 기호들을 연산라고 합니다. # 변수 su는 연산의 대상이 되는 것(피연산자) su = 2 + 3 * 5 print(su) su = (2 + 3) * 5 print(su) # =는 대입 연산자라고 합니다.(우선 순위가 꼴찌) # 비교(관계) 연산자 : > >= < <= ==(같음) !=(다름) # 연산의 결과 물은 반드시 True 또는 False가 된다. # 제어문(if, for 구문 등등)에서 많이 사용되므로 중요!! a = 10 b = 20 result = a >= b print(result) result = a < b print(result) result = a == b print(result) result = a != b print(result) # 논리 연산자 : and, or, not a = 10 b = 20 first = a >= b # False second = a != b # True result = first and second # False and True print(result) # 연산자 우선 순위 : (), * 또는 /, + 또는 -, 관계 연산, not, and, or, ...대입 third = a == b # False result = first and second or third print(result) result = not(result) # 진위 값 반전 print(result)
[ "71619744+wooowsol@users.noreply.github.com" ]
71619744+wooowsol@users.noreply.github.com
b18dd172330c48b377b607fcc29c58bb6995b0b6
5334a6e60851087f4eafc1eaf6c2f06c1ac91c7f
/6th_tests/code.py
5402a3cd76704b72e8520b4951cd453b1b52ee18
[ "MIT" ]
permissive
zkhodzhaev/fiz_analysis_fitting
fa591f1db02757a09f3ec652a262c499d98386d6
1f02d825485e41c7571e62c84719bcd60b711848
refs/heads/master
2021-10-26T04:53:26.833652
2019-04-10T17:50:04
2019-04-10T17:50:04
180,633,115
0
0
null
null
null
null
UTF-8
Python
false
false
1,629
py
#!/usr/bin/env python # coding: utf-8 #Zulfidin Khodzhaev/ zulfidin@inbox.ru """For this to work, first 2 lines are deleted, because the number of column is less than number columns Example: Reading Grams weight 2019:4:3 """ import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt from scipy import stats df = pd.read_csv("ChocoWeightden6d.txt", delim_whitespace=True) df.columns = ['time','weight','temp_inside','temp_top','pressure'] df = df.reset_index(drop=True) df.time = pd.to_timedelta(df.time) l_array=len(df) time_array=np.arange(l_array) n=0 for i in time_array: time_array[n]=datetime.timedelta.total_seconds(df.time[n]-df.time[0]) n=n+1 time_array=pd.DataFrame(data=time_array) df_array=pd.concat([time_array,df],axis=1) df_array = df_array.drop("time", axis=1) df_array.columns = ['time','weight','temp_inside','temp_top','pressure'] # create the plot space upon which to plot the data fig, ax = plt.subplots(figsize = (8,8)) slope, intercept, r_value, p_value, std_err = stats.linregress(df_array.time,df_array['weight']) line = slope*df_array.time+intercept # add the x-axis and the y-axis to the plot ax.plot(df_array.time, df_array['weight'],'o', label='original data') ax.plot(df_array.time, line, label='$y=%.3fx + (%.2f$), [$R^2=%.2f$]' % (slope, intercept, r_value**2)) # rotate tick labels plt.setp(ax.get_xticklabels(), rotation=45) # set title and labels for axes ax.set(xlabel="Time[s]", ylabel="Weight[g]", title="ChocoWeightden6d.txt"); ax.legend(loc='best') plt.savefig('ChocoWeightden6d.png', dpi=600)
[ "noreply@github.com" ]
noreply@github.com
7979017666ab0ad68c04d752577df8dbe5fcfd11
8f273f7499eaf8ad432928714d51cf88a76b0323
/pa/img.py
f797e9e8412bd1fb6c7feac69156e84f93e71bd4
[]
no_license
FanNotFan/Python_momgodb
4abce4a60da36d582947620d604c9cb463722aa5
20dc48e38db546b09950af6a2a1bf79578d8a44a
refs/heads/master
2020-04-28T14:21:16.113631
2018-07-13T09:12:39
2018-07-13T09:12:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
682
py
# -*- coding: UTF-8 -*- # python读取网页的库 import urllib.request # 正则表达式有关模块 from bs4 import BeautifulSoup import re import os def getHTML(url): page = urllib.request.urlopen(url) html = page.read() return html def getImag(html): reg = '<img class="BDE_Image".*?"(.*?)"' pattern = re.compile(reg) html = html.decode('utf-8') imags = re.findall(pattern, html) t = 1 for img in imags: urllib.request.urlretrieve(img,r'C:\Users\Administrator\Desktop\go\%s.jpg' % t) t += 1 print(u'开始保存:', '保存成功') url = 'https://tieba.baidu.com/p/5629017987' html = getHTML(url) getImag(html)
[ "y1wanghui@163.com" ]
y1wanghui@163.com
9905b137698c4c8f41b452623054c57528b70709
f09dc121f213f2881df3572288b7ee5b39246d73
/aliyun-python-sdk-ddoscoo/aliyunsdkddoscoo/request/v20200101/DeleteAsyncTaskRequest.py
55e30bb35da17abec88db8989a885f42142441d6
[ "Apache-2.0" ]
permissive
hetw/aliyun-openapi-python-sdk
2f31378ad6be0896fb8090423f607e9c7d3ae774
7443eacee9fbbaa93c7975c6dbec92d3c364c577
refs/heads/master
2023-01-19T22:42:36.214770
2020-12-04T10:55:14
2020-12-04T10:55:14
318,689,093
1
0
NOASSERTION
2020-12-05T03:03:03
2020-12-05T03:03:03
null
UTF-8
Python
false
false
1,620
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 aliyunsdkddoscoo.endpoint import endpoint_data class DeleteAsyncTaskRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'ddoscoo', '2020-01-01', 'DeleteAsyncTask') 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_ResourceGroupId(self): return self.get_query_params().get('ResourceGroupId') def set_ResourceGroupId(self,ResourceGroupId): self.add_query_param('ResourceGroupId',ResourceGroupId) def get_TaskId(self): return self.get_query_params().get('TaskId') def set_TaskId(self,TaskId): self.add_query_param('TaskId',TaskId)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com