{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \".format(style, body)\r\n\r\n @staticmethod\r\n def __create_rankings_table(ranking, games):\r\n \"\"\"\r\n Ranking is a tuple of (Team, points, score+, score-) tuples.\r\n @type ranking: tuple(tuple(Team, int, int, int))\r\n @param games:\r\n @return:\r\n \"\"\"\r\n games_by_teams = {(game.home_team, game.away_team): game for game in games}\r\n\r\n table = [[\"\", \"\"] + [r[0].name for r in ranking] + [\"Punten\", \"Doelpunten voor\", \"Doelpunten tegen\", \"Saldo\"]]\r\n for i, r in enumerate(ranking):\r\n home_team = r[0]\r\n row = [i + 1, home_team.name]\r\n for o in ranking:\r\n away_team = o[0]\r\n game = games_by_teams.get((home_team, away_team))\r\n row.append(\"{0}-{1}\".format(int(game.result.home_score), int(game.result.away_score))\r\n if game and game.result else \"\")\r\n row.extend([int(r[1]), int(r[2]), int(r[3]), int(r[2] - r[3])])\r\n table.append(row)\r\n\r\n return table\r\n\r\n @staticmethod\r\n def __order_pools(pools, page_layout):\r\n pools_by_abbreviation = {pool.abbreviation: pool for pool in pools}\r\n return [[pools_by_abbreviation[abbreviation] for abbreviation in page] for page in page_layout]\r\n\r\n @staticmethod\r\n def __get_default_pool_order(pools):\r\n return [[pool] for pool in pools]\r\n\r\n @staticmethod\r\n def __create_schedule_table(games):\r\n table = [[\"Tijd\", \"Nr.\", \"Wit\", \"Blauw\", \"Uitslag\", \"Scheidsrechters\", \"Jury\"]]\r\n for game in games:\r\n row = [\r\n game.datetime.strftime(\"%H:%M\"),\r\n game.name,\r\n game.get_home_team_name(),\r\n game.get_away_team_name(),\r\n \"{0} - {1}\".format(int(game.result.home_score), int(game.result.away_score)) if game.result else \"\",\r\n game.get_referees_string(),\r\n game.jury if game.jury else \"\",\r\n ]\r\n table.append(row)\r\n\r\n column_info = {\"width\": [60, 60, 160, 160, 60, 160, 160],\r\n \"header-alignment\": [\"center\", \"center\", \"left\", \"left\", \"center\", \"left\", \"left\"],\r\n \"content-alignment\": [\"center\", \"center\", \"left\", \"left\", \"center\", \"left\", \"left\"],\r\n \"color\": [\"white\"] * 7}\r\n return HtmlGenerator().create_html_table(table, column_info, True, False)\r\n"},"size":{"kind":"number","value":9149,"string":"9,149"}}},{"rowIdx":1348,"cells":{"max_stars_repo_path":{"kind":"string","value":"proj/routers.py"},"max_stars_repo_name":{"kind":"string","value":"azul-cloud/django-rest-server"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2025007"},"content":{"kind":"string","value":"from rest_framework import routers\n\nfrom blog.views import ArticleViewSet\nfrom accounts.views import UserViewSet\n\n\nv1_router = routers.DefaultRouter()\nv1_router.register('articles', ArticleViewSet)\nv1_router.register('users', UserViewSet)\n"},"size":{"kind":"number","value":239,"string":"239"}}},{"rowIdx":1349,"cells":{"max_stars_repo_path":{"kind":"string","value":"first-party/fbjni/docs/build_quickref.py"},"max_stars_repo_name":{"kind":"string","value":"Huxpro/hermes"},"max_stars_count":{"kind":"number","value":1466,"string":"1,466"},"id":{"kind":"string","value":"2024632"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\nimport collections\nimport itertools\nimport re\nimport sys\n\n\ndef main(argv):\n sections = collections.defaultdict(list)\n toc = read_toc(\"docs/quickref_toc.txt\")\n grab_sections(\"test/DocTests.java\", sections)\n grab_sections(\"test/jni/doc_tests.cpp\", sections)\n\n missing_code = toc.keys() - sections.keys()\n if missing_code:\n raise Exception(f\"Missing code for sections: {' '.join(missing_code)}\")\n missing_toc = sections.keys() - toc.keys()\n if missing_toc:\n raise Exception(f\"Missing toc for sections: {' '.join(missing_toc)}\")\n\n with open(\"docs/quickref.md\", \"w\") as handle:\n handle.write(\"# Quick Reference\\n\")\n for section in toc:\n name = toc[section].strip()\n handle.write(f\"- [{name}](#{anchor(name)})\\n\")\n for section in toc:\n render_section(handle, section, toc[section], sections[section])\n\n\ndef anchor(title):\n anchor = title.lower()\n anchor = re.sub(\" \", \"-\", anchor)\n anchor = re.sub(r\"[^-\\w]\", \"\", anchor)\n return anchor\n\n\ndef read_toc(fname):\n with open(fname) as handle:\n return collections.OrderedDict(line.split(\" \", 1) for line in handle)\n\n\ndef grab_sections(fname, sections):\n extension = fname.split(\".\")[1]\n active_block = None\n\n with open(fname) as handle:\n for lnum, line in enumerate(handle):\n lnum += 1\n if line.strip().endswith(\"// END\"):\n active_block = None\n continue\n m = re.search(r\"// SECTION (\\w+)$\", line)\n if m:\n if active_block is not None:\n raise Exception(f\"Nested section at {fname}:{lnum}\")\n active_group = m.group(1)\n active_block = []\n sections[active_group].append((extension, active_block))\n continue\n if line.strip().endswith(\" MARKDOWN\"):\n if active_block is None:\n raise Exception(f\"Orphaned markdown at {fname}:{lnum}\")\n active_block = []\n sections[active_group].append((\"md\", active_block))\n continue\n if active_block is not None:\n active_block.append(line)\n\n\ndef render_section(out, name, title, blocks):\n out.write(f\"## {title}\")\n for syntax, lines in blocks:\n if not lines:\n # This happens with Markdown-first sections\n continue\n if syntax != \"md\":\n lines = itertools.chain(\n [f\"```{syntax}\\n\"],\n lines,\n [\"```\\n\"],\n )\n for line in lines:\n out.write(line)\n out.write(\"\\n\\n\")\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n"},"size":{"kind":"number","value":2801,"string":"2,801"}}},{"rowIdx":1350,"cells":{"max_stars_repo_path":{"kind":"string","value":"sample/crud.py"},"max_stars_repo_name":{"kind":"string","value":"rogrs/pythoncrud"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023685"},"content":{"kind":"string","value":"#!/usr/bin/env python\n'''\nMySQL CRUD (Create Retrieve Update Delete) Operations using Python\n'''\n\n\n# Import MySQLdb $ sudo apt-get install python-mysqldb\nimport MySQLdb as mdb\nimport sys\n\n\n\n# CREATE A NEW TABLE and INSERT SOME VALUES\ndef createTable(con):\n with con:\n\n cur = con.cursor()\n cur.execute(\"DROP TABLE IF EXISTS TableTest\")\n cur.execute(\"CREATE TABLE TableTest(Id INT PRIMARY KEY AUTO_INCREMENT, \\\n Name VARCHAR(25))\")\n cur.execute(\"INSERT INTO TableTest(Name) VALUES('')\")\n cur.execute(\"INSERT INTO TableTest(Name) VALUES('Tizio')\")\n cur.execute(\"INSERT INTO TableTest(Name) VALUES('Caio')\")\n cur.execute(\"INSERT INTO TableTest(Name) VALUES('Sempronio')\")\n cur.execute(\"INSERT INTO TableTest(Name) VALUES('')\")\n\n\n\n# RETRIEVE TABLE ROWS\ndef retrieveTable(con):\n with con:\n\n cur = con.cursor(mdb.cursors.DictCursor)\n cur.execute(\"SELECT * FROM TableTest\")\n\n rows = cur.fetchall()\n\n for row in rows:\n print row[\"Id\"], row[\"Name\"]\n\n\n\n# UPDATE ROW\ndef updateRow(con):\n with con:\n\n cur = con.cursor()\n\n cur.execute(\"UPDATE TableTest SET Name = %s WHERE Id = %s\",\n (\"\", \"4\"))\n\n print \"Number of rows updated:\", cur.rowcount\n\n\n\n# DELETE ROW\ndef deleteRow(con):\n with con:\n\n cur = con.cursor()\n\n cur.execute(\"DELETE FROM TableTest WHERE Id = %s\", \"2\")\n\n print \"Number of rows deleted:\", cur.rowcount\n\n\n\n# SET UP THE CONNECTION\ntry:\n con = mdb.connect('127.0.0.1', 'testuser', 'test2017', 'testDB');\n\n cur = con.cursor()\n cur.execute(\"SELECT VERSION()\")\n\n ver = cur.fetchone()\n\n print \"Database version : %s \" % ver\n\n\n # CRUD OPERATIONS\n createTable(con)\n retrieveTable(con)\n updateRow(con)\n deleteRow(con)\n\n\n\nexcept mdb.Error, e:\n\n print \"Error %d: %s\" % (e.args[0],e.args[1])\n sys.exit(1)\n\n\nfinally:\n\n if con:\n con.close()\n"},"size":{"kind":"number","value":1978,"string":"1,978"}}},{"rowIdx":1351,"cells":{"max_stars_repo_path":{"kind":"string","value":"main.py"},"max_stars_repo_name":{"kind":"string","value":"NilssonHarnertJerhamre/smart-login"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024297"},"content":{"kind":"string","value":"from profile import *\nfrom preprocess import *\nfrom listener import *\nfrom classifier import *\nfrom knn import *\nimport numpy as np\nimport os\n\ndatafile = 'data.txt'\nphrase = '.tie'\nsamples_for_new_profile = 7\nclear = lambda: os.system('cls')\n\npp = Preprocess()\nl = Listener()\nc = Classifier(datafile)\n\ndef login():\n\tuser = raw_input('user: ')\n\tevents = l.listen(phrase)\n\tinput = ''\n\tfor e in events:\n\t\tif e.type is Type.key_pressed and isinstance(e.char, unicode):\n\t\t\tinput += e.char.encode('utf-8')\n\n\tif input != phrase:\n\t\traw_input('wrong phrase \\n')\n\t\treturn\n\n\ttimes = pp.preprocess(events)\n\n\tprediction = c.predict_user(times)\n\n\tprint 'chosen profile is \\'' + str(user) + '\\' prediction was \\'' + str(prediction[0]) + '\\''\n\n\tif str(user) == str(prediction[0]):\n\t\tc.add_data(times, user)\n\t\tc.train_on_data()\n\n\traw_input('')\n\ndef create_profile():\n\tuser = raw_input('user: ')\n\n\tif c.profile_exists(user):\n\t\traw_input('profile already exists ')\n\t\treturn\n\n\ttraining_times = []\n\n\ti = 0\n\twhile i < samples_for_new_profile:\n\t\tprint 'type the phrase ('+str(i+1)+' of '+str(samples_for_new_profile)+' times)'\n\t\tevents = l.listen(phrase)\n\t\t\n\t\ts = ''\n\t\tfor e in events:\n\t\t\tif e.type is Type.key_pressed and isinstance(e.char, unicode):\n\t\t\t\ts += e.char.encode('utf-8')\n\n\t\tif s != phrase:\n\t\t\tprint 'wrong phrase!'\n\t\t\tcontinue\n\t\ttimes = pp.preprocess(events)\n\t\ttraining_times.append(times)\n\t\ti+=1\n\n\tfor t in training_times:\n\t\tc.add_data(t, user)\n\nwhile 1:\n\tclear()\n\tprint 'smart login\\n'\n\tprint '1.\\tlogin'\n\tprint '2.\\tcreate profile'\n\tprint 'q.\\tquit'\n\n\tans = raw_input('choice: ')\n\n\tif ans == '1':\n\t\tlogin()\n\telif ans == '2':\n\t\tcreate_profile()\n\telif ans == 'q': #quit\n\t\tbreak"},"size":{"kind":"number","value":1735,"string":"1,735"}}},{"rowIdx":1352,"cells":{"max_stars_repo_path":{"kind":"string","value":"twitter_monitor/twitter_monitor.py"},"max_stars_repo_name":{"kind":"string","value":"TheRensselaerIDEA/covid19_tweet_ids"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023907"},"content":{"kind":"string","value":"\"\"\"\nScript for running the twitter monitor listener/processor\n\"\"\"\nimport argparse\nimport time\nimport tweepy\nimport logging\nfrom elasticsearch import Elasticsearch\nfrom setup_index import verify_or_setup_index\nfrom config import Config\nfrom tm_stream_listener import TwitterMonitorStreamListener\n\ndef start():\n #load the args & config\n parser = argparse.ArgumentParser(\"Run the twitter monitor listener/processor\")\n parser.add_argument(\"--configfile\", \"-c\", default=\"config.json\", required=False, help=\"Path to the config file to use.\")\n parser.add_argument(\"--logfile\", \"-l\", default=\"tmlog.txt\", required=False, help=\"Path to the log file to write to.\")\n args = parser.parse_args()\n\n config = Config.load(args.configfile)\n\n #Configure logging\n logging.basicConfig(filename=args.logfile, \n format=\"[%(asctime)s - %(levelname)s]: %(message)s\", \n level=logging.getLevelName(config.log_level))\n print(\"Logging level set to {0}...\".format(config.log_level))\n print()\n\n #Verify or setup the elasticsearch index\n es = Elasticsearch(hosts=[config.elasticsearch_host], \n verify_certs=config.elasticsearch_verify_certs,\n timeout=config.elasticsearch_timeout_secs)\n\n index_result = verify_or_setup_index(es, config)\n logging.info(index_result)\n print(index_result)\n print()\n\n #load the credentials and initialize tweepy\n auth = tweepy.OAuthHandler(config.api_key, config.api_secret_key)\n auth.set_access_token(config.access_token, config.access_token_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\n #listen to the stream API\n\n restart_attempts = 0\n while True:\n try:\n streamListener = TwitterMonitorStreamListener(es, config)\n stream = tweepy.Stream(auth=api.auth, listener=streamListener)\n print(\"Listening for tweets...\")\n print()\n logging.info(\"Starting listener...\")\n stream.filter(languages=config.filter_languages, track=config.filter_keywords)\n except Exception as ex:\n logging.exception(\"Exception occurred while listening.\")\n if streamListener.received_data:\n restart_attempts = 0\n \n restart_attempts += 1\n if config.restart_attempts > -1 and restart_attempts > config.restart_attempts:\n logging.critical(\"Restart attempt limit reached. Shutting down...\")\n break\n \n logging.warning(\"Restarting after {0} seconds (attempt {1})...\".format(config.restart_wait_secs, restart_attempts))\n time.sleep(config.restart_wait_secs)\n\nif __name__ == \"__main__\":\n start()"},"size":{"kind":"number","value":2736,"string":"2,736"}}},{"rowIdx":1353,"cells":{"max_stars_repo_path":{"kind":"string","value":"firstapp/migrate_base_data.py"},"max_stars_repo_name":{"kind":"string","value":"mudong1991/DevOpsApi"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"id":{"kind":"string","value":"2023719"},"content":{"kind":"string","value":"# -*- coding:utf-8 -*-\n# Created migrate_base_data at 2017/3/9 0009\n# __author__ = \"Mundy\"\n\"\"\"\n同步数据库时,初始化部分数据\n\"\"\"\nimport threading\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import *\nfrom django.contrib.auth.hashers import make_password\n\nfrom firstapp.models import *\n\n\ndef init():\n \"\"\"\n 初始化数据\n :return:\n \"\"\"\n if AppInstall.objects.filter(name='git').exists():\n return\n # 初始化添加app\n AppInstall.objects.create(name='git', version='2.11.0', app_image='/media/app_images/git.jpg')\n AppInstall.objects.create(name='docker', version='1.7.1', app_image='/media/app_images/docker.jpg')\n AppInstall.objects.create(name='jdk', version='1.8.0_131', app_image='/media/app_images/jdk.jpg')\n AppInstall.objects.create(name='redis', version='3.2.8', app_image='/media/app_images/redis.jpg')\n AppInstall.objects.create(name='mysql', version='5.6.35', app_image='/media/app_images/mysql.jpg')\n AppInstall.objects.create(name='mongodb', version='3.3.3', app_image='/media/app_images/mongodb.jpg')\n AppInstall.objects.create(name='zookeeper', version='3.4.10', app_image='/media/app_images/zookeeper.jpg')\n AppInstall.objects.create(name='kafka', version='0.10.2.1', app_image='/media/app_images/kafka.jpg')\n AppInstall.objects.create(name='nginx', version='1.8.1', app_image='/media/app_images/nginx.jpg')\n AppInstall.objects.create(name='consul', version='2.11.1', app_image='/media/app_images/consul.jpg')\n AppInstall.objects.create(name='maven', version='3.5.0', app_image='/media/app_images/maven.jpg')\n\n # 初始化用户、角色、权限\n admin_permissions = range(1, 500) # 管理员权限,全部权限\n\n # 系统管理用户组\n admin_group = Group.objects.create(name='系统管理员') # 主要控制接口权限\n\n # 角色\n admin_role = Role.objects.create(name='系统管理员') # 主要控制菜单\n\n # 用户\n admin = User.objects.create(username='admin', password=make_password(''), is_superuser=1)\n\n admin.groups.add(admin_group)\n admin.role = admin_role\n admin.save()\n\n\ndef thread_init(sender, **kwargs):\n \"\"\"\n 第一个参数必须是sender,且必须有kwargs参数\n\n :param sender:\n :param kwargs:\n :return:\n \"\"\"\n # 在另一个线程中执行init方法,主要是为了解决数据库事务提交延迟的问题。\n t = threading.Timer(1, init)\n\n t.start()\n"},"size":{"kind":"number","value":2216,"string":"2,216"}}},{"rowIdx":1354,"cells":{"max_stars_repo_path":{"kind":"string","value":"base_state/test.py"},"max_stars_repo_name":{"kind":"string","value":"mando222/tri-25"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024213"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n\nimport requests\n\nBASE = \"http://127.0.0.1:5000/\"\n\nresponse = requests.get(BASE + \"api/get_key/data\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/insert/test=test\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/get_key/test\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/get_state\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/update/data=blah\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/get_state\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/delete/bad_key\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/delete/test\")\nprint(response.json())\n\nresponse = requests.get(BASE + \"api/get_state\")\nprint(response.json())"},"size":{"kind":"number","value":747,"string":"747"}}},{"rowIdx":1355,"cells":{"max_stars_repo_path":{"kind":"string","value":"devel/PRJ4/metaCNN2-1.py"},"max_stars_repo_name":{"kind":"string","value":"mjirik/bodynavigation"},"max_stars_count":{"kind":"number","value":5,"string":"5"},"id":{"kind":"string","value":"2024313"},"content":{"kind":"string","value":"import CT_regression_tools\nimport numpy as np\nfrom pathlib import Path\n\nmodel = CT_regression_tools.VGG_16()\npth = Path(__file__).parent\nmodel.save(pth / 'vgg.h5')"},"size":{"kind":"number","value":163,"string":"163"}}},{"rowIdx":1356,"cells":{"max_stars_repo_path":{"kind":"string","value":"test/test_endec.py"},"max_stars_repo_name":{"kind":"string","value":"isstabb/qpylib"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2025131"},"content":{"kind":"string","value":"# Copyright 2019 IBM Corporation All Rights Reserved.\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n# pylint: disable=redefined-outer-name, unused-argument\n\nimport json\nfrom unittest.mock import patch\nimport os\nimport pytest\nfrom qpylib.encdec import Encryption\n\nDB_STORE = 'test_user_e.db'\n\n@pytest.fixture(scope='module', autouse=True)\ndef pre_testing_setup():\n with patch('qpylib.abstract_qpylib.AbstractQpylib.log'):\n yield\n\n# Mock out get_store_path to return encryption db in test dir, then delete after each test\n@pytest.fixture()\ndef patch_get_store_path():\n file_path = DB_STORE\n with patch('qpylib.qpylib.get_store_path') as mocked_get_store_path:\n mocked_get_store_path.return_value = DB_STORE\n yield\n if os.path.isfile(file_path):\n os.remove(file_path)\n\n@pytest.fixture()\ndef set_unset_qradar_app_uuid_env_var():\n os.environ['QRADAR_APP_UUID'] = \"6599ba78-4896-11e8-842f-0ed5f89f718b\"\n yield\n del os.environ['QRADAR_APP_UUID']\n\ndef test_encryption_raises_value_error_on_missing_name_and_user_fields():\n with pytest.raises(ValueError) as ex:\n Encryption({})\n assert \"Encryption : name and user are mandatory fields!\" == str(ex.value)\n\n with pytest.raises(ValueError) as ex:\n Encryption({\"name\": \"test_name\"})\n assert \"Encryption : name and user are mandatory fields!\" == str(ex.value)\n\n with pytest.raises(ValueError) as ex:\n Encryption({\"user\": \"test_user\"})\n assert \"Encryption : name and user are mandatory fields!\" == str(ex.value)\n\ndef test_encryption_raises_value_error_on_missing_env_var():\n with pytest.raises(KeyError) as ex:\n Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n assert \"'Encryption : QRADAR_APP_UUID not available in environment'\" == str(ex.value)\n\ndef test_encrypt_creates_valid_config_on_start(set_unset_qradar_app_uuid_env_var, patch_get_store_path):\n Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n assert os.path.isfile(DB_STORE)\n\ndef test_encryption_returns_empty_string_encrypting_empty_string(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n assert enc.encrypt('') == ''\n\ndef test_encryption_stores_encrypted_secret_in_config(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n enc_string = enc.encrypt('testing123')\n assert enc_string != 'testing123'\n\n with open(DB_STORE) as db_file:\n file_json = json.load(db_file)\n assert file_json.get('test_name').get('secret') == enc_string\n\ndef test_decrypt_returns_plaintext_after_encryption(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n enc_string = enc.encrypt('testing123')\n assert enc_string != 'testing123'\n assert enc.decrypt() == 'testing123'\n\ndef test_decrypt_raises_error_when_config_missing(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n enc_string = enc.encrypt('testing123')\n assert enc_string != 'testing123'\n os.remove(DB_STORE)\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n with pytest.raises(ValueError) as ex:\n enc.decrypt()\n assert \"Encryption : no secret to decrypt\" == str(ex.value)\n\ndef test_decrypt_returns_incorrect_plaintext_with_altered_salt(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n enc_string = enc.encrypt('testing123')\n assert enc_string != 'testing123'\n\n with open(DB_STORE) as db_file:\n file_json = json.load(db_file)\n file_json['test_name']['salt'] = 'incorrect'\n with open(DB_STORE, 'w') as db_file:\n json.dump(file_json, db_file)\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n assert enc.decrypt() != 'testing123'\n\ndef test_decrypt_raise_value_error_on_engine_version_mismatch(set_unset_qradar_app_uuid_env_var,\n patch_get_store_path):\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n enc_string = enc.encrypt('testing123')\n assert enc_string != 'testing123'\n\n with open(DB_STORE) as db_file:\n file_json = json.load(db_file)\n file_json['test_name']['version'] = -1\n with open(DB_STORE, 'w') as db_file:\n json.dump(file_json, db_file)\n enc = Encryption({\"name\": \"test_name\", \"user\": \"test_user\"})\n with pytest.raises(ValueError) as ex:\n enc.decrypt()\n assert \"Encryption : secret engine mismatch.\" in str(ex.value)\n"},"size":{"kind":"number","value":4978,"string":"4,978"}}},{"rowIdx":1357,"cells":{"max_stars_repo_path":{"kind":"string","value":"filebox/views.py"},"max_stars_repo_name":{"kind":"string","value":"sharmaeklavya2/Filebox"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023773"},"content":{"kind":"string","value":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nimport os\n\ndef base_response(request,body,h1=None):\n\tcontext_dict = {\"base_body\": body}\n\tif h1!=None:\n\t\tcontext_dict[\"base_h1\"] = h1\n\treturn render(request, \"base.html\", context_dict)\n\ndef get_folder_size_and_file_count(path):\n\ttotal_size = 0\n\tfile_count = 0\n\tfor dirpath, dirnames, filenames in os.walk(path):\n\t\tfile_count+= len(filenames)\n\t\tfor fname in filenames:\n\t\t\tfpath = os.path.join(dirpath, fname)\n\t\t\ttotal_size += os.path.getsize(fpath)\n\treturn (total_size, file_count)\n\ndef save_uploaded_file(uploaded_file, overwrite=False):\n\tdest_file_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name)\n\n\tfile_exists = os.path.isfile(dest_file_path)\n\tif file_exists and not overwrite:\n\t\treturn \"already_exists\"\n\tif file_exists:\told_size = os.path.getsize(dest_file_path)\n\telse: old_size = 0\n\n\tfolder_size, file_count = get_folder_size_and_file_count(settings.MEDIA_ROOT)\n\tif folder_size - old_size + uploaded_file.size > settings.FOLDER_SIZE_LIM:\n\t\treturn \"too_large\"\n\tif not file_exists and file_count>=settings.FILE_COUNT_LIM:\n\t\treturn \"too_many\"\n\n\twith open(dest_file_path,\"wb+\") as dest_file:\n\t\tfor chunk in uploaded_file.chunks():\n\t\t\tdest_file.write(chunk)\n\treturn \"success\"\n\nmessage_map = {\n\t\"success\": \"{0} was successfully saved\",\n\t\"already_exists\": \"{0} already exists\",\n\t\"too_large\": \"{0} does not fit because it is too large\",\n\t\"too_many\": \"{0} does not fit because the folder has too many files\",\n}\n\ndef upload(request):\n\tcontext_dict = {}\n\tif request.method==\"POST\":\n\t\tif \"files\" in request.FILES:\n\t\t\tfile_list = request.FILES.getlist(\"files\")\n\t\telse:\n\t\t\tfile_list = []\n\t\tcontext_dict[\"status_list\"] = []\n\t\tfor ufile in file_list:\n\t\t\tretval = save_uploaded_file(ufile)\n\t\t\tprint(ufile.name,type(ufile))\n\t\t\tmessage = message_map[retval].format(ufile.name)\n\t\t\tcontext_dict[\"status_list\"].append(message)\n\tfolder_size, file_count = get_folder_size_and_file_count(settings.MEDIA_ROOT)\n\tcontext_dict[\"num_remaining\"] = settings.FILE_COUNT_LIM - file_count\n\tcontext_dict[\"mib_remaining\"] = (settings.FOLDER_SIZE_LIM - folder_size)/(1024*1024)\n\treturn render(request, \"upload.html\", context_dict)\n"},"size":{"kind":"number","value":2222,"string":"2,222"}}},{"rowIdx":1358,"cells":{"max_stars_repo_path":{"kind":"string","value":"src/tests/basic_deployment.py"},"max_stars_repo_name":{"kind":"string","value":"openstack/charm-tempest"},"max_stars_count":{"kind":"number","value":13,"string":"13"},"id":{"kind":"string","value":"2024333"},"content":{"kind":"string","value":"\nfrom charmhelpers.contrib.openstack.amulet.deployment import (\n OpenStackAmuletDeployment\n)\n\nfrom charmhelpers.contrib.openstack.amulet.utils import (\n OpenStackAmuletUtils,\n DEBUG,\n)\n\n# Use DEBUG to turn on debug logging\nu = OpenStackAmuletUtils(DEBUG)\n\n\nclass TempestBasicDeployment(OpenStackAmuletDeployment):\n \"\"\"Amulet tests on a basic tempest deployment.\"\"\"\n\n def __init__(self, series, openstack=None, source=None, stable=False):\n \"\"\"Deploy the entire test environment.\"\"\"\n super(TempestBasicDeployment, self).__init__(series, openstack,\n source, stable)\n self._add_services()\n self._add_relations()\n self._configure_services()\n self._deploy()\n\n u.log.info('Waiting on extended status checks...')\n exclude_services = []\n self._auto_wait_for_status(exclude_services=exclude_services)\n\n self.d.sentry.wait()\n self._initialize_tests()\n\n def _add_services(self):\n \"\"\"Add services\n\n Add the services that we're testing, where tempest is local,\n and the rest of the service are from lp branches that are\n compatible with the local charm (e.g. stable or next).\n \"\"\"\n this_service = {'name': 'tempest'}\n other_services = [\n {'name': 'percona-cluster', 'constraints': {'mem': '3072M'}},\n {'name': 'rabbitmq-server'},\n {'name': 'keystone'},\n {'name': 'openstack-dashboard'},\n {'name': 'glance'}\n ]\n super(TempestBasicDeployment, self)._add_services(\n this_service,\n other_services,\n no_origin=['tempest'])\n\n def _add_relations(self):\n \"\"\"Add all of the relations for the services.\"\"\"\n relations = {\n 'keystone:identity-admin': 'tempest:identity-admin',\n 'tempest:dashboard': 'openstack-dashboard:website',\n 'openstack-dashboard:identity-service':\n 'keystone:identity-service',\n 'keystone:shared-db': 'percona-cluster:shared-db',\n 'glance:identity-service': 'keystone:identity-service',\n 'glance:shared-db': 'percona-cluster:shared-db',\n 'glance:amqp': 'rabbitmq-server:amqp'\n }\n super(TempestBasicDeployment, self)._add_relations(relations)\n\n def _configure_services(self):\n \"\"\"Configure all of the services.\"\"\"\n pxc_config = {\n 'dataset-size': '25%',\n 'max-connections': 1000,\n 'root-password': '',\n 'sst-password': '',\n }\n configs = {\n 'percona-cluster': pxc_config,\n }\n super(TempestBasicDeployment, self)._configure_services(configs)\n\n def _get_token(self):\n return self.keystone.service_catalog.catalog['token']['id']\n\n def _initialize_tests(self):\n \"\"\"Perform final initialization before tests get run.\"\"\"\n # Access the sentries for inspecting service units\n self.tempest_sentry = self.d.sentry['tempest'][0]\n self.openstack_dashboard_sentry = \\\n self.d.sentry['openstack-dashboard'][0]\n u.log.debug('openstack release val: {}'.format(\n self._get_openstack_release()))\n u.log.debug('openstack release str: {}'.format(\n self._get_openstack_release_string()))\n\n def test_run_tempest(self):\n u.log.debug('Running Tempest...')\n unit = self.tempest_sentry\n assert u.status_get(unit)[0] == \"active\"\n\n action_id = u.run_action(unit, \"run-tempest\")\n assert u.wait_on_action(action_id), \"run-tempest action failed.\"\n"},"size":{"kind":"number","value":3686,"string":"3,686"}}},{"rowIdx":1359,"cells":{"max_stars_repo_path":{"kind":"string","value":"mp/scenarios/migrations/0001_initial.py"},"max_stars_repo_name":{"kind":"string","value":"Ecotrust/COMPASS"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"id":{"kind":"string","value":"2024858"},"content":{"kind":"string","value":"# Generated by Django 2.2.1 on 2019-05-29 16:05\n\nfrom django.conf import settings\nimport django.contrib.gis.db.models.fields\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('contenttypes', '0002_remove_content_type_name'),\n ('auth', '0011_update_proxy_permissions'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='GridCell',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('objectid', models.IntegerField(blank=True, null=True)),\n ('hex_id', models.IntegerField(blank=True, default=None, null=True)),\n ('auspatid', models.IntegerField(blank=True, default=None, null=True)),\n ('ecoregion', models.TextField(blank=True, default=None, null=True)),\n ('coa_name', models.TextField(blank=True, default=None, null=True)),\n ('habitat', models.TextField(blank=True, null=True)),\n ('fish', models.TextField(blank=True, null=True)),\n ('obs_spec', models.TextField(blank=True, null=True)),\n ('mod_spec', models.TextField(blank=True, null=True)),\n ('centroid', django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=3857)),\n ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(blank=True, null=True, srid=3857, verbose_name='Grid Cell Geometry')),\n ],\n ),\n migrations.CreateModel(\n name='Scenario',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, verbose_name='Name')),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date Created')),\n ('date_modified', models.DateTimeField(auto_now=True, verbose_name='Date Modified')),\n ('object_id', models.PositiveIntegerField(blank=True, null=True)),\n ('habitat', models.BooleanField()),\n ('fish', models.BooleanField()),\n ('obs_spec', models.BooleanField()),\n ('mod_spec', models.BooleanField()),\n ('description', models.TextField(blank=True, null=True)),\n ('satisfied', models.BooleanField(default=True, help_text='Am I satisfied?')),\n ('active', models.BooleanField(default=True)),\n ('grid_cells', models.TextField(blank=True, null=True, verbose_name='Grid Cell IDs')),\n ('geometry_final_area', models.FloatField(blank=True, null=True, verbose_name='Total Area')),\n ('geometry_dissolved', django.contrib.gis.db.models.fields.MultiPolygonField(blank=True, null=True, srid=3857, verbose_name='Filter result dissolved')),\n ('content_type', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, related_name='scenarios_scenario_related', to='contenttypes.ContentType')),\n ('sharing_groups', models.ManyToManyField(blank=True, editable=False, null=True, related_name='scenarios_scenario_related', to='auth.Group', verbose_name='Share with the following groups')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scenarios_scenario_related', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n"},"size":{"kind":"number","value":3746,"string":"3,746"}}},{"rowIdx":1360,"cells":{"max_stars_repo_path":{"kind":"string","value":"sdk/python/pulumi_azure/network/get_virtual_network.py"},"max_stars_repo_name":{"kind":"string","value":"Frassle/pulumi-azure"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023942"},"content":{"kind":"string","value":"# coding=utf-8\n# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***\n# *** Do not edit by hand unless you're certain you know what you are doing! ***\n\nimport pulumi\nimport pulumi.runtime\nfrom .. import utilities, tables\n\nclass GetVirtualNetworkResult(object):\n \"\"\"\n A collection of values returned by getVirtualNetwork.\n \"\"\"\n def __init__(__self__, address_spaces=None, dns_servers=None, subnets=None, vnet_peerings=None, id=None):\n if address_spaces and not isinstance(address_spaces, list):\n raise TypeError('Expected argument address_spaces to be a list')\n __self__.address_spaces = address_spaces\n \"\"\"\n The list of address spaces used by the virtual network.\n \"\"\"\n if dns_servers and not isinstance(dns_servers, list):\n raise TypeError('Expected argument dns_servers to be a list')\n __self__.dns_servers = dns_servers\n \"\"\"\n The list of DNS servers used by the virtual network.\n \"\"\"\n if subnets and not isinstance(subnets, list):\n raise TypeError('Expected argument subnets to be a list')\n __self__.subnets = subnets\n \"\"\"\n The list of name of the subnets that are attached to this virtual network.\n \"\"\"\n if vnet_peerings and not isinstance(vnet_peerings, dict):\n raise TypeError('Expected argument vnet_peerings to be a dict')\n __self__.vnet_peerings = vnet_peerings\n \"\"\"\n A mapping of name - virtual network id of the virtual network peerings.\n \"\"\"\n if id and not isinstance(id, str):\n raise TypeError('Expected argument id to be a str')\n __self__.id = id\n \"\"\"\n id is the provider-assigned unique ID for this managed resource.\n \"\"\"\n\nasync def get_virtual_network(name=None, resource_group_name=None):\n \"\"\"\n Use this data source to access information about an existing Virtual Network.\n \"\"\"\n __args__ = dict()\n\n __args__['name'] = name\n __args__['resourceGroupName'] = resource_group_name\n __ret__ = await pulumi.runtime.invoke('azure:network/getVirtualNetwork:getVirtualNetwork', __args__)\n\n return GetVirtualNetworkResult(\n address_spaces=__ret__.get('addressSpaces'),\n dns_servers=__ret__.get('dnsServers'),\n subnets=__ret__.get('subnets'),\n vnet_peerings=__ret__.get('vnetPeerings'),\n id=__ret__.get('id'))\n"},"size":{"kind":"number","value":2449,"string":"2,449"}}},{"rowIdx":1361,"cells":{"max_stars_repo_path":{"kind":"string","value":"data/python/appinit.py"},"max_stars_repo_name":{"kind":"string","value":"Nextpertise/freeradius-amqp"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2022979"},"content":{"kind":"string","value":"#!/usr/bin/env python\nimport pika\nimport time\n\nrabbitmq_host = \"rabbitmq\"\nrabbitmq_port = 5672\nrabbitmq_user = \"radiustest\"\nrabbitmq_password = \"\"\nrabbitmq_virtual_host = \"/\"\nrabbitmq_send_exchange = \"fr.authorize\" \nrabbitmq_rcv_exchange = \"fr.authorize\"\nrabbitmq_rcv_queue = \"queue_radius\"\nrabbitmq_rcv_key = \"rlm_amqp_authorize\"\n\n# The binding area\ncredentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_password)\nconnection = pika.BlockingConnection(pika.ConnectionParameters(rabbitmq_host, rabbitmq_port, rabbitmq_virtual_host, credentials))\nchannel = connection.channel()\n\n# Create queue if not exist\nchannel.exchange_declare(\n\texchange='fr.authorize',\n\texchange_type='direct',\n\tpassive=False,\n\tdurable=True,\n\tauto_delete=False\n)\nchannel.queue_declare(queue=rabbitmq_rcv_queue, auto_delete=False)\nchannel.queue_bind(queue=rabbitmq_rcv_queue, exchange=rabbitmq_rcv_exchange, routing_key=rabbitmq_rcv_key)\nchannel.basic_publish(\n\texchange=rabbitmq_send_exchange, routing_key=rabbitmq_rcv_key,\n\tbody=\"hallo\", mandatory=False\n)\n#channel.queue_bind(exchange=rabbitmq_rcv_exchange, queue=rabbitmq_rcv_queue, routing_key=rabbitmq_rcv_key)\n\n"},"size":{"kind":"number","value":1153,"string":"1,153"}}},{"rowIdx":1362,"cells":{"max_stars_repo_path":{"kind":"string","value":"microservices-2/track.py"},"max_stars_repo_name":{"kind":"string","value":"beaubadilla/cpsc449_backend_engineering"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2022757"},"content":{"kind":"string","value":"import sys\nimport flask_api\nfrom flask import request\nfrom flask_api import status, exceptions\nimport pugsql\nimport uuid\nimport sqlite3\n\n\napp = flask_api.FlaskAPI(__name__)\napp.config.from_envvar('APP_CONFIG')\n\nqueries = pugsql.module('queries/')\nqueries.connect(app.config['DATABASE_URL'])\n\nqueries1 = pugsql.module('tracks1_queries/')\nqueries1.connect(app.config['DATABASE_URL1'])\n\nqueries2 = pugsql.module('tracks2_queries/')\nqueries2.connect(app.config['DATABASE_URL2'])\n\nqueries3 = pugsql.module('tracks3_queries/')\nqueries3.connect(app.config['DATABASE_URL3'])\n\nsqlite3.register_adapter(uuid.UUID, lambda u: u.bytes_le)\nsqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b))\n\n@app.cli.command('init')\ndef init_db():\n with app.app_context():\n db1 = queries1._engine.raw_connection()\n word_file1 = open('tracks1.sql', mode = 'r', encoding='utf-8')\n word_file_read1 = word_file1.read()\n word_file1.close()\n\n db1.cursor().executescript(word_file_read1)\n db1.commit()\n\n db2 = queries2._engine.raw_connection()\n word_file2 = open('tracks2.sql', mode = 'r', encoding='utf-8')\n word_file_read2 = word_file2.read()\n word_file2.close()\n\n db2.cursor().executescript(word_file_read2)\n db2.commit()\n\n db3 = queries3._engine.raw_connection()\n word_file3 = open('tracks3.sql', mode = 'r', encoding='utf-8')\n word_file_read3 = word_file3.read()\n word_file3.close()\n\n db3.cursor().executescript(word_file_read3)\n db3.commit()\n\n db = queries._engine.raw_connection()\n word_file = open('data.sql', mode='r', encoding='utf-8')\n word_file_read = word_file.read()\n word_file.close()\n\n db.cursor().executescript(word_file_read)\n db.commit()\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return '''

Available endpoints:

\n

Tracks:

\n
  1. Create a track

    {\n \"TrackName\": \"sample\",\n \"Album\": \"An Album\",\n \"Artist\": \"An Artist\",\n \"Length\": 12345,\n \"Url\": \"file://aplace/this.mp3\",\n \"Art\": \"something.jpg\"\n}

  2. Retrieve a track
  3. Edit a track

    {\n \"TrackId\": 1,\n \"TrackName\": \"Updated name\",\n \"Album\": \"Updated Album\",\n \"Artist\": \"Updated Artist\",\n \"Length\": 12345,\n \"Url\": \"file://aplace/this.mp3\",\n \"Art\": \"something.jpg\"\n}

  4. Delete a track
\n'''\n\n# all track endpoints will leade here\n@app.route('/api/v1/tracks', methods=['POST', 'GET', 'DELETE', 'PUT'])\ndef tracks():\n if request.method == 'GET':\n return get_track(request.args), status.HTTP_200_OK\n\n elif request.method == 'POST':\n return create_track(request.data)\n\n elif request.method == 'DELETE':\n return delete_track(request.args)\n\n elif request.method == 'PUT':\n return edit_track(request.data)\n\n# allows the creation of a new track to ne inserted into DB.\n # If no Art is given, then we declare it to NULL\ndef create_track(track):\n track = request.data\n required_fields = ['TrackName', 'Album', 'Artist', 'Length', 'Url']\n\n if not all([field in track for field in required_fields]):\n raise exceptions.ParseError()\n try:\n if not 'Art' in track.keys():\n track['Art'] = None\n\n TrackId = uuid.uuid4() # UUID object\n track['TrackID'] = TrackId\n intTrackId = int(TrackId) # int representation of UUID object\n shard_key = intTrackId % 3\n\n if shard_key == 0:\n queries1.create_track(**track)\n elif shard_key == 1:\n queries2.create_track(**track)\n elif shard_key == 2:\n queries3.create_track(**track)\n\n except Exception as e:\n return { 'error': str(e) }, status.HTTP_409_CONFLICT\n\n location_url = f'http://localhost:5300/api/v1/tracks?id={TrackId}'\n\n return track, status.HTTP_201_CREATED, { \"Content-Type\": \"application/json\", \"Location\": location_url}\n\n# edits track given the TrackId. Since this is a PUT,\n # it is expected to pass in the whole object to\n # replace the current object\n #(Optional): since we are given a whole object with PUT, there\n # is no need to have different files for each column update.\n # Unless we are doing PATCH.\ndef edit_track(track):\n track = request.data\n required_fields = ['TrackId']\n\n if not all([field in track for field in required_fields]):\n raise exceptions.ParseError\n try:\n shard_key = track['TrackId'] % 3\n if shard_key == 0:\n for updates in track:\n if updates == 'TrackName':\n b = queries1.update_track_name(**track)\n if updates == 'Album':\n b = queries1.update_track_album(**track)\n if updates == 'Artist':\n b = queries1.update_track_artist(**track)\n if updates == 'Length':\n b = queries1.update_track_length(**track)\n if updates == 'Url':\n b = queries1.update_track_url(**track)\n if updates == 'Art':\n b = queries1.update_track_art(**track)\n track = queries1.track_by_id(**track)\n\n elif shard_key == 1:\n for updates in track:\n if updates == 'TrackName':\n b = queries2.update_track_name(**track)\n if updates == 'Album':\n b = queries2.update_track_album(**track)\n if updates == 'Artist':\n b = queries2.update_track_artist(**track)\n if updates == 'Length':\n b = queries2.update_track_length(**track)\n if updates == 'Url':\n b = queries1.update_track_url(**track)\n if updates == 'Art':\n b = queries2.update_track_art(**track)\n track = queries2.track_by_id(**track)\n\n elif shard_key == 2:\n for updates in track:\n if updates == 'TrackName':\n b = queries3.update_track_name(**track)\n if updates == 'Album':\n b = queries3.update_track_album(**track)\n if updates == 'Artist':\n b = queries3.update_track_artist(**track)\n if updates == 'Length':\n b = queries3.update_track_length(**track)\n if updates == 'Url':\n b = queries3.update_track_url(**track)\n if updates == 'Art':\n b = queries3.update_track_art(**track)\n track = queries3.track_by_id(**track)\n\n except Exception as e:\n return { 'error': str(e) }, status.HTTP_409_CONFLICT\n\n return track, status.HTTP_201_CREATED\n\n# deletes a track, from a given 'id'\n # if no 'id' is given then returns '400 BAD REQUEST'\ndef delete_track(track):\n if 'id' in track:\n track = {\n \"TrackId\": track['id']\n }\n try:\n shard_key = track['TrackId'] % 3\n if shard_key == 0:\n queries1.delist_track_from_playlists(**track)\n track = queries1.delete_track_by_id(**track)\n\n elif shard_key == 1:\n queries2.delist_track_from_playlists(**track)\n track = queries2.delete_track_by_id(**track)\n\n elif shard_key == 2:\n queries3.delist_track_from_playlists(**track)\n track = queries3.delete_track_by_id(**track)\n except Exception as e:\n return { 'error': str(e) }, status.HTTP_409_CONFLICT\n if track:\n return {\"info\": \"Successfully deleted\"}, status.HTTP_200_OK\n else:\n raise exceptions.NotFound()\n return {'error': \"Did not provide an id for track to be deleted\"}, status.HTTP_400_BAD_REQUEST\n\n# Returns all tracks in the DB.\ndef all_tracks():\n all_tracks1 = queries1.all_tracks()\n all_tracks2 = queries2.all_tracks()\n all_tracks3 = queries3.all_tracks()\n all_tracks = all_tracks1 + all_tracks2 + all_tracks3\n return list(all_tracks)\n\n# returns a track given 'id'. If no ID is given then return all tracks.\n # do this to activate flaskAPI, so we can easily POST, PUT...\ndef get_track(track):\n if 'id' in track:\n track = {\n \"TrackId\": track['id']\n }\n myUUID = str(track['TrackId'])\n myUUID = uuid.UUID(myUUID)\n track['TrackId'] = myUUID\n shard_key = myUUID.int % 3\n try:\n if shard_key == 0:\n \ttrack = queries1.track_by_id(**track)\n elif shard_key == 1:\n \ttrack = queries2.track_by_id(**track)\n elif shard_key == 2:\n \ttrack = queries3.track_by_id(**track)\n\n except Exception as e:\n return e\n else:\n return all_tracks()\n track['TrackId'] = str(uuid.UUID(bytes=track['TrackId']))\n if track:\n return track\n else:\n raise exceptions.NotFound()\n"},"size":{"kind":"number","value":9202,"string":"9,202"}}},{"rowIdx":1363,"cells":{"max_stars_repo_path":{"kind":"string","value":"docker/ubuntu/16-04/ub_limonero/limonero/app.py"},"max_stars_repo_name":{"kind":"string","value":"eubr-atmosphere/jenkins"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024792"},"content":{"kind":"string","value":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport argparse\nimport itertools\nimport logging\nimport logging.config\nimport os\nimport signal\n\nimport eventlet\nimport eventlet.wsgi\nimport sqlalchemy_utils\nimport yaml\nfrom flask import Flask, request\nfrom flask_admin import Admin\nfrom flask_babel import get_locale, Babel\nfrom flask_babel import gettext\nfrom flask_cors import CORS\nfrom flask_redis import FlaskRedis\nfrom flask_restful import Api, abort\n\nfrom data_source_api import DataSourceDetailApi, DataSourceListApi, \\\n DataSourcePermissionApi, DataSourceUploadApi, DataSourceInferSchemaApi, \\\n DataSourcePrivacyApi, DataSourceDownload, DataSourceSampleApi\nfrom limonero import CustomJSONEncoder as LimoneroJSONEncoder\nfrom limonero.admin import DataSourceModelView, StorageModelView, HomeView, \\\n init_login, AuthenticatedMenuLink\nfrom limonero.cache import cache\nfrom limonero.model_api import ModelDetailApi, ModelListApi\nfrom limonero.models import db, DataSource, Storage\nfrom limonero.storage_api import StorageDetailApi, StorageListApi\nfrom privacy_api import GlobalPrivacyListApi, AttributePrivacyGroupListApi\nfrom py4j_init import init_jvm\n\nos.chdir(os.environ.get('LIMONERO_HOME', '.'))\nsqlalchemy_utils.i18n.get_locale = get_locale\n\neventlet.monkey_patch(all=True, thread=False)\napp = Flask(__name__, static_url_path='', static_folder='static')\n\napp.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.abspath(\n 'limonero/i18n/locales')\napp.json_encoder = LimoneroJSONEncoder\n\nbabel = Babel(app)\n\nlogging.config.fileConfig('logging_config.ini')\n\napp.secret_key = 'l3m0n4d1'\n\n# Flask Admin\nadmin = Admin(app, name='Lemonade Limonero', template_mode='bootstrap3',\n url=\"/control-panel\", base_template='admin/master.html',\n index_view=HomeView(url='/control-panel'))\n\nadmin.add_link(AuthenticatedMenuLink(name='Logout',\n endpoint='admin.logout_view'))\n\n# Cache\ncache.init_app(app)\n\n# CORS\nCORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\napi = Api(app)\n\nredis_store = FlaskRedis()\n\n# Initialize flask-login\ninit_login(app)\n\nmappings = {\n '/datasources': DataSourceListApi,\n '/datasources/upload': DataSourceUploadApi,\n '/datasources/infer-schema/': DataSourceInferSchemaApi,\n '/datasources/sample/': DataSourceSampleApi,\n '/datasources/': DataSourceDetailApi,\n '/datasources//permission/':\n DataSourcePermissionApi,\n '/datasources//privacy': DataSourcePrivacyApi,\n '/privacy': GlobalPrivacyListApi,\n '/privacy/attribute-groups': AttributePrivacyGroupListApi,\n '/models': ModelListApi,\n '/models/': ModelDetailApi,\n\n '/storages': StorageListApi,\n '/storages/': StorageDetailApi,\n}\ngrouped_mappings = itertools.groupby(sorted(mappings.items()),\n key=lambda path: path[1])\nfor view, g in grouped_mappings:\n api.add_resource(view, *[x[0] for x in g], endpoint=view.__name__)\n\napp.add_url_rule('/datasources//download',\n methods=['GET'], endpoint='DataSourceDownload',\n view_func=DataSourceDownload.as_view('download'))\n\n\n# for route in app.url_map.iter_rules():\n# print route\n\n# @app.before_request\ndef before():\n if request.args and 'lang' in request.args:\n if request.args['lang'] not in ('es', 'en'):\n return abort(404)\n\n\n@app.route('/static/')\ndef static_file(path):\n return app.send_static_file(path)\n\n\n@babel.localeselector\ndef get_locale():\n return request.args.get(\n 'lang', request.accept_languages.best_match(['en', 'pt', 'es']))\n\n\n# noinspection PyUnusedLocal\ndef exit_gracefully(s, frame):\n os.kill(os.getpid(), signal.SIGTERM)\n\n\ndef main(is_main_module):\n config_file = None\n signal.signal(signal.SIGINT, exit_gracefully)\n if is_main_module:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--config\", type=str,\n help=\"Config file\", required=False)\n args = parser.parse_args()\n config_file = args.config\n\n if config_file is None:\n config_file = os.environ.get('LIMONERO_CONFIG')\n\n logger = logging.getLogger(__name__)\n if config_file:\n with open(config_file) as f:\n config = yaml.load(f)['limonero']\n\n app.config['LIMONERO_CONFIG'] = config\n app.config[\"RESTFUL_JSON\"] = {\"cls\": app.json_encoder}\n\n server_config = config.get('servers', {})\n app.config['SQLALCHEMY_DATABASE_URI'] = server_config.get(\n 'database_url')\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SQLALCHEMY_POOL_SIZE'] = 10\n app.config['SQLALCHEMY_POOL_RECYCLE'] = 240\n app.config['SQLALCHEMY_POOL_RECYCLE'] = 240\n\n app.config.update(config.get('config', {}))\n\n db.init_app(app)\n\n port = int(config.get('port', 5000))\n logger.debug(\n gettext('Running in %(mode)s mode', mode=config.get('environment')))\n\n if is_main_module:\n # JVM, used to interact with HDFS.\n init_jvm(app, logger)\n if config.get('environment', 'dev') == 'dev':\n admin.add_view(DataSourceModelView(DataSource, db.session))\n admin.add_view(StorageModelView(Storage, db.session))\n app.run(debug=True, port=port)\n else:\n eventlet.wsgi.server(eventlet.listen(('', port)), app)\n else:\n logger.error(\n gettext('Please, set LIMONERO_CONFIG environment variable'))\n exit(1)\n\n\nif __name__ == '__main__':\n main(__name__ == '__main__')\n"},"size":{"kind":"number","value":5803,"string":"5,803"}}},{"rowIdx":1364,"cells":{"max_stars_repo_path":{"kind":"string","value":"study_example_snippet/chapter_04_serializer/01_serializing_dataclass_support.py"},"max_stars_repo_name":{"kind":"string","value":"KimSoungRyoul/DjangoBackendProgramming"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023215"},"content":{"kind":"string","value":"\"\"\"\"\n순수 Python3.7미만 버전을 사용해서 직렬화 하는 로직 작성하기\n\"\"\"\nfrom __future__ import annotations\n\nimport dataclasses\nimport json\nfrom datetime import date\nfrom datetime import datetime\nfrom datetime import time\nfrom enum import Enum\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Optional\n\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.forms import model_to_dict\nfrom rest_framework.utils.encoders import JSONEncoder\n\n\n@dataclasses.dataclass\nclass Organization:\n class OrganizationType(Enum):\n BUSINESS = \"business\"\n MANAGEMENT_SUPPORT = \"management_support\"\n TECHNOLOGY_RESEARCH = \"technology_research\"\n\n name: str = \"\"\n organization_type: OrganizationType = \"\"\n leader: Optional[User] = None\n\n\n@dataclasses.dataclass\nclass User:\n username: str = dataclasses.field(default=\"\")\n password: str = dataclasses.field(default=\"\")\n email: str = dataclasses.field(default=\"\")\n name: str = dataclasses.field(default=\"\")\n age: int = dataclasses.field(default=-1)\n is_superuser: bool = dataclasses.field(default=False)\n created_at: datetime = dataclasses.field(default_factory=datetime.now)\n organization: Optional[Organization] = dataclasses.field(default=None)\n\n\nclass CustomJSONEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, (datetime, date)):\n return obj.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if isinstance(obj, Organization):\n return obj.__dict__\n return super().default(obj)\n\n\ndictionary_data = {\"나는datetime객체\": datetime.now(), \"나는time객체\": time(11, 34), \"나는date객체\": date(2020, 8, 22)}\nJSONEncoder\nmodel_to_dict()\nprint(json.dumps(dictionary_data, cls=DjangoJSONEncoder))\n\nprint(json.dumps(dictionary_data, cls=CustomJSONEncoder))\n\nif __name__ == \"__main__\":\n\n user: User = User(\n username=\"soungryoul.kim0823\",\n password=\"!\",\n name=\"김성렬\",\n email=\"\",\n age=37,\n is_superuser=False,\n organization=Organization(\n name=\"서버 개발1팀\", leader=User(username=\"teamjang.kim0102\", password=\"!\", name=\"김팀장\"),\n ),\n )\n\n user_serializing_dict: Dict[str, Any] = dataclasses.asdict(user)\n print(f\"Type: {type(user_serializing_dict)}\", f\"Data: {user_serializing_dict}\")\n\n user_serializing_json: str = json.dumps(user_serializing_dict, cls=CustomJSONEncoder)\n print(f\"Type: {type(user_serializing_json)}\", f\"Data: {user_serializing_json}\")\n\n user_serializing_bytes: bytes = user_serializing_json.encode(\"utf-8\")\n print(f\"Type: {type(user_serializing_bytes)}\", f\"Data: {user_serializing_bytes}\")\n"},"size":{"kind":"number","value":2639,"string":"2,639"}}},{"rowIdx":1365,"cells":{"max_stars_repo_path":{"kind":"string","value":"userProfile/migrations/0004_auto_20200404_2135.py"},"max_stars_repo_name":{"kind":"string","value":"TheWITProject/MentorApp"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023827"},"content":{"kind":"string","value":"# Generated by Django 2.2.10 on 2020-04-04 21:35\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('userProfile', '0003_auto_20200404_2111'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='funfact',\n field=models.CharField(default='', max_length=100),\n ),\n migrations.AlterField(\n model_name='profile',\n name='linkedin',\n field=models.URLField(default='', max_length=60),\n ),\n ]\n"},"size":{"kind":"number","value":573,"string":"573"}}},{"rowIdx":1366,"cells":{"max_stars_repo_path":{"kind":"string","value":"AutoFishing.py"},"max_stars_repo_name":{"kind":"string","value":"hiroyukki/AutoFishing"},"max_stars_count":{"kind":"number","value":2,"string":"2"},"id":{"kind":"string","value":"2023240"},"content":{"kind":"string","value":"import sys\nimport os\nimport threading\nimport time\nimport logging\nimport random\nimport cv2\nimport numpy as np\nimport pyautogui\n\ndef screenshot():\n img = pyautogui.screenshot()\n return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n\ndef imageDiff(img1, img2):\n diff = cv2.absdiff(img1, img2)\n _, diff = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)\n return cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n\n# get contour with largest area, that maybe buoy contour if there is no interference\ndef maxContour(img):\n contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n maxContourIdx = -1\n maxContourArea = 0\n for i in range(len(contours)):\n area = cv2.contourArea(contours[i])\n if area > maxContourArea:\n maxContourArea = area\n maxContourIdx = i\n if maxContourIdx != -1:\n return contours[maxContourIdx]\n return None\n\ndef getCentroid(contour):\n try:\n moment = cv2.moments(contour, False)\n if moment['m00'] != 0:\n return int(moment['m10'] / moment['m00']), int(moment['m01'] / moment['m00'])\n except:\n pass\n return 0, 0\n\n# find position of buoy, return position and image at that time on successful\ndef findBuoyPosition(initImg, timeout):\n for i in range(timeout):\n time.sleep(1)\n curImg = screenshot()\n # difference of inital image and current image is buoy\n diff = imageDiff(initImg, curImg)\n try:\n contour = maxContour(diff)\n if cv2.contourArea(contour) > 300:\n # Contour of buoy is irregular, assume that centroid position is the buoy position\n x, y = getCentroid(contour)\n if x != 0:\n return x, y, curImg\n except:\n pass\n\n logger.warn('buoy not found')\n return 0, 0, None\n\ndef waitForBite(initImg, timeout, x, y, width, height):\n beginTime = time.time()\n prevImg = initImg\n exceptCount = 1\n while True:\n lastTime = time.time() - beginTime\n if lastTime > timeout:\n return 2\n # pyautogui.moveTo((1 - lastTime / timeout) * width, height - 10, 0)\n time.sleep(0.1)\n curImg = screenshot()\n # check change around the buoy\n y0 = y - 100 if y - 100 >= 0 else 0\n x0 = x - 100 if x - 100 >= 0 else 0\n y1 = y + 100 if y + 100 <= height else height\n x1 = x + 100 if x + 100 <= width else width\n diff = imageDiff(prevImg[y0:y1, x0:x1], curImg[y0:y1, x0:x1])\n prevImg = curImg\n try:\n contour = maxContour(diff)\n area = cv2.contourArea(contour)\n # print(area)\n if area > 800 + y * 3:\n # print(cv2.contourArea(contour))\n # cv2.imwrite('diff.jpg', diff)\n # cv2.imwrite('prev.jpg', prevImg[y0:y1, x0:x1])\n # cv2.imwrite('cur.jpg', curImg[y0:y1, x0:x1])\n return 0\n except Exception as e:\n # print(e)\n exceptCount = exceptCount + 1\n if exceptCount > 2:\n return 3\n\ndef fishingLoop(key, width, height):\n logger.info('begin fishing loop')\n initImg = screenshot()\n time.sleep(0.2)\n pyautogui.press(key)\n time.sleep(1)\n pyautogui.moveTo(50, 50, 0)\n x, y, buoyImg = findBuoyPosition(initImg, 8)\n if x == 0:\n return 1\n logger.info('buoy found at position ({}, {})'.format(x, y))\n pyautogui.moveTo(100, 100, 0)\n waitResult = waitForBite(buoyImg, 20, x, y, width, height)\n if waitResult == 0:\n # move to buoy and right click\n time.sleep(0.1)\n logger.info('bite! right click ({}, {})'.format(x, y))\n pyautogui.moveTo(x, y, 0)\n pyautogui.rightClick()\n time.sleep(1) # wait for fish load into pack\n pyautogui.moveTo(150, 150, 0)\n else:\n logger.error('waitForBite returned: {}'.format(waitResult))\n\n return waitResult\n\ndef autoFishing():\n pyautogui.FAILSAFE = False\n\n while True:\n width, height = pyautogui.size()\n try:\n pyautogui.press(destroyKey)\n fishingLoop(fishingKey, width, height)\n # Make your character jump randomly to resist cheating detection\n if random.randint(1,100) < 8:\n pyautogui.press('space')\n time.sleep(1)\n except Exception as e:\n logger.error(repr(e))\n time.sleep(1)\n\ndestroyKey = 'r' # destroy bad fishes\nfishingKey = 'f' # replace to your fishing key\nlogger = logging.getLogger('auto_fishing')\ntimeoutMinutes = random.randint(90, 110) # close wow on timeout\n\ndef exitWorker():\n logger.info(\"close wow after {} minutes\".format(timeoutMinutes))\n time.sleep(timeoutMinutes * 60)\n logger.info(\"close wow\")\n # pyautogui.press('r')\n time.sleep(20)\n pyautogui.hotkey('alt', 'f4')\n os._exit(1)\n\ndef main(autoClose):\n logger.setLevel(logging.INFO)\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s %(message)s'))\n logger.addHandler(handler)\n closeThread = threading.Thread(target=exitWorker)\n if autoClose:\n closeThread.start()\n try:\n autoFishing()\n except BaseException as e:\n logger.error(repr(e))\n finally:\n os._exit(1)\n\nif __name__ == '__main__':\n autoClose = False\n if len(sys.argv) == 2 and sys.argv[1] == 'autoClose':\n autoClose = True\n main(autoClose) "},"size":{"kind":"number","value":5490,"string":"5,490"}}},{"rowIdx":1367,"cells":{"max_stars_repo_path":{"kind":"string","value":"RecoBTag/Skimming/python/btagGenBb_EventContent_cff.py"},"max_stars_repo_name":{"kind":"string","value":"ckamtsikis/cmssw"},"max_stars_count":{"kind":"number","value":852,"string":"852"},"id":{"kind":"string","value":"2022987"},"content":{"kind":"string","value":"import FWCore.ParameterSet.Config as cms\n\nfrom Configuration.EventContent.EventContent_cff import *\nbtagGenBbEventContent = cms.PSet(\n outputCommands = cms.untracked.vstring()\n)\nAODSIMbtagGenBbEventContent = cms.PSet(\n outputCommands = cms.untracked.vstring()\n)\nRECOSIMbtagGenBbEventContent = cms.PSet(\n outputCommands = cms.untracked.vstring()\n)\nbtagGenBbEventSelection = cms.PSet(\n SelectEvents = cms.untracked.PSet(\n SelectEvents = cms.vstring('btagGenBbPath')\n )\n)\nAODSIMbtagGenBbEventContent.outputCommands.extend(AODSIMEventContent.outputCommands)\nAODSIMbtagGenBbEventContent.outputCommands.extend(btagGenBbEventContent.outputCommands)\nRECOSIMbtagGenBbEventContent.outputCommands.extend(RECOSIMEventContent.outputCommands)\nRECOSIMbtagGenBbEventContent.outputCommands.extend(btagGenBbEventContent.outputCommands)\n\n"},"size":{"kind":"number","value":841,"string":"841"}}},{"rowIdx":1368,"cells":{"max_stars_repo_path":{"kind":"string","value":"GlucoNet_Loading.py"},"max_stars_repo_name":{"kind":"string","value":"bassignana/Blood-Glucose-Prediction"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023132"},"content":{"kind":"string","value":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 27 19:37:37 2020\n\n@author: tommasobassignana\n\"\"\"\n\nimport pandas as pd\nimport xml.etree.ElementTree as et\n\nxml_file = \"/Users/tommasobassignana/Desktop/GLYFE-master/data/ohio/OhioT1DM-training/559-ws-training.xml\"\nxtree = et.parse(xml_file)\nxroot = xtree.getroot()\n\ndef extract_attribute_values(root, child_index):\n \"\"\"\n to add : element = \"event\"\n extract attribute values inside the specified element \n :param root: tree root\n :param fchild_index: index of the child element from which i want the attributes names\n :return:\n \"\"\"\n for event in root[child_index].iter(\"event\"):\n yield list(event.attrib.values())\n\ndef extract_attribute_names(root, child_index):\n \"\"\"\n extract the name of the attributes from xml tree element\n :param root: root node\n :param child_index: index of the child element from which i want the attributes names\n :return:\n \"\"\"\n return list(root[child_index][0].attrib.keys())\n\n\ndef create_glucose_df_from_root(xroot):\n \"\"\"\n Extract glucose values from xml\n :param xml:\n :return: glucose dataframe\n \"\"\"\n labels = extract_attribute_names(xroot, child_index=0)\n glucose = list(extract_attribute_values(xroot, child_index=0))\n glucose_df = pd.DataFrame(data=glucose, columns=labels)\n glucose_df[\"ts\"] = pd.to_datetime(glucose_df[\"ts\"], format=\"%d-%m-%Y %H:%M:%S\")\n glucose_df[\"value\"] = glucose_df[\"value\"].astype(\"float\")\n glucose_df.rename(columns={'ts': 'datetime', 'value': 'glucose'}, inplace=True)\n\n return glucose_df\n\n\ndef create_CHO_df_from_root(xroot):\n \"\"\"\n Extract CHO values from xml\n :param xml:\n :return: CHO dataframe\n \"\"\"\n labels = extract_attribute_names(xroot, child_index=5)\n CHO = list(extract_attribute_values(xroot, child_index=5))\n CHO_df = pd.DataFrame(data=CHO, columns=labels)\n CHO_df.drop(\"type\", axis=1, inplace=True)\n CHO_df[\"ts\"] = pd.to_datetime(CHO_df[\"ts\"], format=\"%d-%m-%Y %H:%M:%S\")\n CHO_df[\"carbs\"] = CHO_df[\"carbs\"].astype(\"float\")\n CHO_df.rename(columns={'ts': 'datetime', 'carbs': 'CHO'}, inplace=True)\n return CHO_df\n\n\ndef create_insuline_df_from_root(xroot):\n \"\"\"\n Extract insulin values from xml\n :param xml:\n :return: insulin dataframe\n \"\"\"\n labels = extract_attribute_names(xroot, child_index=4)\n insulin = list(extract_attribute_values(xroot, child_index=4))\n insulin_df = pd.DataFrame(data=insulin, columns=labels)\n for col in [\"ts_end\", \"type\", \"bwz_carb_input\"]:\n insulin_df.drop(col, axis=1, inplace=True)\n insulin_df[\"ts_begin\"] = pd.to_datetime(insulin_df[\"ts_begin\"], format=\"%d-%m-%Y %H:%M:%S\")\n insulin_df[\"dose\"] = insulin_df[\"dose\"].astype(\"float\")\n insulin_df.rename(columns={'ts_begin': 'datetime', 'dose': 'insulin'}, inplace=True)\n return insulin_df\n\n \ndef compose_final_df(xroot):\n \"\"\"\n extract glucose, CHO, and insulin from xml and merge the data\n :param xml:\n :return: dataframe\n \"\"\"\n glucose_df = create_glucose_df_from_root(xroot)\n CHO_df = create_CHO_df_from_root(xroot)\n insulin_df = create_insuline_df_from_root(xroot)\n\n df = pd.merge(glucose_df, CHO_df, how=\"outer\", on=\"datetime\")\n df = pd.merge(df, insulin_df, how=\"outer\", on=\"datetime\")\n df = df.sort_values(\"datetime\")\n\n return df\n\ndf = compose_final_df(xroot)\n"},"size":{"kind":"number","value":3390,"string":"3,390"}}},{"rowIdx":1369,"cells":{"max_stars_repo_path":{"kind":"string","value":"desempacotamento.py"},"max_stars_repo_name":{"kind":"string","value":"welykPereira/pythonExerciciosFaculdade"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2022826"},"content":{"kind":"string","value":"def soma(*num):\n soma = 0\n print('Tupla {} '.format(num))\n for i in num:\n soma += i\n return soma\n\n\n# programa principal\nprint('Resultado: {} \\n'.format(soma(5, 8)))\n"},"size":{"kind":"number","value":184,"string":"184"}}},{"rowIdx":1370,"cells":{"max_stars_repo_path":{"kind":"string","value":"GCC-paddle/tests/test_graph_classification.py"},"max_stars_repo_name":{"kind":"string","value":"S-HuaBomb/Contrib"},"max_stars_count":{"kind":"number","value":243,"string":"243"},"id":{"kind":"string","value":"2024270"},"content":{"kind":"string","value":"import argparse\nimport os\n\nfrom gcc.tasks.graph_classification import GraphClassification\nfrom tests.utils import E2E_PATH, MOCO_PATH, get_default_args, generate_emb\n\n\ndef run(dataset, model, emb_path=\"\"):\n args = get_default_args()\n args.dataset = dataset\n args.model = model\n args.emb_path = emb_path\n task = GraphClassification(\n args.dataset,\n args.model,\n args.hidden_size,\n args.num_shuffle,\n args.seed,\n emb_path=args.emb_path,\n )\n return task.train()\n\n\ndef test_e2e_imdb_binary():\n NAME = \"imdb-binary\"\n generate_emb(os.path.join(E2E_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(E2E_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.7, ret\n\n\ndef test_e2e_imdb_multi():\n NAME = \"imdb-multi\"\n generate_emb(os.path.join(E2E_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(E2E_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.48, ret\n\n\ndef test_e2e_collab():\n NAME = \"collab\"\n generate_emb(os.path.join(E2E_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(E2E_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.73, ret\n\n\ndef test_e2e_rdt_b():\n NAME = \"rdt-b\"\n generate_emb(os.path.join(E2E_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(E2E_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.85, ret\n\n\ndef test_e2e_rdt_5k():\n NAME = \"rdt-5k\"\n generate_emb(os.path.join(E2E_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(E2E_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.50, ret\n\n\ndef test_moco_imdb_binary():\n NAME = \"imdb-binary\"\n generate_emb(os.path.join(MOCO_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(MOCO_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.7, ret\n\n\ndef test_moco_imdb_multi():\n NAME = \"imdb-multi\"\n generate_emb(os.path.join(MOCO_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(MOCO_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.48, ret\n\n\ndef test_moco_collab():\n NAME = \"collab\"\n generate_emb(os.path.join(MOCO_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(MOCO_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.77, ret\n\n\ndef test_moco_rdt_b():\n NAME = \"rdt-b\"\n generate_emb(os.path.join(MOCO_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(MOCO_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.88, ret\n\n\ndef test_moco_rdt_5k():\n NAME = \"rdt-5k\"\n generate_emb(os.path.join(MOCO_PATH, \"current.pth\"), NAME)\n ret = run(NAME, \"from_numpy_graph\", os.path.join(MOCO_PATH, f\"{NAME}.npy\"))\n assert ret[\"Micro-F1\"] > 0.52, ret\n"},"size":{"kind":"number","value":2817,"string":"2,817"}}},{"rowIdx":1371,"cells":{"max_stars_repo_path":{"kind":"string","value":"app/common/const.py"},"max_stars_repo_name":{"kind":"string","value":"lkolacz/semantive"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2023759"},"content":{"kind":"string","value":"from model_utils import Choices\n\n\nWEBSITE_STATUSES = Choices(\n ('Sta', \"started\", \"Started\"),\n ('Tpr', \"getting_text\", \"Getting the text in progress\"),\n ('Ipr', \"getting_images\", \"Getting images in progress\"),\n ('Suc', \"success\", \"Success\"),\n ('Fai', \"failed\", \"Failed\"),\n)\n"},"size":{"kind":"number","value":289,"string":"289"}}},{"rowIdx":1372,"cells":{"max_stars_repo_path":{"kind":"string","value":"raspy/lcd/gpio_lcd_transfer_provider_standard.py"},"max_stars_repo_name":{"kind":"string","value":"cyrusbuilt/RasPy"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024184"},"content":{"kind":"string","value":"\"\"\"This module provides the GpioLcdTransferProviderStandard class.\"\"\"\n\n\nfrom raspy.illegal_argument_exception import IllegalArgumentException\nfrom raspy.object_disposed_exception import ObjectDisposedException\nfrom raspy.io import gpio_pins\nfrom raspy.io import pin_mode\nfrom raspy.io import pin_state\nfrom raspy.io.gpio_standard import GpioStandard\nfrom raspy.lcd.lcd_transfer_provider import LcdTransferProvider\n\n\nclass GpioLcdTransferProviderStandard(LcdTransferProvider):\n \"\"\"Raspberry Pi GPIO (via filesystem) provider.\n\n This is for the Micro Liquid Crystal Display.\n \"\"\"\n\n def __init__(self, d0, d1, d2, d3, d4, d5, d6, d7, four_bit_mode, rs, rw, enable):\n \"\"\"Initialize a new instance of the GpioLcdTransferProviderStandard.\n\n Initializes with all the necessary pins and whether or not to use\n 4-bit mode.\n\n :param raspy.io.gpio_pins.GpioPin d0:\n :param raspy.io.gpio_pins.GpioPin d1:\n :param raspy.io.gpio_pins.GpioPin d2:\n :param raspy.io.gpio_pins.GpioPin d3:\n :param raspy.io.gpio_pins.GpioPin d4:\n :param raspy.io.gpio_pins.GpioPin d5:\n :param raspy.io.gpio_pins.GpioPin d6:\n :param raspy.io.gpio_pins.GpioPin d7:\n :param bool four_bit_mode:\n :param raspy.io.gpio_pins.GpioPin rs:\n :param raspy.io.gpio_pins.GpioPin rw:\n :param raspy.io.gpio_pins.GpioPin enable:\n :raises:raspy.illegal_argument_exception.IllegalArgumentException if\n 'rs' or 'enable' params are None, not a GpioPin type, or is\n raspy.io.gpio_pins.GpioNone.\n \"\"\"\n super(LcdTransferProvider, self).__init__()\n self.__fourBitMode = four_bit_mode\n if self.__fourBitMode is None:\n self.__fourBitMode = True\n\n if rs == gpio_pins.GpioNone() or rs is None:\n msg = \"'rs' param must be a GpioPin other than GpioNone.\"\n raise IllegalArgumentException(msg)\n\n self.__registerSelectPort = GpioStandard(rs, pin_mode.OUT, pin_state.LOW)\n self.__registerSelectPort.provision()\n\n # We can save 1 pin by not using RW. Indicate this by passing\n # gpio_pins.GpioNone() instead of pin num.\n self.__readWritePort = gpio_pins.GpioNone()\n if rw != gpio_pins.GpioNone():\n self.__readWritePort = GpioStandard(rw, pin_mode.OUT, pin_state.LOW)\n self.__readWritePort.provision()\n\n if enable is None or enable == gpio_pins.GpioNone():\n msg = \"'enable' param must be a GpioPin other than GpioNone\"\n raise IllegalArgumentException(msg)\n\n self.__enablePort = GpioStandard(enable, pin_mode.OUT, pin_state.LOW)\n self.__enablePort.provision()\n\n data_pins = [\n d0,\n d1,\n d2,\n d3,\n d4,\n d5,\n d6,\n d7\n ]\n\n self.__dataPorts = list()\n for i in range(0, len(data_pins) - 1):\n if (data_pins[i] is None or\n not isinstance(data_pins[i], gpio_pins.GpioPin)):\n data_pins[i] = gpio_pins.GpioNone()\n\n if data_pins[i] != gpio_pins.GpioNone():\n pin = GpioStandard(data_pins[i], pin_mode.OUT, pin_state.LOW)\n pin.provision()\n self.__dataPorts.append(pin)\n\n @property\n def is_four_bit_mode(self):\n \"\"\"Get a value indicating whether this instance is in 4-bit mode.\n\n :returns: True if 4-bit mode; Otherwise, false.\n :rtype: bool\n \"\"\"\n return self.__fourBitMode\n\n def _pulse_enable(self):\n \"\"\"Pulse the enable pin.\"\"\"\n self.__enablePort.write(pin_state.LOW)\n self.__enablePort.write(pin_state.HIGH) # enable pulse must be > 450 ns.\n self.__enablePort.write(pin_state.LOW) # Command needs 37 us to settle.\n\n def write_4_bits(self, value):\n \"\"\"\n Write the command or data in 4-bit mode (the last 4 data lines).\n\n :param byte, int value: The command or data to write.\n \"\"\"\n for i in range(0, 3):\n val = pin_state.LOW\n if ((value >> i) & 0x01) == 0x01:\n val = pin_state.HIGH\n self.__dataPorts[i + 4].write(val)\n self._pulse_enable()\n\n def write_8_bits(self, value):\n \"\"\"Write the command or data in 8-bit mode (all 8 data lines).\n\n :param byte, int value: The command or data to write.\n \"\"\"\n for i in range(0, 7):\n val = pin_state.LOW\n if ((value >> i) & 0x01) == 0x01:\n val = pin_state.HIGH\n self.__dataPorts[i].write(val)\n self._pulse_enable()\n\n def send(self, data, mode, back_light):\n \"\"\"Send the specified data, mode, and backlight.\n\n :param byte, int data: The data to send.\n :param int mode: Mode for register-select pin (pin_state.HIGH = on,\n pin_state.LOW = off).\n :param bool back_light: Set True to turn on the backlight.\n \"\"\"\n if LcdTransferProvider.is_disposed.fget():\n raise ObjectDisposedException(\"GpioLcdTransferProviderStandard\")\n\n # TODO set backlight.\n\n self.__registerSelectPort.write(mode)\n\n # If there is a RW pin indicated, set it low to write.\n if self.__readWritePort is not None:\n self.__readWritePort.write(pin_state.LOW)\n\n if self.__fourBitMode:\n self.write_4_bits(data >> 4)\n self.write_4_bits(data)\n else:\n self.write_8_bits(data)\n\n def dispose(self):\n \"\"\"Dispose this instance.\"\"\"\n if LcdTransferProvider.is_disposed.fget():\n return\n\n if self.__registerSelectPort is not None:\n self.__registerSelectPort.dispose()\n self.__registerSelectPort = None\n\n if self.__readWritePort is not None:\n self.__readWritePort.dispose()\n self.__readWritePort = None\n\n if self.__enablePort is not None:\n self.__enablePort.dispose()\n self.__enablePort = None\n\n if self.__dataPorts is not None and len(self.__dataPorts) > 0:\n for i, port in enumerate(self.__dataPorts):\n if port is not None:\n port.dispose()\n\n self.__dataPorts = None\n LcdTransferProvider.dispose(self)\n"},"size":{"kind":"number","value":6314,"string":"6,314"}}},{"rowIdx":1373,"cells":{"max_stars_repo_path":{"kind":"string","value":"example/dark_count_timebin.py"},"max_stars_repo_name":{"kind":"string","value":"crappyprogrammer/SeQUeNCe"},"max_stars_count":{"kind":"number","value":35,"string":"35"},"id":{"kind":"string","value":"2025179"},"content":{"kind":"string","value":"import math\nimport statistics\n\nimport pandas as pd\nfrom sequence.components.optical_channel import QuantumChannel, ClassicalChannel\nfrom sequence.kernel.event import Event\nfrom sequence.kernel.process import Process\nfrom sequence.kernel.timeline import Timeline\nfrom sequence.protocol import StackProtocol\nfrom sequence.qkd.BB84 import pair_bb84_protocols\nfrom sequence.qkd.cascade import pair_cascade_protocols\nfrom sequence.topology.node import QKDNode\nfrom sequence.utils.encoding import time_bin\n\n\n# dummy parent class to receive cascade keys and end timeline\nclass Parent(StackProtocol):\n def __init__(self, own: \"Node\", keysize: int, keynum: int):\n super().__init__(own, \"\")\n self.upper_protocols = []\n self.lower_protocols = []\n self.keysize = keysize\n self.keynum = keynum\n self.keycounter = 0\n\n def init(self):\n pass\n\n def pop(self, key):\n self.keycounter += 1\n if self.keycounter >= self.keynum:\n self.own.timeline.stop()\n\n def push(self):\n self.lower_protocols[0].push(self.keysize, self.keynum)\n\n def received_message(self):\n pass\n\n\nif __name__ == \"__main__\":\n runtime = math.inf\n dark_count = 425\n distances = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] # distances in km\n # distances = [120]\n KEYSIZE = 256\n KEYNUM = 10\n\n errors = [] # store error rates\n throughputs = [] # store throughputs\n\n # open file to store experiment results\n # Path(\"results/timebin\").mkdir(parents=True, exist_ok=True)\n # filename = \"results/timebin/distance_cascade.log\"\n # fh = open(filename, 'w')\n\n for distance in distances:\n tl = Timeline(runtime)\n tl.seed(1)\n tl.show_progress = True\n qc0 = QuantumChannel(\"qc0\", tl, distance=distance * 1e3, attenuation=0.0002)\n qc1 = QuantumChannel(\"qc1\", tl, distance=distance * 1e3, attenuation=0.0002)\n cc0 = ClassicalChannel(\"cc0\", tl, distance=distance * 1e3)\n cc1 = ClassicalChannel(\"cc1\", tl, distance=distance * 1e3)\n\n # Alice\n ls_params = {\"frequency\": 2e6, \"mean_photon_num\": 0.1}\n alice = QKDNode(\"alice\", tl, encoding=time_bin)\n\n for name, param in ls_params.items():\n alice.update_lightsource_params(name, param)\n \n # Bob\n detector_params = [{\"efficiency\": 0.072, \"dark_count\": dark_count, \"time_resolution\": 10},\n {\"efficiency\": 0.072, \"dark_count\": dark_count, \"time_resolution\": 10},\n {\"efficiency\": 0.072, \"dark_count\": dark_count, \"time_resolution\": 10}]\n bob = QKDNode(\"bob\", tl, encoding=time_bin)\n\n for i in range(len(detector_params)):\n for name, param in detector_params[i].items():\n bob.update_detector_params(i, name, param)\n\n qc0.set_ends(alice, bob)\n qc1.set_ends(bob, alice)\n cc0.set_ends(alice, bob)\n cc1.set_ends(bob, alice)\n\n # BB84 and cascade config\n pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])\n pair_cascade_protocols(alice.protocol_stack[1], bob.protocol_stack[1])\n\n # Parent\n pa = Parent(alice, KEYSIZE, KEYNUM)\n pb = Parent(bob, KEYSIZE, KEYNUM)\n alice.protocol_stack[1].upper_protocols.append(pa)\n pa.lower_protocols.append(alice.protocol_stack[1])\n bob.protocol_stack[1].upper_protocols.append(pb)\n pb.lower_protocols.append(bob.protocol_stack[1])\n\n process = Process(pa, \"push\", [])\n event = Event(0, process)\n tl.schedule(event)\n\n tl.init()\n tl.run()\n\n # get metrics\n bba = alice.protocol_stack[0]\n cascade_a = alice.protocol_stack[1]\n\n if bba.error_rates:\n error = statistics.mean(bba.error_rates)\n else:\n error = None\n\n if bba.throughputs:\n throughput = statistics.mean(bba.throughputs)\n else:\n throughput = None\n\n print(\"\\n{} km:\".format(distance))\n print(\"\\tbb84 error:\\t\\t\\t{}\".format(error))\n print(\"\\tbb84 throughput:\\t{}\".format(throughput))\n\n errors.append(error)\n throughputs.append(throughput)\n\n # fh.write(str(distance))\n # fh.write(' ')\n # fh.write(str(error))\n # fh.write(' ')\n # fh.write(str(throughput))\n # fh.write(' ')\n # fh.write(str(throughput_cascade))\n # fh.write(' ')\n # fh.write(str(throughput_privacy))\n # fh.write(' ')\n # fh.write(str(latency_privacy))\n # fh.write('\\n')\n\n log = {'Distance': distances, 'Error_rate': errors, 'Throughput_BB84': throughputs}\n df = pd.DataFrame(log)\n df.to_csv('dark_count_timebin.csv')\n"},"size":{"kind":"number","value":4752,"string":"4,752"}}},{"rowIdx":1374,"cells":{"max_stars_repo_path":{"kind":"string","value":"Others/panasonic/panasonic2020/b.py"},"max_stars_repo_name":{"kind":"string","value":"KATO-Hiro/AtCoder"},"max_stars_count":{"kind":"number","value":2,"string":"2"},"id":{"kind":"string","value":"2023824"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\r\n\r\n\r\ndef main():\r\n from math import ceil\r\n import sys\r\n input = sys.stdin.readline\r\n\r\n h, w = map(int, input().split())\r\n\r\n # 境界値\r\n if h == 1 or w == 1:\r\n print(1)\r\n exit()\r\n\r\n ans = h // 2 * w\r\n\r\n if h % 2 == 1:\r\n ans += ceil(w / 2)\r\n\r\n print(ans)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n"},"size":{"kind":"number","value":366,"string":"366"}}},{"rowIdx":1375,"cells":{"max_stars_repo_path":{"kind":"string","value":"src-django/api/migrations/0003_auto_20150606_0342.py"},"max_stars_repo_name":{"kind":"string","value":"protocolbuilder/sana.protocol_builder"},"max_stars_count":{"kind":"number","value":6,"string":"6"},"id":{"kind":"string","value":"2024975"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0002_auto_20150605_2258'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='element',\n name='created',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 43, 699662, tzinfo=utc), auto_now_add=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='element',\n name='last_modified',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 47, 163868, tzinfo=utc), auto_now=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='page',\n name='created',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 58, 91929, tzinfo=utc), auto_now_add=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='page',\n name='last_modified',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 1, 859588, tzinfo=utc), auto_now=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='procedure',\n name='created',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 5, 419529, tzinfo=utc), auto_now_add=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='procedure',\n name='last_modified',\n field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 9, 219634, tzinfo=utc), auto_now=True),\n preserve_default=False,\n ),\n ]\n"},"size":{"kind":"number","value":1877,"string":"1,877"}}},{"rowIdx":1376,"cells":{"max_stars_repo_path":{"kind":"string","value":"plaso/formatters/opera.py"},"max_stars_repo_name":{"kind":"string","value":"cvandeplas/plaso"},"max_stars_count":{"kind":"number","value":3,"string":"3"},"id":{"kind":"string","value":"2024179"},"content":{"kind":"string","value":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2013 The Plaso Project Authors.\n# Please see the AUTHORS file for details on individual authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Formatter for Opera history events.\"\"\"\n\nfrom plaso.formatters import interface\n\n\nclass OperaGlobalHistoryFormatter(interface.ConditionalEventFormatter):\n \"\"\"Formatter for an Opera global history event.\"\"\"\n\n DATA_TYPE = 'opera:history:entry'\n\n FORMAT_STRING_PIECES = [\n u'{url}',\n u'({title})',\n u'[{description}]']\n\n SOURCE_LONG = 'Opera Browser History'\n SOURCE_SHORT = 'WEBHIST'\n\n\nclass OperaTypedHistoryFormatter(interface.ConditionalEventFormatter):\n \"\"\"Formatter for an Opera typed history event.\"\"\"\n\n DATA_TYPE = 'opera:history:typed_entry'\n\n FORMAT_STRING_PIECES = [\n u'{url}',\n u'({entry_selection})']\n\n SOURCE_LONG = 'Opera Browser History'\n SOURCE_SHORT = 'WEBHIST'\n"},"size":{"kind":"number","value":1412,"string":"1,412"}}},{"rowIdx":1377,"cells":{"max_stars_repo_path":{"kind":"string","value":"tests/behavior/helpers.py"},"max_stars_repo_name":{"kind":"string","value":"lukaschoebel/POTUSgen"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024799"},"content":{"kind":"string","value":"\"\"\"\n@author: 2019.\n\"\"\"\n\nimport re\n\ndef cleanup_result(s):\n \"\"\"Cleans a given string and fixes punctuation and capitalization\n\n :param s: \n\n \"\"\"\n\n # Whitespace & Padding correction\n s = re.sub('\\\\s+([.,!?])\\\\s*', r'\\1 ', s)\n s = re.sub(r' ([\\,\\.\\/\\-\\\"\\?\\!\\:\\;])', \"\\\\1\", s)\n s = re.sub(r'( [a-zA-Z]) . ([a-zA-Z]) .', \"\\\\1.\\\\2.\", s)\n\n # Capitalization correction\n s = s.capitalize()\n s = re.sub(\" i[,;!]? \", \" I \", s)\n s = re.sub('([.!?]\\\\s+[a-z])', lambda c: c.group(1).upper(), s)\n \n return s"},"size":{"kind":"number","value":538,"string":"538"}}},{"rowIdx":1378,"cells":{"max_stars_repo_path":{"kind":"string","value":"proto_3/ddq/topics/logics/fol/meta/function_definition.py"},"max_stars_repo_name":{"kind":"string","value":"jadnohra/connect"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024249"},"content":{"kind":"string","value":"from typing import List\nfrom ddq.taxonomy.reference import Reference\nfrom ddq.taxonomy.node import Node, NodeRepr\nfrom ddq.topics.logics.logic import Meta, Formulator, Function, Predicate\nfrom ddq.util.check_type import check_type\n\n\nclass PredicativeFunctionDefinitionFormulator(Formulator):\n def info(self) -> str:\n return (\"Definition sugar for functions that can be \"\n \"defined using a predicate\")\n\n def references(self) -> List[Reference]:\n return [\n Reference(\n \"Type Theory and Formal Proof\", \n [\n (\"Rob\", \"Schechter\"), \n (\"Herman\", \"Nederpelt\")\n ],\n [\n \"p.172\"\n ]\n )\n # and EST p.10\n ]\n\n def __call__(self, *parameters) -> Node:\n return PredicativeFunctionDefinition(*parameters)\n\n\nclass PredicativeFunctionDefinition(Meta):\n def __init__(self, *in_children):\n super().__init__()\n children = [Function, Predicate]\n for i in range(len(children)):\n if i < len(in_children):\n children[i] = in_children[i]\n self.set_children(children)\n \n def accepts_child(self, index: int, child: \"Node\") -> bool:\n type_checks = {0: Function, 1: Predicate}\n return check_type(child, type_checks[index])\n \n @staticmethod\n def symbol() -> str:\n return \"≜\"\n \n def repr_node(self) -> NodeRepr:\n return self.symbol()\n "},"size":{"kind":"number","value":1602,"string":"1,602"}}},{"rowIdx":1379,"cells":{"max_stars_repo_path":{"kind":"string","value":"external/vcm/vcm/convenience.py"},"max_stars_repo_name":{"kind":"string","value":"jacnugent/fv3net"},"max_stars_count":{"kind":"number","value":5,"string":"5"},"id":{"kind":"string","value":"2024287"},"content":{"kind":"string","value":"import pathlib\nimport re\nfrom datetime import datetime, timedelta\nfrom typing import List, Union\nfrom functools import singledispatch\n\nimport cftime\nimport numpy as np\nimport xarray as xr\n\n# SpencerC added this function, it is not public API, but we need it\nfrom xarray.core.resample_cftime import exact_cftime_datetime_difference\n\nfrom vcm.cubedsphere.constants import TIME_FMT\n\nTOP_LEVEL_DIR = pathlib.Path(__file__).parent.parent.absolute()\n\n\n@singledispatch\ndef round_time(t, to=timedelta(seconds=1)):\n \"\"\" cftime will introduces noise when decoding values into date objects.\n This rounds time in the date object to the nearest second, assuming the init time\n is at most 1 sec away from a round minute. This is used when merging datasets so\n their time dims match up.\n\n Args:\n t: datetime or cftime object\n to: size of increment to round off to. By default round to closest integer\n second.\n\n Returns:\n datetime or cftime object rounded to nearest minute\n \"\"\"\n midnight = t.replace(hour=0, minute=0, second=0, microsecond=0)\n\n time_since_midnight = exact_cftime_datetime_difference(midnight, t)\n remainder = time_since_midnight % to\n quotient = time_since_midnight // to\n if remainder <= to / 2:\n closest_multiple_of_to = quotient\n else:\n closest_multiple_of_to = quotient + 1\n\n rounded_time_since_midnight = closest_multiple_of_to * to\n\n return midnight + rounded_time_since_midnight\n\n\n@round_time.register\ndef _round_time_numpy(time: np.ndarray) -> np.ndarray:\n return np.vectorize(round_time)(time)\n\n\n@round_time.register\ndef _round_time_xarray(time: xr.DataArray) -> xr.DataArray:\n return xr.apply_ufunc(np.vectorize(round_time), time)\n\n\ndef encode_time(time: cftime.DatetimeJulian) -> str:\n return time.strftime(TIME_FMT)\n\n\ndef parse_timestep_str_from_path(path: str) -> str:\n \"\"\"\n Get the model timestep timestamp from a given path\n\n Args:\n path: A file or directory path that includes a timestep to extract\n\n Returns:\n The extrancted timestep string\n \"\"\"\n\n extracted_time = re.search(r\"(\\d\\d\\d\\d\\d\\d\\d\\d\\.\\d\\d\\d\\d\\d\\d)\", path)\n\n if extracted_time is not None:\n return extracted_time.group(1)\n else:\n raise ValueError(f\"No matching time pattern found in path: {path}\")\n\n\ndef parse_datetime_from_str(time: str) -> cftime.DatetimeJulian:\n \"\"\"\n Retrieve a datetime object from an FV3GFS timestamp string\n \"\"\"\n t = datetime.strptime(time, TIME_FMT)\n return cftime.DatetimeJulian(t.year, t.month, t.day, t.hour, t.minute, t.second)\n\n\ndef parse_current_date_from_str(time: str) -> List[int]:\n \"\"\"Retrieve the 'current_date' in the format required by fv3gfs namelist\n from timestamp string.\"\"\"\n t = parse_datetime_from_str(time)\n return [t.year, t.month, t.day, t.hour, t.minute, t.second]\n\n\n# use typehints to dispatch to overloaded datetime casting function\n@singledispatch\ndef cast_to_datetime(\n time: Union[datetime, cftime.DatetimeJulian, np.datetime64]\n) -> datetime:\n \"\"\"Cast datetime-like object to python datetime. Assumes calendars are\n compatible.\"\"\"\n return datetime(\n time.year,\n time.month,\n time.day,\n time.hour,\n time.minute,\n time.second,\n time.microsecond,\n )\n\n\n@cast_to_datetime.register\ndef _cast_datetime_to_datetime(time: datetime) -> datetime:\n return time\n\n\n@cast_to_datetime.register\ndef _cast_numpytime_to_datetime(time: np.datetime64): # type: ignore\n # https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64\n unix_epoch = np.datetime64(0, \"s\")\n one_second = np.timedelta64(1, \"s\")\n seconds_since_epoch = (time - unix_epoch) / one_second\n return datetime.utcfromtimestamp(seconds_since_epoch)\n\n\n@cast_to_datetime.register\ndef _(time: str):\n return cast_to_datetime(parse_datetime_from_str(parse_timestep_str_from_path(time)))\n\n\ndef convert_timestamps(coord: xr.DataArray) -> xr.DataArray:\n parser = np.vectorize(parse_datetime_from_str)\n return xr.DataArray(parser(coord), dims=coord.dims, attrs=coord.attrs)\n\n\ndef shift_timestamp(time: str, seconds: Union[int, float]) -> str:\n \"\"\"Add an offset in seconds to a timestamp in YYYYMMDD.HHMMSS format\"\"\"\n offset = timedelta(seconds=seconds)\n offset_datetime = parse_datetime_from_str(time) + offset\n return offset_datetime.strftime(\"%Y%m%d.%H%M%S\")\n\n\ndef get_root():\n \"\"\"Returns the absolute path to the root directory for any machine\"\"\"\n return str(TOP_LEVEL_DIR)\n"},"size":{"kind":"number","value":4574,"string":"4,574"}}},{"rowIdx":1380,"cells":{"max_stars_repo_path":{"kind":"string","value":"jupyter_tree_download/handlers.py"},"max_stars_repo_name":{"kind":"string","value":"ryanlovett/jupyter-tree-download"},"max_stars_count":{"kind":"number","value":3,"string":"3"},"id":{"kind":"string","value":"2024595"},"content":{"kind":"string","value":"import asyncio\n\nfrom tornado import web\n\nfrom traitlets import Unicode\nfrom traitlets.config.configurable import Configurable\n\nfrom notebook.base.handlers import IPythonHandler\n\ndef attachment_suffix(compression):\n '''Returns the conventional suffix of the compression type.'''\n if compression == 'zip': return compression\n elif compression == 'gzip': return 'tar.gz'\n elif compression == 'bzip2': return 'tar.bz2'\n else: return f'tar.{compression}'\n\ndef command(compression, path):\n '''Returns a command that can compress our path to standard out.'''\n if compression == 'zip':\n return ['zip', '-q', '-r', '-', path]\n else:\n return ['tar', '-c', f'--{compression}', '-f', '-', path]\n\ndef friendly_name(name, path, suffix):\n '''Return a friendly name for the downloaded file.'''\n # If we're at the top-level, just return what the frontend provides (the\n # hostname). Otherwise return the same followed by some path context.\n normalized_path = path.replace('/', '_')\n if path == '.':\n return f'{name}.{suffix}'\n else:\n return f'{name}-{normalized_path}.{suffix}'\n\nclass TreeDownloadHandler(IPythonHandler):\n\n def initialize(self):\n super().initialize()\n self.c = TreeDownload(config=self.config)\n\n @web.authenticated\n async def get(self):\n '''Accepts arguments:\n name: a hint for the downloaded filename,\n path: path to the directory to download,\n compression: compression type, e.g. zip, gzip, bzip2, etc.\n '''\n _buf_size = 65535\n\n name = self.get_argument('name')\n if name == '': name = 'tree'\n\n path = self.get_argument('path', '.')\n if path == '': path = '.'\n\n compression = self.get_argument('compression', self.c.compression)\n suffix = attachment_suffix(compression)\n\n filename = friendly_name(name, path, suffix)\n\n self.set_header('content-type', 'application/octet-stream')\n self.set_header('cache-control', 'no-cache')\n self.set_header('content-disposition',\n f'attachment; filename=\"{filename}\"'\n )\n\n cmd = command(compression, path)\n p = await asyncio.create_subprocess_exec(*cmd,\n stdout=asyncio.subprocess.PIPE)\n while True:\n data = await p.stdout.read(_buf_size)\n if not data: break\n self.write(data)\n self.flush(data)\n await p.wait()\n self.finish()\n\nclass TreeDownload(Configurable):\n compression = Unicode(\n \"zip\",\n help=\"\"\"Type of compression to use.\n\n If 'zip' a .zip file is produced.\n For anything else, a '.tar.{compression}' file is produced, via tar.\n\n Appropriate compressor program (such as 'zip', 'tar', 'gzip', etc) must be\n already installed in the environment\n \"\"\",\n config=True\n )\n"},"size":{"kind":"number","value":2927,"string":"2,927"}}},{"rowIdx":1381,"cells":{"max_stars_repo_path":{"kind":"string","value":"CodaMais/forum/models.py"},"max_stars_repo_name":{"kind":"string","value":"igor-gme/herokuTest"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024739"},"content":{"kind":"string","value":"'''\n Copyright (C) 2017, CodaMais.\n License: GNU General Public License v3.0, see LICENSE.txt\n App: forum\n File: models.py\n Contains all classes related to the forum, it is django's default to keep all models in single file.\n'''\n\n# Django.\nfrom django.db import models\n\n# local Django.\nfrom forum import constants\nfrom user.models import User\n\n\n# Class: Topic\n# The class represents a topic in the site forum.\nclass Topic(models.Model):\n title = models.CharField(max_length=constants.MAX_LENGTH_TITLE)\n subtitle = models.CharField(max_length=constants.MAX_LENGTH_SUBTITLE)\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,)\n description = models.CharField(max_length=constants.MAX_LENGTH_TOPIC_DESCRIPTION)\n date_topic = models.DateTimeField(auto_now_add=True, blank=True)\n best_answer = models.ForeignKey('Answer', models.SET_NULL, related_name='best_answer', null=True)\n locked = models.BooleanField(default=False)\n\n def new_topics():\n topics = Topic.objects.all().order_by('-id')[:5]\n return topics\n\n def answers(self):\n assert self is not None, \"Topic not exists.\"\n # Getting all current topic answers except the best answer\n answers = Answer.objects.filter(topic=self)\n return answers\n\n def __str__(self):\n return self.title\n\n\n# Class: Answer\n# The class represents a answer to a topic in the site forum.\nclass Answer(models.Model):\n description = models.CharField(max_length=constants.MAX_LENGTH_ANSWER_DESCRIPTION)\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,)\n topic = models.ForeignKey(\n Topic,\n on_delete=models.CASCADE,)\n date_answer = models.DateTimeField(auto_now_add=True, blank=True)\n\n def creates_answer(self, user, topic, description):\n self.user = user\n self.topic = topic\n self.description = description\n self.save()\n\n def __str__(self):\n return self.description\n"},"size":{"kind":"number","value":2004,"string":"2,004"}}},{"rowIdx":1382,"cells":{"max_stars_repo_path":{"kind":"string","value":"25/25.py"},"max_stars_repo_name":{"kind":"string","value":"Scarygami/aoc2019"},"max_stars_count":{"kind":"number","value":3,"string":"3"},"id":{"kind":"string","value":"2024545"},"content":{"kind":"string","value":"import os\nimport sys\nfrom itertools import combinations\ncurrentdir = os.path.dirname(os.path.abspath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\n\ntry:\n from lib.intcode import IntcodeVM\nexcept ImportError:\n print(\"Intcode library could not be found\")\n exit(1)\n\nsource = IntcodeVM.read_intcode(os.path.join(currentdir, \"input.txt\"))\nmachine = IntcodeVM(source, silent=True)\n\n# Path to security checkpoint picking up all safe items\nwalkthrough = [\n \"east\",\n \"east\",\n \"take semiconductor\",\n \"north\",\n \"take planetoid\",\n \"west\",\n \"take food ration\",\n \"west\",\n \"west\",\n \"take monolith\",\n \"east\",\n \"east\",\n \"north\",\n \"take space law space brochure\",\n \"east\",\n \"take jam\",\n \"west\",\n \"north\",\n \"north\",\n \"take weather machine\",\n \"south\",\n \"south\",\n \"south\",\n \"east\",\n \"north\",\n \"take antenna\",\n \"south\",\n \"south\",\n \"east\",\n \"south\",\n \"south\",\n \"east\",\n \"drop food ration\",\n \"drop weather machine\",\n \"drop antenna\",\n \"drop space law space brochure\",\n \"drop jam\",\n \"drop semiconductor\",\n \"drop planetoid\",\n \"drop monolith\"\n]\n\nitems = [\n \"food ration\",\n \"weather machine\",\n \"antenna\",\n \"space law space brochure\",\n \"jam\",\n \"semiconductor\",\n \"planetoid\",\n \"monolith\"\n]\n\n\nmachine.run(\"\\n\".join(walkthrough) + \"\\n\")\n\n# Brute forcing all item combinations until the right weight is reached.\nfor l in range(len(items)):\n for selected in combinations(items, l):\n steps = []\n for item in selected:\n steps.append(\"take %s\" % item)\n steps.append(\"east\")\n\n outputs = machine.resume(\"\\n\".join(steps) + \"\\n\")\n outputs = \"\".join([chr(c) for c in outputs])\n if outputs.find(\"lighter\") >= 0:\n print(\"Too heavy:\", selected)\n elif outputs.find(\"heavier\") >= 0:\n print(\"Too light:\", selected)\n else:\n print(outputs)\n exit()\n\n steps = []\n for item in selected:\n steps.append(\"drop %s\" % item)\n machine.resume(\"\\n\".join(steps) + \"\\n\")\n"},"size":{"kind":"number","value":2140,"string":"2,140"}}},{"rowIdx":1383,"cells":{"max_stars_repo_path":{"kind":"string","value":"tests/async/test_focus.py"},"max_stars_repo_name":{"kind":"string","value":"axelande/playwright-python"},"max_stars_count":{"kind":"number","value":6243,"string":"6,243"},"id":{"kind":"string","value":"2024928"},"content":{"kind":"string","value":"# Copyright (c) Microsoft Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\n\n\nasync def test_should_work(page):\n await page.set_content(\"
\")\n assert await page.evaluate(\"() => document.activeElement.nodeName\") == \"BODY\"\n await page.focus(\"#d1\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"d1\"\n\n\nasync def test_should_emit_focus_event(page):\n await page.set_content(\"
\")\n focused = []\n await page.expose_function(\"focusEvent\", lambda: focused.append(True))\n await page.evaluate(\"() => d1.addEventListener('focus', focusEvent)\")\n await page.focus(\"#d1\")\n assert focused == [True]\n\n\nasync def test_should_emit_blur_event(page):\n await page.set_content(\n \"
DIV1
DIV2
\"\n )\n await page.focus(\"#d1\")\n focused = []\n blurred = []\n await page.expose_function(\"focusEvent\", lambda: focused.append(True))\n await page.expose_function(\"blurEvent\", lambda: blurred.append(True))\n await page.evaluate(\"() => d1.addEventListener('blur', blurEvent)\")\n await page.evaluate(\"() => d2.addEventListener('focus', focusEvent)\")\n await page.focus(\"#d2\")\n assert focused == [True]\n assert blurred == [True]\n\n\nasync def test_should_traverse_focus(page):\n await page.set_content('')\n focused = []\n await page.expose_function(\"focusEvent\", lambda: focused.append(True))\n await page.evaluate(\"() => i2.addEventListener('focus', focusEvent)\")\n\n await page.focus(\"#i1\")\n await page.keyboard.type(\"First\")\n await page.keyboard.press(\"Tab\")\n await page.keyboard.type(\"Last\")\n\n assert focused == [True]\n assert await page.eval_on_selector(\"#i1\", \"e => e.value\") == \"First\"\n assert await page.eval_on_selector(\"#i2\", \"e => e.value\") == \"Last\"\n\n\nasync def test_should_traverse_focus_in_all_directions(page):\n await page.set_content('')\n await page.keyboard.press(\"Tab\")\n assert await page.evaluate(\"() => document.activeElement.value\") == \"1\"\n await page.keyboard.press(\"Tab\")\n assert await page.evaluate(\"() => document.activeElement.value\") == \"2\"\n await page.keyboard.press(\"Tab\")\n assert await page.evaluate(\"() => document.activeElement.value\") == \"3\"\n await page.keyboard.press(\"Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.value\") == \"2\"\n await page.keyboard.press(\"Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.value\") == \"1\"\n\n\n@pytest.mark.only_platform(\"darwin\")\n@pytest.mark.only_browser(\"webkit\")\nasync def test_should_traverse_only_form_elements(page):\n await page.set_content(\n \"\"\"\n \n \n link\n \n \"\"\"\n )\n await page.keyboard.press(\"Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"input-1\"\n await page.keyboard.press(\"Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"input-2\"\n await page.keyboard.press(\"Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"input-1\"\n await page.keyboard.press(\"Alt+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"button\"\n await page.keyboard.press(\"Alt+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"link\"\n await page.keyboard.press(\"Alt+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"input-2\"\n await page.keyboard.press(\"Alt+Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"link\"\n await page.keyboard.press(\"Alt+Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"button\"\n await page.keyboard.press(\"Alt+Shift+Tab\")\n assert await page.evaluate(\"() => document.activeElement.id\") == \"input-1\"\n"},"size":{"kind":"number","value":4516,"string":"4,516"}}},{"rowIdx":1384,"cells":{"max_stars_repo_path":{"kind":"string","value":"l10n_br_stock_account/models/stock_backorder_confirmation.py"},"max_stars_repo_name":{"kind":"string","value":"SandroGauna/odoo-brasil"},"max_stars_count":{"kind":"number","value":181,"string":"181"},"id":{"kind":"string","value":"2024700"},"content":{"kind":"string","value":"# © 2021 - - Code 137\n\nfrom odoo import models\n\n\nclass StockBackorderConfirmation(models.TransientModel):\n _inherit = \"stock.backorder.confirmation\"\n\n \"\"\"Verificar as quantidades dos produtos na invoice após sua criação\"\"\"\n\n def process(self):\n res = super(StockBackorderConfirmation, self).process()\n pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids'))\n pickings_to_validate.action_invoice_picking()\n return res\n\n def process_cancel_backorder(self):\n res = super(StockBackorderConfirmation,\n self).process_cancel_backorder()\n pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids'))\n pickings_to_validate.action_invoice_picking()\n return res\n"},"size":{"kind":"number","value":846,"string":"846"}}},{"rowIdx":1385,"cells":{"max_stars_repo_path":{"kind":"string","value":"python/426_convert_binary_search_tree_to_sorted_doubly_linked_list.py"},"max_stars_repo_name":{"kind":"string","value":"liaison/LeetCode"},"max_stars_count":{"kind":"number","value":17,"string":"17"},"id":{"kind":"string","value":"2024989"},"content":{"kind":"string","value":"\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\"\"\"\n\nclass Solution:\n def treeToDoublyList(self, root: 'Node') -> 'Node':\n\n if not root:\n return None\n\n \"\"\"\n Convert a BST tree to a doubly-linked list\n return the head and tail of the list\n \"\"\"\n def head_and_tail_of_list(node):\n if not node:\n return None, None\n\n # divide and conquer\n if node.left:\n # chain the left subtree to the current node\n left_head, left_tail = head_and_tail_of_list(node.left)\n left_tail.right = node\n node.left = left_tail\n else:\n left_head = node\n\n if node.right:\n # chain the right subtree to the current node\n right_head, right_tail = head_and_tail_of_list(node.right)\n node.right = right_head\n right_head.left = node\n else:\n right_tail = node\n\n # return the head and tail of the entire list\n return left_head, right_tail\n\n head, tail = head_and_tail_of_list(root)\n # chain up head and tail\n head.left = tail\n tail.right = head\n\n return head\n\n\n"},"size":{"kind":"number","value":1395,"string":"1,395"}}},{"rowIdx":1386,"cells":{"max_stars_repo_path":{"kind":"string","value":"generatedata.py"},"max_stars_repo_name":{"kind":"string","value":"QuantumArjun/DeinDoc"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"id":{"kind":"string","value":"2022843"},"content":{"kind":"string","value":"import pandas as pd\nimport itemAPI\n\nitems = itemAPI.createItemDictFromCSV()\n\nnames = list(set(items.keys()))\ndiseases = set()\nfor item in items.values():\n diseases.add(item.disease)\ndiseases = list(diseases)\nindexToName, nameToIndex = itemAPI.generateIndexTable()\ndata = []\n\nfor disease in diseases:\n for name in names:\n feature = []\n feature.append(nameToIndex[name])\n feature.append(disease)\n if items[name].disease == disease:\n feature.append(1)\n else:\n feature.append(0)\n data.append(feature)\n\nprint(data)\ndf = pd.DataFrame(data, columns = ['Name', 'Disease', 'Show'])\n\n\ndf.to_csv('data.csv', index=False)\n\n \n"},"size":{"kind":"number","value":686,"string":"686"}}},{"rowIdx":1387,"cells":{"max_stars_repo_path":{"kind":"string","value":"testing/vulnerable_app/util.py"},"max_stars_repo_name":{"kind":"string","value":"bbhunter/fuzz-lightyear"},"max_stars_count":{"kind":"number","value":169,"string":"169"},"id":{"kind":"string","value":"2024850"},"content":{"kind":"string","value":"from urllib.parse import quote_plus\n\nfrom werkzeug.routing import BaseConverter\n\n\ndef get_name(name):\n \"\"\"\n Blueprint names must be unique, and cannot contain dots.\n This converts filenames to blueprint names.\n\n e.g. vulnerable_app.views.basic => basic\n\n :type name: str\n \"\"\"\n return name.split('.')[-1]\n\n\nclass ListConverter(BaseConverter):\n\n def __init__(self, url_map):\n super(ListConverter, self).__init__(url_map)\n self.delimiter = quote_plus(',')\n\n def to_python(self, value):\n return value.split(self.delimiter)\n\n def to_url(self, values):\n return self.delimiter.join(\n BaseConverter.to_url(value) for value in values\n )\n"},"size":{"kind":"number","value":704,"string":"704"}}},{"rowIdx":1388,"cells":{"max_stars_repo_path":{"kind":"string","value":"round/forms.py"},"max_stars_repo_name":{"kind":"string","value":"archimedeans/integration-bee"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024192"},"content":{"kind":"string","value":"from upload_validator import FileTypeValidator\n\nfrom django import forms\n# from django.utils.html import escape\n# from django.core.exceptions import ValidationError\n# from django.utils.translation import ugettext_lazy as _\n\n\nclass SubmitForProblemForm(forms.Form):\n solution = forms.FileField(\n required=True,\n max_length=40,\n help_text='Upload your solution (PDF only; size up to 5 MB; '\n + 'file name up to 40 characters long)',\n # allow_empty_file=False,\n widget=forms.FileInput(\n attrs={'id': 'solutionInput',\n 'class': 'form-control',\n 'accept': '.pdf,application/pdf'}\n ),\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if self.has_error('solution'):\n self.fields['solution'].widget.attrs.update({\n 'class': 'form-control is-invalid',\n 'aria-describedby': 'solutionValidationFeedback'\n })\n\n def clean_solution(self):\n file = self.cleaned_data['solution']\n # if not file.name.endswith('.pdf'):\n # raise ValidationError(\n # _('The extension of the file is not \\'.pdf\\'.'),\n # code='invalid'\n # )\n\n # Use django-upload-validator for file validation\n # It checks the extension and MIME type of an uploaded file\n # inferred from the file name and the binary signature / magic number\n # using python-magic, which in turn uses the libmagic C library\n validator = FileTypeValidator(\n allowed_types=['application/pdf'],\n allowed_extensions=['.pdf']\n )\n # with file.open() as file_resource:\n file_resource = file.open()\n validator(file_resource)\n return file\n\n\nclass ContactForm(forms.Form):\n email = forms.EmailField(\n required=True,\n help_text='The email address you would like us to send our response to',\n )\n subject = forms.ChoiceField(\n required=True,\n choices=[\n ('paper', 'Contest paper'),\n ('website', 'Website'),\n ('other', 'Other')\n ],\n )\n message = forms.CharField(\n required=True,\n min_length=5,\n strip=True,\n widget=forms.Textarea,\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n input_classes = {\n 'email': 'form-control',\n 'subject': 'form-select',\n 'message': 'form-control'\n }\n\n for field_name in ('email', 'subject', 'message'):\n if not self.has_error(field_name):\n self.fields[field_name].widget.attrs.update({\n 'class': input_classes[field_name],\n })\n else:\n self.fields[field_name].widget.attrs.update({\n 'class': input_classes[field_name] + ' is-invalid',\n 'aria-describedby': field_name + 'ValidationFeedback'\n })\n\n # def clean_message(self):\n # return escape(self.cleaned_data['message'])\n"},"size":{"kind":"number","value":3141,"string":"3,141"}}},{"rowIdx":1389,"cells":{"max_stars_repo_path":{"kind":"string","value":"Python-programs/inputPassword.py"},"max_stars_repo_name":{"kind":"string","value":"manavbansalcoder/Hacktoberfest2021"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2025212"},"content":{"kind":"string","value":"a = input(\"Input password:\")\nb = \"\"\nfor i in range(2):\n if a==b:\n print (\"your login is success\")\n break\n else:\n c = input(\"Sorry, your password is not correct. Input password:\")\n if c==b:\n print (\"Anda berhasil login\")\n break\n elif i==1:\n print (\"you had tried 3 times. your access is dennied.\")\n"},"size":{"kind":"number","value":381,"string":"381"}}},{"rowIdx":1390,"cells":{"max_stars_repo_path":{"kind":"string","value":"Painter_Siglent_DC_PowerSupply/Painter_Siglent_DC_PowerSupply.py"},"max_stars_repo_name":{"kind":"string","value":"sherryue123/Labber-Drivers"},"max_stars_count":{"kind":"number","value":3,"string":"3"},"id":{"kind":"string","value":"2024653"},"content":{"kind":"string","value":"#!/usr/bin/env python\n\nfrom VISA_Driver import VISA_Driver\n\n__version__ = \"0.0.1\"\n\nclass Driver(VISA_Driver):\n \"\"\" The Painter Siglent DC PowerSupply driver re-implements the VISA driver with some more options\"\"\"\n\n def performSetValue(self, quant, value, sweepRate=0.0, options={}):\n \"\"\"Perform the Set Value instrument operation. This function should\n return the actual value set by the instrument\"\"\"\n name = str(quant.name)\n if name == 'Firmware Version':\n # read-only channels don't perform setValue\n pass\n elif name.endswith(('Active Voltage', 'Active Current')):\n return self.getValue(name)\n else:\n # else, call the generic VISA driver\n return VISA_Driver.performSetValue(self, quant, value, sweepRate,\n options=options)\n\n def performGetValue(self, quant, options={}):\n \"\"\"Perform the Get Value instrument operation\"\"\"\n # perform special getValue for delay commands\n name = str(quant.name)\n if name.endswith(('Output', )):\n lName = name.split(' - ')\n return self.getValue(name) # return the local value stored in the driver\n else:\n # run the generic visa driver case\n return VISA_Driver.performGetValue(self, quant, options=options)\n\n\nif __name__ == '__main__':\n pass\n"},"size":{"kind":"number","value":1409,"string":"1,409"}}},{"rowIdx":1391,"cells":{"max_stars_repo_path":{"kind":"string","value":"tests_runner/utils/dir.py"},"max_stars_repo_name":{"kind":"string","value":"RainingComputers/ShnooTalk"},"max_stars_count":{"kind":"number","value":6,"string":"6"},"id":{"kind":"string","value":"2022636"},"content":{"kind":"string","value":"from typing import List\n\nimport os\nimport glob\n\n\ndef remove_if_exists(filename: str) -> None:\n if os.path.exists(filename):\n os.remove(filename)\n\n\ndef list_test_files() -> List[str]:\n files = [file for file in os.listdir() if file.endswith(\".shtk\")]\n files.sort()\n\n return files\n\n\ndef get_files(file_ext: str) -> List[str]:\n return glob.glob(f\"**/*{file_ext}\", recursive=True)\n\n\ndef remove_files(file_ext: str) -> None:\n files = get_files(file_ext)\n\n for file in files:\n remove_if_exists(file)\n\n\ndef dump_string_to_file(file_name: str, content: str) -> None:\n with open(file_name, \"w\") as file:\n file.write(content)\n\n\ndef string_from_file(file_name: str) -> str:\n with open(file_name, \"r\") as file:\n return file.read()\n"},"size":{"kind":"number","value":774,"string":"774"}}},{"rowIdx":1392,"cells":{"max_stars_repo_path":{"kind":"string","value":"general/myException.py"},"max_stars_repo_name":{"kind":"string","value":"jaeilepp/eggie"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2022796"},"content":{"kind":"string","value":"'''\nCreated on 9.1.2015\n\n@author: \n'''\n\nclass MyException(Exception):\n \"\"\"Derived class from exception\"\"\"\n\ntry:\n raise MyException('my detailed description')\nexcept MyException as my:\n print my # outputs 'my detailed description'\n"},"size":{"kind":"number","value":245,"string":"245"}}},{"rowIdx":1393,"cells":{"max_stars_repo_path":{"kind":"string","value":"src/runner.py"},"max_stars_repo_name":{"kind":"string","value":"ModOrganizer2/modorganizer-installer_wizard"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2025009"},"content":{"kind":"string","value":"# -*- encoding: utf-8 -*-\n\nimport sys\n\nfrom pathlib import Path\nfrom typing import Iterable, List, Optional\n\nimport mobase\n\nfrom wizard.interpreter import WizardInterpreter\nfrom wizard.manager import ManagerModInterface\nfrom wizard.severity import SeverityContext\nfrom wizard.value import SubPackage, SubPackages\nfrom wizard.utils import make_runner_context_factory\n\n\nclass MO2SubPackage(SubPackage):\n\n _tree: mobase.IFileTree\n _files: List[str]\n\n def __init__(self, tree: mobase.IFileTree):\n super().__init__(tree.name())\n self._tree = tree\n\n # We cannot perform lazy iteration on the tree in a Python way so we\n # have to list the files:\n\n self._files = []\n\n def fn(folder, entry) -> mobase.IFileTree.WalkReturn:\n self._files.append(entry.path())\n return mobase.IFileTree.CONTINUE\n\n self._tree.walk(fn)\n\n @property\n def files(self) -> Iterable[str]:\n return self._files\n\n\nclass MO2SeverityContext(SeverityContext):\n\n _organizer: mobase.IOrganizer\n\n def __init__(self, organizer: mobase.IOrganizer):\n super().__init__()\n self._organizer = organizer\n\n def warning(self, text: str):\n print(text, file=sys.stderr)\n\n\nclass MO2ManagerModInterface(ManagerModInterface):\n\n _organizer: mobase.IOrganizer\n _game: mobase.IPluginGame\n _subpackages: SubPackages\n\n def __init__(self, tree: mobase.IFileTree, organizer: mobase.IOrganizer):\n\n self._organizer = organizer\n self._game = organizer.managedGame()\n\n checker: mobase.ModDataChecker = self._game.feature(\n mobase.ModDataChecker # type: ignore\n )\n\n # Read the subpackages:\n self._subpackages = SubPackages()\n for entry in tree:\n if isinstance(entry, mobase.IFileTree):\n if checker:\n if checker.dataLooksValid(entry) == mobase.ModDataChecker.VALID:\n self._subpackages.append(MO2SubPackage(entry))\n continue\n\n # Add entry with INI tweaks:\n if entry.exists(\"INI Tweaks\") or entry.exists(\"INI\"):\n self._subpackages.append(MO2SubPackage(entry))\n continue\n\n # We add folder with format \"XXX Docs\" where \"XXX\" is a number.\n parts = entry.name().split()\n if (\n len(parts) >= 2\n and parts[0].isdigit()\n and parts[1].lower().startswith(\"doc\")\n ):\n self._subpackages.append(MO2SubPackage(entry))\n\n @property\n def subpackages(self) -> SubPackages:\n return self._subpackages\n\n def compareGameVersion(self, version: str) -> int:\n v1 = mobase.VersionInfo(version)\n v2 = mobase.VersionInfo(self._game.gameVersion())\n if v1 < v2:\n return 1\n elif v1 > v2:\n return -1\n else:\n return 0\n\n def compareSEVersion(self, version: str) -> int:\n se = self._game.feature(mobase.ScriptExtender) # type: ignore\n if not se:\n return 1\n v1 = mobase.VersionInfo(version)\n v2 = mobase.VersionInfo(se.getExtenderVersion())\n if v1 < v2:\n return 1\n elif v1 > v2:\n return -1\n else:\n return 0\n\n def compareGEVersion(self, version: str) -> int:\n # Cannot do th is in MO2.\n return 1\n\n def compareWBVersion(self, version: str) -> int:\n # Cannot do this in MO2.\n return 1\n\n def _resolve(self, filepath: str) -> Optional[Path]:\n \"\"\"\n Resolve the given filepath.\n\n Args:\n filepath: The path to resolve.\n\n Returns:\n The path to the given file on the disk, or one of the file mapping\n to it in the VFS, or None if the file does not exists.\n \"\"\"\n # TODO: This does not handle weird path that go back (..) and\n # then in data again, e.g. ../data/xxx.esp.\n path: Optional[Path]\n if filepath.startswith(\"..\"):\n path = Path(self._game.dataDirectory().absoluteFilePath(filepath))\n if not path.exists():\n path = None\n else:\n path = Path(filepath)\n parent = path.parent.as_posix()\n if parent == \".\":\n parent = \"\"\n\n files = self._organizer.findFiles(parent, \"*\" + path.name)\n if files:\n path = Path(files[0])\n else:\n path = None\n\n return path\n\n def dataFileExists(self, *filepaths: str) -> bool:\n return all(self._resolve(path) for path in filepaths)\n\n def getPluginLoadOrder(self, filename: str, fallback: int = -1) -> int:\n return self._organizer.pluginList().loadOrder(filename)\n\n def getPluginStatus(self, filename) -> int:\n state = self._organizer.pluginList().state(filename)\n\n if state == mobase.PluginState.ACTIVE:\n return 2\n if state == mobase.PluginState.INACTIVE:\n return 0 # Or 1?\n return -1\n\n def getFilename(self, filepath: str) -> str:\n path = self._resolve(filepath)\n if path:\n if path.is_file():\n return path.name\n return \"\"\n\n def getFolder(self, filepath: str) -> str:\n path = self._resolve(filepath)\n if path:\n if path.is_dir():\n return path.name\n return \"\"\n\n\ndef make_interpreter(\n base: mobase.IFileTree, organizer: mobase.IOrganizer\n) -> WizardInterpreter:\n\n manager = MO2ManagerModInterface(base, organizer)\n severity = MO2SeverityContext(organizer)\n\n factory = make_runner_context_factory(manager.subpackages, manager, severity)\n\n return WizardInterpreter(factory)\n"},"size":{"kind":"number","value":5831,"string":"5,831"}}},{"rowIdx":1394,"cells":{"max_stars_repo_path":{"kind":"string","value":"contact/migrations/0003_auto_20190529_1449.py"},"max_stars_repo_name":{"kind":"string","value":"radoslawdabrowski/radoslawdabrowski.pl"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"id":{"kind":"string","value":"2025128"},"content":{"kind":"string","value":"# Generated by Django 2.2.1 on 2019-05-29 12:49\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contact', '0002_auto_20190522_1259'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='contact',\n name='email',\n field=models.CharField(default='NO_EMAIL', error_messages={'blank': 'You need to fill your email', 'max_length': 'Your email is too long', 'null': 'You need to fill your email'}, max_length=100),\n ),\n migrations.AlterField(\n model_name='contact',\n name='message',\n field=models.TextField(default='NO_MESSAGE', error_messages={'blank': 'You need to fill the message', 'null': 'You need to fill the message'}),\n ),\n migrations.AlterField(\n model_name='contact',\n name='name',\n field=models.CharField(default='NO_NAME', error_messages={'blank': 'You need to fill your name', 'max_length': 'Your name is too long', 'null': 'You need to fill your name'}, max_length=50),\n ),\n ]\n"},"size":{"kind":"number","value":1107,"string":"1,107"}}},{"rowIdx":1395,"cells":{"max_stars_repo_path":{"kind":"string","value":"src/abaqus/Amplitude/ModulatedAmplitude.py"},"max_stars_repo_name":{"kind":"string","value":"Haiiliin/PyAbaqus"},"max_stars_count":{"kind":"number","value":7,"string":"7"},"id":{"kind":"string","value":"2024230"},"content":{"kind":"string","value":"from abaqusConstants import *\nfrom .Amplitude import Amplitude\n\n\nclass ModulatedAmplitude(Amplitude):\n \"\"\"The ModulatedAmplitude object defines a modulated amplitude curve.\n The ModulatedAmplitude object is derived from the Amplitude object. \n\n Notes\n -----\n This object can be accessed by:\n\n .. code-block:: python\n\n import amplitude\n mdb.models[name].amplitudes[name]\n import odbAmplitude\n session.odbs[name].amplitudes[name]\n\n The corresponding analysis keywords are:\n\n - AMPLITUDE\n\n \"\"\"\n\n def __init__(self, name: str, initial: float, magnitude: float, start: float, frequency1: float,\n frequency2: float, timeSpan: SymbolicConstant = STEP):\n \"\"\"This method creates a ModulatedAmplitude object.\n\n Notes\n -----\n This function can be accessed by:\n\n .. code-block:: python\n\n mdb.models[name].ModulatedAmplitude\n session.odbs[name].ModulatedAmplitude\n \n Parameters\n ----------\n name\n A String specifying the repository key. \n initial\n A Float specifying the constant A0A0. \n magnitude\n A Float specifying the coefficient AA. \n start\n A Float specifying the starting time t0t0. Possible values are non-negative numbers. \n frequency1\n A Float specifying the circular frequency 1 (ω1ω1). Possible values are positive \n numbers. \n frequency2\n A Float specifying the circular frequency 2 (ω2ω2). Possible values are positive \n numbers. \n timeSpan\n A SymbolicConstant specifying the time span of the amplitude. Possible values are STEP \n and TOTAL. The default value is STEP. \n\n Returns\n -------\n A ModulatedAmplitude object. \n \n Raises\n ------\n InvalidNameError\n RangeError \n \"\"\"\n super().__init__()\n pass\n\n def setValues(self, timeSpan: SymbolicConstant = STEP):\n \"\"\"This method modifies the ModulatedAmplitude object.\n \n Parameters\n ----------\n timeSpan\n A SymbolicConstant specifying the time span of the amplitude. Possible values are STEP \n and TOTAL. The default value is STEP.\n\n Raises\n ------\n RangeError\n \"\"\"\n pass\n"},"size":{"kind":"number","value":2410,"string":"2,410"}}},{"rowIdx":1396,"cells":{"max_stars_repo_path":{"kind":"string","value":"staticmethod_tutorial.py"},"max_stars_repo_name":{"kind":"string","value":"NightmareQAQ/python-notes"},"max_stars_count":{"kind":"number","value":106,"string":"106"},"id":{"kind":"string","value":"2024314"},"content":{"kind":"string","value":"# ref. https://www.programiz.com/python-programming/methods/built-in/staticmethod\n\n# Static method\n# However, when you need a utility function that doesn't access any properties of\n# a class but makes sense that it belongs to the class, we use static functions.\n\n\n# Static method vs Class method\n# Static method knows nothing about the class and just deals with the parameters.\n# Class method works with the class since its parameter is always the class itself.\n\n# Create utility function as a static method\nclass Dates:\n def __init__(self, date):\n self._date = date\n\n def get_date(self):\n return self._date\n\n @staticmethod\n def to_dash_date(date):\n return date.replace(\"/\", \"-\")\n\n\n# How inheritance works with static method?\nclass DatesWithSlashes(Dates):\n def get_date(self):\n return Dates.to_dash_date(self._date)\n\n\ndef main():\n # tutorial 1\n date = Dates(\"15-12-2016\")\n date_from_birthday = \"15/12/2016\"\n date_with_dash = Dates.to_dash_date(date_from_birthday)\n\n if date.get_date() == date_with_dash:\n print(\"Equal\")\n else:\n print(\"Unequal\")\n\n # tutorial 2\n date2 = Dates(\"15-12-2016\")\n date_with_slash = DatesWithSlashes(\"15/12/2016\")\n\n if date2.get_date() == date_with_slash.get_date():\n print(\"Equal\")\n else:\n print(\"Unequal\")\n\n\nif __name__ == \"__main__\":\n main()\n"},"size":{"kind":"number","value":1379,"string":"1,379"}}},{"rowIdx":1397,"cells":{"max_stars_repo_path":{"kind":"string","value":"Featurize/CalcuDescriptors.py"},"max_stars_repo_name":{"kind":"string","value":"Saoge123/ccgnet"},"max_stars_count":{"kind":"number","value":17,"string":"17"},"id":{"kind":"string","value":"2023931"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem import Descriptors, rdFreeSASA\nimport pybel\nimport openbabel as ob\nimport numpy as np\nimport math\n\n\n'''\nfrom rdkit.Chem import Lipinski, MolSurf, PeriodicTable\nelements_set = ['H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar','Br','I']\npt = Chem.GetPeriodicTable()\nRvdw = {}\nfor i in elements_set:\n Rvdw[i] = pt.GetRvdw(i)\n'''\n\nRvdw = {'H': 1.2,'He': 1.4,'Li': 1.82,'Be': 1.7,'B': 2.08,'C': 1.95,'N': 1.85,\n 'O': 1.7,'F': 1.73,'Ne': 1.54,'Na': 2.27,'Mg': 1.73,'Al': 2.05,'Si': 2.1,\n 'P': 2.08,'S': 2.0,'Cl': 1.97,'Ar': 1.88,'Br': 2.1,'I': 2.15}\n\n\ndef coordinate_adjusting(mol):\n '''\n The algorithm refers from:http://sobereva.com/426\n '''\n mat_coor = [[0,1],[0,2],[1,2]]\n diag_coor = [[1,2],[0,2],[0,1]]\n atoms = mol.GetAtoms()\n atom_coors = np.array([mol.GetConformer().GetAtomPosition(i.GetIdx()) for i in atoms])\n wts = np.array([i.GetMass() for i in atoms])\n wts = np.expand_dims(wts,axis=1)\n diag_val = [np.sum(wts*atom_coors[:,i]**2) for i in diag_coor]\n mat_val = [np.sum(wts*np.prod(atom_coors[:,i],axis=1))*-1 for i in mat_coor]\n imt = np.zeros([3,3])\n for i in range(3):\n imt[i,i] = diag_val[i]\n pos = mat_coor[i]\n imt[pos[0],pos[1]] = mat_val[i]\n imt[pos[1],pos[0]] = mat_val[i]\n eig_v,eig_m = np.linalg.eig(imt)\n am = atom_coors.dot(eig_m)\n return am\n\ndef MaxMinValue(array):\n max_idx, max_val = np.argmax(array), np.max(array)\n min_idx, min_val = np.argmin(array), np.min(array)\n return int(max_idx), max_val, int(min_idx), min_val\n\ndef CalcuAxisLenth(mol):\n coors = coordinate_adjusting(mol)\n axis = []\n for i in range(3):\n max_idx, max_val, min_idx, min_val = MaxMinValue(coors[:,i])\n max_ = max_val + Rvdw[mol.GetAtomWithIdx(max_idx).GetSymbol()]\n min_ = min_val - Rvdw[mol.GetAtomWithIdx(min_idx).GetSymbol()]\n axis.append(max_-min_)\n S, M, L = sorted(axis)\n return S, M, L\n\ndef Ratio_S_M_L(mol):\n S, M, L = CalcuAxisLenth(mol)\n S_L = S/L\n M_L = M/L\n S_M = S/M\n return S_L, M_L, S_M, S\n\ndef GlobularityAndFrTPSA(coformer, includeSandP=1):\n # Calculate globularity: surface of a sphere with the same volume as the molecule / Area\n # FrTPSA = TPSA / SASA\n mol_vol = coformer.csd_mol.molecular_volume\n r_sphere = math.pow(mol_vol*0.75/math.pi, 1.0/3)\n area_sphere = 4*math.pi*r_sphere*r_sphere\n radii = rdFreeSASA.classifyAtoms(coformer.rdkit_mol)\n sasa = rdFreeSASA.CalcSASA(coformer.rdkit_mol, radii)\n globularity = area_sphere / sasa\n FrTPSA = Descriptors.TPSA(coformer.rdkit_mol, includeSandP=includeSandP) / sasa\n return globularity, FrTPSA\n\ndef FractionNO(mol):\n return Descriptors.NOCount(mol) / float(mol.GetNumHeavyAtoms())\n\ndef FractionAromaticAtoms(mol):\n return len(mol.GetAromaticAtoms()) / float(mol.GetNumHeavyAtoms())\n\ndef NumHAcceptorsAndDonors(mol):\n return Descriptors.NumHDonors(mol), Descriptors.NumHAcceptors(mol)\n\ndef RotatableBondNumber(mol):\n mol = Chem.RemoveHs(mol) \n return Descriptors.NumRotatableBonds(mol) #/ float(mol.GetNumBonds())\n\n# Using openbabel for calculating dipole moment\ndef DipoleMoment(mol, charge_model='eem2015bm'):\n mol_block = Chem.MolToMolBlock(mol)\n ob_mol = pybel.readstring('mol', mol_block)\n # We choose 'eem2015bm' to calculate dipole\n # Using 'obabel -L charges' can get a list of charge models\n dipole = ob.OBChargeModel_FindType(charge_model).GetDipoleMoment(ob_mol.OBMol)\n dipole_moment = math.sqrt(dipole.GetX()**2+dipole.GetY()**2+dipole.GetZ()**2)\n return dipole_moment\n\ndef CalcuDescriptors(coformer, includeSandP=1, charge_model='eem2015bm'):\n rdkit_mol = coformer.rdkit_mol\n S_L, M_L, S_M, S = Ratio_S_M_L(rdkit_mol)\n globularity, FrTPSA = GlobularityAndFrTPSA(coformer, includeSandP=includeSandP)\n Fr_NO = FractionNO(rdkit_mol)\n Fr_AromaticAtoms = FractionAromaticAtoms(rdkit_mol)\n HBA,HBD = NumHAcceptorsAndDonors(rdkit_mol)\n RBN = RotatableBondNumber(rdkit_mol)\n dipole_moment = DipoleMoment(rdkit_mol, charge_model=charge_model)\n return np.array([S_L, M_L, S_M, S, globularity, FrTPSA, Fr_NO, Fr_AromaticAtoms, HBA, HBD, RBN, dipole_moment])"},"size":{"kind":"number","value":4304,"string":"4,304"}}},{"rowIdx":1398,"cells":{"max_stars_repo_path":{"kind":"string","value":"problem_solving_py/set_union/set_union.py"},"max_stars_repo_name":{"kind":"string","value":"RootProgrammer/Python"},"max_stars_count":{"kind":"number","value":1,"string":"1"},"id":{"kind":"string","value":"2023842"},"content":{"kind":"string","value":"if __name__ == \"__main__\":\r\n x, y = [set(input().split()) for _ in range(4)][1::2]\r\n print(len(x | y))\r\n"},"size":{"kind":"number","value":110,"string":"110"}}},{"rowIdx":1399,"cells":{"max_stars_repo_path":{"kind":"string","value":"resources/routing-options.py"},"max_stars_repo_name":{"kind":"string","value":"ttsubo/netconf_heat"},"max_stars_count":{"kind":"number","value":0,"string":"0"},"id":{"kind":"string","value":"2024680"},"content":{"kind":"string","value":"# Copyright (c) 2016 ttsubo\n# This software is released under the MIT License.\n# http://opensource.org/licenses/mit-license.php\n\nimport uuid\n\nfrom heat.engine import attributes\nfrom heat.engine import constraints\nfrom heat.engine import properties\nfrom heat.common.i18n import _\nfrom ncclient.xml_ import *\nfrom oslo_log import log as logging\nfrom netconf import Netconf\n\nLOG = logging.getLogger(__name__)\n\nclass RoutingOptionsResource(Netconf):\n\n PROPERTIES = (\n ROUTER_IPADDR, USERNAME, PASSWORD, PORT, STATIC_ROUTE, NEXT_HOP, ROUTER_ID, MY_AS\n ) = (\n 'router_ipaddr', 'username', 'password', 'port', 'static_route', 'next_hop', 'router_id', 'my_as'\n )\n\n ATTRIBUTES = (\n CONFIG_ROUTING_OPTIONS\n ) = (\n 'config_routing_options'\n )\n\n properties_schema = {\n ROUTER_IPADDR: properties.Schema(\n properties.Schema.STRING,\n _('Ip address of the router.'),\n required=True,\n ),\n USERNAME: properties.Schema(\n properties.Schema.STRING,\n _('User name to log on to device.'),\n required=True,\n update_allowed=True\n ),\n PASSWORD: properties.Schema(\n properties.Schema.STRING,\n _('Users password.'),\n required=True,\n update_allowed=True\n ),\n PORT: properties.Schema(\n properties.Schema.INTEGER,\n _('Port of the ssh connection.'),\n default=830,\n update_allowed=True\n ),\n STATIC_ROUTE: properties.Schema(\n properties.Schema.STRING,\n _('prefix for static route.'),\n default=830,\n update_allowed=True\n ),\n NEXT_HOP: properties.Schema(\n properties.Schema.STRING,\n _('nexthop address.'),\n default=830,\n update_allowed=True\n ),\n ROUTER_ID: properties.Schema(\n properties.Schema.STRING,\n _('router id.'),\n required=True,\n update_allowed=True\n ),\n MY_AS: properties.Schema(\n properties.Schema.STRING,\n _('AS number for myself.'),\n required=True,\n update_allowed=True\n ),\n }\n\n attributes_schema = {\n CONFIG_ROUTING_OPTIONS: attributes.Schema(\n _(\"config_routing_options attributes.\"),\n type=attributes.Schema.MAP\n ),\n }\n\n def config_routing_options(self):\n static_route = self.properties[self.STATIC_ROUTE]\n next_hop = self.properties[self.NEXT_HOP]\n router_id = self.properties[self.ROUTER_ID]\n my_as = self.properties[self.MY_AS]\n\n routing_options = \"\"\"\n routing-options {\n static {\n route %s next-hop %s;\n }\n router-id %s;\n autonomous-system %s;\n }\n \"\"\" % (static_route, next_hop, router_id, my_as)\n return routing_options\n\n def delete_routing_options(self):\n routing_options = \"\"\"\n \n \n \n \n none\n \n \n \n \n \n \n \"\"\"\n return routing_options\n\n def handle_create(self):\n config = self.config_routing_options()\n conn = self.connect()\n self.execute_netconf(conn, config, \"create\", \"routing_options\")\n self.resource_id_set(str(uuid.uuid4()))\n\n def handle_delete(self):\n config = self.delete_routing_options()\n conn = self.connect()\n self.execute_netconf(conn, config, \"delete\", \"routing_options\")\n\n def _show_resource(self):\n result = {}\n conn = self.connect()\n\n config_filter = new_ele('configuration')\n sub_ele(config_filter, 'routing-options')\n response = conn.get_configuration(format='text', filter=config_filter)\n response.xpath('configuration-text')[0].text\n LOG.info(\"response=[%s]\"% response.xpath('configuration-text')[0].text)\n result[\"config_routing_options\"] = response.xpath('configuration-text')[0].text\n return result\n\ndef resource_mapping():\n return {\n 'OS::Netconf::RoutingOptionsResource': RoutingOptionsResource,\n }\n"},"size":{"kind":"number","value":4422,"string":"4,422"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":13,"numItemsPerPage":100,"numTotalItems":129320,"offset":1300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjU5MDkwNywic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9zdGFyY29kZXJkYXRhX3B5X3Ntb2wiLCJleHAiOjE3NTY1OTQ1MDcsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.GhKH8kcbRGKyCFujOVorjO-zO9-_cmtJVBoB1zkP72X37nniGjpawdUDnFiTZRlQjoiiCB1uIaGYhmlaoiqhCA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
max_stars_repo_path
stringlengths
4
182
max_stars_repo_name
stringlengths
6
116
max_stars_count
int64
0
191k
id
stringlengths
7
7
content
stringlengths
100
10k
size
int64
100
10k
filters/black_and_white.py
borisboychev/Image-Filters
0
2024760
import cv2 class BlackAndWhite: def __init__(self, capture_device=cv2.VideoCapture(0)): self.capture_device = capture_device def make_1080p(self): self.capture_device.set(3, 1920) self.capture_device.set(4, 1080) def execute_filter(self): self.make_1080p() while True: if cv2.waitKey(20) & 0xFF == ord('q'): break ret, frame = self.capture_device.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('Black&White', gray) self.capture_device.release() cv2.destroyAllWindows()
627
api/serializers/news_heading_serializer.py
pokotsun/kyutechAppServer2018
4
2024377
# coding: utf-8 from rest_framework import serializers from ..models import NewsHeading class NewsHeadingSerializer(serializers.ModelSerializer): class Meta: model = NewsHeading fields = ( 'news_heading_code', 'short_name', 'name', 'color_code', 'updated_at')
324
examples/minitwit/ses.py
txdywy/flask
2
2024089
from config import SMTP_SETTINGS import smtplib import email.utils from email.mime.text import MIMEText # Prompt the user for connection info to_email = raw_input('Recipient: ') servername = SMTP_SETTINGS['smtp_server'] username = SMTP_SETTINGS['smtp_user'] password = SMTP_SETTINGS['smtp_passwd'] support = '<EMAIL>' # Create the message msg = MIMEText('Test message from PyMOTW.') msg.set_unixfrom('author') msg['To'] = email.utils.formataddr(('Recipient', to_email)) msg['From'] = email.utils.formataddr(('Author', support)) msg['Subject'] = 'Test from PyMOTW' server = smtplib.SMTP(servername) try: server.set_debuglevel(True) # identify ourselves, prompting server for supported features server.ehlo() # If we can encrypt this session, do it if server.has_extn('STARTTLS'): server.starttls() server.ehlo() # re-identify ourselves over TLS connection server.login(username, password) server.sendmail(support, [to_email], msg.as_string()) finally: server.quit()
1,019
scikit-learn-lambda/setup.py
alisye/scikit-learn-lambda
41
2025122
from setuptools import find_packages, setup setup( name="scikit-learn-lambda", version="0.1.0", author="Model Zoo, Inc.", install_requires=["scikit-learn", "joblib", "boto3"], packages=find_packages(), description="A handler for scikit learn models on AWS Lambda", author_email="<EMAIL>", license="Apache 2.0", url="https://www.modelzoo.dev", classifiers=[ "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: Implementation :: PyPy", ], test_suite="tests", python_requires=">=3.6", )
721
env/lib/python3.6/site-packages/pytests/test_inputtextmessagecontent.py
rogerscristo/BotFWD
0
2024424
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # <NAME> <<EMAIL>> # # 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 3 of the License, or # (at your option) 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, see [http://www.gnu.org/licenses/]. import json import pytest from telegram import InputTextMessageContent, InputMessageContent, ParseMode @pytest.fixture() def json_dict(): return { 'parse_mode': TestInputTextMessageContent.parse_mode, 'message_text': TestInputTextMessageContent.message_text, 'disable_web_page_preview': TestInputTextMessageContent.disable_web_page_preview, } @pytest.fixture(scope='class') def input_text_message_content(): return InputTextMessageContent(TestInputTextMessageContent.message_text, parse_mode=TestInputTextMessageContent.parse_mode, disable_web_page_preview=TestInputTextMessageContent.disable_web_page_preview) class TestInputTextMessageContent: message_text = '*message text*' parse_mode = ParseMode.MARKDOWN disable_web_page_preview = True def test_de_json(self, json_dict, bot): input_text_message_content_json = InputTextMessageContent.de_json(json_dict, bot) assert input_text_message_content_json.parse_mode == self.parse_mode assert input_text_message_content_json.message_text == self.message_text assert input_text_message_content_json.disable_web_page_preview == \ self.disable_web_page_preview def test_input_text_message_content_json_de_json_factory(self, json_dict, bot): input_text_message_content_json = InputMessageContent.de_json(json_dict, bot) assert isinstance(input_text_message_content_json, InputTextMessageContent) def test_de_json_factory_without_required_args(self, json_dict, bot): del (json_dict['message_text']) input_text_message_content_json = InputMessageContent.de_json(json_dict, bot) assert input_text_message_content_json is None def test_to_json(self, input_text_message_content): json.loads(input_text_message_content.to_json()) def test_to_dict(self, input_text_message_content): input_text_message_content_dict = input_text_message_content.to_dict() assert isinstance(input_text_message_content_dict, dict) assert input_text_message_content_dict['message_text'] == \ input_text_message_content.message_text assert input_text_message_content_dict['parse_mode'] == \ input_text_message_content.parse_mode assert input_text_message_content_dict['disable_web_page_preview'] == \ input_text_message_content.disable_web_page_preview
3,356
Ogrenciler/Haydar/soru5.py
ProEgitim/Python-Dersleri-BEM
1
2024714
ad=str (input("Ad giriniz:")) soyad=str (input("Soyad giriniz:")) numara=int (input("Numaranızı Giriniz:")) print("Adınız:",ad,"\n""Soyadınız",soyad,"\n""Numaranız",numara)
182
ege_problem_solution/t23/n129.py
ablearthy/ege2021kp-problem-solution
0
2022769
""" (<NAME>) Исполнитель ЛенивыйСчетовод преобразует число, записанное на экране. У исполнителя есть три команды, которым присвоены номера: 1. Прибавить 2 2. Прибавить 3 3. Дописать к числу справа 1 Первая команда увеличивает число на 2, вторая – на 3, третья – приписывает к текущему значению цифру 1 (например, для 10 результатом выполнения данной команды будет 101). Сколько существует таких программ, которые исходное число 3 преобразуют в число 25, при этом траектория вычислений содержит число 12? """ from typing import List def solve(src: int, dst: int, points: List[int]): commands = [lambda x: x + 2, lambda x: x + 3, lambda x: 10 * x + 1] dp = [[] for _ in range(dst + 1)] dp[src] = [[]] for i in range(src, dst + 1): precalculated_values = [c(i) for c in commands] for cmd in dp[i]: for k, v in enumerate(precalculated_values): if v > dst: continue dp[v].append(cmd + [k]) out = dp[dst] counter = 0 for sol in out: for point in points: counter += sum([sol[: len(x)] == x for x in dp[point]]) return counter
1,165
nodeconductor/core/utils.py
p-p-m/nodeconductor
0
2024910
import time import calendar import requests from collections import OrderedDict from datetime import datetime from datetime import timedelta from operator import itemgetter from django.utils import timezone from django.utils.crypto import get_random_string from django.core.urlresolvers import reverse from rest_framework.authtoken.models import Token def sort_dict(unsorted_dict): """ Return a OrderedDict ordered by key names from the :unsorted_dict: """ sorted_dict = OrderedDict() # sort items before inserting them into a dict for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)): sorted_dict[key] = value return sorted_dict def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp, end_timestamp, average=False): """ Format time_and_value_list to time segments Parameters ---------- time_and_value_list: list of tuples Have to be sorted by time Example: [(time, value), (time, value) ...] segments_count: integer How many segments will be in result Returns ------- List of dictionaries Example: [{'from': time1, 'to': time2, 'value': sum_of_values_from_time1_to_time2}, ...] """ segment_list = [] time_step = (end_timestamp - start_timestamp) / segments_count for i in range(segments_count): segment_start_timestamp = start_timestamp + time_step * i segment_end_timestamp = segment_start_timestamp + time_step value_list = [ value for time, value in time_and_value_list if time >= segment_start_timestamp and time < segment_end_timestamp] segment_value = sum(value_list) if average and len(value_list) != 0: segment_value /= len(value_list) segment_list.append({ 'from': segment_start_timestamp, 'to': segment_end_timestamp, 'value': segment_value, }) return segment_list def datetime_to_timestamp(datetime): return int(time.mktime(datetime.timetuple())) def timestamp_to_datetime(timestamp, replace_tz=True): dt = datetime.fromtimestamp(int(timestamp)) if replace_tz: dt = dt.replace(tzinfo=timezone.get_current_timezone()) return dt def timeshift(**kwargs): return timezone.now().replace(microsecond=0) + timedelta(**kwargs) def hours_in_month(month=None, year=None): now = datetime.now() if not month: month = now.month if not year: year = now.year days_in_month = calendar.monthrange(year, month)[1] return 24 * days_in_month def request_api(request, url_or_view_name, method='GET', data=None, params=None, verify=False): """ Make a request to API internally. Use 'request.user' for authentication. Return a JSON response. """ token = Token.objects.get(user=request.user) method = getattr(requests, method.lower()) if url_or_view_name.startswith('http'): url = url_or_view_name else: url = request.build_absolute_uri(reverse(url_or_view_name)) response = method(url, headers={'Authorization': 'Token %s' % token.key}, data=data, params=params, verify=verify) result = type('Result', (object,), {}) try: result.data = response.json() except ValueError: result.data = None result.total = int(response.headers.get('X-Result-Count', 0)) result.success = response.status_code in (200, 201) return result def pwgen(pw_len=8): """ Generate a random password with the given length. Allowed chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789')
3,939
scripts/TestHarness/testers/RAVENImageDiff.py
FlanFlanagan/raven
159
2023606
# Copyright 2017 Battelle Energy Alliance, LLC # # 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. """ This tests images against a expected image. """ import os import sys try: from imageio import imread correctImport = True except ImportError: correctImport = False from Tester import Differ class ImageDiff: """ ImageDiff is used for comparing two image files. """ def __init__(self, outFiles, goldFiles, relativeError=1e-10, zeroThreshold=None): """ Create an ImageDiff class @ In, outFiles, the files to be compared. @ In, goldFiles, the files to be compared to the outFiles. @ In, relativeError, float, optional, relative error @ In, zeroThreshold, float, optional, if a number is less equal then abs(zeroThreshold), it will be considered 0 @ Out, None. """ #assert len(outFiles) == len(goldFiles) self.__out_files = outFiles self.__gold_files = goldFiles self.__message = "" self.__same = True self.__rel_err = relativeError self.__zero_threshold = float(zeroThreshold) if zeroThreshold is not None else 0.0 def diff(self): """ Run the comparison. returns (same,messages) where same is true if the image files are the same, and messages is a string with all the differences. In, None Out, None """ # read in files filesRead = False for testFilename, goldFilename in zip(self.__out_files, self.__gold_files): if not os.path.exists(testFilename): self.__same = False self.__message += 'Test file does not exist: '+testFilename elif not os.path.exists(goldFilename): self.__same = False self.__message += 'Gold file does not exist: '+goldFilename else: filesRead = True #read in files if filesRead: if not correctImport: self.__message += 'ImageDiff cannot run without imageio'+\ ' that is an optional RAVEN library. Pleaase install it.' self.__same = False return(self.__same, self.__message) try: # RAK - The original line... # testImage = imread(open(testFilename,'r')) # ...didn't work on Windows Python because it couldn't sense the file type testImage = imread(testFilename) except IOError: self.__message += 'Unrecognized file type for test image in imageio.imread: '+testFilename filesRead = False return (False, self.__message) try: # RAK - The original line... # goldImage = imread(open(goldFilename,'r')) # ...didn't work on Windows Python because it couldn't sense the file type goldImage = imread(goldFilename) except IOError: filesRead = False self.__message += 'Unrecognized file type for test image in imageio.imread: '+goldFilename return (False, self.__message) #first check dimensionality if goldImage.shape != testImage.shape: self.__message += 'Gold and test image are not the same shape: '+\ str(goldImage.shape)+', '+str(testImage.shape) self.__same = False return (self.__same, self.__message) #pixelwise comparison #TODO in the future we can add greyscale, normalized coloring, etc. # For now just do raw comparison of right/wrong pixels diff = goldImage - testImage onlyDiffs = diff[abs(diff) > self.__zero_threshold] pctNumDiff = onlyDiffs.size/float(diff.size) if pctNumDiff > self.__rel_err: self.__message += 'Difference between images is too large:'+\ ' %2.2f pct (allowable: %2.2f)' %(100*pctNumDiff,\ 100*self.__rel_err) self.__same = False return (self.__same, self.__message) class ImageDiffer(Differ): """ This is the class to use for handling the parameters block. """ @staticmethod def get_valid_params(): """ Returns the valid parameters for this class. @ In, None @ Out, params, _ValidParameters, return the parameters. """ params = Differ.get_valid_params() params.add_param('rel_err', '', 'Relative Error for image files') params.add_param('zero_threshold', sys.float_info.min*4.0, 'it represents the value below which a float is '+ 'considered zero in the pixel comparison') return params def __init__(self, name, params, testDir): """ Initializer for the class. Takes a String name and a dictionary params @ In, name, string, name of the test. @ In, params, dictionary, parameters for the class @ In, testDir, string, path to the test. @ Out, None. """ Differ.__init__(self, name, params, testDir) self.__zero_threshold = self.specs['zero_threshold'] if len(self.specs['rel_err']) > 0: self.__rel_err = float(self.specs['rel_err']) else: self.__rel_err = 1e-10 def check_output(self): """ Checks that the output matches the gold. returns (same, message) where same is true if the test passes, or false if the test failes. message should gives a human readable explaination of the differences. @ In, None @ Out, (same, message), same is true if the tests passes. """ imageFiles = self._get_test_files() goldFiles = self._get_gold_files() imageDiff = ImageDiff(imageFiles, goldFiles, relativeError=self.__rel_err, zeroThreshold=self.__zero_threshold) return imageDiff.diff()
6,203
src/caciolai-SRL/data/datasets.py
caciolai/Semantic-Role-Labeling-exploiting-Contextualized-Embeddings
0
2025059
from typing import * import os import json import torch from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence import tqdm def load_data(folder: str, fname: str) -> List[Dict]: """ Loads the data in a suitable format. Args: folder: The folder of the dataset fname: The filename of the dataset Returns: A list of dictionaries (json-like) """ path = os.path.join(folder, fname) with open(path, "r") as f: data = json.load(f) data = [(k, v) for k, v in data.items()] data = [v for k, v in sorted(data, key=lambda item: item[0])] # converting predicate index for role to int for elem in data: elem["roles"] = {int(k): v for k, v in elem["roles"].items()} return data class CustomDataset(Dataset): def __init__(self, sentences: List[Dict[str, Any]]): """ Custom dataset class for task 34 (argument identification, argument classification) """ self.data = self._preprocess_data(sentences) self.bert_embeddings = None self.encoded_data = None def _preprocess_data(self, sentences: List[dict]) -> List[dict]: """ Preprocess a list of sentences from a raw dataset. Args: sentences: list of sentences to process Returns: processed data. """ data = [] for i, s in enumerate(sentences): predicates = [(j, p) for j, p in enumerate(s["predicates"]) if p != "_"] item = { "words": s["words"], "predicates": predicates, "roles": s["roles"], "lemmas": s["lemmas"], "pos_tags": s["pos_tags"] } data.append(item) return data # def bert_embed_data(self, bert_embedder): # """ # Employs a BERT embedder object to build the BERT embeddings of the sentences # in the dataset, then stored to be used in encoding later. # Args: # bert_embedder: see BERTEmbedder class. # """ # self.bert_embeddings = [] # for item in tqdm(self.data, desc="Embedding sentences"): # sent = item["words"] # embedded_sentence = bert_embedder.embed_sentences(sent) # self.bert_embeddings.append(embedded_sentence) def encode_data(self, srl_vocab, pf_vocab, words_vocab, lemmas_vocab, pos_vocab, bert_embeddings): """ Encodes data to be processed by the collate function that expects tensors. Args: srl_vocab, ..., pos_vocab: vocabularies for semantic roles predicate frames words lemmas POS tags bert_embeddings: BERT embeddings for the sentences in the dataset """ self.encoded_data = [] self.encoding_mapping = [] encoding_idx = 0 for i, item in tqdm(enumerate(self.data), desc="Encoding dataset", total=len(self.data)): # unpack preprocessed data preds = item["predicates"] roles = item["roles"] words = item["words"] lemmas = item["lemmas"] pos_tags = item["pos_tags"] bert_embedded_sentence = bert_embeddings[i] sentence_len = bert_embedded_sentence.shape[0] if len(preds) > 0: # duplicate multi-predicate sentences so as to have each sample # only containing one predicate for j, pred in preds: # idx for predicate pred_frame = pf_vocab[pred] # build a 'predicate indicator vector' to make the model aware of the position of the predicate # in the sentence duplicate under consideration # (seq_len x bert_dim) pred_indicator_vector = torch.zeros(sentence_len, 1).to(bert_embedded_sentence.device) pred_indicator_vector[j, 0] = 1 encoded_item = { "pred_frame": pred_frame, "pred_indicator_vector": pred_indicator_vector, "srl": torch.LongTensor(srl_vocab.encode(roles[j])), "word": torch.LongTensor(words_vocab.encode(words)), "lemma": torch.LongTensor(lemmas_vocab.encode(lemmas)), "pos_tag": torch.LongTensor(pos_vocab.encode(pos_tags)), "bert_sent": bert_embedded_sentence, "pred_pos": j, # position of the predicate in the sentence } self.encoded_data.append(encoded_item) else: # treat separately sentences without predicates # (seq_len x bert_dim) pred_indicator_vector = torch.zeros(sentence_len, 1).to(bert_embedded_sentence.device) blank_roles = ["_" for _ in range(sentence_len)] pred_frame = pf_vocab['_'] encoded_item = { "pred_frame": pred_frame, "pred_indicator_vector": pred_indicator_vector, "srl": torch.LongTensor(srl_vocab.encode(blank_roles)), "word": torch.LongTensor(words_vocab.encode(words)), "lemma": torch.LongTensor(lemmas_vocab.encode(lemmas)), "pos_tag": torch.LongTensor(pos_vocab.encode(pos_tags)), "bert_sent": bert_embedded_sentence, "pred_pos": -1, } self.encoded_data.append(encoded_item) def get_raw_element(self, idx): return self.data[idx] def __len__(self): if self.encoded_data is None: return len(self.data) else: return len(self.encoded_data) def __getitem__(self, idx): assert self.encoded_data is not None return self.encoded_data[idx] def collate(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]: # collecting data pred_indicator_vectors = [sample["pred_indicator_vector"] for sample in batch] srl_labels = [sample["srl"] for sample in batch] words = [sample["word"] for sample in batch] lemmas = [sample["lemma"] for sample in batch] pos_tags = [sample["pos_tag"] for sample in batch] bert_sents = [sample["bert_sent"] for sample in batch] # tensorizing lengths = torch.LongTensor([sample["word"].shape[0] for sample in batch]).view(-1) pred_frames = torch.LongTensor([sample["pred_frame"] for sample in batch]).view(-1) preds_pos = torch.LongTensor([max(sample["pred_pos"], 0) for sample in batch]).view(-1) pred_mask = torch.LongTensor([1 if sample["pred_pos"] >= 0 else 0 for sample in batch]).view(-1) # padding pred_indicator_vectors = pad_sequence(pred_indicator_vectors, batch_first=True, padding_value=0) srl_labels = pad_sequence(srl_labels, batch_first=True, padding_value=0) words = pad_sequence(words, batch_first=True, padding_value=0) lemmas = pad_sequence(lemmas, batch_first=True, padding_value=0) pos_tags = pad_sequence(pos_tags, batch_first=True, padding_value=0) bert_sents = pad_sequence(bert_sents, batch_first=True, padding_value=0) bert_sents = torch.cat((bert_sents, pred_indicator_vectors), dim=-1) return { "length": lengths, "srl": srl_labels, "pred_frame": pred_frames, "word": words, "lemma": lemmas, "pos_tag": pos_tags, "bert_sent": bert_sents, "pred_pos": preds_pos, "pred_mask": pred_mask }
8,035
main.py
macinnisrr/ulauncher-journal
0
2024916
import os from datetime import datetime from ulauncher.api.client.EventListener import EventListener from ulauncher.api.client.Extension import Extension from ulauncher.api.shared.action.ExtensionCustomAction import \ ExtensionCustomAction from ulauncher.api.shared.action.RenderResultListAction import \ RenderResultListAction from ulauncher.api.shared.event import ItemEnterEvent, KeywordQueryEvent from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem class JournalExtension(Extension): def __init__(self): super().__init__() self.subscribe(KeywordQueryEvent, KeywordQueryEventListener()) self.subscribe(ItemEnterEvent, ItemEnterEventListener()) class ItemEnterEventListener(EventListener): def on_event(self, event, extension): data = event.get_data() journal_path = extension.preferences['journal_path'] full_path = os.path.expanduser(journal_path) header = data['header'] content = data['content'] with open(full_path, "a") as f: f.write(f'{header}\n{content}\n\n') class KeywordQueryEventListener(EventListener): def on_event(self, event, extension): datetime_format = { 'YYYY.MM.DD.HH.MM.SS.NNN' : '%Y.%m.%d.%H.%M.%S.%3N.%Z', # '2021.07.10.02.20.36.333' 'DD.MM.YYYY HH:MM': '%d.%m.%Y %H:%M', # '17.05.2020 14:46' 'DD-MM-YYYY HH:MM': '%d-%m-%Y %H:%M', # '17-05-2020 14:46' 'MM-DD-YYYY HH:MM': '%m-%d-%Y %H:%M', # '05-17-2020 14:46' 'MM/DD/YYYY HH:MM': '%m/%d/%Y %H:%M', # '05/17/2020 14:46' }[extension.preferences['journal_datetime_format']] data = { 'header': datetime.now().strftime(datetime_format), 'content': event.get_argument() or '' } item = ExtensionResultItem(icon='images/icon.png', name=data['header'], description=data['content'], on_enter=ExtensionCustomAction(data)) return RenderResultListAction([item]) if __name__ == '__main__': JournalExtension().run()
2,165
src/word_segmentation/beamsearch/model_lm.py
ruanchaves/word_segmentation
1
2022904
class ModelLM(object): def __init__(self, model_name_or_path=None, model_type=None, device=None, gpu_batch_size=None): self.gpu_batch_size = gpu_batch_size if model_type == 'gpt2': from word_segmentation.beamsearch.gpt2_lm import GPT2LM self.model = GPT2LM(model_name_or_path, device=device, gpu_batch_size=gpu_batch_size) elif model_type == 'bert': from word_segmentation.beamsearch.bert_lm import BertLM self.model = BertLM(model_name_or_path)
531
personal_site/auth/forms.py
gorel/personal-site
0
2022868
import flask_wtf import wtforms from personal_site import constants, db from personal_site.auth import models class RegisterForm(flask_wtf.FlaskForm): username = wtforms.TextField( "Username", validators=[ wtforms.validators.DataRequired(), wtforms.validators.Length(max=constants.USERNAME_MAX_LEN), ], render_kw={"class": "form-control", "autocomplete": "off"}, ) email = wtforms.TextField( "Email", validators=[ wtforms.validators.DataRequired(), wtforms.validators.Email(), ], ) password = wtforms.PasswordField( "Password", validators=[ wtforms.validators.InputRequired(), wtforms.validators.Length(min=constants.PASSWORD_MIN_LEN), wtforms.validators.EqualTo( "confirm_password", message="Passwords must match", ), ], ) confirm_password = wtforms.PasswordField("<PASSWORD>") remember = wtforms.BooleanField("Remember me?") recaptcha = flask_wtf.RecaptchaField() submit = wtforms.SubmitField("Submit") def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.user = None self.show_forgot = False def validate(self): if not super(RegisterForm, self).validate(): return False # Check if the user has already registered before user = models.User.get_by_email(self.email.data) if user is not None: if user.check_password(self.password.data): # Account exists and passwords match self.user = user return True else: self.email.errors.append("Email already registered. Did you forget your password?") self.show_forgot = True return False # Create new user self.user = models.User( username=self.username.data, email=self.email.data, password=<PASSWORD>, ) db.session.add(self.user) db.session.commit() return True class LoginForm(flask_wtf.FlaskForm): email = wtforms.TextField( "Email", validators=[ wtforms.validators.DataRequired(), wtforms.validators.Email(), ], ) password = wtforms.PasswordField( "Password", validators=[ wtforms.validators.InputRequired(), ], ) remember = wtforms.BooleanField("Remember Me?") submit = wtforms.SubmitField("Submit") def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): if not super(LoginForm, self).validate(): return False user = models.User.get_by_email(self.email.data) if user is None: self.email.errors.append("No account with that email found") return False if not user.check_password(self.password.data): self.password.errors.append("Incorrect password") return False self.user = user return True class ForgotPasswordForm(flask_wtf.FlaskForm): email = wtforms.TextField( "Email", validators=[ wtforms.validators.DataRequired(), wtforms.validators.Email(), ], ) submit = wtforms.SubmitField("Send email") def __init__(self, *args, **kwargs): super(ForgotPasswordForm, self).__init__(*args, **kwargs) self.user = None def validate(self): if not super(ForgotPasswordForm, self).validate(): return False user = models.User.get_by_email(self.email.data) if user is None: self.email.errors.append("No account with that email found") return False self.user = user return True class SetNewPasswordForm(flask_wtf.FlaskForm): password = wtforms.PasswordField( "Password", validators=[ wtforms.validators.InputRequired(), wtforms.validators.Length(min=8), wtforms.validators.EqualTo( "confirm_password", message="Passwords must match", ), ], ) confirm_password = wtforms.PasswordField("Confirm Password") submit = wtforms.SubmitField("Send email") def __init__(self, user, *args, **kwargs): super(SetNewPasswordForm, self).__init__(*args, **kwargs) self.user = user def validate(self): if not super(SetNewPasswordForm, self).validate(): return False self.user.set_password(self.password.data) db.session.commit() return True
4,806
tests/model/test_checker.py
bedia-tv/lippy
0
2024084
from unittest import TestCase, mock from os import makedirs from io import StringIO from imageio import get_reader from torchvision.transforms.functional import to_tensor from src.model.model_tools.checker import check_video, check_vidframes from shutil import rmtree class TestChecker(TestCase): @classmethod def setUpClass(cls): makedirs('./dataset_test/') cls.DIR = './dataset_test/' cls.EMPTY_FILE = cls.DIR+'empty.mp4' cls.PADDING = 11 VALUE = [1]*11 @classmethod def tearDownClass(cls): rmtree(cls.DIR) @mock.patch('src.model.model_tools.checker.to_tensor', return_value=VALUE[1]) @mock.patch('src.model.model_tools.checker.get_reader', return_value=VALUE) def test_check(self, mock_get_reader, mock_to_tensor): self.assertTrue(check_video(self.EMPTY_FILE, 11)) self.assertFalse(check_video(self.EMPTY_FILE, 12)) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('src.model.model_tools.checker.to_tensor', return_value=VALUE[1]) @mock.patch('src.model.model_tools.checker.get_reader', return_value=VALUE) def test_output_false(self, mock_get_reader, mock_to_tensor, mock_stdout): check_video(self.EMPTY_FILE, 12) expected_output_false = f'{self.EMPTY_FILE} is too short to be processed\n' self.assertEqual(mock_stdout.getvalue(), expected_output_false) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('src.model.model_tools.checker.to_tensor', return_value=VALUE[1]) @mock.patch('src.model.model_tools.checker.get_reader', return_value=VALUE) def test_output_true(self, mock_get_reader, mock_to_tensor, mock_stdout): check_vidframes(self.DIR, self.DIR, self.PADDING) expected_output_true = f'All videos can be processed\n' self.assertEqual(mock_stdout.getvalue(), expected_output_true)
1,891
src/tentaclio/credentials/api.py
datavaluepeople/tentaclio
12
2023647
"""Public module functions.""" import functools import logging from tentaclio import urls from .env import add_credentials_from_env from .injection import CredentialsInjector from .reader import add_credentials_from_env_file logger = logging.getLogger(__name__) __all__ = ["load_credentials_injector", "authenticate"] # Singleton @functools.lru_cache(maxsize=1, typed=True) def load_credentials_injector() -> CredentialsInjector: """Load the credentials injector fetching configuration from the environment.""" injector = CredentialsInjector() injector = add_credentials_from_env(injector) injector = add_credentials_from_env_file(injector) return injector def authenticate(url: str) -> urls.URL: """Authenticate url.""" return load_credentials_injector().inject(urls.URL(url))
817
mailie/__init__.py
symonk/mailie
0
2024602
import logging import importlib_metadata from ._attachments import Attachable from ._attachments import FileAttachment from ._client import SyncClient from ._email import Email from ._exceptions import EmptyAttachmentFolderException from ._exceptions import FilePathNotAttachmentException from ._exceptions import InvalidAttachmentException from ._exceptions import MailieException from ._exceptions import SMTPException from ._policy import POLICIES from ._response import SMTPResponse log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # importlib_metadata is necessary here for backwards compat with mkdocs. version = importlib_metadata.version("mailie") # type: ignore [attr-defined] __all__ = [ "Email", "POLICIES", "version", "FileAttachment", "Attachable", "SyncClient", "SMTPResponse", "EmptyAttachmentFolderException", "InvalidAttachmentException", "MailieException", "FilePathNotAttachmentException", "SMTPException", ]
1,007
league_builder.py
mathieu01/team-project
0
2025048
import csv #we import csv before we can use the csv module def player(): # out the Raptor team into a file as required with open("teams.txt","a") as file: file.write("Raptors \n") for players in Raptors: players=",".join(players) file.write ("\n" "\n"+ str(players )) def player1(): # output the Dragons team into a file as required with open("teams.txt","a") as file: file.write('\n' '\n' "Dragons") for player2 in Dragons: player2=",".join(player2) file.write ("\n" "\n"+ str(player2)) def player3():# output the Sharks team into a file as required with open("teams.txt","a") as file: file.write( '\n' '\n' "Sharks") for player4 in Sharks: player4=",".join(player4) file.write ("\n" "\n"+ str(player4)) if __name__ == '__main__': with open('soccer_players.csv',newline='') as csvfile:# open the file as a string soccer_reader = csv.reader(csvfile) # read what is in the file before we can use the file rows = list(soccer_reader) # Convert the file into a list del(rows[0]) # delete the first row which contains just the headings, to make access easier Experienced = [] # define an empty list of experienced players Inexperienced = [] #define an empty list of inexperienced players Raptors = [] #define an empty list of the Raptors team Dragons = [] #define an empty list of the Dragons team Sharks = [] #define an empty list of the Sharks team for row in rows: # loop the through the player list if row[2]=='YES': # sought out the experienced players Experienced.append(row) # convert the experienced players into a list else: Inexperienced.append(row) # sought out the inexperienced players Raptors = Experienced[:3] + Inexperienced[:3] # divide the players evenly and assign them into the various teams Dragons = Experienced[3:6] + Inexperienced[3:6] Sharks = Experienced[6:] + Inexperienced[6:] player() player1() player3()
2,012
cplusplus/level1_single_api/4_op_dev/1_custom_op/tbe/impl/matmul_tik.py
coldenheart/123
0
2022851
from tbe import tik DTYPE_SIZE = { 'bool': 1, 'uint8': 1, 'int8': 1, 'uint16': 2, 'int16': 2, 'int24': 3, 'uint32': 4, 'int32': 4, 'float16': 2, 'float32': 4, 'int48': 6, 'int64': 8, 'uint64': 8, 'float64':8 } def matmul_tik_compute(params, kernel_name): """ matmul tik compute @param params: matmul data @param kernel_name: kernel name @return: tik instance """ tik_instance = tik.Tik() if not isinstance(params, dict): params = params.__dict__ m_size, k_size, n_size = params['M'], params['K'], params['N'] data_type = params["data_type"] m_tiling_size = int(params["m_tiling_size"]) n_tiling_size = int(params["n_tiling_size"]) k_tiling_size = int(params['k_tiling_size']) m_cycle_times = params["m_cycle_times"] n_cycle_times = params["n_cycle_times"] k_cycle_times = params["k_cycle_times"] # Determine the output type if data_type == "float16": C_loc_out_type = "float32" K0 = 16 else: C_loc_out_type = "int32" K0 = 32 block_size = 16 n_thread_num = params['n_thread_num'] m_thread_num = params['m_thread_num'] k_thread_num = params['k_thread_num'] # Occupy the input tensor. output_gm = tik_instance.Tensor(C_loc_out_type, (n_size // block_size, m_size, block_size), name="C_gm", scope=tik.scope_gm) inputa_gm = tik_instance.Tensor(params["data_type"], (k_size // K0, m_size, K0), name="A_gm", scope=tik.scope_gm) inputb_gm = tik_instance.Tensor(params["data_type"], (k_size // K0, n_size, K0), name="B_gm", scope=tik.scope_gm) # Tiling is realized through the for_range() loop. with tik_instance.for_range(0, 2, block_num = 2) as core_id: with tik_instance.for_range(0, n_cycle_times // 2, thread_num=n_thread_num) as n_idx: with tik_instance.for_range(0, m_cycle_times, thread_num=m_thread_num) as m_idx: dst_l0c = tik_instance.Tensor(C_loc_out_type, [n_tiling_size // 16, m_tiling_size, 16], name='dst_l0c', scope=tik.scope_cbuf_out) with tik_instance.for_range(0, k_cycle_times, thread_num=k_thread_num) as k_idx: # Calculation result data transfer. inputa_l1 = tik_instance.Tensor(params['data_type'], [k_tiling_size // K0, m_tiling_size, K0], name="A_tiling_l1", scope=tik.scope_cbuf) tik_instance.data_move(inputa_l1, inputa_gm[k_idx * k_tiling_size // K0, m_idx * m_tiling_size, :], 0, k_tiling_size // K0, m_tiling_size, m_size - m_tiling_size, 0) inputb_l1 = tik_instance.Tensor(params["data_type"], [k_tiling_size // K0, n_tiling_size, K0], name="B_tiling_l1", scope=tik.scope_cbuf) if n_size - n_tiling_size > 65535: with tik_instance.for_range(0, k_tiling_size // K0) \ as dma_k_idx: tik_instance.data_move(inputb_l1[dma_k_idx, :, :], inputb_gm[k_idx * k_tiling_size // K0 + dma_k_idx, (core_id * n_cycle_times // 2 + n_idx) * n_tiling_size, :], 0, 1, n_tiling_size, 0, 0) else: tik_instance.data_move(inputb_l1, inputb_gm[k_idx * k_tiling_size // K0, (core_id * n_cycle_times // 2 + n_idx) * n_tiling_size, :], 0, k_tiling_size // K0, n_tiling_size, n_size - n_tiling_size, 0) # Call matmul API to matrix multiplication calculation. with tik_instance.if_scope(k_idx == 0): tik_instance.matmul(dst_l0c, inputa_l1, inputb_l1, m_tiling_size, k_tiling_size, n_tiling_size, init_l1out=True) with tik_instance.else_scope(): tik_instance.matmul(dst_l0c, inputa_l1, inputb_l1, m_tiling_size, k_tiling_size, n_tiling_size, init_l1out=False) tik_instance.fixpipe(output_gm[n_tiling_size // 16 * (core_id * n_cycle_times // 2 + n_idx), m_idx * m_tiling_size, :], dst_l0c, n_tiling_size // 16, m_tiling_size * 16 * DTYPE_SIZE[C_loc_out_type]//32, (m_size - m_tiling_size) * 16 * DTYPE_SIZE[C_loc_out_type] // 32, 0) tik_instance.BuildCCE(kernel_name=kernel_name, inputs=[inputa_gm, inputb_gm], outputs=[output_gm], config={'l2_mode': 1}) return tik_instance def matmul_tik(input_x1, input_x2, output_y=None, kernel_name="simple_matmul"): """ matmul_tik main func Parameters ---------- input_x1: input data 1 input_x2: input data 2 output_y: output dta """ shape_a = input_x1.get("ori_shape") shape_b = input_x2.get("ori_shape") output_y = output_y m = shape_a[0] k = shape_a[1] n = shape_b[1] data_type = input_x1.get("dtype").lower() params = { 'M': m, 'K': k, 'N': n, 'data_type': data_type, 'm_tiling_size': 16, 'm_cycle_times': 1, 'm_thread_num': 1, 'n_tiling_size': 64, 'n_cycle_times': 16, 'n_thread_num': 1, 'k_tiling_size': 32, 'k_cycle_times': 2, 'k_thread_num': 2, 'output_y':output_y } return matmul_tik_compute(params, kernel_name)
7,908
rating_system/check_earnings_news.py
kaiznanji/Kalgo
0
2023389
# In this file we will check a companies upcoming earnings and recent news headlines through Yahoo Finance # Import libraries import datetime as dt import yfinance as yf import time from time import strptime from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import re from tqdm import tqdm # Main function def seekingalpha(tickers, gecko_path, seleniumOptions): tickers = past_earnings(tickers, gecko_path, seleniumOptions) print("|***** EARNINGS RATED *****|") tickers = news(tickers, gecko_path, seleniumOptions) print("|***** NEWS RATED *****|") return tickers # EARNINGS # RATINGS: # 0 --> Earnings are far from now # 1 --> Earnings are approaching (This is a good indicator if a company gives grants before earnings which we know from our script before) def past_earnings(tickers, gecko_path, options): keys = list(tickers) driver = webdriver.Firefox(executable_path=gecko_path, options=options) for i in tqdm(range(len(keys))): url = 'https://finance.yahoo.com/quote/{}'.format(keys[i]) driver.get(url) earnings_date = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[@data-test='EARNINGS_DATE-value']"))) if ("N/A" in earnings_date.text): continue else: earnings_date = earnings_date.find_element_by_tag_name("span").text month_number = dt.datetime.strptime(re.sub("[^A-Za-z]", "", earnings_date), "%b").month date = re.sub("[^0-9,]", "", earnings_date) earnings_date = dt.datetime.strptime(str(month_number) + "," + date, '%m,%d,%Y') if ((dt.datetime.now() + dt.timedelta(weeks=3)) > earnings_date > dt.datetime.now()): tickers[keys[i]] += 1 driver.quit() return tickers # NEWS # RATINGS: # 0 --> No signal for upcoming conferences to discuss potential good news # 1 --> Signal for upcoming conferences to discuss potential good news def news(tickers, gecko_path, options): main_url = 'https://seekingalpha.com' keys = list(tickers) driver = webdriver.Firefox(executable_path=gecko_path, options=options) for i in tqdm(range(len(keys))): link = 'https://finance.yahoo.com/quote/{}'.format(keys[i]) driver.get(link) titles = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, "//h3[@class='Mb(5px)']"))) dates = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, "//div[@class='C(#959595) Fz(11px) D(ib) Mb(6px)']"))) # Find the past 5 articles to analyze for title, date in zip(titles[:5], dates[:5]): span_tags = date.find_elements_by_tag_name("span") if (len(span_tags) != 2): date = "" else: date = span_tags[-1].text if ("hour" in date): article_date = dt.datetime.now() elif ("day" in date): number_of_days = re.sub("[^0-9]", "", date) if (number_of_days == ""): # Edge case for when article is yesterday article_date = dt.datetime.now() - dt.timedelta(days=1) else: article_date = dt.datetime.now() - dt.timedelta(days=int(number_of_days)) elif ("month" in date): number_of_months = re.sub("[^0-9]", "", date) if (number_of_months == ""): # Edge case for when article is last month article_date = dt.datetime.now() - dt.timedelta(weeks=4) else: article_date = dt.datetime.now() - dt.timedelta(weeks=int(number_of_months)*4) else: article_date = dt.datetime.now() - - dt.timedelta(weeks=52) title = title.text.lower() three_weeks_ago = dt.datetime.now() - dt.timedelta(weeks=3) if (article_date >= three_weeks_ago and ('conference' in title or 'meeting' in title)): tickers[keys[i]] += 1 break driver.quit() return tickers # A helper function that gets the overall sentiment of a piece of text def get_sentiment(text): analyser = SentimentIntensityAnalyzer() score = analyser.polarity_scores(text) sentiment = score['compound'] if (sentiment >= 0.50): return 1 elif ((sentiment > -0.50) and (sentiment < 0.50)): return 0 else: return -1 # A helper function that grabs the article date def get_date(date): if 'Today' in date: date = dt.datetime.now() elif 'Yesterday' in date: date = dt.datetime.now() - dt.timedelta(days=1) else: date = date.split(", ")[1] month = date.split(". ")[0] month = str(strptime(month,'%b').tm_mon) + '/' day = date.split(". ")[1] year = '/' + str(dt.datetime.now().year) date = dt.datetime.strptime(month + day + year, '%m/%d/%Y') return date # A helper function that grabs a company name given a ticker def get_company(symbol): try: tickerInfo = yf.Ticker(symbol) company_name = tickerInfo.info['longName'] return company_name except: return ""
5,462
ArubaCloud/Compute/LoadBalancer/Models/NewLoadBalancerRule.py
luigidacunto/pyArubaCloud
39
2023672
from LoadBalancerAlgorithmType import LoadBalancerAlgorithmType from LoadBalancerProtocol import LoadBalancerProtocol from datetime import datetime class NewLoadBalancerRule(object): def __init__(self, balancerType, certificate, creationDate, id, instancePort, loadBalancerPort, protocol): """ :type balancerType: LoadBalancerAlgorithmType :type certificate: str :type creationDate: datetime :type id: int :type instancePort: int :type loadBalancerPort: int :type protocol: LoadBalancerProtocol :param balancerType: :param certificate: :param creationDate: :param id: :param instancePort: :param loadBalancerPort: :param protocol: """ self.BalancerType = balancerType self.Certificate = certificate self.CreationDate = creationDate self.ID = id self.InstancePort = instancePort self.LoadBalancerPort = loadBalancerPort self.Protocol = protocol
1,034
src/sage/combinat/designs/latin_squares.py
bopopescu/classic_diff_geom
0
2022811
# -*- coding: utf-8 -*- r""" Mutually Orthogonal Latin Squares (MOLS) A Latin square is an `n\times n` array filled with `n` different symbols, each occurring exactly once in each row and exactly once in each column. For Sage's methods related to Latin Squares, see the module :mod:`sage.combinat.matrices.latin`. This module gathers constructions of Mutually Orthogonal Latin Squares, which are equivalent to Transversal Designs and specific Orthogonal Arrays. For more information on MOLS, see the :wikipedia:`Wikipedia entry on MOLS <Graeco-Latin_square#Mutually_orthogonal_Latin_squares>`. TODO: * Implement Wilson's construction (page 146 of [Stinson2004]_) * Look at [ColDin01]_. REFERENCES: .. [Stinson2004] <NAME>, Combinatorial designs: construction and analysis, Springer, 2004. .. [ColDin01] <NAME>, <NAME>, Mutually orthogonal latin squares: a brief survey of constructions, Volume 95, Issues 1-2, Pages 9-48, Journal of Statistical Planning and Inference, Springer, 1 May 2001. """ def are_mutually_orthogonal_latin_squares(l, verbose=False): r""" Check wether the list of matrices in ``l`` form mutually orthogonal latin squares. INPUT: - ``verbose`` - if ``True`` then print why the list of matrices provided are not mutually orthogonal latin squares EXAMPLES:: sage: from sage.combinat.designs.latin_squares import are_mutually_orthogonal_latin_squares sage: m1 = matrix([[0,1,2],[2,0,1],[1,2,0]]) sage: m2 = matrix([[0,1,2],[1,2,0],[2,0,1]]) sage: m3 = matrix([[0,1,2],[2,0,1],[1,2,0]]) sage: are_mutually_orthogonal_latin_squares([m1,m2]) True sage: are_mutually_orthogonal_latin_squares([m1,m3]) False sage: are_mutually_orthogonal_latin_squares([m2,m3]) True sage: are_mutually_orthogonal_latin_squares([m1,m2,m3], verbose=True) matrices 0 and 2 are not orthogonal False sage: m = designs.mutually_orthogonal_latin_squares(8) sage: are_mutually_orthogonal_latin_squares(m) True """ if not l: raise ValueError("the list must be non empty") n = l[0].nrows() if any(M.nrows() != n and M.ncols() != n for M in l): if verbose: print "some matrix has wrong dimension" return False # check that the matrices in l are actually latin for i,M in enumerate(l): if (any(sorted(r) != range(n) for r in M.rows()) or any(sorted(c) != range(n) for c in M.columns())): if verbose: print "matrix %d is not latin"%i return False # check orthogonality of each pair for k1 in xrange(len(l)): M1 = l[k1] for k2 in xrange(k1): M2 = l[k2] L = [(M1[i,j],M2[i,j]) for i in xrange(n) for j in xrange(n)] if len(set(L)) != len(L): if verbose: print "matrices %d and %d are not orthogonal"%(k2,k1) return False return True def mutually_orthogonal_latin_squares(n,k=None, partitions = False): r""" Returns `k` Mutually Orthogonal `n\times n` Latin Squares (MOLS). For more information on Latin Squares and MOLS, see :mod:`~sage.combinat.designs.latin_squares` or the :wikipedia:`Latin_square`, or even the :wikipedia:`Wikipedia entry on MOLS <Graeco-Latin_square#Mutually_orthogonal_Latin_squares>`. INPUT: - ``n`` (integer) -- size of the latin square. - ``k`` (integer) -- returns `k` MOLS. If set to ``None`` (default), returns the maximum number of MOLS that Sage can build. .. WARNING:: This has no reason to be the maximum number of `n\times n` MOLS, just the best Sage can do ! - ``partition`` (boolean) -- a Latin Square can be seen as 3 partitions of the `n^2` cells of the array into `n` sets of size `n`, respectively : * The partition of rows * The partition of columns * The partition of number (cells numbered with 0, cells numbered with 1, ...) These partitions have the additional property that any two sets from different partitions intersect on exactly one element. When ``partition`` is set to ``True``, this function returns a list of `k+2` partitions satisfying this intersection property instead of the `k+2` MOLS (though the data is exactly the same in both cases). EXAMPLES:: sage: designs.mutually_orthogonal_latin_squares(5) [ [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [0 1 2 3 4] [3 0 1 4 2] [4 3 0 2 1] [1 2 4 0 3] [2 4 3 1 0] [4 3 0 2 1] [1 2 4 0 3] [2 4 3 1 0] [3 0 1 4 2] [1 2 4 0 3] [2 4 3 1 0] [3 0 1 4 2] [4 3 0 2 1] [2 4 3 1 0], [3 0 1 4 2], [4 3 0 2 1], [1 2 4 0 3] ] sage: designs.mutually_orthogonal_latin_squares(7,3) [ [0 1 2 3 4 5 6] [0 1 2 3 4 5 6] [0 1 2 3 4 5 6] [4 0 3 1 6 2 5] [5 6 0 4 2 1 3] [6 4 1 0 5 3 2] [5 6 0 4 2 1 3] [6 4 1 0 5 3 2] [1 3 5 2 0 6 4] [6 4 1 0 5 3 2] [1 3 5 2 0 6 4] [2 5 4 6 3 0 1] [1 3 5 2 0 6 4] [2 5 4 6 3 0 1] [3 2 6 5 1 4 0] [2 5 4 6 3 0 1] [3 2 6 5 1 4 0] [4 0 3 1 6 2 5] [3 2 6 5 1 4 0], [4 0 3 1 6 2 5], [5 6 0 4 2 1 3] ] sage: designs.mutually_orthogonal_latin_squares(5,2,partitions=True) [[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], [[0, 5, 10, 15, 20], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]], [[0, 6, 12, 18, 24], [1, 7, 14, 15, 23], [2, 9, 13, 16, 20], [3, 5, 11, 19, 22], [4, 8, 10, 17, 21]], [[0, 7, 13, 19, 21], [1, 9, 10, 18, 22], [2, 8, 11, 15, 24], [3, 6, 14, 17, 20], [4, 5, 12, 16, 23]]] TESTS:: sage: designs.mutually_orthogonal_latin_squares(5,5) Traceback (most recent call last): ... ValueError: There exist at most n-1 MOLS of size n. """ from sage.rings.finite_rings.constructor import FiniteField from sage.combinat.designs.block_design import AffineGeometryDesign from sage.rings.arith import is_prime_power from sage.matrix.constructor import Matrix from sage.rings.arith import factor if k is not None and k >= n: raise ValueError("There exist at most n-1 MOLS of size n.") if is_prime_power(n): if k is None: k = n-1 # Section 6.4.1 of [Stinson2004] Fp = FiniteField(n,'x') B = AffineGeometryDesign(2,1,Fp).blocks() parallel_classes = [[] for _ in range(k+2)] for b in B: for p in parallel_classes: if (not p) or all(i not in p[0] for i in b): p.append(b) break if partitions: return parallel_classes coord = {v:i for i,L in enumerate(parallel_classes[0]) for v in L} coord = {v:(coord[v],i) for i,L in enumerate(parallel_classes[1]) for v in L} matrices = [] for P in parallel_classes[2:]: matrices.append(Matrix({coord[v]:i for i,L in enumerate(P) for v in L })) return matrices else: # Theorem 6.33 of [Stinson2004], MacNeish's theorem. subcases = [p**i for p,i in factor(n)] s = min(subcases)-1 if k is None: k = s elif k > s: raise NotImplementedError("I don't know how to build these MOLS.") subcalls = [mutually_orthogonal_latin_squares(p,k) for p in subcases] matrices = [latin_square_product(*[sc[i] for sc in subcalls]) for i in range(k)] if partitions: partitions = [[[i*n+j for j in range(n)] for i in range(n)], [[j*n+i for j in range(n)] for i in range(n)]] for m in matrices: partition = [[] for i in range(n)] for i in range(n): for j in range(n): partition[m[i,j]].append(i*n+j) partitions.append(partition) return partitions else: return matrices def latin_square_product(M,N,*others): r""" Returns the product of two (or more) latin squares. Given two Latin Squares `M,N` of respective sizes `m,n`, the direct product `M\times N` of size `mn` is defined by `(M\times N)((i_1,i_2),(j_1,j_2))=(M(i_1,j_1),N(i_2,j_2))` where `i_1,j_1\in [m], i_2,j_2\in [n]` Each pair of values `(i,j)\in [m]\times [n]` is then relabeled to `in+j`. This is Lemma 6.25 of [Stinson2004]_. INPUT: An arbitrary number of latin squares (greater than 2). EXAMPLES:: sage: from sage.combinat.designs.latin_squares import latin_square_product sage: m=designs.mutually_orthogonal_latin_squares(4)[0] sage: latin_square_product(m,m,m) 64 x 64 sparse matrix over Integer Ring """ from sage.matrix.constructor import Matrix m = M.nrows() n = N.nrows() D = {((i,j),(ii,jj)):(M[i,ii],N[j,jj]) for i in range(m) for ii in range(m) for j in range(n) for jj in range(n)} L = lambda i_j: i_j[0] * n + i_j[1] D = {(L(c[0]),L(c[1])): L(v) for c,v in D.iteritems()} P = Matrix(D) if others: return latin_square_product(P, others[0],*others[1:]) else: return P
9,652
tmanager/commands/delete.py
Leovalcante/tmanager
0
2023314
import sys import tmanager.core.messages.messages as msg import tmanager.utilities.commands as utl_cmds import tmanager.utilities.file_system as utl_fs from tmanager.core.config.config import Config CMD_NAME = "delete" @click.command() @click.option("-n", "--name", help="Delete tool by name.", metavar="<tool-name>") @click.option("-i", "--input-file", help="Read tool names from input file.", metavar="<pathname>") @click.option("-a", "--all", is_flag=True, help="Delete all tools.") @click.option("-l", "--log", help="Log to file instead of printing to stdout.", metavar="<filename>") @click.option("-y", "--assume-yes", is_flag=True, help="Assume yes.") @click.pass_context def delete(ctx: click.core.Context, name: str, input_file: str, all: bool, log: str, assume_yes: bool) -> None: """ Delete tools. \f :param click.core.Context ctx: click context :param str name: tool name to delete :param str input_file: file containing tools to delete :param bool all: should delete all? :param str log: log filename :param bool assume_yes: assume yes as the answer for any user prompt :return: None """ cfg = utl_cmds.get_configs_from_context(ctx) # Make sure that at least one options is set if not (bool(name) ^ bool(input_file) ^ bool(all)): utl_cmds.usage_error("delete") sys.exit(1) # if a filename for logs is provided, then make sure it exists and it's writable. log_fname = "" if log: log_fname = utl_cmds.validate_log_filename(log, CMD_NAME, assume_yes) if not log_fname: sys.exit(1) tools_to_delete = [] # Retrieve all the managed tools tools = cfg.get_tools() # Retrieve every tool that has to be removed if name: # Search by name tools_to_delete += utl_cmds.find_tool(cfg, name=name) elif input_file: # Read tool names from file (one per line) try: with open(input_file, "r") as f: for tool_name in f.readlines(): tool_name = tool_name.strip() # Retrieve repos by tool_name tools_to_delete += utl_cmds.find_tool(cfg, name=tool_name) except FileNotFoundError: raise click.BadOptionUsage("--input-file", "The file {} doesn't exist or it's not readable, try with another one" .format(input_file)) # Display an info message if there's no repository to delete if (bool(all) is False and len(tools_to_delete) == 0) or (bool(all) and len(tools) == 0): msg.Prints.warning("No tool to delete", log_fname, CMD_NAME) sys.exit(1) elif bool(all): # Delete every tool _delete_all(cfg, tools, assume_yes, log_fname) else: # Delete the retrieved tools for tool in tools_to_delete: cfg.remove_tool(tool) msg.Prints.success("{} has been removed".format(tool.get_name()), log_fname, CMD_NAME) # Ensure the user wishes to delete the tools from file system too if tool.is_installed() and (assume_yes or click.confirm(msg.Echoes.input( "Delete {} from file system too?".format(tool.get_name())), default=False)): utl_fs.delete_from_fs(tool.get_directory()) msg.Prints.success("{} successfully deleted from file system!".format(tool.get_name()), log_fname, CMD_NAME) cfg.save() sys.exit(0) def _delete_all(cfg: Config, deleted_tools: list, assume_yes: bool, log_fname: str) -> None: """ Delete Every managed tool. :param Config cfg: tman configuration object :param list deleted_tools: tool list to delete :param bool assume_yes: assume all positive response for any prompt :param str log_fname: log filename :return: None """ # Prompt for confirmation delete_all_repos = assume_yes or click.confirm(msg.Echoes.input("Remove every tool from tman?"), default=True) if not delete_all_repos: raise click.Abort() # Remove all the tools msg.Prints.info("{} tools removed".format(cfg.remove_all_tools()), log_fname, CMD_NAME) # Update the configuration file cfg.save() # Ensure the user wishes to delete the tools from file system (FS) delete_all_file_system = click.confirm(msg.Echoes.input("Delete every tool from the file system?"), default=False) if not assume_yes else False # Delete every tool from the file system if the user confirmed if delete_all_file_system: for tool in deleted_tools: if tool.is_installed(): utl_fs.delete_from_fs(tool.get_directory()) msg.Prints.info("{} deleted".format(tool.get_directory()), log_fname, CMD_NAME, icon=False) # Let the user decide which tool he wishes to delete permanently! elif deleted_tools and not assume_yes: msg.Prints.info("Enter comma-separated list of indexes to remove (i.e. 1,3,4)", log_fname, CMD_NAME) for tool in deleted_tools: click.echo("[{}]: {}".format(str(deleted_tools.index(tool)+1), tool.get_name())) to_delete = None tool_to_save_indexes = input(">>> ") if tool_to_save_indexes and tool_to_save_indexes.lower() not in ["no", "n", "quit", "q", "none"]: # Check if they're all valid numbers to_delete = utl_cmds.sanitize_indexes(deleted_tools, tool_to_save_indexes) # Delete valid number repos for index in to_delete: repo = deleted_tools[index] utl_fs.delete_from_fs(repo.get_directory()) msg.Prints.success("{} deleted successfully from file system".format(repo.get_name()), log_fname, CMD_NAME) if not to_delete: msg.Prints.info("No tool will be erased from file system", log_fname, CMD_NAME) sys.exit(1) sys.exit(0)
6,064
commanderbot/ext/automod/conditions/thread_auto_archive_duration.py
CommanderBot-Dev/commanderbot-ext
4
2024656
from dataclasses import dataclass from typing import Type, TypeVar from commanderbot.ext.automod.automod_condition import ( AutomodCondition, AutomodConditionBase, ) from commanderbot.ext.automod.automod_event import AutomodEvent from commanderbot.lib import JsonObject from commanderbot.lib.integer_range import IntegerRange ST = TypeVar("ST") @dataclass class ThreadAutoArchiveDuration(AutomodConditionBase): """ Passes if the thread's auto archive duration is within the given range. Attributes ---------- auto_archive_duration The range of the auto archive duration to check. """ auto_archive_duration: IntegerRange @classmethod def from_data(cls: Type[ST], data: JsonObject) -> ST: auto_archive_duration = IntegerRange.from_field(data, "auto_archive_duration") return cls( description=data.get("description"), auto_archive_duration=auto_archive_duration, ) async def check(self, event: AutomodEvent) -> bool: if thread := event.thread: return self.auto_archive_duration.includes(thread.auto_archive_duration) return False def create_condition(data: JsonObject) -> AutomodCondition: return ThreadAutoArchiveDuration.from_data(data)
1,282
AutoConfig/AutoConfig.py
Guifgr/AutoConfig
1
2025085
import os from clean import clean from downloadFile import downloadGameFile from csGo import csGo from r6 import r6 continuar = True while(continuar): try: clean() name = input("Digite o nome do player: ").upper() clean() game = input("Digite de qual jogo quer as configurações como exemplos abaixo\nPara Counter Strike Global Offensive digite ➡ CS \nPara Rainbow Six Siege digite ➡ R6\nDigite: ").upper() fileTxt = downloadGameFile(game, name) if(game == "CS"): csGo(fileTxt) elif(game == "R6"): r6(fileTxt) except: clean() print("Nome do jogador pode estar inválido ou ele não tem configurações nesse jogo 😢") continuar = input("\n\nDeseja continuar?").upper() if(continuar == "YES" or continuar == "Y" or continuar == "SIM" or continuar == "S"): continuar = True else: continuar = False
937
survival/sim.py
morningmorningwind/complexity
0
2023210
from pylab import * from numpy import * from mymath import statistic,revcumsum N = 100000 # number of users t0 = 500 # initial time for observation T = t0 +1000 P = [0.45, 0.5, 0.55] # probability of joining a banned group mxP = 5 # maximum cumulative position for banning #randomize initial time for each user T0 = random.randint(0,t0,N) POS = [] LSP = [] POS0 = [] for p in P: Pos = zeros([N,T]) # position vs time for each user Lsp = [] # life span #do simulation Pos[:,1:] = (random.random([N,T-1]) < p) * 2.0 - 1.0 for u in range(N): Pos[u,:T0[u]+1] = 0.0 Pos = Pos.cumsum(1) Pos0 = Pos[t0,:].tolist() for u in range(N): L = where(Pos[u,:]>=mxP)[0] if len(L)>0: L=L[0] if L>t0: Lsp.append(L-max(t0,T0[u])) POS.append(Pos) LSP.append(Lsp) POS0.append(Pos0) f=figure(1,figsize=(6,4)) for i in range(len(P)): Lsp=LSP[i] x,y=statistic(Lsp,norm=True) _=loglog(x,y,label='$p$='+str(P[i]),alpha=0.5) xlabel(r'$Lifespan$') ylabel(r'$Fraction$') legend(loc='best') savefig('figs/lifespan-sim.pdf',bbox_inches='tight') for i in range(len(P)): f.clf() Pos=POS[i] for u in range(300): _=plot(Pos[u,:],alpha=0.5) _=plot([t0,t0],[100,-100],'r--',linewidth=2.0) _=plot([t0,T],[mxP,mxP],'r--',linewidth=2.0) xlabel(r'$Time$') ylabel(r'$Position$') savefig('figs/Time-Position-sim-p'+str(P[i])+'.png',bbox_inches='tight') f.clf() for i in range(len(P)): Pos0=POS0[i] x,y=statistic(Pos0,norm=True) _=loglog(x,y,label='$p$='+str(P[i]),alpha=0.5) xlabel(r'$Position$') ylabel(r'$Fraction$') legend(loc='best') savefig('figs/InitialPosition-sim.pdf',bbox_inches='tight') close(1)
1,753
ginga/examples/gw/widgets.py
kyraikeda/ginga
1
2024268
""" Test program for trying widgets in the different wrapped toolkits supported by Ginga. Usage: $ python widgets.py <toolkit-name> <widget-name> [logging options] Examples: $ python widgets.py qt5 gridbox $ python widgets.py gtk3 label $ python widgets.py pg button """ import sys import os from ginga.misc import log import ginga.toolkit as ginga_toolkit # decide our toolkit, then import tkit = sys.argv[1] wname = sys.argv[2] ginga_toolkit.use(tkit) from ginga.gw import Widgets, Viewers, GwHelp # noqa from ginga.util.paths import icondir # noqa top = None def quit(*args): if top is not None: top.delete() sys.exit() def popup_dialog(parent): dia = Widgets.Dialog(title="Dialog Title", buttons=[('ok', 0), ('cancel', 1)], parent=parent, modal=True) cntr = dia.get_content_area() cntr.add_widget(Widgets.Label("My Dialog Content")) dia.show() logger = log.get_logger('test', log_stderr=True, level=20) app = Widgets.Application(logger=logger) if hasattr(app, 'script_imports'): app.script_imports.append('jqx') app.add_callback('shutdown', quit) top = app.make_window("Ginga Wrapped Widgets Example: %s" % (wname)) top.add_callback('close', quit) vbox = Widgets.VBox() vbox.set_border_width(2) vbox.set_spacing(1) dia = None if wname == 'label': w = Widgets.Label("Hello World label") vbox.add_widget(w, stretch=1) elif wname == 'button': w = Widgets.Button("Press me") w.add_callback('activated', lambda w: logger.info("button was clicked")) w.add_callback('activated', lambda w: popup_dialog(top)) vbox.add_widget(w, stretch=1) elif wname == 'textentry': w = Widgets.TextEntry() w.set_text("Hello, World!") vbox.add_widget(w, stretch=1) elif wname == 'textentryset': w = Widgets.TextEntrySet() w.set_text("Hello, World!") vbox.add_widget(w, stretch=1) elif wname == 'textarea': w = Widgets.TextArea(editable=True) w.set_text("Hello, World!") vbox.add_widget(w, stretch=1) elif wname == 'checkbox': w = Widgets.CheckBox("Check me") vbox.add_widget(w, stretch=1) elif wname == 'togglebutton': w = Widgets.ToggleButton("Toggle me") vbox.add_widget(w, stretch=1) elif wname == 'radiobutton': w = Widgets.RadioButton("Option 1") vbox.add_widget(w) vbox.add_widget(Widgets.RadioButton("Option 2", group=w)) vbox.add_widget(Widgets.RadioButton("Option 3", group=w)) elif wname == 'combobox': w = Widgets.ComboBox() for name in ["Larry", "Curly", "Moe"]: w.append_text(name) vbox.add_widget(w) elif wname == 'spinbox': w = Widgets.SpinBox(dtype=int) w.set_limits(-10, 10, incr_value=1) w.set_value(4) vbox.add_widget(w) elif wname == 'slider': w = Widgets.Slider(orientation='horizontal') w.set_limits(-10, 10, incr_value=1) w.set_value(4) vbox.add_widget(w) elif wname == 'scrollbar': w = Widgets.ScrollBar(orientation='horizontal') w.add_callback('activated', lambda w, val: logger.info("value is %d" % val)) vbox.add_widget(w) elif wname == 'progressbar': w = Widgets.ProgressBar() w.set_value(0.6) vbox.add_widget(w) elif wname == 'statusbar': w = Widgets.StatusBar() w.set_message("Hello, World! is my status") vbox.add_widget(w) elif wname == 'image': w = Widgets.Image() w.load_file(os.path.join(icondir, 'ginga-512x512.png')) vbox.add_widget(w) elif wname == 'treeview': w = Widgets.TreeView(selection='single', sortable=True, use_alt_row_color=True) columns = [("Meal", 'meal'), ("Critic 1", 'review1'), ("Critic 2", 'review2'), ("Critic 3", 'review3')] w.setup_table(columns, 1, 'meal') tree = dict(Breakfast=dict(meal='Breakfast', review1="Delish!", review2="Ugh!", review3="Meh"), Lunch=dict(meal='Lunch', review1="Gross!", review2="Interesting...", review3="Meh"), Supper=dict(meal='Supper', review1="Meh", review2="Meh", review3="Jolly good!")) w.set_tree(tree) vbox.add_widget(w, stretch=1) elif wname == 'webview': w = Widgets.WebView() w.load_url("http://www.google.com/") vbox.add_widget(w) elif wname == 'frame': w = Widgets.Frame(title="Frame Title") w.set_widget(Widgets.Label("Framed content")) vbox.add_widget(w) elif wname == 'expander': w = Widgets.Expander(title="Expander Title") w.set_widget(Widgets.Label("Expander content")) vbox.add_widget(w) elif wname == 'hbox': w = Widgets.HBox() w.add_widget(Widgets.Label("Item 1"), stretch=0) w.add_widget(Widgets.Label("Item 2"), stretch=1) vbox.add_widget(w) elif wname == 'vbox': w = Widgets.VBox() w.add_widget(Widgets.Label("Item 1"), stretch=0) w.add_widget(Widgets.Label("Item 2"), stretch=1) vbox.add_widget(w) elif wname == 'splitter': w = Widgets.Splitter(orientation='horizontal') w.add_widget(Widgets.Label('Content of Pane 1')) w.add_widget(Widgets.Label('Content of Pane 2')) vbox.add_widget(w, stretch=1) elif wname == 'scrollarea': w = Widgets.ScrollArea() img = Widgets.Image() img.load_file(os.path.join(icondir, 'ginga-512x512.png')) w.set_widget(img) vbox.add_widget(w, stretch=1) elif wname == 'tabwidget': w = Widgets.TabWidget() w.add_widget(Widgets.Label('Content of Tab 1'), title='Tab 1') w.add_widget(Widgets.Label('Content of Tab 2'), title='Tab 2') hbox = Widgets.HBox() sbox = Widgets.SpinBox(dtype=int) sbox.set_limits(0, 1, incr_value=1) sbox.set_value(0) sbox.add_callback('value-changed', lambda sbx, val: w.set_index(val)) hbox.add_widget(sbox) vbox.add_widget(w, stretch=1) vbox.add_widget(hbox, stretch=0) elif wname == 'stackwidget': w = Widgets.StackWidget() w.add_widget(Widgets.Label('Content of Stack 1')) w.add_widget(Widgets.Label('Content of Stack 2')) vbox.add_widget(w, stretch=1) elif wname == 'mdiwidget': w = Widgets.MDIWidget() w.add_widget(Widgets.Label('Content of MDI Area 1')) w.add_widget(Widgets.Label('Content of MDI Area 2')) vbox.add_widget(w, stretch=1) elif wname == 'gridbox': w = Widgets.GridBox(rows=2, columns=2) w.add_widget(Widgets.Label('Content of Grid Area 1'), 0, 0) w.add_widget(Widgets.Label('Content of Grid Area 2'), 0, 1) w.add_widget(Widgets.Label('Content of Grid Area 3'), 1, 0) w.add_widget(Widgets.Label('Content of Grid Area 4'), 1, 1) vbox.add_widget(w, stretch=1) elif wname == 'menubar': w = Widgets.Menubar() menu = w.add_name('Menu 1') menu.add_name('Larry').add_callback('activated', lambda *args: print("chose Larry")) menu.add_name('Curly').add_callback('activated', lambda *args: logger.info("chose Curly")) menu.add_name('Moe').add_callback('activated', lambda *args: logger.info("chose Moe")) vbox.add_widget(w) vbox.add_widget(Widgets.Label("App content"), stretch=1) elif wname == 'toolbar': w = Widgets.Toolbar() menu = w.add_menu('Menu Type 1', mtype='tool') menu.add_name('Larry').add_callback('activated', lambda w: logger.info("chose Larry")) menu.add_name('Curly').add_callback('activated', lambda w: logger.info("chose Curly")) menu.add_name('Moe').add_callback('activated', lambda w: logger.info("chose Moe")) menu = w.add_menu('Menu Type 2', mtype='mbar') menu.add_name('Frank') menu.add_name('Dean') menu.add_name('Sammy') w.add_widget(Widgets.Button('A Button')) w.add_separator() w.add_action("Toggle me", toggle=True) w.add_action(None, iconpath=os.path.join(icondir, 'hand_48.png')) vbox.add_widget(w) vbox.add_widget(Widgets.Label("App content"), stretch=1) elif wname == 'dialog': dia = Widgets.Dialog(title="Dialog Title", buttons=[('ok', 0), ('cancel', 1)], parent=top, modal=False) dia.add_callback('activated', lambda w, rsp: logger.info("user chose %s" % (rsp))) cntr = dia.get_content_area() cntr.add_widget(Widgets.Label("My Dialog Content")) # add some content to main app widget w = Widgets.Label("Hello World label") vbox.add_widget(w, stretch=1) hbox = Widgets.HBox() w = Widgets.Button("Open Dialog") w.add_callback('activated', lambda w: dia.show()) hbox.add_widget(w) w = Widgets.Button("Close Dialog") w.add_callback('activated', lambda w: dia.hide()) hbox.add_widget(w) vbox.add_widget(hbox) else: # default to label logger.error("Don't understand kind of widget '%s'" % (wname)) w = Widgets.Label("Hello World label") vbox.add_widget(w, stretch=1) top.set_widget(vbox) top.show() top.raise_() if dia is not None: dia.show() try: app.mainloop() except KeyboardInterrupt: print("Terminating viewer...") if top is not None: top.close()
9,253
ao3_cli/utils/processing.py
arzkar/ao3-cli
2
2024870
from typing import Tuple import re import os from colorama import Fore, Style from tqdm import tqdm from loguru import logger from .logging import downloaded_log def get_format_type(_format: str = "epub") -> int: if re.search(r"\bepub\b", _format, re.I): format_type = 0 elif re.search(r"\bmobi\b", _format, re.I): format_type = 1 elif re.search(r"\bpdf\b", _format, re.I): format_type = 2 elif re.search(r"\bhtml\b", _format, re.I): format_type = 3 elif re.search(r"\azw3\b", _format, re.I): format_type = 4 else: # default epub format format_type = 0 return format_type def check_url(pbar, url: str, debug: bool = False, exit_status: int = 0) -> Tuple[bool, int]: if re.search(r"archiveofourown.org", url): supported_flag = True else: supported_flag = False if not supported_flag: pbar.update(1) exit_status = 1 if debug: logger.error( f"Skipping unsupported URL: {url}\nOnly archiveofourown.org is supported.") else: tqdm.write( Fore.RED + f"Skipping unsupported URL: {url}" + Style.RESET_ALL + "\nOnly archiveofourown.org is supported.") return supported_flag, exit_status def save_data(fic, out_dir: str, file_name: str, download_url: str, debug: bool, force: bool, exit_status: int) -> int: file_name = sanitize_filename(file_name) ebook_file = out_dir+file_name if os.path.exists(out_dir+file_name) and force is False: exit_status = 1 if debug: logger.error( f"{out_dir+file_name} already exists. Skipping download. Use --force flag to overwrite.") else: tqdm.write( Fore.RED + f"{out_dir+file_name} already exists. Skipping download. Use --force flag to overwrite.") else: if force and debug: logger.warning( f"--force flag was passed. Overwriting {out_dir+file_name}") fic.get_fic_data(download_url) downloaded_log(debug, file_name) with open(ebook_file, "wb") as f: f.write(fic.response_data.content) exit_status = 0 return exit_status def show_urls_from_page(fic): exit_status = 0 found_flag = False if fic.ao3_works_list: found_flag = True tqdm.write(Fore.GREEN + f"\nFound {len(fic.ao3_works_list)} works urls.") ao3_works_list = '\n'.join(fic.ao3_works_list) tqdm.write(ao3_works_list) if fic.ao3_series_list: found_flag = True tqdm.write(Fore.GREEN + f"\nFound {len(fic.ao3_series_list)} series urls.") ao3_series_list = '\n'.join(fic.ao3_series_list) tqdm.write(ao3_series_list) if found_flag is False: tqdm.write(Fore.RED + "\nFound 0 urls.") exit_status = 1 return exit_status def sanitize_filename(file_name: str): fixits = ['/'] for i in fixits: file_name = file_name.replace(i, " ") return file_name
3,158
animal_size/migrations/0002_alter_animalsize_table.py
5akusei/test-project-django
0
2024162
# Generated by Django 4.0.3 on 2022-03-21 16:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('animal_size', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='animalsize', table='animal_size', ), ]
329
function/python/brightics/function/timeseries/test/holt_winters_test.py
parkjh80/studio
202
2024539
""" Copyright 2019 Samsung SDS 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. """ from brightics.function.timeseries import holt_winters_train, holt_winters_predict from brightics.common.datasets import load_iris import unittest import HtmlTestRunner import os class TestHoltWinters(unittest.TestCase): def setUp(self): print("*** Holt-Winters UnitTest Start ***") self.testdata = load_iris() def tearDown(self): print("*** Holt-Winters UnitTest End ***") def test(self): hw_train = holt_winters_train(self.testdata, input_cols=['sepal_length'], period=12, model_type='multiplicative') DF1 = hw_train['model'] self.assertAlmostEqual(DF1['sse_sepal_length'], 75.0985720516664, 10) self.assertAlmostEqual(DF1['aic_sepal_length'], -71.77506241991551, 10) self.assertAlmostEqual(DF1['bic_sepal_length'], -23.604897714375426, 10) hw_predict = holt_winters_predict(model=DF1, prediction_num=24) DF2 = hw_predict['out_table'].values self.assertAlmostEqual(DF2[0][1], 5.602275321420261, 10) self.assertAlmostEqual(DF2[1][1], 5.5832064381953055, 10) self.assertAlmostEqual(DF2[2][1], 5.496285744490528, 10) self.assertAlmostEqual(DF2[3][1], 5.449483922508893, 10) self.assertAlmostEqual(DF2[4][1], 5.183025448632435, 10) if __name__ == '__main__': filepath = os.path.dirname(os.path.abspath(__file__)) reportFoler = filepath + "/../../../../../../../reports" unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(combine_reports=True, output=reportFoler))
2,141
ghizmo/configs.py
jlevy/ghizmo
87
2024088
""" Ghizmo config handling. """ import logging as log import os import re import yaml import subprocess from functools import lru_cache __author__ = 'jlevy' CONFIG_FILENAME = ".ghizmo.yml" @lru_cache() def load_config_file(): path = os.path.join(os.environ["HOME"], CONFIG_FILENAME) parsed_configs = None if os.path.exists(path): with open(path) as f: parsed_configs = yaml.safe_load(f) return parsed_configs def get_username(): configs = load_config_file() return configs and configs["username"] def get_access_token(): """Return GitHub auth token, if in config file.""" configs = load_config_file() return configs and configs["access_token"] def _extract_github_repo_info(url): m = re.match("^<EMAIL>:([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+).git$", url) or \ re.match("^https://github.com/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+).git$", url) return (m.group(1), m.group(2)) if m else None def infer_repo(remote_name="origin"): """ Extract the current repository info, if available, using .git/config in current working directory. """ log.info("Checking in cwd for git dirctory: %s", os.getcwd()) remote_url = bytes.decode(subprocess.check_output(["git", "config", "--get", "remote.%s.url" % remote_name])) (owner, repo_name) = _extract_github_repo_info(remote_url) log.info("Inferred repository: %s/%s", owner, repo_name) return (owner, repo_name)
1,406
video_palyer.py
vilgurin/DM_Project_II
0
2025107
""" Simple video player. (Without sound) """ import cv2 import time class VideoPlayer: """Allows play video (without a sound)""" def __init__(self,video_path): self.cap = cv2.VideoCapture(video_path) self.waitkey = cv2.waitKey(0) self.isStop = False def get_cap(self): """Gets capture of video""" return self.cap.read() def get_cap_frame(self): """Get every frame""" return self.cap.get(cv2.CAP_PROP_POS_FRAMES) def restart(self): """Sets video in starting position""" # if self.isStop == True: # self.isStop = False self.cap.set(cv2.CAP_PROP_POS_FRAMES,0) def main(file_name: str): """Main function""" player = VideoPlayer(file_name) i=0 while(1): if player.isStop == False: ret, frame = player.get_cap() # PRINTS i AND WHICH FRAME IS RIGHT NOW print(i, player.get_cap_frame()) cv2.imshow('frame', frame) # ENDS THE VIDEO if cv2.waitKey(7) & 0xFF == ord('q'): break # PAUSE if cv2.waitKey(15) & 0xFF == ord('s') and player.isStop == False: player.isStop = True # RESUME if cv2.waitKey(15) & 0xFF == ord('f') and player.isStop == True: player.isStop = False # RESTART if cv2.waitKey(15) & 0xFF == ord('r'): player.restart() i += 1 player.cap.release() cv2.destroyAllWindows() if __name__ == "__main__": main('example.mp4')
1,544
j5/backends/console/sb/arduino.py
j5api/j5
10
2023792
"""Console Backend for the SourceBots Arduino.""" from datetime import timedelta from typing import List, Optional, Set, Type, cast from j5.backends.console import Console from j5.backends.console.j5.arduino import ArduinoConsoleBackend from j5.boards import Board from j5.boards.sb import SBArduinoBoard from j5.components import GPIOPinMode, ServoInterface, ServoPosition from j5.components.derived import UltrasoundInterface class SBArduinoConsoleBackend( ServoInterface, UltrasoundInterface, ArduinoConsoleBackend, ): """Console Backend for the SourceBots Arduino.""" board = SBArduinoBoard def __init__(self, serial: str, console_class: Type[Console] = Console) -> None: super().__init__(serial, console_class) self._servo_states: List[ServoPosition] = [None] * 16 @classmethod def discover(cls) -> Set[Board]: """ Discover boards that this backend can control. :returns: set of boards that this backend can control. """ return {cast(Board, SBArduinoBoard("SERIAL", cls("SERIAL")))} def get_servo_position(self, identifier: int) -> ServoPosition: """ Get the position of a servo. :param identifier: Port of servo to check. :returns: Position of servo. """ return self._servo_states[identifier] def set_servo_position( self, identifier: int, position: ServoPosition, ) -> None: """ Set the position of a servo. :param identifier: Port of servo to set position. :param position: Position to set the servo to. """ self._servo_states[identifier] = position self._console.info(f"Set servo {identifier} to {position}") def get_ultrasound_pulse( self, trigger_pin_identifier: int, echo_pin_identifier: int, ) -> Optional[timedelta]: """ Get a timedelta for the ultrasound time. :param trigger_pin_identifier: pin number of the trigger pin. :param echo_pin_identifier: pin number of the echo pin. :returns: Time taken for the pulse, or None if it timed out. """ microseconds = self._console.read( f"Response time for ultrasound sensor on pins " f"{trigger_pin_identifier}/{echo_pin_identifier} [microseconds]", float, ) self._update_ultrasound_pin_modes(trigger_pin_identifier, echo_pin_identifier) return timedelta(microseconds=microseconds) def get_ultrasound_distance( self, trigger_pin_identifier: int, echo_pin_identifier: int, ) -> Optional[float]: """ Get a distance in metres. :param trigger_pin_identifier: pin number of the trigger pin. :param echo_pin_identifier: pin number of the echo pin. :returns: Distance measured in metres, or None if it timed out. """ metres = self._console.read( f"Distance for ultrasound sensor on pins " f"{trigger_pin_identifier}/{echo_pin_identifier} [metres]", float, ) self._update_ultrasound_pin_modes(trigger_pin_identifier, echo_pin_identifier) return metres def _update_ultrasound_pin_modes( self, trigger_pin_identifier: int, echo_pin_identifier: int, ) -> None: """ Ultrasound functions force the pins into particular modes. :param trigger_pin_identifier: pin number of the trigger pin. :param echo_pin_identifier: pin number of the echo pin. """ self._pins[trigger_pin_identifier].mode = GPIOPinMode.DIGITAL_OUTPUT self._pins[trigger_pin_identifier].digital_state = False self._pins[echo_pin_identifier].mode = GPIOPinMode.DIGITAL_INPUT
3,858
label.py
timvandermeij/sentiment-analysis
12
2022822
import sys import os import linecache import json from collections import OrderedDict from analyze import Analyzer from utils import Utilities class Labeler: def __init__(self, dataset): self.dataset = dataset self.labels = OrderedDict([ ('p', 'positive'), ('n', 'negative'), ('t', 'neutral'), ('u', 'unknown') ]) if not os.path.isfile(dataset + '.json'): print('Dataset file "' + dataset + '" not found') sys.exit(1) self.original_num_lines = sum(1 for line in open(dataset + '.json')) self.labeled_num_lines = 0 if os.path.isfile(dataset + '.labeled.json'): self.labeled_num_lines = sum(1 for line in open(dataset + '.labeled.json')) def start(self): analyzer = Analyzer('id') options = [] for k, v in self.labels.items(): opt = '[{}]'.format(Utilities.get_colored_text(v, k)) options.append(v.replace(k, opt) if k in v else "{} {}".format(opt, v)) choices = ', '.join(options) while self.labeled_num_lines < self.original_num_lines: line = self.labeled_num_lines + 1 # linecache provides random access to lines in (large) text files raw_json = linecache.getline(self.dataset + '.json', line) json_object = json.loads(raw_json) message = json_object['body'] (label, disp, message) = analyzer.analyze(message) print(Utilities.get_colored_text('head', '--- Labeling message {} (ID: {}) ---'.format(line, json_object['id']))) print(message + '\n') print('Guess: {}'.format(Utilities.get_colored_text(label))) choice = '?' while choice != '' and choice not in self.labels: choice = raw_input('Label (Enter to confirm, or {}): '.format(choices)) if choice == 'q': return text = self.labels[choice] if choice is not '' else Utilities.score_to_label(label) print('You entered: {}\n'.format(Utilities.get_colored_text(text, text))) json_object['label'] = text Utilities.write_json(self.dataset + '.labeled.json', json_object, ["id", "label"]) self.labeled_num_lines += 1 def main(argv): dataset = argv[0] if len(argv) > 0 else 'commit_comments-dump.2015-01-29' labeler = Labeler(dataset) labeler.start() if __name__ == "__main__": main(sys.argv[1:])
2,559
ansible/roles/cloud_master/files/api_srv/take_snapshot.py
tinh-sau-di-v/hitbsecconf-ctf-2021
16
2024961
#!/usr/bin/python3 # Developed by <NAME> from Hackerdom team, <EMAIL> """Takes a snapshot of vm""" import sys import time import os import traceback import re import do_api from cloud_common import (log_progress, call_unitl_zero_exit, #get_cloud_ip, SSH_OPTS #SSH_YA_OPTS ) TEAM = int(sys.argv[1]) NAME = sys.argv[2] IMAGE_VM_NAME = "team%d" % TEAM def log_stderr(*params): print("Team %d:" % TEAM, *params, file=sys.stderr) def main(): if not re.fullmatch(r"[0-9a-zA-Z_]{,64}", NAME): print("msg: ERR, name validation error") return 1 image_state = open("db/team%d/image_deploy_state" % TEAM).read().strip() if image_state == "NOT_STARTED": print("msg: ERR, vm is not started") return 1 if image_state == "RUNNING": ids = do_api.get_ids_by_vmname(IMAGE_VM_NAME) if not ids: log_stderr("failed to find vm") return 1 if len(ids) > 1: log_stderr("more than one vm with this name exists") return 1 result = do_api.take_vm_snapshot(list(ids)[0], IMAGE_VM_NAME + "-" + NAME) if not result: log_stderr("take shapshot failed") return 1 print("msg: OK, snapshoting is in progress, it takes several minutes") return 0 if __name__ == "__main__": sys.stdout = os.fdopen(1, 'w', 1) print("started: %d" % time.time()) exitcode = 1 try: os.chdir(os.path.dirname(os.path.realpath(__file__))) exitcode = main() except: traceback.print_exc() print("exit_code: %d" % exitcode) print("finished: %d" % time.time())
1,690
tarea_23/solitario.py
zumaia/theEgg
0
2024604
#!/usr/bin/env python # coding: utf-8 # ## Tarea 23. Ejercicio Solitario # 1.- Una primera función a la que enviemos una variable (que será una frase o cadena e texto) para que la función lo cifre mediante el solitario. En programación existen diferentes tipos de variables: strings, enteros, flotantes, booleanos, ... y en este caso la variable o parámetro que se le envía a la función es de tipo String. # # 2.- Una segunda función que recoja el mensaje cifrado y lo descifre utilizando este mismo algoritmo. # # In[3]: # La primera parte consiste en crear la baraja de póker: el número 53 corrsponde al comodín A y el 54 al B # baraja = list(range(1,55)) # Barajamos la baraja utilizando el método shuffle # random.shuffle(baraja) # Algoritmo Solitario def solitario(): """ Generamos stream mediante Solitario Paso 1: Buscamos el comodín A que equivale a la carta 53 de nuestra baraja y lo intercambiamos con la carta de debajo suyo Hay que checkear con sentencia if si A está en última posición para pasarlo al principio de la baraja """ # print(baraja) baraja = [ 18, 8, 53, 17, 48, 24, 11, 35, 22, 27, 10, 16, 51, 23, 47, 2, 40, 44, 43, 19, 49, 6, 3, 1, 25, 12, 38, 54, 20, 21, 52, 45, 37, 26, 42, 32, 39, 14, 4, 50, 28, 5, 9, 29, 36, 33, 46, 13, 15, 34, 41, 30, 31, 7, ] baraja2 = baraja posicion_A = baraja2.index(53) if posicion_A == 53: baraja2[posicion_A] = baraja2[0] baraja2[0] = 53 else: baraja2[posicion_A] = baraja2[posicion_A + 1] baraja2[posicion_A + 1] = 53 # print(baraja2) """ Paso 2: Buscamos el comodín B que equivale a la carta 54 de nuestra baraja y lo movemos debajo de la segunda carta Hay que checkear con sentencia if si B está en penúltima o última posición para pasarlo al principio de la baraja """ posicion_B = baraja2.index(54) if posicion_B == 52: # El comodín se desplaza al principio de la baraja baraja2[posicion_B] = baraja2[posicion_B + 1] baraja2[posicion_B + 1] = baraja2[0] baraja2[0] = 54 elif posicion_B == 53: # El comodín se desplaza a la segunda posición de la baraja baraja2[posicion_B] = baraja2[0] baraja2[0] = baraja2[1] baraja2[1] = 54 else: baraja2[posicion_B] = baraja2[posicion_B + 1] baraja2[posicion_B + 1] = baraja2[posicion_B + 2] baraja2[posicion_B + 2] = 54 # print(baraja2) """ Paso 3: Corta la baraja en tres, intercambiando las cartas antes del primer comodín con las cartas que están detrás del segundo comodín. """ posicion_A = baraja2.index(53) posicion_B = baraja2.index(54) if posicion_A < posicion_B: # El comodín A está antes que el comodín B baraja_corte_1 = baraja2[0:posicion_A] baraja_corte_2 = baraja2[posicion_A : (posicion_B + 1)] baraja_corte_3 = baraja2[(posicion_B + 1) : 54] else: # El comodín B está antes que el comodín A baraja_corte_1 = baraja2[0:posicion_B] baraja_corte_2 = baraja2[posicion_B : (posicion_A + 1)] baraja_corte_3 = baraja2[(posicion_A + 1) : 54] baraja_corte = baraja_corte_3 + baraja_corte_2 + baraja_corte_1 # print(baraja_corte) """ Paso 4: Mira la última carta. Conviértela a un número de 1 a 53 (usa el orden normal: tréboles, diamantes, corazones y picas. Si la carta es un trébol, toma su número tal cual. Si es de diamantes, suma 13 a su valor. Si es de corazones, súmale 26. Si es de picas, súmale 39. Ambos comodines suman 53). Cuenta el valor valor obtenido empezando en la carta superior (normamente yo cuento de 1 a 13 una y otra vez, si es preciso; es más fácil que contar hasta un número alto de forma secuencial). Corta tras esa carta, dejando la última carta de la baraja a final. """ ultima_carta = baraja_corte[53] baraja_corte2_1 = baraja_corte[0:ultima_carta] baraja_corte2_2 = baraja_corte[ultima_carta:53] barajada = baraja_corte2_2 + baraja_corte2_1 + [ultima_carta] # print(barajada) return barajada # In[4]: # print(solitario()) # In[5]: # Definimos función que tiene como parámetro la cadena de caracteres a cifrar y devuelve el mensaje cifrado def cifrado(frase): # Paso 1: Toma el mensaje cifrado y divídelo en grupos de cinco letras (ya debería estar en ese formato) # Quitamos los espacios en blanco de la cadena de caracteres frase_sinesp = frase.replace(" ", "") while ( len(frase_sinesp) < 10 ): # Le añado 'X' en caso de que el mensaje no sea multiplo de 5 frase_sinesp += "X" # Paso 2: Usa Solitario para generar la ristra. Si el receptor usa la misma clave que el transmisor, la ristra será la misma. # Definimos función que tiene como parámetro el mensaje cifrado y devuelve el mensaje original alfabeto = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ] stream = list(range(1, 11)) stream_alfabeto = list(range(1, 11)) suma = list(range(1, 11)) mensaje_original = list(range(1, 11)) for i in range(0, 10): baraja_solitario = solitario() # Mira la primera carta. Conviértela en un número de 1 a 53, de la misma manera que en el paso 4. Cuenta esas cartas (la primera carta es la uno) while ( baraja_solitario[0] == 53 or baraja_solitario[0] == 54 ): # Comprobamos que la primera carta no es un comodín baraja_solitario = solitario() contar = baraja_solitario[0] # numero = baraja_solitario[contar-1] if contar > 26: contar = contar - 26 # Necesitamos que llegue a 26 else: contar = contar stream[i] = contar # Paso 3: Convertimos el mensaje original de letras a números, A=1, B=2, etc mensaje_original[i] = alfabeto.index(frase_sinesp[i]) # Sumamos el mensaje original y el stream de Solitario, módulo 26. suma[i] = mensaje_original[i] + stream[i] if suma[i] > 26: suma[i] = suma[i] - 26 else: suma[i] = suma[i] stream_alfabeto[i] = alfabeto[suma[i] - 1] # print(stream_alfabeto) # print(suma) return suma, stream_alfabeto # In[6]: def descifrado(suma): # Paso 1 Usa Solitario para generar la ristra. Si el receptor usa la misma clave que el transmisor, la ristra será la misma. alfabeto = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ] stream = list(range(1, 11)) stream_alfabeto = list(range(1, 11)) resta = list(range(1, 11)) for i in range(0, 10): baraja_solitario = solitario() # Mira la primera carta. Conviértela en un número de 1 a 53, de la misma manera que en el paso 4. Cuenta esas cartas (la primera carta es la uno) while ( baraja_solitario[0] == 53 or baraja_solitario[0] == 54 ): # Comprobamos que la primera carta no es un comodín baraja_solitario = solitario() contar = baraja_solitario[0] # numero = baraja_solitario[contar-1] if contar > 26: contar = contar - 26 # Necesitamos que llegue a 26 else: contar = contar stream[i] = contar # Restamos el mensaje original y el stream de Solitario, módulo 26. resta[i] = suma[i] - stream[i] if resta[i] < 0: resta[i] = resta[i] + 26 else: resta[i] = resta[i] stream_alfabeto[i] = alfabeto[resta[i]] # print(stream_alfabeto) # print(resta) return stream_alfabeto # In[7]: def RespuestaCorrecta(x): """Funcion para comprobar que la respuesta del usuario es SI o NO Parametros: -x= String Return: -Devuelve la respuesta SI o NO """ while x.upper() != "NO" and x.upper() != "SI": print("RESPUESTA INCORRECTA, RESPONDA CON UN SI O UN NO") x = input("¿Desea CIFRAR-DESCIFRAR otro mensaje?") return x # Llamamos a las dos funciones para cifrar y descifrar el mensaje y mostramos por pantalla el mensaje cifrado y descifrado # In[8]: def main(): frase = input( "\n\tIntroduzca una frase a cifrar: \n" ) # Esta es la frase que tenemos que cifrar frase = frase.upper() suma, mensaje_cifrado = cifrado(frase) mensaje_descifrado = descifrado(suma) print("\nEl mensaje original es: ", frase) print("\nEl mensaje cifrado es el siguiente: " + str(mensaje_cifrado)) print("\nEl mensaje descifrado es el siguiente: " + str(mensaje_descifrado)) # nueva pregunta respuesta = "" while respuesta.upper() != "NO": main() respuesta = RespuestaCorrecta( input("¿Desea CIFRAR-DESCIFRAR otro mensaje (si o no)?") ) # In[ ]:
9,826
libs/utils/config.py
fyabc/NMT
0
2024768
#! /usr/bin/python # -*- encoding: utf-8 -*- from __future__ import print_function import json import re from .constants import ConfigFilePath, GeneratedPrefix __author__ = 'fyabc' def load_config(filename): """Load JSON config file and remove line comments.""" with open(filename, 'r') as f: _lines = list(f) for _i, _line in enumerate(_lines): _lines[_i] = re.sub(r'//.*\n', '\n', _line) return json.loads(''.join(_lines)) def save_config(config, filename, filter_prefix=GeneratedPrefix): """Save configuration to JSON config file. [NOTE]: do NOT save generated options (start with `filter_prefix`) """ filtered_config = { k: v for k, v in config.iteritems() if not k.startswith(filter_prefix) } with open(filename, 'w') as f: json.dump(filtered_config, f, indent=4) Config = load_config(ConfigFilePath) C = Config
924
myrelax/getMTR.py
fragrussu/MyRelax
3
2025018
### Voxel-wise calculation of MTR # # Author: <NAME>, University College London # CDSQuaMRI Project # <<EMAIL>> <<EMAIL>> # # Code released under BSD Two-Clause license # # Copyright (c) 2019 University College London. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are those # of the authors and should not be interpreted as representing official policies, # either expressed or implied, of the FreeBSD Project. ### Load useful modules import argparse, os, sys import nibabel as nib import numpy as np import warnings def MTRmap(*argv): ''' Calculate MTR from a MT "on" and a MT "off" acquisition INTERFACES MTRmap(mton_nifti,mtoff_nifti,mtr_output) MTRmap(mton_nifti,mtoff_nifti,mtr_output,mask_nifti) PARAMETERS - mton_nifti: path of a Nifti file storing the 3D MT "on" image (with off-res. pulse) - mtoff_nifti: path of a Nifti file storing the 3D MT "off" image (without off-res. pulse) - mtr_output: path of the Nifti file that will store the 3D output MTR image (saved as a double-precision floating point image FLOAT64); such an output map is calculated as MTR = 100 * (MToff - MTon)/MToff above, MTon is the image where the off-resonance pulse is played (so is "on") while MToff is the image where the off-resonance pulse is not played (so is "off") - mask_nifti: path of a Nifti file storting a mask (MTR will be calculated only where mask_nifti equals 1; 0 will be set in the MTR output map otherwise) Dependencies (Python packages): nibabel, numpy (other than standard library). References: "T1, T2 relaxation and magnetization transfer in tissue at 3T", Stanisz GJ, Magnetic Resonance in Medicine (2005), 54:507-512 Author: <NAME>, University College London CDSQuaMRI Project <<EMAIL>> <<EMAIL>>''' ### Get input parametrs Nargv = len(argv) mton_nifti = argv[0] mtoff_nifti = argv[1] mtr_output = argv[2] ### Load MT "on" data and check for consistency print(' ... loading input data') try: mton_obj = nib.load(mton_nifti) except: print('') print('ERROR: the 3D input MT "on" file {} does not exist or is not in NIFTI format. Exiting with 1.'.format(mton_nifti)) print('') sys.exit(1) mton_data = mton_obj.get_fdata() imgsize = mton_data.shape imgsize = np.array(imgsize) if imgsize.size!=3: print('') print('ERROR: the 3D input MT "on" file {} is not a 3D NIFTI. Exiting with 1.'.format(mton_nifti)) print('') sys.exit(1) ### Load MT off data and check for consistency try: mtoff_obj = nib.load(mtoff_nifti) except: print('') print('ERROR: the 3D input MT "off" file {} does not exist or is not in NIFTI format. Exiting with 1.'.format(mtoff_nifti)) print('') sys.exit(1) mtoff_data = mtoff_obj.get_fdata() mton_header = mton_obj.header mton_affine = mton_header.get_best_affine() mton_dims = mton_obj.shape mtoff_header = mtoff_obj.header mtoff_affine = mtoff_header.get_best_affine() mtoff_dims = mtoff_obj.shape mtoff_size = mtoff_data.shape mtoff_size = np.array(mtoff_size) if mtoff_size.size!=3: print('') print('ERROR: the 3D input MT "off" file {} is not a 3D NIFTI. Exiting with 1.'.format(mtoff_nifti)) print('') sys.exit(1) elif ( (np.sum(mton_affine==mtoff_affine)!=16) or (mton_dims[0]!=mtoff_dims[0]) or (mton_dims[1]!=mtoff_dims[1]) or (mton_dims[2]!=mtoff_dims[2]) ): print('') print('ERROR: the geometry of the MT on file {} and the MT off file {} do not match. Exiting with 1.'.format(mton_nifti,mtoff_nifti)) print('') sys.exit(1) ### Deal with optional arguments: mask if Nargv==4: got_mask = True mask_nifti = argv[3] try: mask_obj = nib.load(mask_nifti) except: print('') print('ERROR: the mask file {} does not exist or is not in NIFTI format. Exiting with 1.'.format(mask_nifti)) print('') sys.exit(1) # Make sure that the mask geometry matches that of the other files mask_data = mask_obj.get_fdata() mask_size = mask_data.shape mask_size = np.array(mask_size) mask_header = mask_obj.header mask_affine = mask_header.get_best_affine() mask_dims = mask_obj.shape if mask_size.size!=3: print('') print('WARNING: the mask file {} is not a 3D NIFTI file. Ignoring mask...'.format(mask_nifti)) print('') mask_data = np.ones(imgsize[0:3],'float64') elif ( (np.sum(mton_affine==mask_affine)!=16) or (mton_dims[0]!=mask_dims[0]) or (mton_dims[1]!=mask_dims[1]) or (mton_dims[2]!=mask_dims[2]) ): print('') print('WARNING: the geometry of the the mask file {} does not match that of the MT data. Ignoring mask...'.format(mask_nifti)) print('') mask_data = np.ones(imgsize[0:3],'float64') else: mask_data = np.array(mask_data,'float64') # Make sure mask is a binary file mask_data[mask_data>1] = 1 mask_data[mask_data<0] = 0 else: got_mask = False ### Calculate MTR map print(' ... calculating MTR') mton_data = np.array(mton_data,'float64') mtoff_data = np.array(mtoff_data,'float64') warnings.filterwarnings('ignore') # Ignore warnings - these are going to happen in the background for sure mtr_map = 100*(mtoff_data - mton_data) / mtoff_data # Calculate MTR mtr_map[np.isnan(mtr_map)] = 0.0 # Remove NaNs mtr_map[np.isinf(mtr_map)] = 0.0 # Remove Inf print(' ... substituting any nan and inf values with 0') # Use mask if required if got_mask==True: mtr_map[mask_data==0]=0 ### Save output print(' ... saving output file') buffer_header = mton_obj.header buffer_header.set_data_dtype('float64') # Make sure we save quantitative map as a float64 mtr_obj = nib.Nifti1Image(mtr_map,mton_obj.affine,buffer_header) nib.save(mtr_obj, mtr_output) ### Done print('') # Run the module as a script when required if __name__ == "__main__": ### Print help and parse arguments parser = argparse.ArgumentParser(description='Voxel-wise calculation of Magnetisation Transfer Ratio (MTR) from MT "on" and MT "off" images, which have already been co-registered. Dependencies (Python packages): nibabel, numpy (other than standard library). References: "T1, T2 relaxation and magnetization transfer in tissue at 3T", <NAME>, Magnetic Resonance in Medicine (2005), 54:507-512. Author: <NAME>, University College London, CDSQuaMRI Project. Email: <<EMAIL>> <<EMAIL>>.') parser.add_argument('mton_file', help='3D Nifti file storing the MT "on" image (with off-resonance pulse)') parser.add_argument('mtoff_file', help='3D Nifti file storing the MT "off" image (without off-resonance pulse)') parser.add_argument('out_file', help='3D Nifti file that will store the MTR map (100 x (MToff - MTon)/MToff), as double-precision floating point (FLOAT64)') parser.add_argument('--mask', metavar='<file>', help='mask in Nifti format where 1 flags voxels where MTR is required, 0 where is not') args = parser.parse_args() ### Get input arguments mtonfile = args.mton_file mtofffile = args.mtoff_file outfile = args.out_file maskfile = args.mask ### Deal with optional arguments if isinstance(maskfile, str)==1: # A mask for MT calculation has been provided maskrequest = True else: # A mask for MT calculation has not been provided maskrequest = False print('') print('********************************************************************') print(' MTR calculation ') print('********************************************************************') print('') print('Called on 3D Nifti files: {} (MT "on", with off-resonance pulse) and {} (MT "off", without off-resonance pulse)'.format(mtonfile,mtofffile)) print('Output MTR file: {}'.format(outfile)) print('') if (maskrequest==False): MTRmap(mtonfile, mtofffile, outfile) else: MTRmap(mtonfile, mtofffile, outfile, maskfile) ### Done print('Processing completed.') print('') sys.exit(0)
9,284
Jarvis_final_fORM.py
Nhildria/Pandora-Box-
0
2024449
import pyttsx3 #pip install pyttsx3 import speech_recognition as sr #pip install speechRecognition import datetime import wikipedia #pip install wikipedia import webbrowser import os import smtplib engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') # print(voices[1].id) #engine.setProperty('voice', 'english_rp+f3') engine.setProperty("rate", 178) def speak(audio): engine.say(audio) engine.runAndWait() def wishMe(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good Morning!") elif hour>=12 and hour<18: speak("Good Afternoon!") else: speak("Good Evening!") speak(" At your Service , I am Jarvis . Please tell me how may I help you") def takeCommand(): #It takes microphone input from the user and returns string output r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing...") query = r.recognize_google(audio, language='en-in') print(f"User said: {query}\n") except Exception as e: # print(e) print("Say that again please...") return "None" return query def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login('<EMAIL>', '<PASSWORD>') server.sendmail('<EMAIL>', to, content) server.close() if __name__ == "__main__": wishMe() while True: # if 1: query = takeCommand().lower() # Logic for executing tasks based on query if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) speak(results) elif 'open youtube' in query: webbrowser.open("youtube.com") elif 'open google' in query: webbrowser.open("google.com") elif 'open stackoverflow' in query: webbrowser.open("stackoverflow.com") elif 'open spotify' in query: os.system("Spotify") elif 'open note' in query: Note = "C:\\Users\\Phera\\AppData\\Local\\Programs\\standard-notes\\Standard Notes.exe" os.startfile(Note) elif 'open shell' in query: shell = "C:\\Users\\Phera\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Windows PowerShell\\Windows PowerShell (x86).lnk" os.startfile(shell) elif 'slay' in query: Slay= "C:\Program Files (x86)\Slay the Spire\SlayTheSpire.exe" os.startfile(Slay) elif 'play music' in query: music_dir = 'D:\\Non Critical\\songs\\Favorite Songs2' songs = os.listdir(music_dir) print(songs) os.startfile(os.path.join(music_dir, songs[0])) elif 'the time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"Sir, the time is {strTime}") elif 'open code' in query: codePath = "C:\\Users\\Phera\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" os.startfile(codePath) elif 'email to harry' in query: try: speak("What should I say?") content = takeCommand() to = "<EMAIL>" sendEmail(to, content) speak("Email has been sent!") except Exception as e: print(e) speak("Sorry my friend harry bhai. I am not able to send this email") elif 'exit' in query: exit()
3,931
AnuOyeboade/phase1/BASIC/DAY5/Q33.py
nkem1010/python-challenge-solutions
0
2022947
""" Write a Python program to sum of three given integers. However, if two values are equal sum will be zero. """ x = int(input("x = ")) y = int(input("y = ")) z = int(input("z = ")) Ans = str(x+y+z) if x==y or x==z or y==z: print("sum equals 0") else: print(Ans)
271
configs/curriculum/curriculum_config.py
pyrateml/agent
0
2022776
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnheider' ''' Description: Config for training Author: <NAME> ''' from utilities import * CONFIG_NAME = __name__ CONFIG_FILE = __file__ # Architecture POLICY_ARCH_PARAMS = { 'input_size': None, # Obtain from environment 'activation': F.leaky_relu, 'hidden_layers':[128, 64, 32, 16], 'output_size': None, # Obtain from environment, 'use_bias': False, } POLICY_ARCH = CategoricalMLP VALUE_ARCH_PARAMS = { 'input_size': None, # Obtain from environment 'activation': F.relu, 'hidden_layers':[128, 64, 32, 16], 'output_size': None, # Obtain from environment 'use_bias': False, } VALUE_ARCH = MLP # Optimiser OPTIMISER = torch.optim.Adam # OPTIMISER = torch.optim.RMSprop LEARNING_RATE = 0.00025 WEIGHT_DECAY = 1e-5 ALPHA = 0.95 EPSILON = 0.01 # Curriculum RANDOM_MOTION_HORIZON = 20 CANDIDATE_SET_SIZE = 3 CANDIDATE_ROLLOUTS = 3 LOW = 0.1 HIGH = 0.9
959
data_aggregator/tests/test_jobs_api.py
uw-it-aca/canvas-analytics
0
2024716
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 import unittest from data_aggregator.models import Job from data_aggregator.views.api.jobs import JobRestartView from django.utils import timezone from data_aggregator.tests.view_utils import BaseViewTestCase from data_aggregator.utilities import datestring_to_datetime from mock import patch class TestJobRestartView(BaseViewTestCase): fixtures = ['data_aggregator/fixtures/mock_data/da_job.json', 'data_aggregator/fixtures/mock_data/da_jobtype.json'] def test_post(self): with patch.object( timezone, "now", return_value=datestring_to_datetime("2021-04-2T12:00:00.0Z")): """ restart list of jobs and assert that their statuses changed """ jobs_to_restart = Job.objects.filter(id__in=[1, 2]) # claim jobs in order to reset the test for job in jobs_to_restart: self.assertEqual(job.status, "pending") job.claim_job() self.assertEqual(job.status, "claimed") # post to endpoint to restart jobs request = self.get_post_request('/api/internal/jobs/restart/', {"job_ids": [1, 2]}) response = JobRestartView().post(request) self.assertEqual(response.status_code, 200) # confirm that jobs were restarted and now pending reset_jobs = Job.objects.filter(id__in=[1, 2]) for job in reset_jobs: self.assertEqual(job.status, "pending") """ restart single of job and assert that other jobs are not effected """ # claim both jobs #1 and #2 for job in Job.objects.filter(id__in=[1, 2]): self.assertEqual(job.status, "pending") job.claim_job() self.assertEqual(job.status, "claimed") # post to endpoint to restart job #1 request = self.get_post_request('/api/internal/jobs/restart/', {"job_ids": [1]}) response = JobRestartView().post(request) self.assertEqual(response.status_code, 200) # confirm that job #1 were restarted and now pending jobs_to_restart = Job.objects.filter(id__in=[1]) for job in jobs_to_restart: self.assertEqual(job.status, "pending") # confirm that job #2 is still claimed job_to_exclude = Job.objects.get(id=2) self.assertEqual(job_to_exclude.status, "claimed") # assert that Job.objects.restart_jobs is called with patch.object(Job.objects, "restart_jobs") as mock_restart_jobs: request = self.get_post_request('/api/internal/jobs/restart/', {"job_ids": [1]}) JobRestartView().post(request) self.assertTrue(mock_restart_jobs.called) if __name__ == "__main__": unittest.main()
3,098
nicos_virt_mlz/treff/setups/counter.py
jkrueger1/nicos
12
2022968
# -*- coding: utf-8 -*- description = 'counter setup' group = 'lowlevel' devices = dict( mon0 = device('nicos.devices.generic.VirtualCounter', description = 'Monitor 0', type = 'monitor', fmtstr = '%d', ), mon1 = device('nicos.devices.generic.VirtualCounter', description = 'Monitor 1', type = 'monitor', fmtstr = '%d', ), )
391
lm/util/data.py
Tou7and/meta-transfer-learning
43
2023293
import os import torch from torch.autograd import Variable import math import util.datahelper as datahelper import util.texthelper as texthelper import random import numpy as np class LMDataset(object): def __init__(self, task_list, args): self.bptt = args.bptt self.batch_size = args.batch_size self.args = args self.task_list = [] for i in range(len(task_list)): self.task_list.append(self.batchify(task_list[i], self.batch_size)) super(LMDataset, self).__init__() def batchify(self, data, bsz): # Work out how cleanly we can divide the dataset into bsz parts. nbatch = data.size(0) // bsz # Trim off any extra elements that wouldn't cleanly fit (remainders). data = data.narrow(0, 0, nbatch * bsz) # Evenly divide the data across the bsz batches. data = data.view(bsz, -1).t().contiguous() if self.args.cuda: data = data.cuda() return data def get_batch(self, source, i, evaluation=False): seq_len = min(self.bptt, len(source) - 1 - i) if evaluation: with torch.no_grad(): data = Variable(source[i:i+seq_len]) else: data = Variable(source[i:i+seq_len]) target = Variable(source[i+1:i+1+seq_len].view(-1)) return data, target def sample(self, manifest_id, i): def func(p): return p.size(1) def func_trg(p): return len(p) ids = self.task_list[manifest_id] num_batch = math.ceil(ids.size(0) / self.bptt) # shuffled_indices = np.random.choice(np.arange(0, num_batch), 2, replace=True) # tr_id = shuffled_indices[0] # val_id = shuffled_indices[1] tr_id = i val_id = i+1 tr_ids = ((tr_id * self.bptt) % len(ids)) - (((tr_id * self.bptt) % len(ids)) % self.bptt) val_ids = (((val_id) * self.bptt) % len(ids)) - ((((val_id) * self.bptt) % len(ids)) % self.bptt) tr_src, tr_target = self.get_batch(ids, tr_ids) val_src, val_target = self.get_batch(ids, val_ids) return (tr_src, tr_target, val_src, val_target) class Dictionary(object): def __init__(self): self.word2idx = {} self.idx2word = {} def add_word(self, word): if word not in self.word2idx: self.idx2word[len(self.idx2word)] = word self.word2idx[word] = len(self.idx2word) - 1 return self.word2idx[word] def __len__(self): return len(self.idx2word) class Corpus(object): def __init__(self, train_path, valid_path=None, test_path=None, dictionary=None, seed=1000): random.seed(seed) if dictionary is None: self.dictionary = Dictionary() else: self.dictionary = dictionary print("load dictionary") self.train, self.train_lang = self.tokenize(train_path, True) print("train:", len(self.dictionary)) if valid_path is not None: self.valid, self.valid_lang = self.tokenize(valid_path, False) print("valid:", len(self.dictionary)) else: print("valid_path is None") if test_path is not None: self.test, self.test_lang = self.tokenize(test_path, False) print("test:", len(self.dictionary)) else: print("test_path is None") print("dictionary size:", len(self.dictionary)) def create_seq_idx_matrix(self, path): assert os.path.exists(path) matrix = [] with open(path, 'r') as f: for line in f: line = line.strip() line = line.replace(" ", " ") words = line.split() + ['<eos>'] word_tokens = torch.LongTensor(len(words)) for i in range(len(words)): word = words[i] if not word in self.dictionary.word2idx: word_id = self.dictionary.word2idx["<oov>"] else: word_id = self.dictionary.word2idx[word] word_tokens[i] = word_id matrix.append(word_tokens.unsqueeze_(1)) return matrix def create_seq_word_matrix(self, path): assert os.path.exists(path) matrix = [] with open(path, 'r') as f: for line in f: line = line.strip() line = line.replace(" ", " ") words = line.split() + ['<eos>'] word_tokens = [] for word in words: word_tokens.append(word) matrix.append(word_tokens) return matrix def tokenize(self, path, save, randomize=False): """Tokenizes a text file.""" assert os.path.exists(path) # Add words to the dictionary self.dictionary.add_word("<oov>") data = [] with open(path, 'r') as f: for line in f: data.append(line) # if randomize: # random.shuffle(data) # with open(path, 'r') as f: tokens = 0 for i in range(len(data)): line = data[i] line = line.strip().lower() line = line.replace(" ", " ") words = line.split() + ['<eos>'] tokens += len(words) for word in words: if save: self.dictionary.add_word(word) # Tokenize file content with open(path, 'r') as f: ids = torch.LongTensor(tokens) langs = torch.LongTensor(tokens) token = 0 for line in f: line = line.strip().lower() line = line.replace(" ", " ") words = line.split() + ['<eos>'] for word in words: if not word in self.dictionary.word2idx: ids[token] = self.dictionary.word2idx["<oov>"] else: ids[token] = self.dictionary.word2idx[word] if texthelper.is_contain_chinese_word(word): langs[token] = 1 else: langs[token] = 0 token += 1 return ids, langs
6,580
client/client_test.py
zkactivity/imtest
0
2022626
import socket HOST = '192.168.199.216' PORT = 9877 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True: cmd = input("Please input msg:") s.send(cmd) data = s.recv(1024) print(data) #s.close()
252
camera/videoRecording.py
Caizhi111/Prototype
0
2025028
# yiling #import os #os.system('ffmpeg -t 30 -f v4l2 -framerate 25 -video_size 640x80 -i /prototype/camera/ -t 300 output.mkv') #yufei import numpy as np import cv2 import time import os import random import sys #fourcc = cv2.VideoWriter_fourcc(*'MJPG') fourcc = cv2.VideoWriter_fourcc(*'X264') path = "/home/pi/Prototype/web/static/video" try: os.makedirs(path) except FileExistsError: # directory already exists pass cap = cv2.VideoCapture(0) cur_dir = os.path.dirname(os.path.abspath(sys.argv[0])) start = time.time() video_file = path + "/video.mp4" print("Capture video saved location : {}".format(video_file)) # Create a video write before entering the loop out = cv2.VideoWriter(video_file, fourcc, 24, (640, 480)) while cap.isOpened(): start_time = time.time() ret, frame = cap.read() if ret == True: cv2.imshow("frame", frame) if time.time() - start > 30: #Every ten seconds save the video in created directory file start = time.time() path = "/home/pi/Prototype/web/static/video" video_file = path + "/video.mp4" out = cv2.VideoWriter(video_file, fourcc, 24, (640, 480)) # No sleeping! We don't want to sleep, we want to write # time.sleep(10) # Write the frame to the current video writer out.write(frame) if cv2.waitKey(1) & 0xFF == ord("q"): break else: break cap.release() out.release() cv2.destroyAllWindows()
1,499
app/db/schemas/projects.py
Luivatra/ergopad-api
0
2024529
from pydantic import BaseModel import typing as t ### SCHEMAS FOR PROJECTS ### class Socials(BaseModel): telegram: t.Optional[str] twitter: t.Optional[str] discord: t.Optional[str] github: t.Optional[str] website: t.Optional[str] class CreateAndUpdateProject(BaseModel): name: str shortDescription: str description: t.Optional[str] fundsRaised: t.Optional[float] socials: Socials bannerImgUrl: str isLaunched: bool class Project(CreateAndUpdateProject): id: int class Config: orm_mode = True class CreateAndUpdateProjectTeamMember(BaseModel): name: str description: t.Optional[str] # we do not know projectId when project is created projectId: t.Optional[int] profileImgUrl: t.Optional[str] class ProjectTeamMember(CreateAndUpdateProjectTeamMember): id: int class Config: orm_mode = True class ProjectWithTeam(Project): team: t.List[ProjectTeamMember] class Config: orm_mode = True class CreateAndUpdateProjectWithTeam(CreateAndUpdateProject): team: t.Optional[t.List[CreateAndUpdateProjectTeamMember]]
1,141
package/PartSeg/common_gui/select_multiple_files.py
monotropauniflora/PartSeg
0
2024665
import os from glob import glob from pathlib import Path from qtpy.QtCore import Qt, Signal from qtpy.QtWidgets import ( QAbstractItemView, QDialog, QFileDialog, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton, QVBoxLayout, QWidget, ) from ..common_backend.base_settings import BaseSettings class AcceptFiles(QDialog): def __init__(self, files): super(AcceptFiles, self).__init__() self.ok = QPushButton("Add", self) self.ok.clicked.connect(self.accept) discard = QPushButton("Discard", self) discard.clicked.connect(self.close) self.files = QListWidget(self) self.files.setSelectionMode(QAbstractItemView.ExtendedSelection) for file_name in files: self.files.addItem(file_name) for i in range(self.files.count()): self.files.item(i).setSelected(True) self.ok.setDefault(True) self.ok.setAutoDefault(True) layout = QVBoxLayout() layout.addWidget(QLabel("Found {} files".format(len(files)))) layout.addWidget(self.files) butt_layout = QHBoxLayout() butt_layout.addWidget(discard) butt_layout.addStretch() butt_layout.addWidget(self.ok) layout.addLayout(butt_layout) self.setLayout(layout) def selection_changed(self): if self.files.selectedItems().count() == 0: self.ok.setDisabled(True) else: self.ok.setEnabled(True) def get_files(self): return [str(item.text()) for item in self.files.selectedItems()] class AddFiles(QWidget): """Docstring for AddFiles. """ file_list_changed = Signal(set) def __init__(self, settings: BaseSettings, parent=None, btn_layout=QHBoxLayout): """TODO: to be defined1. """ QWidget.__init__(self, parent) self.settings = settings self.files_to_proceed = set() self.paths = QLineEdit(self) self.selected_files = QListWidget(self) self.selected_files.itemSelectionChanged.connect(self.file_chosen) self.found_button = QPushButton("Find all", self) self.found_button.clicked.connect(self.find_all) self.select_files_button = QPushButton("Select files") self.select_dir_button = QPushButton("Select directory") self.select_files_button.clicked.connect(self.select_files) self.select_dir_button.clicked.connect(self.select_directory) self.delete_button = QPushButton("Remove file", self) self.delete_button.setDisabled(True) self.delete_button.clicked.connect(self.delete_element) self.clean_button = QPushButton("Remove all", self) self.clean_button.clicked.connect(self.clean) layout = QVBoxLayout() layout.addWidget(self.paths) select_layout = btn_layout() select_layout.addWidget(self.select_files_button) select_layout.addWidget(self.select_dir_button) select_layout.addWidget(self.found_button) select_layout.addStretch() select_layout.addWidget(self.clean_button) select_layout.addWidget(self.delete_button) layout.addLayout(select_layout) layout.addWidget(self.selected_files) self.setLayout(layout) def find_all(self): paths = glob(str(self.paths.text())) paths = sorted([x for x in (set(paths) - self.files_to_proceed) if not os.path.isdir(x)]) if len(paths) > 0: dialog = AcceptFiles(paths) if dialog.exec_(): new_paths = dialog.get_files() for path in new_paths: size = os.stat(path).st_size size = float(size) / (1024 ** 2) lwi = QListWidgetItem("{:s} ({:.2f} MB)".format(path, size)) lwi.setTextAlignment(Qt.AlignRight) self.selected_files.addItem(lwi) self.files_to_proceed.update(new_paths) self.file_list_changed.emit(self.files_to_proceed) else: QMessageBox.warning(self, "No new files", "No new files found", QMessageBox.Ok) def select_files(self): dial = QFileDialog(self, "Select files") dial.setDirectory( self.settings.get("io.batch_directory", self.settings.get("io.load_image_directory", str(Path.home()))) ) dial.setFileMode(QFileDialog.ExistingFiles) if dial.exec_(): self.settings.set("io.batch_directory", os.path.dirname(str(dial.selectedFiles()[0]))) new_paths = sorted(set(map(str, dial.selectedFiles())) - self.files_to_proceed) for path in new_paths: size = os.stat(path).st_size size = float(size) / (1024 ** 2) lwi = QListWidgetItem("{:s} ({:.2f} MB)".format(path, size)) lwi.setTextAlignment(Qt.AlignRight) self.selected_files.addItem(lwi) self.files_to_proceed.update(new_paths) self.file_list_changed.emit(self.files_to_proceed) def select_directory(self): dial = QFileDialog(self, "Select directory") dial.setDirectory( self.settings.get("io.batch_directory", self.settings.get("io.load_image_directory", str(Path.home()))) ) dial.setFileMode(QFileDialog.Directory) if dial.exec_(): self.paths.setText(dial.selectedFiles()[0]) self.settings.set("io.batch_directory", str(dial.selectedFiles()[0])) def file_chosen(self): self.delete_button.setEnabled(True) def delete_element(self): item = self.selected_files.takeItem(self.selected_files.currentRow()) path = str(item.text()) path = path[: path.rfind("(") - 1] self.files_to_proceed.remove(path) self.file_list_changed.emit(self.files_to_proceed) if self.selected_files.count() == 0: self.delete_button.setDisabled(True) def clean(self): self.selected_files.clear() self.files_to_proceed.clear() self.file_list_changed.emit(self.files_to_proceed) def get_paths(self): return list(sorted(self.files_to_proceed))
6,253
lib/pdf_export/pdf_exporter.py
SBC2000/excel-scripts
0
2025026
import os import pdfkit from html_generator import HtmlGenerator from lib.model.game import RankGame, ResultGame from lib.model.pool import PoolType from lib.model.game_schedule import GameSchedule class PdfExporter: def __init__(self): self.generator = HtmlGenerator() def export_rankings(self, pools, page_layout=None): file_name = "Standen.pdf" ordered_pools = self.__order_pools(pools, page_layout) if page_layout else self.__get_default_pool_order(pools) body = self.__create_rankings_body(ordered_pools) html = self.__create_html(body) pdfkit.from_string(html, file_name, options={"quiet": ""}) os.startfile(file_name, 'open') def export_schedule(self, game_schedule, export_saturday, export_sunday): file_name = "Schema.pdf" body = self.__create_schedule_body(game_schedule, export_saturday, export_sunday) html = self.__create_html(body) pdfkit.from_string(html, file_name, options={"quiet": ""}) os.startfile(file_name, 'open') def __create_rankings_body(self, ordered_pools): """ @type ordered_pools: list[list[Pool]] @rtype: str """ return self.__create_page_separator().join( [self.__create_pool_separator().join( ["<h1>{0}<h1>{1}{2}".format(pool.name, self.__create_pool_tables(pool), self.__create_finals(pool)) for pool in pools] ) for pools in ordered_pools] ) def __create_pool_tables(self, pool): result = "" for sub_pool in (pool.sub_pools if pool.sub_pools else [pool]): if sub_pool != pool: result += "<h2>{0}</h2>".format(sub_pool.name) table = self.__create_rankings_table(sub_pool.compute_ranking(), sub_pool.games) table_width = len(iter(table).next()) column_info = {"width": [15, 150] + [40] * (table_width - 6) + [26] * 4, "header-alignment": ["center", "left"] + ["center"] * (table_width - 2), "content-alignment": ["center", "left"] + ["center"] * (table_width - 2), "color": ["white"] * (table_width - 4) + ["lightgray"] + ["white"] * 3} result += self.generator.create_html_table(table, column_info, True, True) return result def __create_finals(self, pool): """ @type pool: Pool @rtype: str """ # warning: this does probably not scale well for generic pool formats!! if pool.pool_type in [PoolType.full_with_semi_finals, PoolType.split_with_semi_finals]: cross_finals = [final for final in pool.finals if isinstance(final, RankGame)] finals = [final for final in pool.finals if isinstance(final, ResultGame)] else: cross_finals = [] finals = [final for final in pool.finals if isinstance(final, RankGame)] result = "" if cross_finals: result += "<h2>{0}</h2>".format("Kruisfinales") result += self.__create_finals_table(cross_finals) numbered_finals = zip(range(1, 2 * len(finals), 2), reversed(finals)) for i, final in numbered_finals: result += "<h2>Om plaats {0} / {1}</h2>".format(i, i + 1) result += self.__create_finals_table([final]) return result def __create_schedule_body(self, game_schedule, export_saturday, export_sunday): """ @type game_schedule: GameSchedule @type export_saturday: bool @type export_sunday: bool @return: """ dates = [date for date, include in zip(game_schedule.dates, [export_saturday, export_sunday]) if include] return self.__create_page_separator() \ .join(["<h1>{0} &#8211; {1}<h1>{2}".format(pitch.name, "Zaterdag" if date == game_schedule.dates[0] else "Zondag", self.__create_schedule_table( [game for game in game_schedule.get_games_by_pitch(pitch) if game.datetime.date() == date]) ) for date in dates for pitch in game_schedule.pitches]) @staticmethod def __create_finals_table(finals): result = "" result += "<table class=\"finals\">" for final in finals: result += "<tr>" result += "<td width=\"160\" class=\"finals\">" + final.get_home_team_name() + "</td>" result += "<td width=\"10\" class=\"finals\">-</td>" result += "<td width=\"160\" class=\"finals\">" + final.get_away_team_name() + "</td>" result += "<td width=\"20\" class=\"finals\"></td>" result += "<td align=\"center\" width=\"20\" class=\"finals\">" + str( int(final.result.home_score)) if final.result else "" + "</td>" result += "<td align=\"center\" width=\"10\" class=\"finals\">" + "-" if final.result else "" + "</td>" result += "<td align=\"center\" width=\"20\" class=\"finals\">" + str( int(final.result.away_score)) if final.result else "" + "</td>" result += "</tr>" result += "</table>" return result @staticmethod def __create_pool_separator(): return "<br/><br/>" @staticmethod def __create_page_separator(): return "<div style=\"page-break-after:always !important;\"></div>" @staticmethod def __create_html(body): style = "<style>" \ "body { font-family: Helvetica }" \ "@page { size: a4 portrait, margin: 2cm } " \ "h1, tr, td, th {-pdf-keep-with-next: true; }" \ "table { border: 2pt solid black; " \ "border-spacing: 0; border-collapse: collapse; }" \ "td, th { border: 1pt solid black; padding: 2pt;}" \ "th.rotate { height: 160px; width: 40px; white-space: nowrap; }" \ "th.rotate > div { -webkit-transform: rotate(270deg) }" \ "th.rotate > div > span { position: absolute; left:-64px; top: -16px; padding: 5px 10px; }" \ "table.finals, td.finals { border: 0pt }" \ "</style>" return "<html><head>{0}</head><body>{1}</body></html>".format(style, body) @staticmethod def __create_rankings_table(ranking, games): """ Ranking is a tuple of (Team, points, score+, score-) tuples. @type ranking: tuple(tuple(Team, int, int, int)) @param games: @return: """ games_by_teams = {(game.home_team, game.away_team): game for game in games} table = [["", ""] + [r[0].name for r in ranking] + ["Punten", "Doelpunten voor", "Doelpunten tegen", "Saldo"]] for i, r in enumerate(ranking): home_team = r[0] row = [i + 1, home_team.name] for o in ranking: away_team = o[0] game = games_by_teams.get((home_team, away_team)) row.append("{0}-{1}".format(int(game.result.home_score), int(game.result.away_score)) if game and game.result else "") row.extend([int(r[1]), int(r[2]), int(r[3]), int(r[2] - r[3])]) table.append(row) return table @staticmethod def __order_pools(pools, page_layout): pools_by_abbreviation = {pool.abbreviation: pool for pool in pools} return [[pools_by_abbreviation[abbreviation] for abbreviation in page] for page in page_layout] @staticmethod def __get_default_pool_order(pools): return [[pool] for pool in pools] @staticmethod def __create_schedule_table(games): table = [["Tijd", "Nr.", "Wit", "Blauw", "Uitslag", "Scheidsrechters", "Jury"]] for game in games: row = [ game.datetime.strftime("%H:%M"), game.name, game.get_home_team_name(), game.get_away_team_name(), "{0} - {1}".format(int(game.result.home_score), int(game.result.away_score)) if game.result else "", game.get_referees_string(), game.jury if game.jury else "", ] table.append(row) column_info = {"width": [60, 60, 160, 160, 60, 160, 160], "header-alignment": ["center", "center", "left", "left", "center", "left", "left"], "content-alignment": ["center", "center", "left", "left", "center", "left", "left"], "color": ["white"] * 7} return HtmlGenerator().create_html_table(table, column_info, True, False)
9,149
proj/routers.py
azul-cloud/django-rest-server
0
2025007
from rest_framework import routers from blog.views import ArticleViewSet from accounts.views import UserViewSet v1_router = routers.DefaultRouter() v1_router.register('articles', ArticleViewSet) v1_router.register('users', UserViewSet)
239
first-party/fbjni/docs/build_quickref.py
Huxpro/hermes
1,466
2024632
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import collections import itertools import re import sys def main(argv): sections = collections.defaultdict(list) toc = read_toc("docs/quickref_toc.txt") grab_sections("test/DocTests.java", sections) grab_sections("test/jni/doc_tests.cpp", sections) missing_code = toc.keys() - sections.keys() if missing_code: raise Exception(f"Missing code for sections: {' '.join(missing_code)}") missing_toc = sections.keys() - toc.keys() if missing_toc: raise Exception(f"Missing toc for sections: {' '.join(missing_toc)}") with open("docs/quickref.md", "w") as handle: handle.write("# Quick Reference\n") for section in toc: name = toc[section].strip() handle.write(f"- [{name}](#{anchor(name)})\n") for section in toc: render_section(handle, section, toc[section], sections[section]) def anchor(title): anchor = title.lower() anchor = re.sub(" ", "-", anchor) anchor = re.sub(r"[^-\w]", "", anchor) return anchor def read_toc(fname): with open(fname) as handle: return collections.OrderedDict(line.split(" ", 1) for line in handle) def grab_sections(fname, sections): extension = fname.split(".")[1] active_block = None with open(fname) as handle: for lnum, line in enumerate(handle): lnum += 1 if line.strip().endswith("// END"): active_block = None continue m = re.search(r"// SECTION (\w+)$", line) if m: if active_block is not None: raise Exception(f"Nested section at {fname}:{lnum}") active_group = m.group(1) active_block = [] sections[active_group].append((extension, active_block)) continue if line.strip().endswith(" MARKDOWN"): if active_block is None: raise Exception(f"Orphaned markdown at {fname}:{lnum}") active_block = [] sections[active_group].append(("md", active_block)) continue if active_block is not None: active_block.append(line) def render_section(out, name, title, blocks): out.write(f"## {title}") for syntax, lines in blocks: if not lines: # This happens with Markdown-first sections continue if syntax != "md": lines = itertools.chain( [f"```{syntax}\n"], lines, ["```\n"], ) for line in lines: out.write(line) out.write("\n\n") if __name__ == "__main__": sys.exit(main(sys.argv))
2,801
sample/crud.py
rogrs/pythoncrud
0
2023685
#!/usr/bin/env python ''' MySQL CRUD (Create Retrieve Update Delete) Operations using Python ''' # Import MySQLdb $ sudo apt-get install python-mysqldb import MySQLdb as mdb import sys # CREATE A NEW TABLE and INSERT SOME VALUES def createTable(con): with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS TableTest") cur.execute("CREATE TABLE TableTest(Id INT PRIMARY KEY AUTO_INCREMENT, \ Name VARCHAR(25))") cur.execute("INSERT INTO TableTest(Name) VALUES('<NAME>')") cur.execute("INSERT INTO TableTest(Name) VALUES('Tizio')") cur.execute("INSERT INTO TableTest(Name) VALUES('Caio')") cur.execute("INSERT INTO TableTest(Name) VALUES('Sempronio')") cur.execute("INSERT INTO TableTest(Name) VALUES('<NAME>')") # RETRIEVE TABLE ROWS def retrieveTable(con): with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM TableTest") rows = cur.fetchall() for row in rows: print row["Id"], row["Name"] # UPDATE ROW def updateRow(con): with con: cur = con.cursor() cur.execute("UPDATE TableTest SET Name = %s WHERE Id = %s", ("<NAME>", "4")) print "Number of rows updated:", cur.rowcount # DELETE ROW def deleteRow(con): with con: cur = con.cursor() cur.execute("DELETE FROM TableTest WHERE Id = %s", "2") print "Number of rows deleted:", cur.rowcount # SET UP THE CONNECTION try: con = mdb.connect('127.0.0.1', 'testuser', 'test2017', 'testDB'); cur = con.cursor() cur.execute("SELECT VERSION()") ver = cur.fetchone() print "Database version : %s " % ver # CRUD OPERATIONS createTable(con) retrieveTable(con) updateRow(con) deleteRow(con) except mdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) finally: if con: con.close()
1,978
main.py
NilssonHarnertJerhamre/smart-login
0
2024297
from profile import * from preprocess import * from listener import * from classifier import * from knn import * import numpy as np import os datafile = 'data.txt' phrase = '.tie<PASSWORD>' samples_for_new_profile = 7 clear = lambda: os.system('cls') pp = Preprocess() l = Listener() c = Classifier(datafile) def login(): user = raw_input('user: ') events = l.listen(phrase) input = '' for e in events: if e.type is Type.key_pressed and isinstance(e.char, unicode): input += e.char.encode('utf-8') if input != phrase: raw_input('wrong phrase \n<enter to continue>') return times = pp.preprocess(events) prediction = c.predict_user(times) print 'chosen profile is \'' + str(user) + '\' prediction was \'' + str(prediction[0]) + '\'' if str(user) == str(prediction[0]): c.add_data(times, user) c.train_on_data() raw_input('<enter to continue>') def create_profile(): user = raw_input('user: ') if c.profile_exists(user): raw_input('profile already exists <enter to continue>') return training_times = [] i = 0 while i < samples_for_new_profile: print 'type the phrase ('+str(i+1)+' of '+str(samples_for_new_profile)+' times)' events = l.listen(phrase) s = '' for e in events: if e.type is Type.key_pressed and isinstance(e.char, unicode): s += e.char.encode('utf-8') if s != phrase: print 'wrong phrase!' continue times = pp.preprocess(events) training_times.append(times) i+=1 for t in training_times: c.add_data(t, user) while 1: clear() print 'smart login\n' print '1.\tlogin' print '2.\tcreate profile' print 'q.\tquit' ans = raw_input('choice: ') if ans == '1': login() elif ans == '2': create_profile() elif ans == 'q': #quit break
1,735
twitter_monitor/twitter_monitor.py
TheRensselaerIDEA/covid19_tweet_ids
0
2023907
""" Script for running the twitter monitor listener/processor """ import argparse import time import tweepy import logging from elasticsearch import Elasticsearch from setup_index import verify_or_setup_index from config import Config from tm_stream_listener import TwitterMonitorStreamListener def start(): #load the args & config parser = argparse.ArgumentParser("Run the twitter monitor listener/processor") parser.add_argument("--configfile", "-c", default="config.json", required=False, help="Path to the config file to use.") parser.add_argument("--logfile", "-l", default="tmlog.txt", required=False, help="Path to the log file to write to.") args = parser.parse_args() config = Config.load(args.configfile) #Configure logging logging.basicConfig(filename=args.logfile, format="[%(asctime)s - %(levelname)s]: %(message)s", level=logging.getLevelName(config.log_level)) print("Logging level set to {0}...".format(config.log_level)) print() #Verify or setup the elasticsearch index es = Elasticsearch(hosts=[config.elasticsearch_host], verify_certs=config.elasticsearch_verify_certs, timeout=config.elasticsearch_timeout_secs) index_result = verify_or_setup_index(es, config) logging.info(index_result) print(index_result) print() #load the credentials and initialize tweepy auth = tweepy.OAuthHandler(config.api_key, config.api_secret_key) auth.set_access_token(config.access_token, config.access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) #listen to the stream API restart_attempts = 0 while True: try: streamListener = TwitterMonitorStreamListener(es, config) stream = tweepy.Stream(auth=api.auth, listener=streamListener) print("Listening for tweets...") print() logging.info("Starting listener...") stream.filter(languages=config.filter_languages, track=config.filter_keywords) except Exception as ex: logging.exception("Exception occurred while listening.") if streamListener.received_data: restart_attempts = 0 restart_attempts += 1 if config.restart_attempts > -1 and restart_attempts > config.restart_attempts: logging.critical("Restart attempt limit reached. Shutting down...") break logging.warning("Restarting after {0} seconds (attempt {1})...".format(config.restart_wait_secs, restart_attempts)) time.sleep(config.restart_wait_secs) if __name__ == "__main__": start()
2,736
firstapp/migrate_base_data.py
mudong1991/DevOpsApi
1
2023719
# -*- coding:utf-8 -*- # Created migrate_base_data at 2017/3/9 0009 # __author__ = "Mundy" """ 同步数据库时,初始化部分数据 """ import threading from django.conf import settings from django.contrib.auth.models import * from django.contrib.auth.hashers import make_password from firstapp.models import * def init(): """ 初始化数据 :return: """ if AppInstall.objects.filter(name='git').exists(): return # 初始化添加app AppInstall.objects.create(name='git', version='2.11.0', app_image='/media/app_images/git.jpg') AppInstall.objects.create(name='docker', version='1.7.1', app_image='/media/app_images/docker.jpg') AppInstall.objects.create(name='jdk', version='1.8.0_131', app_image='/media/app_images/jdk.jpg') AppInstall.objects.create(name='redis', version='3.2.8', app_image='/media/app_images/redis.jpg') AppInstall.objects.create(name='mysql', version='5.6.35', app_image='/media/app_images/mysql.jpg') AppInstall.objects.create(name='mongodb', version='3.3.3', app_image='/media/app_images/mongodb.jpg') AppInstall.objects.create(name='zookeeper', version='3.4.10', app_image='/media/app_images/zookeeper.jpg') AppInstall.objects.create(name='kafka', version='0.10.2.1', app_image='/media/app_images/kafka.jpg') AppInstall.objects.create(name='nginx', version='1.8.1', app_image='/media/app_images/nginx.jpg') AppInstall.objects.create(name='consul', version='2.11.1', app_image='/media/app_images/consul.jpg') AppInstall.objects.create(name='maven', version='3.5.0', app_image='/media/app_images/maven.jpg') # 初始化用户、角色、权限 admin_permissions = range(1, 500) # 管理员权限,全部权限 # 系统管理用户组 admin_group = Group.objects.create(name='系统管理员') # 主要控制接口权限 # 角色 admin_role = Role.objects.create(name='系统管理员') # 主要控制菜单 # 用户 admin = User.objects.create(username='admin', password=make_password('<PASSWORD>'), is_superuser=1) admin.groups.add(admin_group) admin.role = admin_role admin.save() def thread_init(sender, **kwargs): """ 第一个参数必须是sender,且必须有kwargs参数 :param sender: :param kwargs: :return: """ # 在另一个线程中执行init方法,主要是为了解决数据库事务提交延迟的问题。 t = threading.Timer(1, init) t.start()
2,216
base_state/test.py
mando222/tri-25
0
2024213
#!/usr/bin/env python3 import requests BASE = "http://127.0.0.1:5000/" response = requests.get(BASE + "api/get_key/data") print(response.json()) response = requests.get(BASE + "api/insert/test=test") print(response.json()) response = requests.get(BASE + "api/get_key/test") print(response.json()) response = requests.get(BASE + "api/get_state") print(response.json()) response = requests.get(BASE + "api/update/data=blah") print(response.json()) response = requests.get(BASE + "api/get_state") print(response.json()) response = requests.get(BASE + "api/delete/bad_key") print(response.json()) response = requests.get(BASE + "api/delete/test") print(response.json()) response = requests.get(BASE + "api/get_state") print(response.json())
747
devel/PRJ4/metaCNN2-1.py
mjirik/bodynavigation
5
2024313
import CT_regression_tools import numpy as np from pathlib import Path model = CT_regression_tools.VGG_16() pth = Path(__file__).parent model.save(pth / 'vgg.h5')
163
test/test_endec.py
isstabb/qpylib
0
2025131
# Copyright 2019 IBM Corporation All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 # # pylint: disable=redefined-outer-name, unused-argument import json from unittest.mock import patch import os import pytest from qpylib.encdec import Encryption DB_STORE = 'test_user_e.db' @pytest.fixture(scope='module', autouse=True) def pre_testing_setup(): with patch('qpylib.abstract_qpylib.AbstractQpylib.log'): yield # Mock out get_store_path to return encryption db in test dir, then delete after each test @pytest.fixture() def patch_get_store_path(): file_path = DB_STORE with patch('qpylib.qpylib.get_store_path') as mocked_get_store_path: mocked_get_store_path.return_value = DB_STORE yield if os.path.isfile(file_path): os.remove(file_path) @pytest.fixture() def set_unset_qradar_app_uuid_env_var(): os.environ['QRADAR_APP_UUID'] = "6599ba78-4896-11e8-842f-0ed5f89f718b" yield del os.environ['QRADAR_APP_UUID'] def test_encryption_raises_value_error_on_missing_name_and_user_fields(): with pytest.raises(ValueError) as ex: Encryption({}) assert "Encryption : name and user are mandatory fields!" == str(ex.value) with pytest.raises(ValueError) as ex: Encryption({"name": "test_name"}) assert "Encryption : name and user are mandatory fields!" == str(ex.value) with pytest.raises(ValueError) as ex: Encryption({"user": "test_user"}) assert "Encryption : name and user are mandatory fields!" == str(ex.value) def test_encryption_raises_value_error_on_missing_env_var(): with pytest.raises(KeyError) as ex: Encryption({"name": "test_name", "user": "test_user"}) assert "'Encryption : QRADAR_APP_UUID not available in environment'" == str(ex.value) def test_encrypt_creates_valid_config_on_start(set_unset_qradar_app_uuid_env_var, patch_get_store_path): Encryption({"name": "test_name", "user": "test_user"}) assert os.path.isfile(DB_STORE) def test_encryption_returns_empty_string_encrypting_empty_string(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) assert enc.encrypt('') == '' def test_encryption_stores_encrypted_secret_in_config(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) enc_string = enc.encrypt('testing123') assert enc_string != 'testing123' with open(DB_STORE) as db_file: file_json = json.load(db_file) assert file_json.get('test_name').get('secret') == enc_string def test_decrypt_returns_plaintext_after_encryption(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) enc_string = enc.encrypt('testing123') assert enc_string != 'testing123' assert enc.decrypt() == 'testing123' def test_decrypt_raises_error_when_config_missing(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) enc_string = enc.encrypt('testing123') assert enc_string != 'testing123' os.remove(DB_STORE) enc = Encryption({"name": "test_name", "user": "test_user"}) with pytest.raises(ValueError) as ex: enc.decrypt() assert "Encryption : no secret to decrypt" == str(ex.value) def test_decrypt_returns_incorrect_plaintext_with_altered_salt(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) enc_string = enc.encrypt('testing123') assert enc_string != 'testing123' with open(DB_STORE) as db_file: file_json = json.load(db_file) file_json['test_name']['salt'] = 'incorrect' with open(DB_STORE, 'w') as db_file: json.dump(file_json, db_file) enc = Encryption({"name": "test_name", "user": "test_user"}) assert enc.decrypt() != 'testing123' def test_decrypt_raise_value_error_on_engine_version_mismatch(set_unset_qradar_app_uuid_env_var, patch_get_store_path): enc = Encryption({"name": "test_name", "user": "test_user"}) enc_string = enc.encrypt('testing123') assert enc_string != 'testing123' with open(DB_STORE) as db_file: file_json = json.load(db_file) file_json['test_name']['version'] = -1 with open(DB_STORE, 'w') as db_file: json.dump(file_json, db_file) enc = Encryption({"name": "test_name", "user": "test_user"}) with pytest.raises(ValueError) as ex: enc.decrypt() assert "Encryption : secret engine mismatch." in str(ex.value)
4,978
filebox/views.py
sharmaeklavya2/Filebox
0
2023773
from django.shortcuts import render from django.http import HttpResponseRedirect from django.conf import settings import os def base_response(request,body,h1=None): context_dict = {"base_body": body} if h1!=None: context_dict["base_h1"] = h1 return render(request, "base.html", context_dict) def get_folder_size_and_file_count(path): total_size = 0 file_count = 0 for dirpath, dirnames, filenames in os.walk(path): file_count+= len(filenames) for fname in filenames: fpath = os.path.join(dirpath, fname) total_size += os.path.getsize(fpath) return (total_size, file_count) def save_uploaded_file(uploaded_file, overwrite=False): dest_file_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name) file_exists = os.path.isfile(dest_file_path) if file_exists and not overwrite: return "already_exists" if file_exists: old_size = os.path.getsize(dest_file_path) else: old_size = 0 folder_size, file_count = get_folder_size_and_file_count(settings.MEDIA_ROOT) if folder_size - old_size + uploaded_file.size > settings.FOLDER_SIZE_LIM: return "too_large" if not file_exists and file_count>=settings.FILE_COUNT_LIM: return "too_many" with open(dest_file_path,"wb+") as dest_file: for chunk in uploaded_file.chunks(): dest_file.write(chunk) return "success" message_map = { "success": "{0} was successfully saved", "already_exists": "{0} already exists", "too_large": "{0} does not fit because it is too large", "too_many": "{0} does not fit because the folder has too many files", } def upload(request): context_dict = {} if request.method=="POST": if "files" in request.FILES: file_list = request.FILES.getlist("files") else: file_list = [] context_dict["status_list"] = [] for ufile in file_list: retval = save_uploaded_file(ufile) print(ufile.name,type(ufile)) message = message_map[retval].format(ufile.name) context_dict["status_list"].append(message) folder_size, file_count = get_folder_size_and_file_count(settings.MEDIA_ROOT) context_dict["num_remaining"] = settings.FILE_COUNT_LIM - file_count context_dict["mib_remaining"] = (settings.FOLDER_SIZE_LIM - folder_size)/(1024*1024) return render(request, "upload.html", context_dict)
2,222
src/tests/basic_deployment.py
openstack/charm-tempest
13
2024333
from charmhelpers.contrib.openstack.amulet.deployment import ( OpenStackAmuletDeployment ) from charmhelpers.contrib.openstack.amulet.utils import ( OpenStackAmuletUtils, DEBUG, ) # Use DEBUG to turn on debug logging u = OpenStackAmuletUtils(DEBUG) class TempestBasicDeployment(OpenStackAmuletDeployment): """Amulet tests on a basic tempest deployment.""" def __init__(self, series, openstack=None, source=None, stable=False): """Deploy the entire test environment.""" super(TempestBasicDeployment, self).__init__(series, openstack, source, stable) self._add_services() self._add_relations() self._configure_services() self._deploy() u.log.info('Waiting on extended status checks...') exclude_services = [] self._auto_wait_for_status(exclude_services=exclude_services) self.d.sentry.wait() self._initialize_tests() def _add_services(self): """Add services Add the services that we're testing, where tempest is local, and the rest of the service are from lp branches that are compatible with the local charm (e.g. stable or next). """ this_service = {'name': 'tempest'} other_services = [ {'name': 'percona-cluster', 'constraints': {'mem': '3072M'}}, {'name': 'rabbitmq-server'}, {'name': 'keystone'}, {'name': 'openstack-dashboard'}, {'name': 'glance'} ] super(TempestBasicDeployment, self)._add_services( this_service, other_services, no_origin=['tempest']) def _add_relations(self): """Add all of the relations for the services.""" relations = { 'keystone:identity-admin': 'tempest:identity-admin', 'tempest:dashboard': 'openstack-dashboard:website', 'openstack-dashboard:identity-service': 'keystone:identity-service', 'keystone:shared-db': 'percona-cluster:shared-db', 'glance:identity-service': 'keystone:identity-service', 'glance:shared-db': 'percona-cluster:shared-db', 'glance:amqp': 'rabbitmq-server:amqp' } super(TempestBasicDeployment, self)._add_relations(relations) def _configure_services(self): """Configure all of the services.""" pxc_config = { 'dataset-size': '25%', 'max-connections': 1000, 'root-password': '<PASSWORD>', 'sst-password': '<PASSWORD>', } configs = { 'percona-cluster': pxc_config, } super(TempestBasicDeployment, self)._configure_services(configs) def _get_token(self): return self.keystone.service_catalog.catalog['token']['id'] def _initialize_tests(self): """Perform final initialization before tests get run.""" # Access the sentries for inspecting service units self.tempest_sentry = self.d.sentry['tempest'][0] self.openstack_dashboard_sentry = \ self.d.sentry['openstack-dashboard'][0] u.log.debug('openstack release val: {}'.format( self._get_openstack_release())) u.log.debug('openstack release str: {}'.format( self._get_openstack_release_string())) def test_run_tempest(self): u.log.debug('Running Tempest...') unit = self.tempest_sentry assert u.status_get(unit)[0] == "active" action_id = u.run_action(unit, "run-tempest") assert u.wait_on_action(action_id), "run-tempest action failed."
3,686
mp/scenarios/migrations/0001_initial.py
Ecotrust/COMPASS
1
2024858
# Generated by Django 2.2.1 on 2019-05-29 16:05 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('auth', '0011_update_proxy_permissions'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='GridCell', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('objectid', models.IntegerField(blank=True, null=True)), ('hex_id', models.IntegerField(blank=True, default=None, null=True)), ('auspatid', models.IntegerField(blank=True, default=None, null=True)), ('ecoregion', models.TextField(blank=True, default=None, null=True)), ('coa_name', models.TextField(blank=True, default=None, null=True)), ('habitat', models.TextField(blank=True, null=True)), ('fish', models.TextField(blank=True, null=True)), ('obs_spec', models.TextField(blank=True, null=True)), ('mod_spec', models.TextField(blank=True, null=True)), ('centroid', django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=3857)), ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(blank=True, null=True, srid=3857, verbose_name='Grid Cell Geometry')), ], ), migrations.CreateModel( name='Scenario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='Name')), ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Date Created')), ('date_modified', models.DateTimeField(auto_now=True, verbose_name='Date Modified')), ('object_id', models.PositiveIntegerField(blank=True, null=True)), ('habitat', models.BooleanField()), ('fish', models.BooleanField()), ('obs_spec', models.BooleanField()), ('mod_spec', models.BooleanField()), ('description', models.TextField(blank=True, null=True)), ('satisfied', models.BooleanField(default=True, help_text='Am I satisfied?')), ('active', models.BooleanField(default=True)), ('grid_cells', models.TextField(blank=True, null=True, verbose_name='Grid Cell IDs')), ('geometry_final_area', models.FloatField(blank=True, null=True, verbose_name='Total Area')), ('geometry_dissolved', django.contrib.gis.db.models.fields.MultiPolygonField(blank=True, null=True, srid=3857, verbose_name='Filter result dissolved')), ('content_type', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, related_name='scenarios_scenario_related', to='contenttypes.ContentType')), ('sharing_groups', models.ManyToManyField(blank=True, editable=False, null=True, related_name='scenarios_scenario_related', to='auth.Group', verbose_name='Share with the following groups')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scenarios_scenario_related', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), ]
3,746
sdk/python/pulumi_azure/network/get_virtual_network.py
Frassle/pulumi-azure
0
2023942
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime from .. import utilities, tables class GetVirtualNetworkResult(object): """ A collection of values returned by getVirtualNetwork. """ def __init__(__self__, address_spaces=None, dns_servers=None, subnets=None, vnet_peerings=None, id=None): if address_spaces and not isinstance(address_spaces, list): raise TypeError('Expected argument address_spaces to be a list') __self__.address_spaces = address_spaces """ The list of address spaces used by the virtual network. """ if dns_servers and not isinstance(dns_servers, list): raise TypeError('Expected argument dns_servers to be a list') __self__.dns_servers = dns_servers """ The list of DNS servers used by the virtual network. """ if subnets and not isinstance(subnets, list): raise TypeError('Expected argument subnets to be a list') __self__.subnets = subnets """ The list of name of the subnets that are attached to this virtual network. """ if vnet_peerings and not isinstance(vnet_peerings, dict): raise TypeError('Expected argument vnet_peerings to be a dict') __self__.vnet_peerings = vnet_peerings """ A mapping of name - virtual network id of the virtual network peerings. """ if id and not isinstance(id, str): raise TypeError('Expected argument id to be a str') __self__.id = id """ id is the provider-assigned unique ID for this managed resource. """ async def get_virtual_network(name=None, resource_group_name=None): """ Use this data source to access information about an existing Virtual Network. """ __args__ = dict() __args__['name'] = name __args__['resourceGroupName'] = resource_group_name __ret__ = await pulumi.runtime.invoke('azure:network/getVirtualNetwork:getVirtualNetwork', __args__) return GetVirtualNetworkResult( address_spaces=__ret__.get('addressSpaces'), dns_servers=__ret__.get('dnsServers'), subnets=__ret__.get('subnets'), vnet_peerings=__ret__.get('vnetPeerings'), id=__ret__.get('id'))
2,449
data/python/appinit.py
Nextpertise/freeradius-amqp
0
2022979
#!/usr/bin/env python import pika import time rabbitmq_host = "rabbitmq" rabbitmq_port = 5672 rabbitmq_user = "radiustest" rabbitmq_password = "<PASSWORD>" rabbitmq_virtual_host = "/" rabbitmq_send_exchange = "fr.authorize" rabbitmq_rcv_exchange = "fr.authorize" rabbitmq_rcv_queue = "queue_radius" rabbitmq_rcv_key = "rlm_amqp_authorize" # The binding area credentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_password) connection = pika.BlockingConnection(pika.ConnectionParameters(rabbitmq_host, rabbitmq_port, rabbitmq_virtual_host, credentials)) channel = connection.channel() # Create queue if not exist channel.exchange_declare( exchange='fr.authorize', exchange_type='direct', passive=False, durable=True, auto_delete=False ) channel.queue_declare(queue=rabbitmq_rcv_queue, auto_delete=False) channel.queue_bind(queue=rabbitmq_rcv_queue, exchange=rabbitmq_rcv_exchange, routing_key=rabbitmq_rcv_key) channel.basic_publish( exchange=rabbitmq_send_exchange, routing_key=rabbitmq_rcv_key, body="hallo", mandatory=False ) #channel.queue_bind(exchange=rabbitmq_rcv_exchange, queue=rabbitmq_rcv_queue, routing_key=rabbitmq_rcv_key)
1,153
microservices-2/track.py
beaubadilla/cpsc449_backend_engineering
0
2022757
import sys import flask_api from flask import request from flask_api import status, exceptions import pugsql import uuid import sqlite3 app = flask_api.FlaskAPI(__name__) app.config.from_envvar('APP_CONFIG') queries = pugsql.module('queries/') queries.connect(app.config['DATABASE_URL']) queries1 = pugsql.module('tracks1_queries/') queries1.connect(app.config['DATABASE_URL1']) queries2 = pugsql.module('tracks2_queries/') queries2.connect(app.config['DATABASE_URL2']) queries3 = pugsql.module('tracks3_queries/') queries3.connect(app.config['DATABASE_URL3']) sqlite3.register_adapter(uuid.UUID, lambda u: u.bytes_le) sqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b)) @app.cli.command('init') def init_db(): with app.app_context(): db1 = queries1._engine.raw_connection() word_file1 = open('tracks1.sql', mode = 'r', encoding='utf-8') word_file_read1 = word_file1.read() word_file1.close() db1.cursor().executescript(word_file_read1) db1.commit() db2 = queries2._engine.raw_connection() word_file2 = open('tracks2.sql', mode = 'r', encoding='utf-8') word_file_read2 = word_file2.read() word_file2.close() db2.cursor().executescript(word_file_read2) db2.commit() db3 = queries3._engine.raw_connection() word_file3 = open('tracks3.sql', mode = 'r', encoding='utf-8') word_file_read3 = word_file3.read() word_file3.close() db3.cursor().executescript(word_file_read3) db3.commit() db = queries._engine.raw_connection() word_file = open('data.sql', mode='r', encoding='utf-8') word_file_read = word_file.read() word_file.close() db.cursor().executescript(word_file_read) db.commit() @app.route('/', methods=['GET']) def home(): return '''<h1>Available endpoints: </h1> <h2>Tracks: </h2> <ol><li><a href="/api/v1/tracks">Create a track</a><p>{ "TrackName": "sample", "Album": "An Album", "Artist": "An Artist", "Length": 12345, "Url": "file://aplace/this.mp3", "Art": "something.jpg" }</p></li><li><a href="/api/v1/tracks?id=2">Retrieve a track</a></li><li><a href="/api/v1/tracks">Edit a track</a><p>{ "TrackId": 1, "TrackName": "Updated name", "Album": "Updated Album", "Artist": "Updated Artist", "Length": 12345, "Url": "file://aplace/this.mp3", "Art": "something.jpg" }</p></li><li><a href="/api/v1/tracks?id=1">Delete a track</a></li></ol> ''' # all track endpoints will leade here @app.route('/api/v1/tracks', methods=['POST', 'GET', 'DELETE', 'PUT']) def tracks(): if request.method == 'GET': return get_track(request.args), status.HTTP_200_OK elif request.method == 'POST': return create_track(request.data) elif request.method == 'DELETE': return delete_track(request.args) elif request.method == 'PUT': return edit_track(request.data) # allows the creation of a new track to ne inserted into DB. # If no Art is given, then we declare it to NULL def create_track(track): track = request.data required_fields = ['TrackName', 'Album', 'Artist', 'Length', 'Url'] if not all([field in track for field in required_fields]): raise exceptions.ParseError() try: if not 'Art' in track.keys(): track['Art'] = None TrackId = uuid.uuid4() # UUID object track['TrackID'] = TrackId intTrackId = int(TrackId) # int representation of UUID object shard_key = intTrackId % 3 if shard_key == 0: queries1.create_track(**track) elif shard_key == 1: queries2.create_track(**track) elif shard_key == 2: queries3.create_track(**track) except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT location_url = f'http://localhost:5300/api/v1/tracks?id={TrackId}' return track, status.HTTP_201_CREATED, { "Content-Type": "application/json", "Location": location_url} # edits track given the TrackId. Since this is a PUT, # it is expected to pass in the whole object to # replace the current object #(Optional): since we are given a whole object with PUT, there # is no need to have different files for each column update. # Unless we are doing PATCH. def edit_track(track): track = request.data required_fields = ['TrackId'] if not all([field in track for field in required_fields]): raise exceptions.ParseError try: shard_key = track['TrackId'] % 3 if shard_key == 0: for updates in track: if updates == 'TrackName': b = queries1.update_track_name(**track) if updates == 'Album': b = queries1.update_track_album(**track) if updates == 'Artist': b = queries1.update_track_artist(**track) if updates == 'Length': b = queries1.update_track_length(**track) if updates == 'Url': b = queries1.update_track_url(**track) if updates == 'Art': b = queries1.update_track_art(**track) track = queries1.track_by_id(**track) elif shard_key == 1: for updates in track: if updates == 'TrackName': b = queries2.update_track_name(**track) if updates == 'Album': b = queries2.update_track_album(**track) if updates == 'Artist': b = queries2.update_track_artist(**track) if updates == 'Length': b = queries2.update_track_length(**track) if updates == 'Url': b = queries1.update_track_url(**track) if updates == 'Art': b = queries2.update_track_art(**track) track = queries2.track_by_id(**track) elif shard_key == 2: for updates in track: if updates == 'TrackName': b = queries3.update_track_name(**track) if updates == 'Album': b = queries3.update_track_album(**track) if updates == 'Artist': b = queries3.update_track_artist(**track) if updates == 'Length': b = queries3.update_track_length(**track) if updates == 'Url': b = queries3.update_track_url(**track) if updates == 'Art': b = queries3.update_track_art(**track) track = queries3.track_by_id(**track) except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT return track, status.HTTP_201_CREATED # deletes a track, from a given 'id' # if no 'id' is given then returns '400 BAD REQUEST' def delete_track(track): if 'id' in track: track = { "TrackId": track['id'] } try: shard_key = track['TrackId'] % 3 if shard_key == 0: queries1.delist_track_from_playlists(**track) track = queries1.delete_track_by_id(**track) elif shard_key == 1: queries2.delist_track_from_playlists(**track) track = queries2.delete_track_by_id(**track) elif shard_key == 2: queries3.delist_track_from_playlists(**track) track = queries3.delete_track_by_id(**track) except Exception as e: return { 'error': str(e) }, status.HTTP_409_CONFLICT if track: return {"info": "Successfully deleted"}, status.HTTP_200_OK else: raise exceptions.NotFound() return {'error': "Did not provide an id for track to be deleted"}, status.HTTP_400_BAD_REQUEST # Returns all tracks in the DB. def all_tracks(): all_tracks1 = queries1.all_tracks() all_tracks2 = queries2.all_tracks() all_tracks3 = queries3.all_tracks() all_tracks = all_tracks1 + all_tracks2 + all_tracks3 return list(all_tracks) # returns a track given 'id'. If no ID is given then return all tracks. # do this to activate flaskAPI, so we can easily POST, PUT... def get_track(track): if 'id' in track: track = { "TrackId": track['id'] } myUUID = str(track['TrackId']) myUUID = uuid.UUID(myUUID) track['TrackId'] = myUUID shard_key = myUUID.int % 3 try: if shard_key == 0: track = queries1.track_by_id(**track) elif shard_key == 1: track = queries2.track_by_id(**track) elif shard_key == 2: track = queries3.track_by_id(**track) except Exception as e: return e else: return all_tracks() track['TrackId'] = str(uuid.UUID(bytes=track['TrackId'])) if track: return track else: raise exceptions.NotFound()
9,202
docker/ubuntu/16-04/ub_limonero/limonero/app.py
eubr-atmosphere/jenkins
0
2024792
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import argparse import itertools import logging import logging.config import os import signal import eventlet import eventlet.wsgi import sqlalchemy_utils import yaml from flask import Flask, request from flask_admin import Admin from flask_babel import get_locale, Babel from flask_babel import gettext from flask_cors import CORS from flask_redis import FlaskRedis from flask_restful import Api, abort from data_source_api import DataSourceDetailApi, DataSourceListApi, \ DataSourcePermissionApi, DataSourceUploadApi, DataSourceInferSchemaApi, \ DataSourcePrivacyApi, DataSourceDownload, DataSourceSampleApi from limonero import CustomJSONEncoder as LimoneroJSONEncoder from limonero.admin import DataSourceModelView, StorageModelView, HomeView, \ init_login, AuthenticatedMenuLink from limonero.cache import cache from limonero.model_api import ModelDetailApi, ModelListApi from limonero.models import db, DataSource, Storage from limonero.storage_api import StorageDetailApi, StorageListApi from privacy_api import GlobalPrivacyListApi, AttributePrivacyGroupListApi from py4j_init import init_jvm os.chdir(os.environ.get('LIMONERO_HOME', '.')) sqlalchemy_utils.i18n.get_locale = get_locale eventlet.monkey_patch(all=True, thread=False) app = Flask(__name__, static_url_path='', static_folder='static') app.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.abspath( 'limonero/i18n/locales') app.json_encoder = LimoneroJSONEncoder babel = Babel(app) logging.config.fileConfig('logging_config.ini') app.secret_key = 'l3m0n4d1' # Flask Admin admin = Admin(app, name='Lemonade Limonero', template_mode='bootstrap3', url="/control-panel", base_template='admin/master.html', index_view=HomeView(url='/control-panel')) admin.add_link(AuthenticatedMenuLink(name='Logout', endpoint='admin.logout_view')) # Cache cache.init_app(app) # CORS CORS(app, resources={r"/*": {"origins": "*"}}) api = Api(app) redis_store = FlaskRedis() # Initialize flask-login init_login(app) mappings = { '/datasources': DataSourceListApi, '/datasources/upload': DataSourceUploadApi, '/datasources/infer-schema/<int:data_source_id>': DataSourceInferSchemaApi, '/datasources/sample/<int:data_source_id>': DataSourceSampleApi, '/datasources/<int:data_source_id>': DataSourceDetailApi, '/datasources/<int:data_source_id>/permission/<int:user_id>': DataSourcePermissionApi, '/datasources/<int:data_source_id>/privacy': DataSourcePrivacyApi, '/privacy': GlobalPrivacyListApi, '/privacy/attribute-groups': AttributePrivacyGroupListApi, '/models': ModelListApi, '/models/<int:model_id>': ModelDetailApi, '/storages': StorageListApi, '/storages/<int:storage_id>': StorageDetailApi, } grouped_mappings = itertools.groupby(sorted(mappings.items()), key=lambda path: path[1]) for view, g in grouped_mappings: api.add_resource(view, *[x[0] for x in g], endpoint=view.__name__) app.add_url_rule('/datasources/<int:data_source_id>/download', methods=['GET'], endpoint='DataSourceDownload', view_func=DataSourceDownload.as_view('download')) # for route in app.url_map.iter_rules(): # print route # @app.before_request def before(): if request.args and 'lang' in request.args: if request.args['lang'] not in ('es', 'en'): return abort(404) @app.route('/static/<path:path>') def static_file(path): return app.send_static_file(path) @babel.localeselector def get_locale(): return request.args.get( 'lang', request.accept_languages.best_match(['en', 'pt', 'es'])) # noinspection PyUnusedLocal def exit_gracefully(s, frame): os.kill(os.getpid(), signal.SIGTERM) def main(is_main_module): config_file = None signal.signal(signal.SIGINT, exit_gracefully) if is_main_module: parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, help="Config file", required=False) args = parser.parse_args() config_file = args.config if config_file is None: config_file = os.environ.get('LIMONERO_CONFIG') logger = logging.getLogger(__name__) if config_file: with open(config_file) as f: config = yaml.load(f)['limonero'] app.config['LIMONERO_CONFIG'] = config app.config["RESTFUL_JSON"] = {"cls": app.json_encoder} server_config = config.get('servers', {}) app.config['SQLALCHEMY_DATABASE_URI'] = server_config.get( 'database_url') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_POOL_SIZE'] = 10 app.config['SQLALCHEMY_POOL_RECYCLE'] = 240 app.config['SQLALCHEMY_POOL_RECYCLE'] = 240 app.config.update(config.get('config', {})) db.init_app(app) port = int(config.get('port', 5000)) logger.debug( gettext('Running in %(mode)s mode', mode=config.get('environment'))) if is_main_module: # JVM, used to interact with HDFS. init_jvm(app, logger) if config.get('environment', 'dev') == 'dev': admin.add_view(DataSourceModelView(DataSource, db.session)) admin.add_view(StorageModelView(Storage, db.session)) app.run(debug=True, port=port) else: eventlet.wsgi.server(eventlet.listen(('', port)), app) else: logger.error( gettext('Please, set LIMONERO_CONFIG environment variable')) exit(1) if __name__ == '__main__': main(__name__ == '__main__')
5,803
study_example_snippet/chapter_04_serializer/01_serializing_dataclass_support.py
KimSoungRyoul/DjangoBackendProgramming
0
2023215
"""" 순수 Python3.7미만 버전을 사용해서 직렬화 하는 로직 작성하기 """ from __future__ import annotations import dataclasses import json from datetime import date from datetime import datetime from datetime import time from enum import Enum from typing import Any from typing import Dict from typing import Optional from django.core.serializers.json import DjangoJSONEncoder from django.forms import model_to_dict from rest_framework.utils.encoders import JSONEncoder @dataclasses.dataclass class Organization: class OrganizationType(Enum): BUSINESS = "business" MANAGEMENT_SUPPORT = "management_support" TECHNOLOGY_RESEARCH = "technology_research" name: str = "" organization_type: OrganizationType = "" leader: Optional[User] = None @dataclasses.dataclass class User: username: str = dataclasses.field(default="") password: str = dataclasses.field(default="") email: str = dataclasses.field(default="") name: str = dataclasses.field(default="") age: int = dataclasses.field(default=-1) is_superuser: bool = dataclasses.field(default=False) created_at: datetime = dataclasses.field(default_factory=datetime.now) organization: Optional[Organization] = dataclasses.field(default=None) class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (datetime, date)): return obj.strftime("%Y-%m-%d %H:%M:%S") if isinstance(obj, Organization): return obj.__dict__ return super().default(obj) dictionary_data = {"나는datetime객체": datetime.now(), "나는time객체": time(11, 34), "나는date객체": date(2020, 8, 22)} JSONEncoder model_to_dict() print(json.dumps(dictionary_data, cls=DjangoJSONEncoder)) print(json.dumps(dictionary_data, cls=CustomJSONEncoder)) if __name__ == "__main__": user: User = User( username="soungryoul.kim0823", password="<PASSWORD>!", name="김성렬", email="<EMAIL>", age=37, is_superuser=False, organization=Organization( name="서버 개발1팀", leader=User(username="teamjang.kim0102", password="<PASSWORD>!", name="김팀장"), ), ) user_serializing_dict: Dict[str, Any] = dataclasses.asdict(user) print(f"Type: {type(user_serializing_dict)}", f"Data: {user_serializing_dict}") user_serializing_json: str = json.dumps(user_serializing_dict, cls=CustomJSONEncoder) print(f"Type: {type(user_serializing_json)}", f"Data: {user_serializing_json}") user_serializing_bytes: bytes = user_serializing_json.encode("utf-8") print(f"Type: {type(user_serializing_bytes)}", f"Data: {user_serializing_bytes}")
2,639
userProfile/migrations/0004_auto_20200404_2135.py
TheWITProject/MentorApp
0
2023827
# Generated by Django 2.2.10 on 2020-04-04 21:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userProfile', '0003_auto_20200404_2111'), ] operations = [ migrations.AlterField( model_name='profile', name='funfact', field=models.CharField(default='', max_length=100), ), migrations.AlterField( model_name='profile', name='linkedin', field=models.URLField(default='', max_length=60), ), ]
573
AutoFishing.py
hiroyukki/AutoFishing
2
2023240
import sys import os import threading import time import logging import random import cv2 import numpy as np import pyautogui def screenshot(): img = pyautogui.screenshot() return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) def imageDiff(img1, img2): diff = cv2.absdiff(img1, img2) _, diff = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY) return cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # get contour with largest area, that maybe buoy contour if there is no interference def maxContour(img): contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) maxContourIdx = -1 maxContourArea = 0 for i in range(len(contours)): area = cv2.contourArea(contours[i]) if area > maxContourArea: maxContourArea = area maxContourIdx = i if maxContourIdx != -1: return contours[maxContourIdx] return None def getCentroid(contour): try: moment = cv2.moments(contour, False) if moment['m00'] != 0: return int(moment['m10'] / moment['m00']), int(moment['m01'] / moment['m00']) except: pass return 0, 0 # find position of buoy, return position and image at that time on successful def findBuoyPosition(initImg, timeout): for i in range(timeout): time.sleep(1) curImg = screenshot() # difference of inital image and current image is buoy diff = imageDiff(initImg, curImg) try: contour = maxContour(diff) if cv2.contourArea(contour) > 300: # Contour of buoy is irregular, assume that centroid position is the buoy position x, y = getCentroid(contour) if x != 0: return x, y, curImg except: pass logger.warn('buoy not found') return 0, 0, None def waitForBite(initImg, timeout, x, y, width, height): beginTime = time.time() prevImg = initImg exceptCount = 1 while True: lastTime = time.time() - beginTime if lastTime > timeout: return 2 # pyautogui.moveTo((1 - lastTime / timeout) * width, height - 10, 0) time.sleep(0.1) curImg = screenshot() # check change around the buoy y0 = y - 100 if y - 100 >= 0 else 0 x0 = x - 100 if x - 100 >= 0 else 0 y1 = y + 100 if y + 100 <= height else height x1 = x + 100 if x + 100 <= width else width diff = imageDiff(prevImg[y0:y1, x0:x1], curImg[y0:y1, x0:x1]) prevImg = curImg try: contour = maxContour(diff) area = cv2.contourArea(contour) # print(area) if area > 800 + y * 3: # print(cv2.contourArea(contour)) # cv2.imwrite('diff.jpg', diff) # cv2.imwrite('prev.jpg', prevImg[y0:y1, x0:x1]) # cv2.imwrite('cur.jpg', curImg[y0:y1, x0:x1]) return 0 except Exception as e: # print(e) exceptCount = exceptCount + 1 if exceptCount > 2: return 3 def fishingLoop(key, width, height): logger.info('begin fishing loop') initImg = screenshot() time.sleep(0.2) pyautogui.press(key) time.sleep(1) pyautogui.moveTo(50, 50, 0) x, y, buoyImg = findBuoyPosition(initImg, 8) if x == 0: return 1 logger.info('buoy found at position ({}, {})'.format(x, y)) pyautogui.moveTo(100, 100, 0) waitResult = waitForBite(buoyImg, 20, x, y, width, height) if waitResult == 0: # move to buoy and right click time.sleep(0.1) logger.info('bite! right click ({}, {})'.format(x, y)) pyautogui.moveTo(x, y, 0) pyautogui.rightClick() time.sleep(1) # wait for fish load into pack pyautogui.moveTo(150, 150, 0) else: logger.error('waitForBite returned: {}'.format(waitResult)) return waitResult def autoFishing(): pyautogui.FAILSAFE = False while True: width, height = pyautogui.size() try: pyautogui.press(destroyKey) fishingLoop(fishingKey, width, height) # Make your character jump randomly to resist cheating detection if random.randint(1,100) < 8: pyautogui.press('space') time.sleep(1) except Exception as e: logger.error(repr(e)) time.sleep(1) destroyKey = 'r' # destroy bad fishes fishingKey = 'f' # replace to your fishing key logger = logging.getLogger('auto_fishing') timeoutMinutes = random.randint(90, 110) # close wow on timeout def exitWorker(): logger.info("close wow after {} minutes".format(timeoutMinutes)) time.sleep(timeoutMinutes * 60) logger.info("close wow") # pyautogui.press('r') time.sleep(20) pyautogui.hotkey('alt', 'f4') os._exit(1) def main(autoClose): logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s %(message)s')) logger.addHandler(handler) closeThread = threading.Thread(target=exitWorker) if autoClose: closeThread.start() try: autoFishing() except BaseException as e: logger.error(repr(e)) finally: os._exit(1) if __name__ == '__main__': autoClose = False if len(sys.argv) == 2 and sys.argv[1] == 'autoClose': autoClose = True main(autoClose)
5,490
RecoBTag/Skimming/python/btagGenBb_EventContent_cff.py
ckamtsikis/cmssw
852
2022987
import FWCore.ParameterSet.Config as cms from Configuration.EventContent.EventContent_cff import * btagGenBbEventContent = cms.PSet( outputCommands = cms.untracked.vstring() ) AODSIMbtagGenBbEventContent = cms.PSet( outputCommands = cms.untracked.vstring() ) RECOSIMbtagGenBbEventContent = cms.PSet( outputCommands = cms.untracked.vstring() ) btagGenBbEventSelection = cms.PSet( SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('btagGenBbPath') ) ) AODSIMbtagGenBbEventContent.outputCommands.extend(AODSIMEventContent.outputCommands) AODSIMbtagGenBbEventContent.outputCommands.extend(btagGenBbEventContent.outputCommands) RECOSIMbtagGenBbEventContent.outputCommands.extend(RECOSIMEventContent.outputCommands) RECOSIMbtagGenBbEventContent.outputCommands.extend(btagGenBbEventContent.outputCommands)
841
GlucoNet_Loading.py
bassignana/Blood-Glucose-Prediction
0
2023132
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 27 19:37:37 2020 @author: tommasobassignana """ import pandas as pd import xml.etree.ElementTree as et xml_file = "/Users/tommasobassignana/Desktop/GLYFE-master/data/ohio/OhioT1DM-training/559-ws-training.xml" xtree = et.parse(xml_file) xroot = xtree.getroot() def extract_attribute_values(root, child_index): """ to add : element = "event" extract attribute values inside the specified element :param root: tree root :param fchild_index: index of the child element from which i want the attributes names :return: """ for event in root[child_index].iter("event"): yield list(event.attrib.values()) def extract_attribute_names(root, child_index): """ extract the name of the attributes from xml tree element :param root: root node :param child_index: index of the child element from which i want the attributes names :return: """ return list(root[child_index][0].attrib.keys()) def create_glucose_df_from_root(xroot): """ Extract glucose values from xml :param xml: :return: glucose dataframe """ labels = extract_attribute_names(xroot, child_index=0) glucose = list(extract_attribute_values(xroot, child_index=0)) glucose_df = pd.DataFrame(data=glucose, columns=labels) glucose_df["ts"] = pd.to_datetime(glucose_df["ts"], format="%d-%m-%Y %H:%M:%S") glucose_df["value"] = glucose_df["value"].astype("float") glucose_df.rename(columns={'ts': 'datetime', 'value': 'glucose'}, inplace=True) return glucose_df def create_CHO_df_from_root(xroot): """ Extract CHO values from xml :param xml: :return: CHO dataframe """ labels = extract_attribute_names(xroot, child_index=5) CHO = list(extract_attribute_values(xroot, child_index=5)) CHO_df = pd.DataFrame(data=CHO, columns=labels) CHO_df.drop("type", axis=1, inplace=True) CHO_df["ts"] = pd.to_datetime(CHO_df["ts"], format="%d-%m-%Y %H:%M:%S") CHO_df["carbs"] = CHO_df["carbs"].astype("float") CHO_df.rename(columns={'ts': 'datetime', 'carbs': 'CHO'}, inplace=True) return CHO_df def create_insuline_df_from_root(xroot): """ Extract insulin values from xml :param xml: :return: insulin dataframe """ labels = extract_attribute_names(xroot, child_index=4) insulin = list(extract_attribute_values(xroot, child_index=4)) insulin_df = pd.DataFrame(data=insulin, columns=labels) for col in ["ts_end", "type", "bwz_carb_input"]: insulin_df.drop(col, axis=1, inplace=True) insulin_df["ts_begin"] = pd.to_datetime(insulin_df["ts_begin"], format="%d-%m-%Y %H:%M:%S") insulin_df["dose"] = insulin_df["dose"].astype("float") insulin_df.rename(columns={'ts_begin': 'datetime', 'dose': 'insulin'}, inplace=True) return insulin_df def compose_final_df(xroot): """ extract glucose, CHO, and insulin from xml and merge the data :param xml: :return: dataframe """ glucose_df = create_glucose_df_from_root(xroot) CHO_df = create_CHO_df_from_root(xroot) insulin_df = create_insuline_df_from_root(xroot) df = pd.merge(glucose_df, CHO_df, how="outer", on="datetime") df = pd.merge(df, insulin_df, how="outer", on="datetime") df = df.sort_values("datetime") return df df = compose_final_df(xroot)
3,390
desempacotamento.py
welykPereira/pythonExerciciosFaculdade
0
2022826
def soma(*num): soma = 0 print('Tupla {} '.format(num)) for i in num: soma += i return soma # programa principal print('Resultado: {} \n'.format(soma(5, 8)))
184
GCC-paddle/tests/test_graph_classification.py
S-HuaBomb/Contrib
243
2024270
import argparse import os from gcc.tasks.graph_classification import GraphClassification from tests.utils import E2E_PATH, MOCO_PATH, get_default_args, generate_emb def run(dataset, model, emb_path=""): args = get_default_args() args.dataset = dataset args.model = model args.emb_path = emb_path task = GraphClassification( args.dataset, args.model, args.hidden_size, args.num_shuffle, args.seed, emb_path=args.emb_path, ) return task.train() def test_e2e_imdb_binary(): NAME = "imdb-binary" generate_emb(os.path.join(E2E_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(E2E_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.7, ret def test_e2e_imdb_multi(): NAME = "imdb-multi" generate_emb(os.path.join(E2E_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(E2E_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.48, ret def test_e2e_collab(): NAME = "collab" generate_emb(os.path.join(E2E_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(E2E_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.73, ret def test_e2e_rdt_b(): NAME = "rdt-b" generate_emb(os.path.join(E2E_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(E2E_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.85, ret def test_e2e_rdt_5k(): NAME = "rdt-5k" generate_emb(os.path.join(E2E_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(E2E_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.50, ret def test_moco_imdb_binary(): NAME = "imdb-binary" generate_emb(os.path.join(MOCO_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(MOCO_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.7, ret def test_moco_imdb_multi(): NAME = "imdb-multi" generate_emb(os.path.join(MOCO_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(MOCO_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.48, ret def test_moco_collab(): NAME = "collab" generate_emb(os.path.join(MOCO_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(MOCO_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.77, ret def test_moco_rdt_b(): NAME = "rdt-b" generate_emb(os.path.join(MOCO_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(MOCO_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.88, ret def test_moco_rdt_5k(): NAME = "rdt-5k" generate_emb(os.path.join(MOCO_PATH, "current.pth"), NAME) ret = run(NAME, "from_numpy_graph", os.path.join(MOCO_PATH, f"{NAME}.npy")) assert ret["Micro-F1"] > 0.52, ret
2,817
app/common/const.py
lkolacz/semantive
0
2023759
from model_utils import Choices WEBSITE_STATUSES = Choices( ('Sta', "started", "Started"), ('Tpr', "getting_text", "Getting the text in progress"), ('Ipr', "getting_images", "Getting images in progress"), ('Suc', "success", "Success"), ('Fai', "failed", "Failed"), )
289
raspy/lcd/gpio_lcd_transfer_provider_standard.py
cyrusbuilt/RasPy
0
2024184
"""This module provides the GpioLcdTransferProviderStandard class.""" from raspy.illegal_argument_exception import IllegalArgumentException from raspy.object_disposed_exception import ObjectDisposedException from raspy.io import gpio_pins from raspy.io import pin_mode from raspy.io import pin_state from raspy.io.gpio_standard import GpioStandard from raspy.lcd.lcd_transfer_provider import LcdTransferProvider class GpioLcdTransferProviderStandard(LcdTransferProvider): """Raspberry Pi GPIO (via filesystem) provider. This is for the Micro Liquid Crystal Display. """ def __init__(self, d0, d1, d2, d3, d4, d5, d6, d7, four_bit_mode, rs, rw, enable): """Initialize a new instance of the GpioLcdTransferProviderStandard. Initializes with all the necessary pins and whether or not to use 4-bit mode. :param raspy.io.gpio_pins.GpioPin d0: :param raspy.io.gpio_pins.GpioPin d1: :param raspy.io.gpio_pins.GpioPin d2: :param raspy.io.gpio_pins.GpioPin d3: :param raspy.io.gpio_pins.GpioPin d4: :param raspy.io.gpio_pins.GpioPin d5: :param raspy.io.gpio_pins.GpioPin d6: :param raspy.io.gpio_pins.GpioPin d7: :param bool four_bit_mode: :param raspy.io.gpio_pins.GpioPin rs: :param raspy.io.gpio_pins.GpioPin rw: :param raspy.io.gpio_pins.GpioPin enable: :raises:raspy.illegal_argument_exception.IllegalArgumentException if 'rs' or 'enable' params are None, not a GpioPin type, or is raspy.io.gpio_pins.GpioNone. """ super(LcdTransferProvider, self).__init__() self.__fourBitMode = four_bit_mode if self.__fourBitMode is None: self.__fourBitMode = True if rs == gpio_pins.GpioNone() or rs is None: msg = "'rs' param must be a GpioPin other than GpioNone." raise IllegalArgumentException(msg) self.__registerSelectPort = GpioStandard(rs, pin_mode.OUT, pin_state.LOW) self.__registerSelectPort.provision() # We can save 1 pin by not using RW. Indicate this by passing # gpio_pins.GpioNone() instead of pin num. self.__readWritePort = gpio_pins.GpioNone() if rw != gpio_pins.GpioNone(): self.__readWritePort = GpioStandard(rw, pin_mode.OUT, pin_state.LOW) self.__readWritePort.provision() if enable is None or enable == gpio_pins.GpioNone(): msg = "'enable' param must be a GpioPin other than GpioNone" raise IllegalArgumentException(msg) self.__enablePort = GpioStandard(enable, pin_mode.OUT, pin_state.LOW) self.__enablePort.provision() data_pins = [ d0, d1, d2, d3, d4, d5, d6, d7 ] self.__dataPorts = list() for i in range(0, len(data_pins) - 1): if (data_pins[i] is None or not isinstance(data_pins[i], gpio_pins.GpioPin)): data_pins[i] = gpio_pins.GpioNone() if data_pins[i] != gpio_pins.GpioNone(): pin = GpioStandard(data_pins[i], pin_mode.OUT, pin_state.LOW) pin.provision() self.__dataPorts.append(pin) @property def is_four_bit_mode(self): """Get a value indicating whether this instance is in 4-bit mode. :returns: True if 4-bit mode; Otherwise, false. :rtype: bool """ return self.__fourBitMode def _pulse_enable(self): """Pulse the enable pin.""" self.__enablePort.write(pin_state.LOW) self.__enablePort.write(pin_state.HIGH) # enable pulse must be > 450 ns. self.__enablePort.write(pin_state.LOW) # Command needs 37 us to settle. def write_4_bits(self, value): """ Write the command or data in 4-bit mode (the last 4 data lines). :param byte, int value: The command or data to write. """ for i in range(0, 3): val = pin_state.LOW if ((value >> i) & 0x01) == 0x01: val = pin_state.HIGH self.__dataPorts[i + 4].write(val) self._pulse_enable() def write_8_bits(self, value): """Write the command or data in 8-bit mode (all 8 data lines). :param byte, int value: The command or data to write. """ for i in range(0, 7): val = pin_state.LOW if ((value >> i) & 0x01) == 0x01: val = pin_state.HIGH self.__dataPorts[i].write(val) self._pulse_enable() def send(self, data, mode, back_light): """Send the specified data, mode, and backlight. :param byte, int data: The data to send. :param int mode: Mode for register-select pin (pin_state.HIGH = on, pin_state.LOW = off). :param bool back_light: Set True to turn on the backlight. """ if LcdTransferProvider.is_disposed.fget(): raise ObjectDisposedException("GpioLcdTransferProviderStandard") # TODO set backlight. self.__registerSelectPort.write(mode) # If there is a RW pin indicated, set it low to write. if self.__readWritePort is not None: self.__readWritePort.write(pin_state.LOW) if self.__fourBitMode: self.write_4_bits(data >> 4) self.write_4_bits(data) else: self.write_8_bits(data) def dispose(self): """Dispose this instance.""" if LcdTransferProvider.is_disposed.fget(): return if self.__registerSelectPort is not None: self.__registerSelectPort.dispose() self.__registerSelectPort = None if self.__readWritePort is not None: self.__readWritePort.dispose() self.__readWritePort = None if self.__enablePort is not None: self.__enablePort.dispose() self.__enablePort = None if self.__dataPorts is not None and len(self.__dataPorts) > 0: for i, port in enumerate(self.__dataPorts): if port is not None: port.dispose() self.__dataPorts = None LcdTransferProvider.dispose(self)
6,314
example/dark_count_timebin.py
crappyprogrammer/SeQUeNCe
35
2025179
import math import statistics import pandas as pd from sequence.components.optical_channel import QuantumChannel, ClassicalChannel from sequence.kernel.event import Event from sequence.kernel.process import Process from sequence.kernel.timeline import Timeline from sequence.protocol import StackProtocol from sequence.qkd.BB84 import pair_bb84_protocols from sequence.qkd.cascade import pair_cascade_protocols from sequence.topology.node import QKDNode from sequence.utils.encoding import time_bin # dummy parent class to receive cascade keys and end timeline class Parent(StackProtocol): def __init__(self, own: "Node", keysize: int, keynum: int): super().__init__(own, "") self.upper_protocols = [] self.lower_protocols = [] self.keysize = keysize self.keynum = keynum self.keycounter = 0 def init(self): pass def pop(self, key): self.keycounter += 1 if self.keycounter >= self.keynum: self.own.timeline.stop() def push(self): self.lower_protocols[0].push(self.keysize, self.keynum) def received_message(self): pass if __name__ == "__main__": runtime = math.inf dark_count = 425 distances = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] # distances in km # distances = [120] KEYSIZE = 256 KEYNUM = 10 errors = [] # store error rates throughputs = [] # store throughputs # open file to store experiment results # Path("results/timebin").mkdir(parents=True, exist_ok=True) # filename = "results/timebin/distance_cascade.log" # fh = open(filename, 'w') for distance in distances: tl = Timeline(runtime) tl.seed(1) tl.show_progress = True qc0 = QuantumChannel("qc0", tl, distance=distance * 1e3, attenuation=0.0002) qc1 = QuantumChannel("qc1", tl, distance=distance * 1e3, attenuation=0.0002) cc0 = ClassicalChannel("cc0", tl, distance=distance * 1e3) cc1 = ClassicalChannel("cc1", tl, distance=distance * 1e3) # Alice ls_params = {"frequency": 2e6, "mean_photon_num": 0.1} alice = QKDNode("alice", tl, encoding=time_bin) for name, param in ls_params.items(): alice.update_lightsource_params(name, param) # Bob detector_params = [{"efficiency": 0.072, "dark_count": dark_count, "time_resolution": 10}, {"efficiency": 0.072, "dark_count": dark_count, "time_resolution": 10}, {"efficiency": 0.072, "dark_count": dark_count, "time_resolution": 10}] bob = QKDNode("bob", tl, encoding=time_bin) for i in range(len(detector_params)): for name, param in detector_params[i].items(): bob.update_detector_params(i, name, param) qc0.set_ends(alice, bob) qc1.set_ends(bob, alice) cc0.set_ends(alice, bob) cc1.set_ends(bob, alice) # BB84 and cascade config pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0]) pair_cascade_protocols(alice.protocol_stack[1], bob.protocol_stack[1]) # Parent pa = Parent(alice, KEYSIZE, KEYNUM) pb = Parent(bob, KEYSIZE, KEYNUM) alice.protocol_stack[1].upper_protocols.append(pa) pa.lower_protocols.append(alice.protocol_stack[1]) bob.protocol_stack[1].upper_protocols.append(pb) pb.lower_protocols.append(bob.protocol_stack[1]) process = Process(pa, "push", []) event = Event(0, process) tl.schedule(event) tl.init() tl.run() # get metrics bba = alice.protocol_stack[0] cascade_a = alice.protocol_stack[1] if bba.error_rates: error = statistics.mean(bba.error_rates) else: error = None if bba.throughputs: throughput = statistics.mean(bba.throughputs) else: throughput = None print("\n{} km:".format(distance)) print("\tbb84 error:\t\t\t{}".format(error)) print("\tbb84 throughput:\t{}".format(throughput)) errors.append(error) throughputs.append(throughput) # fh.write(str(distance)) # fh.write(' ') # fh.write(str(error)) # fh.write(' ') # fh.write(str(throughput)) # fh.write(' ') # fh.write(str(throughput_cascade)) # fh.write(' ') # fh.write(str(throughput_privacy)) # fh.write(' ') # fh.write(str(latency_privacy)) # fh.write('\n') log = {'Distance': distances, 'Error_rate': errors, 'Throughput_BB84': throughputs} df = pd.DataFrame(log) df.to_csv('dark_count_timebin.csv')
4,752
Others/panasonic/panasonic2020/b.py
KATO-Hiro/AtCoder
2
2023824
# -*- coding: utf-8 -*- def main(): from math import ceil import sys input = sys.stdin.readline h, w = map(int, input().split()) # 境界値 if h == 1 or w == 1: print(1) exit() ans = h // 2 * w if h % 2 == 1: ans += ceil(w / 2) print(ans) if __name__ == '__main__': main()
366
src-django/api/migrations/0003_auto_20150606_0342.py
protocolbuilder/sana.protocol_builder
6
2024975
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20150605_2258'), ] operations = [ migrations.AddField( model_name='element', name='created', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 43, 699662, tzinfo=utc), auto_now_add=True), preserve_default=False, ), migrations.AddField( model_name='element', name='last_modified', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 47, 163868, tzinfo=utc), auto_now=True), preserve_default=False, ), migrations.AddField( model_name='page', name='created', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 41, 58, 91929, tzinfo=utc), auto_now_add=True), preserve_default=False, ), migrations.AddField( model_name='page', name='last_modified', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 1, 859588, tzinfo=utc), auto_now=True), preserve_default=False, ), migrations.AddField( model_name='procedure', name='created', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 5, 419529, tzinfo=utc), auto_now_add=True), preserve_default=False, ), migrations.AddField( model_name='procedure', name='last_modified', field=models.DateField(default=datetime.datetime(2015, 6, 6, 3, 42, 9, 219634, tzinfo=utc), auto_now=True), preserve_default=False, ), ]
1,877
plaso/formatters/opera.py
cvandeplas/plaso
3
2024179
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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. """Formatter for Opera history events.""" from plaso.formatters import interface class OperaGlobalHistoryFormatter(interface.ConditionalEventFormatter): """Formatter for an Opera global history event.""" DATA_TYPE = 'opera:history:entry' FORMAT_STRING_PIECES = [ u'{url}', u'({title})', u'[{description}]'] SOURCE_LONG = 'Opera Browser History' SOURCE_SHORT = 'WEBHIST' class OperaTypedHistoryFormatter(interface.ConditionalEventFormatter): """Formatter for an Opera typed history event.""" DATA_TYPE = 'opera:history:typed_entry' FORMAT_STRING_PIECES = [ u'{url}', u'({entry_selection})'] SOURCE_LONG = 'Opera Browser History' SOURCE_SHORT = 'WEBHIST'
1,412
tests/behavior/helpers.py
lukaschoebel/POTUSgen
0
2024799
""" @author: <NAME> 2019. """ import re def cleanup_result(s): """Cleans a given string and fixes punctuation and capitalization :param s: """ # Whitespace & Padding correction s = re.sub('\\s+([.,!?])\\s*', r'\1 ', s) s = re.sub(r' ([\,\.\/\-\"\?\!\:\;])', "\\1", s) s = re.sub(r'( [a-zA-Z]) . ([a-zA-Z]) .', "\\1.\\2.", s) # Capitalization correction s = s.capitalize() s = re.sub(" i[,;!]? ", " I ", s) s = re.sub('([.!?]\\s+[a-z])', lambda c: c.group(1).upper(), s) return s
538
proto_3/ddq/topics/logics/fol/meta/function_definition.py
jadnohra/connect
0
2024249
from typing import List from ddq.taxonomy.reference import Reference from ddq.taxonomy.node import Node, NodeRepr from ddq.topics.logics.logic import Meta, Formulator, Function, Predicate from ddq.util.check_type import check_type class PredicativeFunctionDefinitionFormulator(Formulator): def info(self) -> str: return ("Definition sugar for functions that can be " "defined using a predicate") def references(self) -> List[Reference]: return [ Reference( "Type Theory and Formal Proof", [ ("Rob", "Schechter"), ("Herman", "Nederpelt") ], [ "p.172" ] ) # and EST p.10 ] def __call__(self, *parameters) -> Node: return PredicativeFunctionDefinition(*parameters) class PredicativeFunctionDefinition(Meta): def __init__(self, *in_children): super().__init__() children = [Function, Predicate] for i in range(len(children)): if i < len(in_children): children[i] = in_children[i] self.set_children(children) def accepts_child(self, index: int, child: "Node") -> bool: type_checks = {0: Function, 1: Predicate} return check_type(child, type_checks[index]) @staticmethod def symbol() -> str: return "≜" def repr_node(self) -> NodeRepr: return self.symbol()
1,602
external/vcm/vcm/convenience.py
jacnugent/fv3net
5
2024287
import pathlib import re from datetime import datetime, timedelta from typing import List, Union from functools import singledispatch import cftime import numpy as np import xarray as xr # SpencerC added this function, it is not public API, but we need it from xarray.core.resample_cftime import exact_cftime_datetime_difference from vcm.cubedsphere.constants import TIME_FMT TOP_LEVEL_DIR = pathlib.Path(__file__).parent.parent.absolute() @singledispatch def round_time(t, to=timedelta(seconds=1)): """ cftime will introduces noise when decoding values into date objects. This rounds time in the date object to the nearest second, assuming the init time is at most 1 sec away from a round minute. This is used when merging datasets so their time dims match up. Args: t: datetime or cftime object to: size of increment to round off to. By default round to closest integer second. Returns: datetime or cftime object rounded to nearest minute """ midnight = t.replace(hour=0, minute=0, second=0, microsecond=0) time_since_midnight = exact_cftime_datetime_difference(midnight, t) remainder = time_since_midnight % to quotient = time_since_midnight // to if remainder <= to / 2: closest_multiple_of_to = quotient else: closest_multiple_of_to = quotient + 1 rounded_time_since_midnight = closest_multiple_of_to * to return midnight + rounded_time_since_midnight @round_time.register def _round_time_numpy(time: np.ndarray) -> np.ndarray: return np.vectorize(round_time)(time) @round_time.register def _round_time_xarray(time: xr.DataArray) -> xr.DataArray: return xr.apply_ufunc(np.vectorize(round_time), time) def encode_time(time: cftime.DatetimeJulian) -> str: return time.strftime(TIME_FMT) def parse_timestep_str_from_path(path: str) -> str: """ Get the model timestep timestamp from a given path Args: path: A file or directory path that includes a timestep to extract Returns: The extrancted timestep string """ extracted_time = re.search(r"(\d\d\d\d\d\d\d\d\.\d\d\d\d\d\d)", path) if extracted_time is not None: return extracted_time.group(1) else: raise ValueError(f"No matching time pattern found in path: {path}") def parse_datetime_from_str(time: str) -> cftime.DatetimeJulian: """ Retrieve a datetime object from an FV3GFS timestamp string """ t = datetime.strptime(time, TIME_FMT) return cftime.DatetimeJulian(t.year, t.month, t.day, t.hour, t.minute, t.second) def parse_current_date_from_str(time: str) -> List[int]: """Retrieve the 'current_date' in the format required by fv3gfs namelist from timestamp string.""" t = parse_datetime_from_str(time) return [t.year, t.month, t.day, t.hour, t.minute, t.second] # use typehints to dispatch to overloaded datetime casting function @singledispatch def cast_to_datetime( time: Union[datetime, cftime.DatetimeJulian, np.datetime64] ) -> datetime: """Cast datetime-like object to python datetime. Assumes calendars are compatible.""" return datetime( time.year, time.month, time.day, time.hour, time.minute, time.second, time.microsecond, ) @cast_to_datetime.register def _cast_datetime_to_datetime(time: datetime) -> datetime: return time @cast_to_datetime.register def _cast_numpytime_to_datetime(time: np.datetime64): # type: ignore # https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64 unix_epoch = np.datetime64(0, "s") one_second = np.timedelta64(1, "s") seconds_since_epoch = (time - unix_epoch) / one_second return datetime.utcfromtimestamp(seconds_since_epoch) @cast_to_datetime.register def _(time: str): return cast_to_datetime(parse_datetime_from_str(parse_timestep_str_from_path(time))) def convert_timestamps(coord: xr.DataArray) -> xr.DataArray: parser = np.vectorize(parse_datetime_from_str) return xr.DataArray(parser(coord), dims=coord.dims, attrs=coord.attrs) def shift_timestamp(time: str, seconds: Union[int, float]) -> str: """Add an offset in seconds to a timestamp in YYYYMMDD.HHMMSS format""" offset = timedelta(seconds=seconds) offset_datetime = parse_datetime_from_str(time) + offset return offset_datetime.strftime("%Y%m%d.%H%M%S") def get_root(): """Returns the absolute path to the root directory for any machine""" return str(TOP_LEVEL_DIR)
4,574
jupyter_tree_download/handlers.py
ryanlovett/jupyter-tree-download
3
2024595
import asyncio from tornado import web from traitlets import Unicode from traitlets.config.configurable import Configurable from notebook.base.handlers import IPythonHandler def attachment_suffix(compression): '''Returns the conventional suffix of the compression type.''' if compression == 'zip': return compression elif compression == 'gzip': return 'tar.gz' elif compression == 'bzip2': return 'tar.bz2' else: return f'tar.{compression}' def command(compression, path): '''Returns a command that can compress our path to standard out.''' if compression == 'zip': return ['zip', '-q', '-r', '-', path] else: return ['tar', '-c', f'--{compression}', '-f', '-', path] def friendly_name(name, path, suffix): '''Return a friendly name for the downloaded file.''' # If we're at the top-level, just return what the frontend provides (the # hostname). Otherwise return the same followed by some path context. normalized_path = path.replace('/', '_') if path == '.': return f'{name}.{suffix}' else: return f'{name}-{normalized_path}.{suffix}' class TreeDownloadHandler(IPythonHandler): def initialize(self): super().initialize() self.c = TreeDownload(config=self.config) @web.authenticated async def get(self): '''Accepts arguments: name: a hint for the downloaded filename, path: path to the directory to download, compression: compression type, e.g. zip, gzip, bzip2, etc. ''' _buf_size = 65535 name = self.get_argument('name') if name == '': name = 'tree' path = self.get_argument('path', '.') if path == '': path = '.' compression = self.get_argument('compression', self.c.compression) suffix = attachment_suffix(compression) filename = friendly_name(name, path, suffix) self.set_header('content-type', 'application/octet-stream') self.set_header('cache-control', 'no-cache') self.set_header('content-disposition', f'attachment; filename="{filename}"' ) cmd = command(compression, path) p = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE) while True: data = await p.stdout.read(_buf_size) if not data: break self.write(data) self.flush(data) await p.wait() self.finish() class TreeDownload(Configurable): compression = Unicode( "zip", help="""Type of compression to use. If 'zip' a .zip file is produced. For anything else, a '.tar.{compression}' file is produced, via tar. Appropriate compressor program (such as 'zip', 'tar', 'gzip', etc) must be already installed in the environment """, config=True )
2,927
CodaMais/forum/models.py
igor-gme/herokuTest
0
2024739
''' Copyright (C) 2017, CodaMais. License: GNU General Public License v3.0, see LICENSE.txt App: forum File: models.py Contains all classes related to the forum, it is django's default to keep all models in single file. ''' # Django. from django.db import models # local Django. from forum import constants from user.models import User # Class: Topic # The class represents a topic in the site forum. class Topic(models.Model): title = models.CharField(max_length=constants.MAX_LENGTH_TITLE) subtitle = models.CharField(max_length=constants.MAX_LENGTH_SUBTITLE) author = models.ForeignKey( User, on_delete=models.CASCADE,) description = models.CharField(max_length=constants.MAX_LENGTH_TOPIC_DESCRIPTION) date_topic = models.DateTimeField(auto_now_add=True, blank=True) best_answer = models.ForeignKey('Answer', models.SET_NULL, related_name='best_answer', null=True) locked = models.BooleanField(default=False) def new_topics(): topics = Topic.objects.all().order_by('-id')[:5] return topics def answers(self): assert self is not None, "Topic not exists." # Getting all current topic answers except the best answer answers = Answer.objects.filter(topic=self) return answers def __str__(self): return self.title # Class: Answer # The class represents a answer to a topic in the site forum. class Answer(models.Model): description = models.CharField(max_length=constants.MAX_LENGTH_ANSWER_DESCRIPTION) user = models.ForeignKey( User, on_delete=models.CASCADE,) topic = models.ForeignKey( Topic, on_delete=models.CASCADE,) date_answer = models.DateTimeField(auto_now_add=True, blank=True) def creates_answer(self, user, topic, description): self.user = user self.topic = topic self.description = description self.save() def __str__(self): return self.description
2,004
25/25.py
Scarygami/aoc2019
3
2024545
import os import sys from itertools import combinations currentdir = os.path.dirname(os.path.abspath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) try: from lib.intcode import IntcodeVM except ImportError: print("Intcode library could not be found") exit(1) source = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")) machine = IntcodeVM(source, silent=True) # Path to security checkpoint picking up all safe items walkthrough = [ "east", "east", "take semiconductor", "north", "take planetoid", "west", "take food ration", "west", "west", "take monolith", "east", "east", "north", "take space law space brochure", "east", "take jam", "west", "north", "north", "take weather machine", "south", "south", "south", "east", "north", "take antenna", "south", "south", "east", "south", "south", "east", "drop food ration", "drop weather machine", "drop antenna", "drop space law space brochure", "drop jam", "drop semiconductor", "drop planetoid", "drop monolith" ] items = [ "food ration", "weather machine", "antenna", "space law space brochure", "jam", "semiconductor", "planetoid", "monolith" ] machine.run("\n".join(walkthrough) + "\n") # Brute forcing all item combinations until the right weight is reached. for l in range(len(items)): for selected in combinations(items, l): steps = [] for item in selected: steps.append("take %s" % item) steps.append("east") outputs = machine.resume("\n".join(steps) + "\n") outputs = "".join([chr(c) for c in outputs]) if outputs.find("lighter") >= 0: print("Too heavy:", selected) elif outputs.find("heavier") >= 0: print("Too light:", selected) else: print(outputs) exit() steps = [] for item in selected: steps.append("drop %s" % item) machine.resume("\n".join(steps) + "\n")
2,140
tests/async/test_focus.py
axelande/playwright-python
6,243
2024928
# Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest async def test_should_work(page): await page.set_content("<div id=d1 tabIndex=0></div>") assert await page.evaluate("() => document.activeElement.nodeName") == "BODY" await page.focus("#d1") assert await page.evaluate("() => document.activeElement.id") == "d1" async def test_should_emit_focus_event(page): await page.set_content("<div id=d1 tabIndex=0></div>") focused = [] await page.expose_function("focusEvent", lambda: focused.append(True)) await page.evaluate("() => d1.addEventListener('focus', focusEvent)") await page.focus("#d1") assert focused == [True] async def test_should_emit_blur_event(page): await page.set_content( "<div id=d1 tabIndex=0>DIV1</div><div id=d2 tabIndex=0>DIV2</div>" ) await page.focus("#d1") focused = [] blurred = [] await page.expose_function("focusEvent", lambda: focused.append(True)) await page.expose_function("blurEvent", lambda: blurred.append(True)) await page.evaluate("() => d1.addEventListener('blur', blurEvent)") await page.evaluate("() => d2.addEventListener('focus', focusEvent)") await page.focus("#d2") assert focused == [True] assert blurred == [True] async def test_should_traverse_focus(page): await page.set_content('<input id="i1"><input id="i2">') focused = [] await page.expose_function("focusEvent", lambda: focused.append(True)) await page.evaluate("() => i2.addEventListener('focus', focusEvent)") await page.focus("#i1") await page.keyboard.type("First") await page.keyboard.press("Tab") await page.keyboard.type("Last") assert focused == [True] assert await page.eval_on_selector("#i1", "e => e.value") == "First" assert await page.eval_on_selector("#i2", "e => e.value") == "Last" async def test_should_traverse_focus_in_all_directions(page): await page.set_content('<input value="1"><input value="2"><input value="3">') await page.keyboard.press("Tab") assert await page.evaluate("() => document.activeElement.value") == "1" await page.keyboard.press("Tab") assert await page.evaluate("() => document.activeElement.value") == "2" await page.keyboard.press("Tab") assert await page.evaluate("() => document.activeElement.value") == "3" await page.keyboard.press("Shift+Tab") assert await page.evaluate("() => document.activeElement.value") == "2" await page.keyboard.press("Shift+Tab") assert await page.evaluate("() => document.activeElement.value") == "1" @pytest.mark.only_platform("darwin") @pytest.mark.only_browser("webkit") async def test_should_traverse_only_form_elements(page): await page.set_content( """ <input id="input-1"> <button id="button">buttton</button> <a href id="link">link</a> <input id="input-2"> """ ) await page.keyboard.press("Tab") assert await page.evaluate("() => document.activeElement.id") == "input-1" await page.keyboard.press("Tab") assert await page.evaluate("() => document.activeElement.id") == "input-2" await page.keyboard.press("Shift+Tab") assert await page.evaluate("() => document.activeElement.id") == "input-1" await page.keyboard.press("Alt+Tab") assert await page.evaluate("() => document.activeElement.id") == "button" await page.keyboard.press("Alt+Tab") assert await page.evaluate("() => document.activeElement.id") == "link" await page.keyboard.press("Alt+Tab") assert await page.evaluate("() => document.activeElement.id") == "input-2" await page.keyboard.press("Alt+Shift+Tab") assert await page.evaluate("() => document.activeElement.id") == "link" await page.keyboard.press("Alt+Shift+Tab") assert await page.evaluate("() => document.activeElement.id") == "button" await page.keyboard.press("Alt+Shift+Tab") assert await page.evaluate("() => document.activeElement.id") == "input-1"
4,516
l10n_br_stock_account/models/stock_backorder_confirmation.py
SandroGauna/odoo-brasil
181
2024700
# © 2021 - <NAME> - Code 137 from odoo import models class StockBackorderConfirmation(models.TransientModel): _inherit = "stock.backorder.confirmation" """Verificar as quantidades dos produtos na invoice após sua criação""" def process(self): res = super(StockBackorderConfirmation, self).process() pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids')) pickings_to_validate.action_invoice_picking() return res def process_cancel_backorder(self): res = super(StockBackorderConfirmation, self).process_cancel_backorder() pickings_to_validate = self.env['stock.picking'].browse(self.env.context.get('button_validate_picking_ids')) pickings_to_validate.action_invoice_picking() return res
846
python/426_convert_binary_search_tree_to_sorted_doubly_linked_list.py
liaison/LeetCode
17
2024989
""" # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': if not root: return None """ Convert a BST tree to a doubly-linked list return the head and tail of the list """ def head_and_tail_of_list(node): if not node: return None, None # divide and conquer if node.left: # chain the left subtree to the current node left_head, left_tail = head_and_tail_of_list(node.left) left_tail.right = node node.left = left_tail else: left_head = node if node.right: # chain the right subtree to the current node right_head, right_tail = head_and_tail_of_list(node.right) node.right = right_head right_head.left = node else: right_tail = node # return the head and tail of the entire list return left_head, right_tail head, tail = head_and_tail_of_list(root) # chain up head and tail head.left = tail tail.right = head return head
1,395
generatedata.py
QuantumArjun/DeinDoc
1
2022843
import pandas as pd import itemAPI items = itemAPI.createItemDictFromCSV() names = list(set(items.keys())) diseases = set() for item in items.values(): diseases.add(item.disease) diseases = list(diseases) indexToName, nameToIndex = itemAPI.generateIndexTable() data = [] for disease in diseases: for name in names: feature = [] feature.append(nameToIndex[name]) feature.append(disease) if items[name].disease == disease: feature.append(1) else: feature.append(0) data.append(feature) print(data) df = pd.DataFrame(data, columns = ['Name', 'Disease', 'Show']) df.to_csv('data.csv', index=False)
686
testing/vulnerable_app/util.py
bbhunter/fuzz-lightyear
169
2024850
from urllib.parse import quote_plus from werkzeug.routing import BaseConverter def get_name(name): """ Blueprint names must be unique, and cannot contain dots. This converts filenames to blueprint names. e.g. vulnerable_app.views.basic => basic :type name: str """ return name.split('.')[-1] class ListConverter(BaseConverter): def __init__(self, url_map): super(ListConverter, self).__init__(url_map) self.delimiter = quote_plus(',') def to_python(self, value): return value.split(self.delimiter) def to_url(self, values): return self.delimiter.join( BaseConverter.to_url(value) for value in values )
704
round/forms.py
archimedeans/integration-bee
0
2024192
from upload_validator import FileTypeValidator from django import forms # from django.utils.html import escape # from django.core.exceptions import ValidationError # from django.utils.translation import ugettext_lazy as _ class SubmitForProblemForm(forms.Form): solution = forms.FileField( required=True, max_length=40, help_text='Upload your solution (PDF only; size up to 5 MB; ' + 'file name up to 40 characters long)', # allow_empty_file=False, widget=forms.FileInput( attrs={'id': 'solutionInput', 'class': 'form-control', 'accept': '.pdf,application/pdf'} ), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.has_error('solution'): self.fields['solution'].widget.attrs.update({ 'class': 'form-control is-invalid', 'aria-describedby': 'solutionValidationFeedback' }) def clean_solution(self): file = self.cleaned_data['solution'] # if not file.name.endswith('.pdf'): # raise ValidationError( # _('The extension of the file is not \'.pdf\'.'), # code='invalid' # ) # Use django-upload-validator for file validation # It checks the extension and MIME type of an uploaded file # inferred from the file name and the binary signature / magic number # using python-magic, which in turn uses the libmagic C library validator = FileTypeValidator( allowed_types=['application/pdf'], allowed_extensions=['.pdf'] ) # with file.open() as file_resource: file_resource = file.open() validator(file_resource) return file class ContactForm(forms.Form): email = forms.EmailField( required=True, help_text='The email address you would like us to send our response to', ) subject = forms.ChoiceField( required=True, choices=[ ('paper', 'Contest paper'), ('website', 'Website'), ('other', 'Other') ], ) message = forms.CharField( required=True, min_length=5, strip=True, widget=forms.Textarea, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) input_classes = { 'email': 'form-control', 'subject': 'form-select', 'message': 'form-control' } for field_name in ('email', 'subject', 'message'): if not self.has_error(field_name): self.fields[field_name].widget.attrs.update({ 'class': input_classes[field_name], }) else: self.fields[field_name].widget.attrs.update({ 'class': input_classes[field_name] + ' is-invalid', 'aria-describedby': field_name + 'ValidationFeedback' }) # def clean_message(self): # return escape(self.cleaned_data['message'])
3,141
Python-programs/inputPassword.py
manavbansalcoder/Hacktoberfest2021
0
2025212
a = input("Input password:") b = "<PASSWORD>" for i in range(2): if a==b: print ("your login is success") break else: c = input("Sorry, your password is not correct. Input password:") if c==b: print ("Anda berhasil login") break elif i==1: print ("you had tried 3 times. your access is dennied.")
381
Painter_Siglent_DC_PowerSupply/Painter_Siglent_DC_PowerSupply.py
sherryue123/Labber-Drivers
3
2024653
#!/usr/bin/env python from VISA_Driver import VISA_Driver __version__ = "0.0.1" class Driver(VISA_Driver): """ The Painter Siglent DC PowerSupply driver re-implements the VISA driver with some more options""" def performSetValue(self, quant, value, sweepRate=0.0, options={}): """Perform the Set Value instrument operation. This function should return the actual value set by the instrument""" name = str(quant.name) if name == 'Firmware Version': # read-only channels don't perform setValue pass elif name.endswith(('Active Voltage', 'Active Current')): return self.getValue(name) else: # else, call the generic VISA driver return VISA_Driver.performSetValue(self, quant, value, sweepRate, options=options) def performGetValue(self, quant, options={}): """Perform the Get Value instrument operation""" # perform special getValue for delay commands name = str(quant.name) if name.endswith(('Output', )): lName = name.split(' - ') return self.getValue(name) # return the local value stored in the driver else: # run the generic visa driver case return VISA_Driver.performGetValue(self, quant, options=options) if __name__ == '__main__': pass
1,409
tests_runner/utils/dir.py
RainingComputers/ShnooTalk
6
2022636
from typing import List import os import glob def remove_if_exists(filename: str) -> None: if os.path.exists(filename): os.remove(filename) def list_test_files() -> List[str]: files = [file for file in os.listdir() if file.endswith(".shtk")] files.sort() return files def get_files(file_ext: str) -> List[str]: return glob.glob(f"**/*{file_ext}", recursive=True) def remove_files(file_ext: str) -> None: files = get_files(file_ext) for file in files: remove_if_exists(file) def dump_string_to_file(file_name: str, content: str) -> None: with open(file_name, "w") as file: file.write(content) def string_from_file(file_name: str) -> str: with open(file_name, "r") as file: return file.read()
774
general/myException.py
jaeilepp/eggie
0
2022796
''' Created on 9.1.2015 @author: <NAME> ''' class MyException(Exception): """Derived class from exception""" try: raise MyException('my detailed description') except MyException as my: print my # outputs 'my detailed description'
245
src/runner.py
ModOrganizer2/modorganizer-installer_wizard
0
2025009
# -*- encoding: utf-8 -*- import sys from pathlib import Path from typing import Iterable, List, Optional import mobase from wizard.interpreter import WizardInterpreter from wizard.manager import ManagerModInterface from wizard.severity import SeverityContext from wizard.value import SubPackage, SubPackages from wizard.utils import make_runner_context_factory class MO2SubPackage(SubPackage): _tree: mobase.IFileTree _files: List[str] def __init__(self, tree: mobase.IFileTree): super().__init__(tree.name()) self._tree = tree # We cannot perform lazy iteration on the tree in a Python way so we # have to list the files: self._files = [] def fn(folder, entry) -> mobase.IFileTree.WalkReturn: self._files.append(entry.path()) return mobase.IFileTree.CONTINUE self._tree.walk(fn) @property def files(self) -> Iterable[str]: return self._files class MO2SeverityContext(SeverityContext): _organizer: mobase.IOrganizer def __init__(self, organizer: mobase.IOrganizer): super().__init__() self._organizer = organizer def warning(self, text: str): print(text, file=sys.stderr) class MO2ManagerModInterface(ManagerModInterface): _organizer: mobase.IOrganizer _game: mobase.IPluginGame _subpackages: SubPackages def __init__(self, tree: mobase.IFileTree, organizer: mobase.IOrganizer): self._organizer = organizer self._game = organizer.managedGame() checker: mobase.ModDataChecker = self._game.feature( mobase.ModDataChecker # type: ignore ) # Read the subpackages: self._subpackages = SubPackages() for entry in tree: if isinstance(entry, mobase.IFileTree): if checker: if checker.dataLooksValid(entry) == mobase.ModDataChecker.VALID: self._subpackages.append(MO2SubPackage(entry)) continue # Add entry with INI tweaks: if entry.exists("INI Tweaks") or entry.exists("INI"): self._subpackages.append(MO2SubPackage(entry)) continue # We add folder with format "XXX Docs" where "XXX" is a number. parts = entry.name().split() if ( len(parts) >= 2 and parts[0].isdigit() and parts[1].lower().startswith("doc") ): self._subpackages.append(MO2SubPackage(entry)) @property def subpackages(self) -> SubPackages: return self._subpackages def compareGameVersion(self, version: str) -> int: v1 = mobase.VersionInfo(version) v2 = mobase.VersionInfo(self._game.gameVersion()) if v1 < v2: return 1 elif v1 > v2: return -1 else: return 0 def compareSEVersion(self, version: str) -> int: se = self._game.feature(mobase.ScriptExtender) # type: ignore if not se: return 1 v1 = mobase.VersionInfo(version) v2 = mobase.VersionInfo(se.getExtenderVersion()) if v1 < v2: return 1 elif v1 > v2: return -1 else: return 0 def compareGEVersion(self, version: str) -> int: # Cannot do th is in MO2. return 1 def compareWBVersion(self, version: str) -> int: # Cannot do this in MO2. return 1 def _resolve(self, filepath: str) -> Optional[Path]: """ Resolve the given filepath. Args: filepath: The path to resolve. Returns: The path to the given file on the disk, or one of the file mapping to it in the VFS, or None if the file does not exists. """ # TODO: This does not handle weird path that go back (..) and # then in data again, e.g. ../data/xxx.esp. path: Optional[Path] if filepath.startswith(".."): path = Path(self._game.dataDirectory().absoluteFilePath(filepath)) if not path.exists(): path = None else: path = Path(filepath) parent = path.parent.as_posix() if parent == ".": parent = "" files = self._organizer.findFiles(parent, "*" + path.name) if files: path = Path(files[0]) else: path = None return path def dataFileExists(self, *filepaths: str) -> bool: return all(self._resolve(path) for path in filepaths) def getPluginLoadOrder(self, filename: str, fallback: int = -1) -> int: return self._organizer.pluginList().loadOrder(filename) def getPluginStatus(self, filename) -> int: state = self._organizer.pluginList().state(filename) if state == mobase.PluginState.ACTIVE: return 2 if state == mobase.PluginState.INACTIVE: return 0 # Or 1? return -1 def getFilename(self, filepath: str) -> str: path = self._resolve(filepath) if path: if path.is_file(): return path.name return "" def getFolder(self, filepath: str) -> str: path = self._resolve(filepath) if path: if path.is_dir(): return path.name return "" def make_interpreter( base: mobase.IFileTree, organizer: mobase.IOrganizer ) -> WizardInterpreter: manager = MO2ManagerModInterface(base, organizer) severity = MO2SeverityContext(organizer) factory = make_runner_context_factory(manager.subpackages, manager, severity) return WizardInterpreter(factory)
5,831
contact/migrations/0003_auto_20190529_1449.py
radoslawdabrowski/radoslawdabrowski.pl
1
2025128
# Generated by Django 2.2.1 on 2019-05-29 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contact', '0002_auto_20190522_1259'), ] operations = [ migrations.AlterField( model_name='contact', name='email', field=models.CharField(default='NO_EMAIL', error_messages={'blank': 'You need to fill your email', 'max_length': 'Your email is too long', 'null': 'You need to fill your email'}, max_length=100), ), migrations.AlterField( model_name='contact', name='message', field=models.TextField(default='NO_MESSAGE', error_messages={'blank': 'You need to fill the message', 'null': 'You need to fill the message'}), ), migrations.AlterField( model_name='contact', name='name', field=models.CharField(default='NO_NAME', error_messages={'blank': 'You need to fill your name', 'max_length': 'Your name is too long', 'null': 'You need to fill your name'}, max_length=50), ), ]
1,107
src/abaqus/Amplitude/ModulatedAmplitude.py
Haiiliin/PyAbaqus
7
2024230
from abaqusConstants import * from .Amplitude import Amplitude class ModulatedAmplitude(Amplitude): """The ModulatedAmplitude object defines a modulated amplitude curve. The ModulatedAmplitude object is derived from the Amplitude object. Notes ----- This object can be accessed by: .. code-block:: python import amplitude mdb.models[name].amplitudes[name] import odbAmplitude session.odbs[name].amplitudes[name] The corresponding analysis keywords are: - AMPLITUDE """ def __init__(self, name: str, initial: float, magnitude: float, start: float, frequency1: float, frequency2: float, timeSpan: SymbolicConstant = STEP): """This method creates a ModulatedAmplitude object. Notes ----- This function can be accessed by: .. code-block:: python mdb.models[name].ModulatedAmplitude session.odbs[name].ModulatedAmplitude Parameters ---------- name A String specifying the repository key. initial A Float specifying the constant A0A0. magnitude A Float specifying the coefficient AA. start A Float specifying the starting time t0t0. Possible values are non-negative numbers. frequency1 A Float specifying the circular frequency 1 (ω1ω1). Possible values are positive numbers. frequency2 A Float specifying the circular frequency 2 (ω2ω2). Possible values are positive numbers. timeSpan A SymbolicConstant specifying the time span of the amplitude. Possible values are STEP and TOTAL. The default value is STEP. Returns ------- A ModulatedAmplitude object. Raises ------ InvalidNameError RangeError """ super().__init__() pass def setValues(self, timeSpan: SymbolicConstant = STEP): """This method modifies the ModulatedAmplitude object. Parameters ---------- timeSpan A SymbolicConstant specifying the time span of the amplitude. Possible values are STEP and TOTAL. The default value is STEP. Raises ------ RangeError """ pass
2,410
staticmethod_tutorial.py
NightmareQAQ/python-notes
106
2024314
# ref. https://www.programiz.com/python-programming/methods/built-in/staticmethod # Static method # However, when you need a utility function that doesn't access any properties of # a class but makes sense that it belongs to the class, we use static functions. # Static method vs Class method # Static method knows nothing about the class and just deals with the parameters. # Class method works with the class since its parameter is always the class itself. # Create utility function as a static method class Dates: def __init__(self, date): self._date = date def get_date(self): return self._date @staticmethod def to_dash_date(date): return date.replace("/", "-") # How inheritance works with static method? class DatesWithSlashes(Dates): def get_date(self): return Dates.to_dash_date(self._date) def main(): # tutorial 1 date = Dates("15-12-2016") date_from_birthday = "15/12/2016" date_with_dash = Dates.to_dash_date(date_from_birthday) if date.get_date() == date_with_dash: print("Equal") else: print("Unequal") # tutorial 2 date2 = Dates("15-12-2016") date_with_slash = DatesWithSlashes("15/12/2016") if date2.get_date() == date_with_slash.get_date(): print("Equal") else: print("Unequal") if __name__ == "__main__": main()
1,379
Featurize/CalcuDescriptors.py
Saoge123/ccgnet
17
2023931
# -*- coding: utf-8 -*- from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem import Descriptors, rdFreeSASA import pybel import openbabel as ob import numpy as np import math ''' from rdkit.Chem import Lipinski, MolSurf, PeriodicTable elements_set = ['H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar','Br','I'] pt = Chem.GetPeriodicTable() Rvdw = {} for i in elements_set: Rvdw[i] = pt.GetRvdw(i) ''' Rvdw = {'H': 1.2,'He': 1.4,'Li': 1.82,'Be': 1.7,'B': 2.08,'C': 1.95,'N': 1.85, 'O': 1.7,'F': 1.73,'Ne': 1.54,'Na': 2.27,'Mg': 1.73,'Al': 2.05,'Si': 2.1, 'P': 2.08,'S': 2.0,'Cl': 1.97,'Ar': 1.88,'Br': 2.1,'I': 2.15} def coordinate_adjusting(mol): ''' The algorithm refers from:http://sobereva.com/426 ''' mat_coor = [[0,1],[0,2],[1,2]] diag_coor = [[1,2],[0,2],[0,1]] atoms = mol.GetAtoms() atom_coors = np.array([mol.GetConformer().GetAtomPosition(i.GetIdx()) for i in atoms]) wts = np.array([i.GetMass() for i in atoms]) wts = np.expand_dims(wts,axis=1) diag_val = [np.sum(wts*atom_coors[:,i]**2) for i in diag_coor] mat_val = [np.sum(wts*np.prod(atom_coors[:,i],axis=1))*-1 for i in mat_coor] imt = np.zeros([3,3]) for i in range(3): imt[i,i] = diag_val[i] pos = mat_coor[i] imt[pos[0],pos[1]] = mat_val[i] imt[pos[1],pos[0]] = mat_val[i] eig_v,eig_m = np.linalg.eig(imt) am = atom_coors.dot(eig_m) return am def MaxMinValue(array): max_idx, max_val = np.argmax(array), np.max(array) min_idx, min_val = np.argmin(array), np.min(array) return int(max_idx), max_val, int(min_idx), min_val def CalcuAxisLenth(mol): coors = coordinate_adjusting(mol) axis = [] for i in range(3): max_idx, max_val, min_idx, min_val = MaxMinValue(coors[:,i]) max_ = max_val + Rvdw[mol.GetAtomWithIdx(max_idx).GetSymbol()] min_ = min_val - Rvdw[mol.GetAtomWithIdx(min_idx).GetSymbol()] axis.append(max_-min_) S, M, L = sorted(axis) return S, M, L def Ratio_S_M_L(mol): S, M, L = CalcuAxisLenth(mol) S_L = S/L M_L = M/L S_M = S/M return S_L, M_L, S_M, S def GlobularityAndFrTPSA(coformer, includeSandP=1): # Calculate globularity: surface of a sphere with the same volume as the molecule / Area # FrTPSA = TPSA / SASA mol_vol = coformer.csd_mol.molecular_volume r_sphere = math.pow(mol_vol*0.75/math.pi, 1.0/3) area_sphere = 4*math.pi*r_sphere*r_sphere radii = rdFreeSASA.classifyAtoms(coformer.rdkit_mol) sasa = rdFreeSASA.CalcSASA(coformer.rdkit_mol, radii) globularity = area_sphere / sasa FrTPSA = Descriptors.TPSA(coformer.rdkit_mol, includeSandP=includeSandP) / sasa return globularity, FrTPSA def FractionNO(mol): return Descriptors.NOCount(mol) / float(mol.GetNumHeavyAtoms()) def FractionAromaticAtoms(mol): return len(mol.GetAromaticAtoms()) / float(mol.GetNumHeavyAtoms()) def NumHAcceptorsAndDonors(mol): return Descriptors.NumHDonors(mol), Descriptors.NumHAcceptors(mol) def RotatableBondNumber(mol): mol = Chem.RemoveHs(mol) return Descriptors.NumRotatableBonds(mol) #/ float(mol.GetNumBonds()) # Using openbabel for calculating dipole moment def DipoleMoment(mol, charge_model='eem2015bm'): mol_block = Chem.MolToMolBlock(mol) ob_mol = pybel.readstring('mol', mol_block) # We choose 'eem2015bm' to calculate dipole # Using 'obabel -L charges' can get a list of charge models dipole = ob.OBChargeModel_FindType(charge_model).GetDipoleMoment(ob_mol.OBMol) dipole_moment = math.sqrt(dipole.GetX()**2+dipole.GetY()**2+dipole.GetZ()**2) return dipole_moment def CalcuDescriptors(coformer, includeSandP=1, charge_model='eem2015bm'): rdkit_mol = coformer.rdkit_mol S_L, M_L, S_M, S = Ratio_S_M_L(rdkit_mol) globularity, FrTPSA = GlobularityAndFrTPSA(coformer, includeSandP=includeSandP) Fr_NO = FractionNO(rdkit_mol) Fr_AromaticAtoms = FractionAromaticAtoms(rdkit_mol) HBA,HBD = NumHAcceptorsAndDonors(rdkit_mol) RBN = RotatableBondNumber(rdkit_mol) dipole_moment = DipoleMoment(rdkit_mol, charge_model=charge_model) return np.array([S_L, M_L, S_M, S, globularity, FrTPSA, Fr_NO, Fr_AromaticAtoms, HBA, HBD, RBN, dipole_moment])
4,304
problem_solving_py/set_union/set_union.py
RootProgrammer/Python
1
2023842
if __name__ == "__main__": x, y = [set(input().split()) for _ in range(4)][1::2] print(len(x | y))
110
resources/routing-options.py
ttsubo/netconf_heat
0
2024680
# Copyright (c) 2016 ttsubo # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php import uuid from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.common.i18n import _ from ncclient.xml_ import * from oslo_log import log as logging from netconf import Netconf LOG = logging.getLogger(__name__) class RoutingOptionsResource(Netconf): PROPERTIES = ( ROUTER_IPADDR, USERNAME, PASSWORD, PORT, STATIC_ROUTE, NEXT_HOP, ROUTER_ID, MY_AS ) = ( 'router_ipaddr', 'username', 'password', 'port', 'static_route', 'next_hop', 'router_id', 'my_as' ) ATTRIBUTES = ( CONFIG_ROUTING_OPTIONS ) = ( 'config_routing_options' ) properties_schema = { ROUTER_IPADDR: properties.Schema( properties.Schema.STRING, _('Ip address of the router.'), required=True, ), USERNAME: properties.Schema( properties.Schema.STRING, _('User name to log on to device.'), required=True, update_allowed=True ), PASSWORD: properties.Schema( properties.Schema.STRING, _('Users password.'), required=True, update_allowed=True ), PORT: properties.Schema( properties.Schema.INTEGER, _('Port of the ssh connection.'), default=830, update_allowed=True ), STATIC_ROUTE: properties.Schema( properties.Schema.STRING, _('prefix for static route.'), default=830, update_allowed=True ), NEXT_HOP: properties.Schema( properties.Schema.STRING, _('nexthop address.'), default=830, update_allowed=True ), ROUTER_ID: properties.Schema( properties.Schema.STRING, _('router id.'), required=True, update_allowed=True ), MY_AS: properties.Schema( properties.Schema.STRING, _('AS number for myself.'), required=True, update_allowed=True ), } attributes_schema = { CONFIG_ROUTING_OPTIONS: attributes.Schema( _("config_routing_options attributes."), type=attributes.Schema.MAP ), } def config_routing_options(self): static_route = self.properties[self.STATIC_ROUTE] next_hop = self.properties[self.NEXT_HOP] router_id = self.properties[self.ROUTER_ID] my_as = self.properties[self.MY_AS] routing_options = """ routing-options { static { route %s next-hop %s; } router-id %s; autonomous-system %s; } """ % (static_route, next_hop, router_id, my_as) return routing_options def delete_routing_options(self): routing_options = """ <edit-config> <target> <candidate/> </target> <default-operation>none</default-operation> <config> <configuration> <routing-options operation="delete"/> </configuration> </config> </edit-config> """ return routing_options def handle_create(self): config = self.config_routing_options() conn = self.connect() self.execute_netconf(conn, config, "create", "routing_options") self.resource_id_set(str(uuid.uuid4())) def handle_delete(self): config = self.delete_routing_options() conn = self.connect() self.execute_netconf(conn, config, "delete", "routing_options") def _show_resource(self): result = {} conn = self.connect() config_filter = new_ele('configuration') sub_ele(config_filter, 'routing-options') response = conn.get_configuration(format='text', filter=config_filter) response.xpath('configuration-text')[0].text LOG.info("response=[%s]"% response.xpath('configuration-text')[0].text) result["config_routing_options"] = response.xpath('configuration-text')[0].text return result def resource_mapping(): return { 'OS::Netconf::RoutingOptionsResource': RoutingOptionsResource, }
4,422