diff --git "a/4410.jsonl" "b/4410.jsonl" new file mode 100644--- /dev/null +++ "b/4410.jsonl" @@ -0,0 +1,787 @@ +{"seq_id":"150878310","text":"class Sorter:\n\n def __init__(self, group):\n self.group = group\n self.found = False\n\n def __call__(self, x):\n if x in self.group:\n self.found = True\n return (0, x)\n return (1, x)\n\nsorter = Sorter({2, 3, 4, 6})\nnumbers = [8, 3, 1, 2, 5, 4, 7, 6]\n\nnumbers.sort(key=sorter)\n\nassert sorter.found is True\n\n# The above is an example of a magic method in python\n# You can use __call__ on a class to make it behave like a function\n# and the sort I presume is checking for a call on the class\n# which in this case is the Sorter class. That's how it probably works.","sub_path":"python/sorter.py","file_name":"sorter.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546689681","text":"from datetime import datetime\n\nERROR = 1\nALERT = 2\nWARN = 3\nINFO = 4\nDEBUG = 5\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nlogOutput = DEBUG\n_logLevels = {ERROR: \"ERROR\", ALERT: \"ALERT\", WARN:\"WARN\", INFO: \"INFO\", DEBUG:\"DEBUG\"}\n\n_levelMap = {ERROR: bcolors.FAIL + bcolors.UNDERLINE + bcolors.BOLD,\n ALERT: bcolors.WARNING + bcolors.UNDERLINE + bcolors.BOLD,\n WARN: bcolors.WARNING + bcolors.BOLD,\n INFO: bcolors.OKGREEN + bcolors.BOLD,\n DEBUG: bcolors.OKBLUE }\n\ndef log(level, msg):\n if level <= logOutput:\n print(\"[%s] - %s%s%s: %s\" %\n (\"{:%d/%m/%Y %H:%M:%S}\".format(datetime.now()), _levelMap[level], _logLevels[level], bcolors.ENDC, msg))\n","sub_path":"poisonberry/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44043875","text":"import json\nfrom pathlib import Path\nimport re\n\nimport requests\n\nfrom lark import Lark\nimport lark\n\nfrom wikipedia_ql import fragment\nfrom wikipedia_ql.parser import Parser\n\nclass Wikipedia:\n API_URI = 'https://en.wikipedia.org/w/api.php'\n PARSE_PARAMS = {\n 'action': 'parse',\n 'format': 'json',\n 'disablelimitreport': True,\n 'disableeditsection': True,\n 'disabletoc': True\n }\n QUERY_PARAMS = {\n 'action': 'query',\n 'format': 'json',\n 'redirects': 1\n }\n\n def __init__(self, cache_folder=None):\n self.parser = Parser()\n if cache_folder:\n self.cache_folder = Path(cache_folder)\n self.cache_folder.mkdir(exist_ok=True)\n else:\n self.cache_folder = None\n\n def query(self, query_text):\n type, page, selector = self.parser.parse(query_text)\n if type == 'page':\n return self.get_page(page).query(selector)\n elif type == 'category':\n return [fragment.query(selector) for fragment in self.get_category(page)]\n\n def iquery(self, query_text):\n type, page, selector = self.parser.parse(query_text)\n if type == 'page':\n yield self.get_page(page).query(selector)\n elif type == 'category':\n yield from (fragment.query(selector) for fragment in self.get_category(page))\n\n def get_page(self, title):\n metadata = self.cache_get(title + '.props')\n if not metadata:\n response = requests.get(self.API_URI, params={'titles': title, **self.QUERY_PARAMS})\n metadata = [*json.loads(response.content.decode('utf-8'))['query']['pages'].values()][0]\n self.cache_put(title + '.props', json_data=metadata)\n\n # TODO: save metadata to cache under the real title, too!\n return self._parse_page(metadata)\n\n def get_category(self, category):\n response = requests.get(self.API_URI,\n params={\n 'generator': 'categorymembers',\n 'gcmtitle': f'Category:{category}',\n 'gcmnamespace': 0,\n 'gcmlimit': 100,\n **self.QUERY_PARAMS\n }\n )\n metadata = [*json.loads(response.content.decode('utf-8'))['query']['pages'].values()]\n\n yield from (self._parse_page(m) for m in metadata)\n\n def _parse_page(self, metadata):\n real_title = metadata['title']\n\n text_data = self.cache_get(real_title)\n if not text_data:\n response = requests.get(self.API_URI, params={'page': real_title, **self.PARSE_PARAMS})\n text_data = json.loads(response.content.decode('utf-8'))\n self.cache_put(real_title, json_data=text_data)\n\n return fragment.Fragment.parse(text_data['parse']['text']['*'], metadata=metadata)\n\n def cache_get(self, key):\n if not self.cache_folder:\n return\n\n key = re.sub(r'[?\\/&]', '-', key)\n path = self.cache_folder.joinpath(f'{key}.json')\n if path.exists():\n return json.loads(path.read_text())\n\n def cache_put(self, key, *, text=None, json_data=None):\n if not self.cache_folder:\n return\n\n key = re.sub(r'[?\\/&]', '-', key)\n path = self.cache_folder.joinpath(f'{key}.json')\n if json_data:\n text = json.dumps(json_data)\n path.write_text(text)\n\n","sub_path":"wikipedia_ql/media_wiki.py","file_name":"media_wiki.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"539292771","text":"# Compute saliency with ground-truth captions as input\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport glob\nimport sys\nimport json\nimport os.path as osp\nimport scipy\nimport numpy as np\nimport argparse\n\nfrom im2txt import metrics\n\ndef prepare_resize_saliency(saliency_mask, w, h):\n saliency_mask_upscaled = scipy.misc.imresize(saliency_mask, (w, h), interp='bilinear', mode='F')\n # Anja: I know that scipy.misc.imresize is depricated but skimage.transform.resize gives a different result :(\n return saliency_mask_upscaled\n\ncoco_dir = 'data/mscoco/'\ndataType = 'val2014'\ncoco_masks = '{}/masks/{}/'.format(coco_dir, dataType)\n\ndef evaluate(checkpoint_path, vocab_file, model_name, img_path, save_path):\n save_path = osp.join(save_path, osp.basename(model_name)+'_gt')\n\n of = open(img_path, 'r')\n image_ids = of.read().split('\\n')\n if image_ids[-1] == '':\n image_ids = image_ids[0:-1]\n\n json_path = coco_dir + '/annotations/captions_val2014.json'\n json_data = json.load(open(json_path, 'r'))\n json_dict = {}\n for entry in json_data['annotations']:\n image_id = entry['image_id']\n if str(image_id) not in image_ids: continue\n if image_id not in json_dict:\n caption = entry['caption']\n caption = caption.lower()\n tokens = caption.split(' ') \n if '_man' in img_path: look_for = 'man'\n elif '_woman' in img_path: look_for = 'woman'\n else: assert(False)\n if look_for in tokens:\n json_dict[image_id] = caption\n if len(json_dict) == 500: break\n\n image_ids = json_dict.keys()\n\n pointing_sum = 0\n global_count = 0\n\n for i, image_id in enumerate(image_ids):\n image_id = int(image_id)\n #sys.stdout.write('\\r%d/%d' %(i, len(image_ids)))\n filename = coco_dir + '/images/val2014/COCO_val2014_' + \"%012d\" % (image_id) +'.jpg'\n\n coco_mask_file = '%s/COCO_%s_%012d.npy' %(coco_masks, dataType, image_id)\n coco_mask = np.load(coco_mask_file)\n if np.sum(coco_mask) == 0: \n # no person, perhaps man/woman was not referring to an actual person\n #import ipdb; ipdb.set_trace()\n continue\n\n caption = json_dict[image_id]\n #print(caption)\n if caption[-1] == '.':\n caption = caption[0:-1] \n tokens = caption.split(' ')\n tokens.insert(0, '')\n man_ids = [i for i, c in enumerate(tokens) if c == 'man']\n woman_ids = [i for i, c in enumerate(tokens) if c == 'woman']\n if not (man_ids or woman_ids):\n assert(False) # ground-truth captions definitely contain a man or a woman\n else:\n files = glob.glob(save_path + \"/*COCO_val2014_\" + \"%012d*.npy\" % (image_id))\n for f in files:\n sal_file = f\n saliency_mask = np.load(sal_file)\n mask_grayscale_upscaled = prepare_resize_saliency(saliency_mask, coco_mask.shape[0], coco_mask.shape[1])\n mask_grayscale_upscaled = mask_grayscale_upscaled / float(np.sum(mask_grayscale_upscaled))\n met = metrics.heatmap_metrics(coco_mask, mask_grayscale_upscaled, gt_type='human', SIZE=coco_mask.shape)\n pointing_sum += met.pointing()\n global_count += 1\n\n return (global_count, float(pointing_sum/global_count))\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Generate bbox output from a Fast R-CNN network')\n parser.add_argument('--checkpoint_path', dest='checkpoint_path', help='Model checkpoint file.', default='', type=str)\n parser.add_argument('--vocab_file', dest='vocab_file', help='Text file containing the vocabulary.', default='', type=str)\n parser.add_argument('--model_name', dest='model_name', help='Model name.', default='', type=str)\n parser.add_argument('--img_path', dest='img_path', help='Text file containing image IDs', default='', type=str)\n parser.add_argument('--save_path', dest='save_path', help='Path to the location where outputs are saved.', default='', type=str)\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n count, acc = evaluate(args.checkpoint_path, args.vocab_file, args.model_name, args.img_path, args.save_path)\n print(\"\\ncount: %d instances\" % (count))\n print(\"pointing: %.5f\" % acc)\n\n\n","sub_path":"research/im2txt/data_analysis/evaluate_saliency_with_gt.py","file_name":"evaluate_saliency_with_gt.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107386932","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractor import LinkExtractor\nfrom ..items import BookItem\nfrom scrapy import Request\nimport logging\n\nclass BookSpiderSpider(scrapy.Spider):\n name = \"book_spider\"\n # allowed_domains = [\"books.toscrape.com\"]\n start_urls = ['http://books.toscrape.com/']\n\n def parse(self, response):\n for data in response.css('li.col-xs-6'):\n \titem = BookItem()\n \titem['name'] = data.css('a[href]::attr(title)').extract_first()\n \titem['dollar'] = data.css('p.price_color::text').extract_first()\n \tyield item\n le = LinkExtractor(restrict_css=\"li.next>a\")\n links = le.extract_links(response)\n for link in links:\n \tlogging.warning(link.url)\n \tyield Request(link.url, callback = self.parse)\n","sub_path":"精通SCRAPY爬虫/exsample/exsample/spiders/book_spider.py","file_name":"book_spider.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"299845636","text":"# Copyright 2022 Google LLC\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 json\nfrom pathlib import Path\nimport shutil\n\nimport synthtool as s\nimport synthtool.gcp as gcp\nfrom synthtool.languages import python\n\n# ----------------------------------------------------------------------------\n# Copy the generated client from the owl-bot staging directory\n# ----------------------------------------------------------------------------\n\nclean_up_generated_samples = True\n\n# Load the default version defined in .repo-metadata.json.\ndefault_version = json.load(open(\".repo-metadata.json\", \"rt\")).get(\n \"default_version\"\n)\n\nfor library in s.get_staging_dirs(default_version):\n if clean_up_generated_samples:\n shutil.rmtree(\"samples/generated_samples\", ignore_errors=True)\n clean_up_generated_samples = False\n\n # Work around sphinx docs issue\n # Determine if this is a gapic-generator-python bug or docstring issue\n s.replace(library / f\"google/cloud/devtools/cloudbuild_{library.name}/services/cloud_build/*client.py\",\n \"`WorkerPool`s.\",\n r\"`WorkerPool`\\\\s.\",\n )\n\n # Remove replacement once repo has migrated to google-cloud-python\n assert 1 == s.replace(\n library / \"setup.py\",\n \"\"\"url = \\\"https://github.com/googleapis/python-build\\\"\"\"\",\n \"\"\"url = \\\"https://github.com/googleapis/python-cloudbuild\\\"\"\"\"\n )\n\n # grpc-google-iam-v1 is required by cloud build v2 however setup.py does not reflect this.\n # The issue is that both v1 and v2 are generated which have different requirements for setup.py files.\n # The setup.py for v2 is clobbered by the setup.py for v1 which does not require grpc-google-iam-v1.\n assert 1 == s.replace(\n library / \"setup.py\",\n r\"\"\"\\\"protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5\\\",\\n\"\"\",\n \"\"\"\\\"protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5\\\",\n \"grpc-google-iam-v1 >= 0.12.4, < 1.0.0dev\",\\n\"\"\",\n )\n\n s.move([library], excludes=[\"**/gapic_version.py\"])\ns.remove_staging_dirs()\n\n# ----------------------------------------------------------------------------\n# Add templated files\n# ----------------------------------------------------------------------------\n\ntemplated_files = gcp.CommonTemplates().py_library(\n cov_level=100,\n microgenerator=True,\n versions=gcp.common.detect_versions(path=\"./google\", default_first=True),\n)\ns.move(templated_files, excludes=[\".coveragerc\", \".github/release-please.yml\"])\n\npython.py_samples(skip_readmes=True)\n\n# run format session for all directories which have a noxfile\nfor noxfile in Path(\".\").glob(\"**/noxfile.py\"):\n s.shell.run([\"nox\", \"-s\", \"blacken\"], cwd=noxfile.parent, hide_output=False)\n","sub_path":"owlbot.py","file_name":"owlbot.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"280531262","text":"from itertools import permutations\nfrom intcode import IntcodeMachine\n\n\ndef thruster_power(program, phase_setting_sequence):\n amp_input = 0\n\n for ii in range(5):\n amp = IntcodeMachine(program[:], input=[phase_setting_sequence[ii], amp_input])\n amp.run()\n amp_input = amp.output[0]\n\n return amp_input\n\n\ndef max_thruster_power(program):\n max_power = thruster_power(program, [0, 1, 2, 3, 4])\n for phase_setting_sequence in permutations(list(range(5))):\n power = thruster_power(program, phase_setting_sequence)\n max_power = max(max_power, power)\n\n return max_power\n\n\ndef thruster_power_part2(program, phase_setting_sequence):\n amps = [\n IntcodeMachine(program[:], input=[phase_setting_sequence[ii]])\n for ii in range(5)\n ]\n\n amp_input = 0\n while not any([amp.halted for amp in amps]):\n for amp in amps:\n amp.input.append(amp_input)\n amp.run()\n amp_input = amp.output.pop()\n\n return amp_input\n\n\ndef max_thruster_power_part2(program):\n max_power = thruster_power_part2(program, [5, 6, 7, 8, 9])\n for phase_setting_sequence in permutations(list(range(5, 10))):\n power = thruster_power_part2(program, phase_setting_sequence)\n max_power = max(max_power, power)\n\n return max_power\n\n\nif __name__ == \"__main__\":\n with open(\"input\") as fp:\n source_code = fp.read()\n program = [int(instr) for instr in source_code.split(\",\")]\n\n assert max_thruster_power(program) == 79723\n\n print(max_thruster_power_part2(program))\n","sub_path":"a7/thruster_power.py","file_name":"thruster_power.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35590682","text":"import numpy as np\nimport json\nimport matplotlib.pyplot as plt\nfrom math import exp, erfc, sqrt\n\nc = 1.\nD = 5.\n\nx_split = 0.1\nt_split = 0.1\nt_size = 5000\nx_size = 5000\nphi = np.zeros((t_size,x_size))\n\nfor t in range(t_size):\n for x in range(x_size):\n if t == 0:\n phi[0,x] = 0.\n elif x == 0:\n phi[t,x] = 1.\n else:\n phi[t,x] = 0.5 * np.exp(x*x_split*c/(2*D)) * ( np.exp( -x*x_split*c/(2*D) ) * erfc( (x*x_split-c*t*t_split)/(2*sqrt(D*t*t_split)) )\n + np.exp( x*x_split*c/(2*D) ) * erfc( (x*x_split+c*t*t_split)/(2*sqrt(D*t*t_split)) ) )\n\n# ### 移流拡散のプロット\n# for t in range(t_size):\n# plt.plot( [x_split*x for x in range(x_size) ], phi[t,:] , lw=5)\n# plt.ylim([0,1])\n# plt.draw()\n# plt.pause(0.001)\n# plt.clf()\n\nfilepath = './data/data_1D.csv'\nnp.savetxt(filepath, phi, delimiter=',')\n","sub_path":"generate_1D.py","file_name":"generate_1D.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597716748","text":"\"\"\"empty message\n\nRevision ID: 1d337e183d47\nRevises: None\nCreate Date: 2016-01-26 21:33:22.356000\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1d337e183d47'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('roles',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=64), nullable=True),\n sa.Column('default', sa.Boolean(), nullable=True),\n sa.Column('permissions', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_index('ix_roles_default', 'roles', ['default'], unique=False)\n op.create_table('restaurant',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=64), nullable=True),\n sa.Column('phone', sa.String(length=64), nullable=True),\n sa.Column('coordinates', sa.String(length=64), nullable=True),\n sa.Column('menu_url', sa.String(length=64), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('ix_restaurant_name', 'restaurant', ['name'], unique=True)\n op.create_table('menus',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date', sa.DATE(), nullable=False),\n sa.Column('content', sa.String(length=300), nullable=False),\n sa.Column('restaurant_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['restaurant_id'], ['restaurant.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=64), nullable=True),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('role_id', sa.Integer(), nullable=True),\n sa.Column('password_hash', sa.String(length=128), nullable=True),\n sa.Column('confirmed', sa.Boolean(), nullable=True),\n sa.Column('name', sa.String(length=64), nullable=True),\n sa.Column('location', sa.String(length=64), nullable=True),\n sa.Column('about_me', sa.Text(), nullable=True),\n sa.Column('member_since', sa.DateTime(), nullable=True),\n sa.Column('last_seen', sa.DateTime(), nullable=True),\n sa.Column('avatar_hash', sa.String(length=32), nullable=True),\n sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index('ix_users_email', 'users', ['email'], unique=True)\n op.create_index('ix_users_username', 'users', ['username'], unique=True)\n op.create_table('votes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date', sa.DATE(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('restaurant_id', sa.Integer(), nullable=True),\n sa.Column('comment', sa.String(length=64), nullable=True),\n sa.ForeignKeyConstraint(['restaurant_id'], ['restaurant.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('votes')\n op.drop_index('ix_users_username', 'users')\n op.drop_index('ix_users_email', 'users')\n op.drop_table('users')\n op.drop_table('menus')\n op.drop_index('ix_restaurant_name', 'restaurant')\n op.drop_table('restaurant')\n op.drop_index('ix_roles_default', 'roles')\n op.drop_table('roles')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/1d337e183d47_.py","file_name":"1d337e183d47_.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"41878392","text":"from tkinter import *\nimport os\nimport client\nimport titleBar\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))\n\nclass BanUser:\n def __init__(self, window, user_list, darkModeOn):\n # 자신의 창을 가리킴\n self.myParent = window\n # 가져온 유저 리스트\n self.user_list = user_list\n #유저 체크박스리스트\n self.CheckBoxVarList = []\n\n # 타이틀바 설정\n window.title('유저 강퇴 투표')\n self.myParent.iconbitmap(\"./Icon/BanUser.ico\")\n #self.titlebar = titleBar.TitleBar(self.myParent)\n \n #상단 프레임\n self.topFrame = Frame(window)\n self.titleLabel = Label(self.topFrame, text=\"유저 강퇴 투표\")\n \n self.titleLabel.pack(fill=X, side=TOP)\n self.topFrame.pack(fill=X, side=TOP)\n\n #메인 프레임\n self.mainFrame = Frame(window)\n self.mainFrame.pack(fill=BOTH, expand=TRUE, side=TOP) \n\n self.centerWindow(window)\n \n self.centerFrame = Frame(window)\n self.inputUser(darkModeOn)\n self.centerFrame.pack()\n\n #하단 버튼 프레임\n self.btnFrame = Frame(self.myParent)\n self.enterBtn = Button(self.btnFrame, width=20, text=\"강퇴 요청하기\", command=self.cutOff)\n self.enterBtn.pack(side=BOTTOM)\n self.btnFrame.pack(fill=BOTH, side=BOTTOM)\n self.darkMode(darkModeOn)\n\n def darkMode(self, darkModeOn):\n if darkModeOn == True:\n self.myParent.configure(background='#242424')\n self.topFrame.configure(background='#242424')\n self.mainFrame.configure(background='#242424')\n self.btnFrame.configure(background='#242424')\n self.titleLabel['bg'] = '#242424'\n self.titleLabel['fg'] = '#ffffff'\n self.enterBtn['bg'] = '#424242'\n self.enterBtn['fg'] = '#ffffff'\n else:\n self.myParent.configure(background='#f0f0f0')\n self.topFrame.configure(background='#f0f0f0')\n self.mainFrame.configure(background='#f0f0f0')\n self.btnFrame.configure(background='#f0f0f0')\n self.titleLabel['bg'] = '#f0f0f0'\n self.titleLabel['fg'] = '#000000'\n self.enterBtn['bg'] = '#f0f0f0'\n self.enterBtn['fg'] = '#000000'\n\n def cutOff(self):\n pass\n\n def inputUser(self, darkModeOn):\n for userName in self.user_list:\n #print(\"hi\")\n tempVar = BooleanVar(value=False)\n tempFrame = Frame(self.mainFrame)\n temp = Checkbutton(tempFrame, variable=tempVar, text=userName)\n self.CheckBoxVarList.append(tempVar)\n if darkModeOn == True:\n tempFrame.configure(background=\"#242424\")\n temp['bg'] = '#242424'\n temp['fg'] = '#ffffff'\n temp['selectcolor'] = '#424242'\n else:\n pass\n tempFrame.pack(side=TOP, fill=X)\n temp.pack(side=LEFT)\n\n\n #가운데로 오게 하는 함수\n def centerWindow(self, window):\n width = 300\n height = 400\n screen_width = window.winfo_screenwidth()\n screen_height = window.winfo_screenheight()\n #x = screen_width/2 - width/2 + 400\n x = screen_width / 2 - height/2 + 50\n y = screen_height/2 - height/2\n window.geometry('%dx%d+%d+%d' %(width,height,x,y))\n","sub_path":"client/userListManage/banUser.py","file_name":"banUser.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"25064661","text":"\"\"\"\nCalculates volume of cell outline drawn on blank background.\nT.Wilson 23/12/18\n\nfuture updates: Speed up major axis finder - slow optimize routine\n Move functions to class - as originally indended\n Background function - allow for non blank Background\n Paralize loops\n Increase Accuracy\n\n\"\"\"\n\nfrom astropy.io import fits\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport math\nfrom math import *\n\n###############################################################\n###############################################################\npixel_size = 1 #i.e. how many mm/m/km per pixel\ninteg_steps = 100 #number of steps to take along axis of rotation numbers\ninput_file = 'Cell4.png' #name of input file\noutput_file = 'output_'+input_file\n###############################################################\n###############################################################\n\n\n#dynamic memory expansion\ndef expand_array(array):\n size = np.shape(array)\n array1 = np.zeros((2*size[0],size[1]))\n for i in range(size[0]):\n array1[i,0] = array[i,0]\n array1[i,1] = array[i,1]\n return array1\n\ndef cut_array(array,array_size):\n new_array = np.zeros((array_size,2))\n for i in range(array_size):\n new_array[i,0] = array[i,0]\n new_array[i,1] = array[i,1]\n return new_array\n\ndef find_pixels(pix,background):\n array_size = 100\n points = np.zeros((array_size,2))\n count = 0\n for x in range(image_width):\n for y in range(image_height):\n if(count >= array_size):\n points = expand_array(points)\n array_size *= 2\n\n if(pix[x,y][0] > background[0] or pix[x,y][1] > background[1] or pix[x,y][2] > background[2]):\n points[count,0] = x\n points[count,1] = y\n count += 1\n points = cut_array(points,count)\n return points\n\n#this takes the average background\n#adjust this function if it does not correctly\n#identitfy your cell boundary ie if your\n#background is not black enough\ndef find_background_average(pix):\n sum = np.zeros((3))\n for x in range(image_width):\n for y in range(image_height):\n for i in range(3):\n sum[i] += pix[x,y][i]\n sum /= image_width*image_height\n print(\"Average background RGB value is: {}\".format(sum))\n return sum\n\ndef find_major_axis(pixels,num_pixels):\n pos = np.zeros((2,2))\n temp = np.zeros((2))\n old_dist = 0.\n for j in range(num_pixels):\n temp[0] = pixels[j,0]\n temp[1] = pixels[j,1]\n for i in range(num_pixels):\n dist = sqrt((pixels[i,0] - temp[0])**2 + (pixels[i,1] - temp[1])**2)\n if(dist > old_dist):\n pos[0,0] = temp[0]\n pos[0,1] = temp[1]\n pos[1,0] = pixels[i,0]\n pos[1,1] = pixels[i,1]\n old_dist = dist\n return pos\n\ndef draw_axis(pix,axis):\n grad = (axis[1,1] - axis[0,1]) / (axis[1,0] - axis[0,0])\n c = axis[0,1] - (grad*axis[0,0])\n\n for x in range(image_width):\n for y in range(image_height):\n if( abs(y - ((grad*x) + c)) <= 0.2):\n pix[x,y] = (0,250,0)\n\ndef find_axis_angle(axis):\n theta = atan((axis[1,1] - axis[0,1]) / (axis[1,0] - axis[0,0]))\n print(\"angle of axis to horizontal is {0:.2f} deg\".format(theta*180/pi))\n return theta\n\ndef find_widest_points_at_xy(x,y,pixels,num_pixels,pix):\n\n pix[x,y] = (250,0,0)\n grad = (axis[1,1] - axis[0,1]) / (axis[1,0] - axis[0,0])\n grad = - 1. / grad\n c = y - (grad*x)\n\n array_size = 2\n count = 0\n temp = np.zeros((array_size,2))\n dist = 0.\n prec = 1\n\n while(1):\n for i in range(num_pixels):\n if(abs(pixels[i,1] - (grad*pixels[i,0]) - c) <= prec):\n if(count >=array_size):\n temp = expand_array(temp)\n array_size *= 2\n\n temp[count,0] = pixels[i,0]\n temp[count,1] = pixels[i,1]\n count += 1\n\n greatest_sep = find_major_axis(cut_array(temp,count),count)\n distance = sqrt((greatest_sep[1,0] - greatest_sep[0,0])**2 + (greatest_sep[1,1] - greatest_sep[0,1])**2)\n\n if(count <= 10 or distance <= 2):\n prec += 0.5\n elif(count >= 1000):\n return np.inf\n else:\n break\n pix[greatest_sep[0,0],greatest_sep[0,1]] = (250,0,0)\n pix[greatest_sep[1,0],greatest_sep[1,1]] = (250,0,0)\n return distance\n\ndef integrate_area(pixels,num_pixels,axis,pix):\n volume = 0.0\n axis_length = sqrt((axis[1,0] - axis[0,0])**2 + (axis[1,1] - axis[0,1])**2)\n\n theta = find_axis_angle(axis)\n length = 0.\n dl = axis_length / integ_steps\n pos = axis[0,:]\n temp_diametre = 0.\n while(length <= axis_length):\n diametre = find_widest_points_at_xy(pos[0],pos[1],pixels,num_pixels,pix)\n if(diametre == \"inf\"):\n diametre = temp_diametre\n print(\"no, pixels found, using neares neighbour\")\n else:\n volume += (0.25 * pi * (diametre*pixel_size)**2 *dl*pixel_size)\n pos[0] += dl * cos(theta)\n pos[1] += dl * sin(theta)\n length += dl\n return volume\n\n\n###############################################################\n###############################################################\n\nim = Image.open(input_file)\npix = im.load()\n\nimage_width, image_height = im.size\nprint(\"Image dimensions {}x{}\".format(image_width,image_height))\n\npixels = find_pixels(pix,find_background_average(pix))\nnum_pixels = np.shape(pixels)[0]\nprint(\"Number of coloured pixels found = {}\".format(num_pixels))\n\n#re-colouring to blue so you can check it correctly finds cell boundary\nfor i in range(num_pixels):\n pix[pixels[i,0],pixels[i,1]] = (0,0,250)\n\n\naxis = find_major_axis(pixels,num_pixels)\ndraw_axis(pix,axis)\nvolume = integrate_area(pixels,num_pixels,axis,pix)\n\nprint(volume)\n\nim.rotate(0).save(output_file,\"PNG\")\n","sub_path":"cal_volume.py","file_name":"cal_volume.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588988904","text":"from queue import PriorityQueue\n\ndef shortest_path(_map, start, goal):\n \n previous_node = {}\n score = {}\n \n previous_node[start]=None\n score[start]=0\n \n path_queue = PriorityQueue()\n path_queue.put(start)\n \n while not path_queue.empty():\n current_node = path_queue.get()\n\n #break state\n if current_node == goal:\n return_path_as_list(previous_node, start, goal)\n\n #loop through chilren of current node and calculate distance from origin \n for node in _map.roads[current_node]:\n\n #update current score for node\n g_score = score[current_node] + point_distance(_map.intersections[current_node],\n _map.intersections[node])\n \n if node not in score or g_score < score[node]:\n \n score[node] = g_score\n\n h_score = point_distance(_map.intersections[current_node],\n _map.intersections[goal])\n\n f_score = g_score + h_score #a star search criteria\n\n path_queue.put(node, f_score)\n previous_node[node] = current_node\n\n path = return_path_as_list(previous_node, start, goal)\n\n return path\n\n\ndef point_distance(point_a, point_b) -> int:\n\n \"\"\" heuristic helper, direct distance between points \"\"\"\n\n x = abs(point_a[0] - point_b[0])\n y = abs(point_a[1] - point_b[1])\n\n return x + y \n\n\ndef return_path_as_list(previous_node, start, goal):\n\n \"\"\" loop back and create a list of nodes visited for that path \"\"\"\n \n node = goal\n path = [node]\n \n while node:\n node = previous_node[node]\n path.insert(0,node)\n \n return path[1:]","sub_path":"a_star_route_planner/a_star_search.py","file_name":"a_star_search.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231424867","text":"import shutil, os, json\nimport util\nimport notebook_convert as nbconv\n\n\nclass tester:\n \"\"\" This class is responsible for testing submissions and writing to a log location\n with various, language-specific forms of output.\n \"\"\"\n\n def __init__(self, manager):\n \"\"\" Initialization function, does a lot of setup but nothing actually gets done yet\n \"\"\"\n self.name = \"tester\"\n self.test_funcs = {\n \"c\": self.test_c,\n \"java\": self.test_java,\n \"python\": self.test_python,\n \"jupyter\": self.test_jupyter\n }\n self.manager = manager\n self.abs_path = self.manager.abs_path\n self.define_abs_paths()\n self.test_contents = {}\n\n def define_abs_paths(self):\n \"\"\" Helper to set class variables\n \"\"\"\n self.workspace_path = \"/home/codio/workspace\"\n self.guides_path = \"{}/.guides\".format(self.workspace_path)\n self.submission_path = \"{}/submit\".format(self.workspace_path)\n self.is_secure = False if '{}/test/'.format(self.guides_path) in self.abs_path else True\n self.current_root = \"{}/{}\".format(self.guides_path, \"secure\" if self.is_secure else \"test\")\n self.manager.log(\"Current Root: {}\\tIs Secure: {}\".format(self.current_root, self.is_secure),\n raising_class=self)\n\n def test_unit_testing(self):\n \"\"\" Parse the unit testing files to confirm whether student completed\n the required number of additional tests\n \"\"\"\n\n # Check to make sure that this assignment actually uses unit testing\n if 'unit_testing' not in self.manager.assignment_manifest_contents.keys():\n return\n requires_unit_testing = False\n for asg_lang in self.manager.assignment_manifest_contents['assignment_overview']['assignment_types']:\n if 'unit_testing' not in self.manager.assignment_manifest_contents['scoring'][asg_lang].keys():\n continue\n elif self.manager.assignment_manifest_contents['scoring'][asg_lang]['unit_testing'] > 0:\n requires_unit_testing = True\n continue\n if not requires_unit_testing:\n return\n\n # Check each assignment language to figure out which unit testing to grade\n for asg_lang in self.manager.assignment_manifest_contents['assignment_overview']['assignment_types']:\n self.test_contents[asg_lang] = {}\n for file in self.manager.assignment_manifest_contents['unit_testing'][asg_lang]:\n self.test_contents[asg_lang][file] = {}\n contents = util.get_file_contents_as_list(\"{}/{}\".format(self.submission_path, file))\n is_test_case = False\n test_case_name = None\n# file = \".\".join(file.split(\"/\")[-1].split(\".\")[:-1])\n for line in contents:\n line = line.strip()\n\n # Java-specific parsing\n if asg_lang == 'java':\n # Case: beginning of a test\n if line.startswith(\"@Test\") and not is_test_case:\n is_test_case = True\n test_case_name = None\n # Case: actual test contents\n elif is_test_case and test_case_name is None:\n split = line.split(' ')\n for elt in split:\n if 'test' in elt.lower():\n test_case_name = elt.split('(')[0]\n is_test_case = False\n self.test_contents[asg_lang][file][test_case_name] = {\"asserts\": []}\n break\n # Case: scan for asserts\n elif test_case_name is not None and not is_test_case:\n if line.startswith(\"assert\"):\n self.test_contents[asg_lang][file][test_case_name][\"asserts\"].append(line)\n\n # Python-specific parsing\n elif asg_lang == \"python\":\n if line.startswith(\"def\"):\n split = line.split(' ')\n for elt in split:\n if 'test' in elt.lower():\n test_case_name = elt.split('(')[0]\n self.test_contents[asg_lang][file][test_case_name] = {\"asserts\": []}\n break\n elif test_case_name is not None:\n if line.startswith(\"self.assert\"):\n self.test_contents[asg_lang][file][test_case_name][\"asserts\"].append(line)\n\n # Figure out which test cases were actually required\n required = self.manager.assignment_manifest_contents['unit_testing'][asg_lang][file]\n for test_case in self.test_contents[asg_lang][file]:\n\n # Make sure that we're actually interested in this one\n if test_case not in required['min_asserts']:\n continue\n \n this_test = {\n 'provided': required['provided_asserts'][test_case],\n 'required': required['min_asserts'][test_case],\n 'found': len(self.test_contents[asg_lang][file][test_case]['asserts']),\n }\n this_test['required_new'] = this_test['required'] - this_test['provided']\n self.test_contents[asg_lang][file][test_case] = this_test\n return self.test_contents\n \n\n def test_submission(self):\n \"\"\" This determines which test function should be used based on the language being tested. This is\n the function that should be called to actually perform testing\n \"\"\"\n for lang in self.manager.assignment_manifest_contents['assignment_overview']['assignment_types']:\n self.manager.log(\"Testing {}\".format(lang), raising_class=self)\n try:\n # Grab the appropriate language-specific function, then execute\n fn = self.test_funcs[lang]\n fn(\"{}/execution-environment/{}\".format(self.current_root, lang))\n except Exception as e:\n msg = \"Ran into an error while testing {}\".format(lang)\n print(msg)\n self.manager.log(msg, e, self)\n\n def test_c(self, test_env_path):\n ''' This method will clear out the testing environment, copy in the test cases along with the submission,\n then execute the tests using the Aceunit framework\n '''\n # Clear test location for compilation\n util.clear_out_dir(test_env_path, exclude=['src', 'tests', 'Makefile'])\n util.clear_out_dir('{}/src'.format(test_env_path))\n util.clear_out_dir('{}/tests'.format(test_env_path))\n\n # Copy in the appropriate files (extra credit agnostic)\n dont_copy = []\n dont_copy += self.manager.assignment_manifest_contents['assignment_overview']['ignore_files']\n dont_copy += ['java', 'class', 'py', 'ipynb', 'Makefile']\n util.copy_files_from_dir(self.submission_path, '{}/src'.format(test_env_path), exclude_types=dont_copy)\n util.copy_files_from_dir('{}/test-cases/c'.format(self.current_root), '{}/tests'.format(test_env_path),\n exclude_types=['Makefile'])\n util.copy_files_from_dir('{}/test-cases/c'.format(self.current_root), test_env_path, include_types=['Makefile'])\n\n # If there are extra credit implementations, parse through the test cases\n ec_implementations = self.check_files_for_ec_funcs(\n self.manager.assignment_manifest_contents['assignment_overview'])\n if len(ec_implementations) > 0:\n self.parse_ec_tests(\n '{}/tests'.format(test_env_path),\n ec_implementations)\n\n files_present, _ = util.get_dir_contents(test_env_path)\n os.chdir(test_env_path)\n os.system('make test 2>&1 | tee -a {}/log_c.txt'.format(self.manager.log_path))\n os.system('mv results_c.xml {}/test_results_c.xml'.format(self.manager.log_path))\n\n def test_java(self, test_env_path):\n ''' This method will perform actions needed to clear the testing library (test location),\n copy in all test cases, copy in the submission, then execute the test cases for java\n submissions\n '''\n conf_json = json.loads(self.manager.config_contents)\n\n # Clear test location\n util.clear_out_dir(test_env_path)\n\n # Copy in the appropriate files (submissions, tests, libraries)\n dont_copy = []\n dont_copy += self.manager.assignment_manifest_contents['assignment_overview']['ignore_files']\n dont_copy += ['py', 'class', 'ipynb']\n util.copy_files_from_dir(self.submission_path, test_env_path, exclude_types=dont_copy, keep_structure=True)\n\n # Make sure that the tests are copied to the proper directory\n path_modifier = ''\n if 'package_location' in conf_json.keys():\n if conf_json['package_location'] != \"\":\n path_modifier = conf_json['package_location']\n util.copy_files_from_dir('{}/test-cases/java'.format(self.current_root),\n '{}/{}'.format(test_env_path, path_modifier))\n util.copy_files_from_dir('{}/libs'.format(self.workspace_path), test_env_path)\n\n # Determine relevant jar files\n files_present, _ = util.get_dir_contents(test_env_path)\n jar_files = ''\n for file in files_present:\n if util.get_file_ext(file) == 'jar':\n jar_files += file\n\n # Check for the config.json overrides; set the compile and run commands\n compile_cmd = \"\"\n if 'compile_override' in conf_json.keys():\n if conf_json['compile_override'] != \"\":\n compile_cmd = conf_json['compile_override']\n if compile_cmd == \"\":\n compile_cmd = 'javac -cp {}:{} {}/*.java'.format(test_env_path, jar_files, test_env_path)\n self.manager.log(\"Compile command is: {}\".format(compile_cmd), raising_class=self)\n run_cmd = \"\"\"java -jar junit-platform-console-standalone-1.3.2.jar \\\n --disable-ansi-colors \\\n --classpath=\"{}:{}:bin\" \\\n --reports-dir=\"{}\" \\\n --scan-class-path 2>&1 | tee -a {}/results_java.txt\"\"\".format(test_env_path,\n jar_files,\n self.manager.log_path,\n self.manager.log_path)\n\n # Compile the submission, then run it\n print(' > Attempting to compile submission')\n os.chdir(test_env_path)\n res = os.system(compile_cmd)\n if res != 0:\n print(\" > ERROR: Could not compile submission\")\n exit(9)\n else:\n print(\" > Successfully compiled\")\n print(\"\\n > Running test cases\")\n res = os.system(run_cmd)\n\n def test_python(self, test_env_path):\n ''' This method will perform actions needed to clear the testing library (test location),\n copy in all test cases, copy in the submission, then execute the test cases for python\n submissions\n '''\n\n # Clear test location\n util.clear_out_dir(test_env_path)\n\n # Copy in the appropriate files\n dont_copy = []\n dont_copy += self.manager.assignment_manifest_contents['assignment_overview']['ignore_files']\n dont_copy += ['java', 'class', 'ipynb']\n util.copy_files_from_dir(self.submission_path, test_env_path, exclude_types=dont_copy)\n util.copy_files_from_dir('{}/test-cases/python'.format(self.current_root), test_env_path)\n\n # Execute test cases\n os.chdir(test_env_path)\n os.system(\n 'python3 {}/runner.py 2>&1 | tee -a {}/results_python.txt'.format(test_env_path, self.manager.log_path))\n\n def test_jupyter(self, test_env_path):\n ''' This method will perform actions needed to clear the testing library (test location),\n copy in all test cases, copy in the submission, then execute the test cases for Jupyter NB\n submissions\n '''\n\n # Clear test location, get submission files to see which need to be converted\n # using runipy\n util.clear_out_dir(test_env_path)\n\n # Copy in the appropriate files\n dont_copy = []\n dont_copy += self.manager.assignment_manifest_contents['assignment_overview']['ignore_files']\n dont_copy += ['java', 'class', 'py']\n util.copy_files_from_dir(self.submission_path, test_env_path, exclude_types=dont_copy)\n util.copy_files_from_dir('{}/test-cases/jupyter'.format(self.current_root), test_env_path)\n\n files_present, _ = util.get_dir_contents(test_env_path)\n\n # Execute each file using runipy, then parse to a .py file for actual testing\n # also copy in all additional files\n for file in files_present:\n infile = '{}/{}'.format(test_env_path, file)\n\n if file[-6:] == '.ipynb':\n outfile = '{}/{}.py'.format(test_env_path, file.split('.')[0])\n os.system('/home/codio/.local/bin/runipy -o -q {}'.format(infile))\n self.manager.log(\"About to convert notebook {}\".format(infile), raising_class=self)\n try:\n nbconv.convert_notebook(infile, outfile, self.manager.log_path)\n self.manager.log(\"Successfully converted {}\".format(infile), raising_class=self)\n except Exception as e:\n self.manager.log(\"Error converting {}\".format(infile), e, raising_class=self)\n\n # Execute test cases\n os.chdir(test_env_path)\n os.system(\n 'python3 {}/runner.py 2>&1 | tee -a {}/results_jupyter.txt'.format(test_env_path, self.manager.log_path))\n\n def check_files_for_ec_funcs(self, asg_overview):\n ''' This function will check whether the student attempted any of the extra credit\n implementations. It will then return a dictionary with those that were attempted\n '''\n ec_func_files = asg_overview['extra_credit_functions']\n implementations = {}\n for file in ec_func_files:\n self.manager.log(\"Looking in {} for extra credit functions\".format(file), raising_class=self)\n try:\n submission_file = open('{}/{}'.format(self.submission_path, file), 'r')\n contents = submission_file.read()\n submission_file.close()\n ec_funcs = ec_func_files[file] # Student function names in student submission file\n\n for ec_func in ec_funcs:\n self.manager.log('Searching for function {}'.format(ec_func), raising_class=self)\n if ec_func not in contents:\n self.manager.log('Not found', raising_class=self)\n else:\n self.manager.log('Found', raising_class=self)\n if file not in implementations:\n implementations[file] = ec_func_files[file]\n except IOError as e:\n self.manager.log(\"Unable to open file: {}\".format(file), raising_class=self)\n return []\n return implementations\n\n def parse_ec_tests(path_to_excec_env, ec_funcs_included):\n ''' This function will go through the extra credit tests and uncomment them\n based on specified regular expression below. It currently is only implemented\n for C language.\n '''\n regex = ['BEGIN_EC_TEST_', 'END_EC_TEST_']\n\n ec_files_and_funcs = {}\n for student_file in ec_funcs_included:\n for student_func in ec_funcs_included[student_file]:\n ec_file = ec_funcs_included[student_file][student_func]\n for key in ec_file:\n if key not in ec_files_and_funcs:\n ec_files_and_funcs[key] = [ec_file[key]]\n else:\n ec_files_and_funcs[key].append(ec_file[key])\n\n # In each test case file that's included, look for the regex indicating the\n # start and end of a conditional test case.\n for file in ec_files_and_funcs:\n parsed_file = []\n ec_file = open('{}/{}'.format(path_to_excec_env, file), 'r').read().split('\\n')\n for line in ec_file:\n skip = False\n for expression in regex:\n if expression in line:\n split_line = line.replace('/*', '').replace('*/', '').strip().split(expression)\n test_name = split_line[1]\n # If it's a test case regex, we're deleting the comment, so set skip flag to be true\n if test_name in ec_files_and_funcs[file]:\n skip = True\n # Base case, add the line as is\n if skip:\n continue\n parsed_file.append(line)\n\n # Overwrite existing file if there are changes\n if len(parsed_file) != len(ec_file):\n write_to = open('{}/{}'.format(path_to_excec_env, file), 'w+')\n write_to.write('\\n'.join(parsed_file))\n write_to.close()\n\n def check_files_for_required_funcs(self):\n \"\"\" This function will confirm that all required functions are present\n for student submission, then return the number of missing (if any)\n \"\"\"\n missing = 0\n required_funcs_files = self.manager.assignment_manifest_contents['assignment_overview']['required_functions']\n for file in required_funcs_files:\n self.manager.log(\"Looking in {} for required functions\".format(file), raising_class=self)\n try:\n fd = open('{}/{}'.format(self.submission_path, file), 'r')\n contents = fd.read()\n req_funcs = required_funcs_files[file]\n for req_func in req_funcs:\n self.manager.log('Searching for function {}'.format(req_func), raising_class=self)\n if req_func not in contents:\n self.manager.log(\"Not Found\".format(file), raising_class=self)\n missing += 1\n else:\n self.manager.log(\"Found\".format(file), raising_class=self)\n fd.close()\n except IOError as e:\n self.manager.log(\"Error checking files for required functions\", e, self)\n return -1\n return missing\n\n def check_for_required_files(self):\n \"\"\" This function will confirm that all required files are present\n for student submission, then return the number of missing (if any)\n \"\"\"\n required_files = self.manager.assignment_manifest_contents['assignment_overview']['required_files']\n files_present = []\n self.manager.log(\"Determining present files\", raising_class=self)\n for (_, _, filenames) in os.walk('{}'.format(self.submission_path)):\n files_present.extend(filenames)\n break\n missing = 0\n for req_file in required_files:\n self.manager.log('Searching for {}'.format(req_file), raising_class=self)\n if req_file not in files_present:\n self.manager.log(\"Not found\", raising_class=self)\n missing += 1\n else:\n self.manager.log(\"Found\", raising_class=self)\n return missing","sub_path":"Inheritance & Data Structures in Java_HW 2/module-2/.guides/test/control/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":19957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372084288","text":"import os, subprocess, sys\nfrom MuseParse.classes import Exceptions\n\nclass LilypondRenderer(object):\n\n def __init__(\n self,\n piece_obj,\n fname,\n lyscript=\"\"):\n self.piece_obj = piece_obj\n self.file = fname\n self.lyfile = self.file.split(\".\")[0] + \".ly\"\n self.pdf = self.file.split(\".\")[0] + \".pdf\"\n self.folder = \"/\".join(self.file.split(\"/\")[:-1])\n\n self.defaults = {\"darwin\":\"/Users/charlottegodley/bin/lilypond\", \"win32\":\"lilypond\"}\n if lyscript != \"\":\n self.lily_script = lyscript\n else:\n if sys.platform.startswith(\"linux\"):\n self.lily_script = \"lilypond\"\n else:\n self.lily_script = self.defaults[sys.platform]\n\n def run(self, wrappers=[\"\", \"\"]):\n '''\n run the lilypond script on the hierarchy class\n :param wrappers: this is useful for testing: use wrappers to put something around the outputted \"lilypond string\" from the hierarchy class.\n For example if you're testing a pitch, you might put \\relative c {} around the note so that lilypond handles it properly without causing an error\n :return: doesn't return anything, side effect that a PDF should be created.\n '''\n opened_file = open(self.lyfile, 'w')\n lilystring = self.piece_obj.toLily()\n opened_file.writelines(\n wrappers[0] +\n \"\\\\version \\\"2.18.2\\\" \\n\" +\n lilystring +\n wrappers[1])\n opened_file.close()\n # subprocess.Popen(['sudo', self.lily_script,\" --output=\" +\n # self.folder, self.lyfile])\n os.system(self.lily_script +\n \" --output=\" +\n self.folder + \" \" + self.lyfile\n )\n\n def cleanup(self, pdf=False):\n if os.path.exists(self.lyfile):\n os.remove(self.lyfile)\n\n if pdf:\n if os.path.exists(self.pdf):\n os.remove(self.pdf)\n","sub_path":"MuseParse/classes/Output/LilypondOutput.py","file_name":"LilypondOutput.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626334476","text":"import json\nfrom base64 import b64decode\n\nfrom config import settings\nfrom limesurveyrc2api import LimeSurveyRemoteControl2API\n\n# Make a session.\napi = LimeSurveyRemoteControl2API(settings.rpc_url)\nsession_req = api.sessions.get_session_key(settings.username, settings.password)\nsession_key = session_req.get('result')\n\nsurveys_req = api.surveys.list_surveys(session_key, settings.username)\nsurveys = surveys_req.get('result')\nfor survey in surveys:\n if survey.get('surveyls_title') == 'yunity Contributors page':\n sid = survey.get('sid')\n responses_req = api.surveys.export_responses(session_key, sid)\n response_b64 = responses_req.get('result')\n responses = json.loads(b64decode(response_b64).decode())\n picture_list = []\n for _ in responses['responses']:\n for rid, response in _.items():\n print(response)\n if response['picture']:\n pic_dict = json.loads(response['picture'])[0]\n picture_list.append({'name': pic_dict['name'], 'rid': rid, 'sid': sid})\n\n\nfrom requests import session\nwith session() as s:\n response = s.get(settings.login_url)\n csrf = response.cookies['YII_CSRF_TOKEN']\n response = s.post(settings.login_url,\n {'YII_CSRF_TOKEN': csrf,\n 'authMethod': 'Authdb',\n 'user': settings.username,\n 'password': settings.password,\n 'loginlang': 'default',\n 'action': 'login',\n 'login_submit': 'login'}\n )\n for p in picture_list:\n response = s.get(settings.response_url,\n params={\n 'sa': 'actionDownloadfile',\n 'sFileName': p['name'],\n 'iResponseId': p['rid'],\n 'surveyid': p['sid']})\n with open('{}{}'.format(p['rid'], p['name']), 'bw') as f:\n f.write(response.content)\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535167134","text":"#!/usr/bin/python3\n\"\"\"\nRoute that return the status\n\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify\nfrom models import storage\n\n\n@app_views.route('/status')\ndef status():\n \"\"\"\n function for status route that returns the status\n \"\"\"\n response = {\"status\": \"OK\"}\n return jsonify(response)\n\n\n@app_views.route('/stats')\ndef stats():\n \"\"\"\n Endpoint that retrieves the number of each objects by type\n \"\"\"\n response = {}\n classes = {\n \"Amenity\": \"amenities\",\n \"City\": \"cities\",\n \"Place\": \"places\",\n \"Review\": \"reviews\",\n \"State\": \"states\",\n \"User\": \"users\"\n }\n for key, value in classes.items():\n response[value] = storage.count(key)\n return jsonify(response)\n","sub_path":"api/v1/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574982300","text":"\"\"\"\n Jake Pitkin - u0891770\n CS 6490 - Fall 2017\n Programming Assignment 4\n\"\"\"\n\nimport time\nimport math\nimport sys\nimport os.path\nimport random as r\nfrom Crypto import Random\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import hashes\nfrom OpenSSL import crypto\nfrom Crypto.Hash import SHA256\nfrom Crypto.Hash import HMAC\nfrom Crypto.Cipher import DES3\nfrom Crypto.Util import Padding\n\n\ndef generate_master_secret(n1, n2):\n \"\"\" Generates a 32-byte master secret by performing an xor\n function on the client and server's nonces.abs\n\n Args:\n n1 (string) - client's nonce in hexadecimal.\n n2 (string) - server's nonce in hexadecimal.\n \n Return:\n master_secret (hex) - xor'ed shared secret.\n \"\"\"\n n1_bytes = bytes.fromhex(n1)\n n2_bytes = bytes.fromhex(n2)\n xor_bytes = []\n for b1, b2 in zip(n1_bytes, n2_bytes):\n xor_bytes.append(bytes([b1 ^ b2]))\n return (b''.join(xor_bytes)).hex()\n\n\ndef create_certificate_and_key(cert_path, key_path):\n print()\n print(\"Creating SSL certificate and key set.\")\n # If the certificate and key pair already exist, do nothing.\n if os.path.isfile(cert_path) and os.path.isfile(key_path):\n return\n\n # Generate the key pair.\n key = crypto.PKey()\n key.generate_key(crypto.TYPE_RSA, 1024)\n\n # Generate the certificate.\n certificate = crypto.X509()\n certificate.get_subject().C = \"US\"\n certificate.get_subject().ST = \"Utah\"\n certificate.get_subject().L = \"Salt Lake City\"\n certificate.get_subject().O = \"jsp\"\n certificate.get_subject().OU = \"University of Utah\"\n certificate.get_subject().CN = \"localhost\"\n certificate.gmtime_adj_notBefore(0)\n certificate.gmtime_adj_notAfter(int(math.pow(2, 32)))\n certificate.set_serial_number(10)\n certificate.set_issuer(certificate.get_subject())\n certificate.set_pubkey(key)\n certificate.sign(key, 'sha1')\n\n # Write the key pair to file.\n with open(key_path, 'wb') as f:\n f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))\n \n # Write the certificate to file.\n with open(cert_path, 'wb') as f:\n f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, certificate))\n return\n\n\ndef read_certificate(cert_path):\n with open(cert_path, 'r') as f:\n cert = f.read()\n certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert)\n return certificate\n\n\ndef read_key(key_path):\n with open(key_path, 'r') as f:\n k = f.read()\n key = crypto.load_privatekey(crypto.FILETYPE_PEM, k)\n return key\n\n\ndef get_public_key(key_path):\n keys = read_key(key_path)\n public_key = crypto.dump_publickey(crypto.FILETYPE_PEM, keys)\n key_bytes = crypto.load_publickey(crypto.FILETYPE_PEM, public_key)\n rsa_public_key = key_bytes.to_cryptography_key()\n return rsa_public_key\n\n\ndef get_private_key(key_path):\n keys = read_key(key_path)\n private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, keys)\n key_bytes = crypto.load_privatekey(crypto.FILETYPE_PEM, private_key)\n rsa_private_key = key_bytes.to_cryptography_key()\n return rsa_private_key\n\n\ndef get_public_key_cert(cert):\n public_key = cert.get_pubkey()\n pub_key = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key)\n key_bytes = crypto.load_publickey(crypto.FILETYPE_PEM, pub_key)\n rsa_public_key = key_bytes.to_cryptography_key()\n return rsa_public_key\n\n\ndef get_padding():\n return padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)\n\n\ndef rsa_encrypt(plaintext, public_key):\n return public_key.encrypt(plaintext, get_padding())\n\n\ndef rsa_decrypt(ciphertext, private_key):\n return private_key.decrypt(ciphertext, get_padding())\n\n\ndef generate_50kbyte_file():\n \"\"\" Generate a file containing 50,000 bytes. \"\"\"\n characters = [\"a\", \"b\", \"c\", \"x\", \"y\", \"z\", \" \"]\n output_string = \"\"\n for i in range(1000):\n for j in range(49):\n output_string += r.choice(characters)\n output_string += '\\n'\n with open('test.txt', 'w') as f:\n f.write(output_string)\n\n\ndef generate_keys(K):\n print()\n print(\"Generating keys from master secret.\")\n serv_encrypt = K[0:32]\n serv_integ = K[32:]\n sha256_hasher = SHA256.new()\n sha256_hasher.update(bytes.fromhex(K))\n K = sha256_hasher.hexdigest()\n client_encrypt = K[0:32]\n client_integ = K[32:]\n print(\"S_ENC: {}\".format(serv_encrypt))\n print(\"S_INT: {}\".format(serv_integ))\n print(\"C_ENC: {}\".format(client_encrypt))\n print(\"C_INT: {}\".format(client_integ))\n print()\n keys = { 'S_ENC' : serv_encrypt,\n 'S_INT' : serv_integ,\n 'C_ENC' : client_encrypt,\n 'C_INT' : client_integ }\n return keys\n\n\ndef generate_HMAC(key, message):\n message = message.encode('utf-8')\n h = HMAC.new(bytes.fromhex(key), digestmod=SHA256)\n h.update(message)\n return h.hexdigest()\n\n\ndef encrypt_plaintext(key, plaintext):\n \"\"\" Encrypts plaintext with the given key.\n\n Args:\n key (hex): DES3 key.\n plaintext (hex): unpadded plaintext.\n\n Return:\n ciphertext (hex): padded encrypted plaintext.\n \"\"\"\n\n key = bytes.fromhex(key)\n plaintext = bytes.fromhex(plaintext)\n des3 = DES3.new(key, DES3.MODE_ECB)\n ciphertext = des3.encrypt(Padding.pad(plaintext, DES3.block_size))\n return ciphertext.hex()\n\n\ndef decrypt_plaintext(key, ciphertext):\n \"\"\" Decrypts a ciphertext with the given key.\n \n Args:\n key (hex): DES3 key.\n ciphertext (hex): padded ciphertext.\n \n Return:\n unpadded_plaintext (hex): decrypted plaintext.\n \"\"\"\n\n key = bytes.fromhex(key)\n ciphertext = bytes.fromhex(ciphertext)\n des3 = DES3.new(key, DES3.MODE_ECB)\n plaintext = des3.decrypt(ciphertext)\n unpadded_plaintext = Padding.unpad(plaintext, DES3.block_size)\n return unpadded_plaintext.hex()\n\n\ndef generate_SSL_data_record(enc_key, int_key, msg, seq):\n record = \"\"\n header = \"application_data \"\n header += \"23 \"\n header += \"10k\"\n msg = msg.encode('utf-8').hex()\n HMAC = generate_HMAC(int_key, str(seq) + header + msg)\n cipher = encrypt_plaintext(enc_key, msg + HMAC)\n return header, cipher, HMAC\n\n\ndef diff(data):\n expected_data = read('test.txt')\n if expected_data != data:\n raise Exception(\"Diff of received data fails with original file.\")\n print()\n print(\"-----------------------------------------------\")\n print(\"DATA TRANSFER COMPLETE.\")\n print(\"-----------------------------------------------\")\n print()\n print(\"Full message received from server.\")\n print(\"Performing diff on message . . . \")\n print()\n print(\"Diff of file is correct.\")\n\n\ndef read(path):\n result = \"\"\n with open(path, 'r') as f:\n for line in f:\n result += line\n return result","sub_path":"security/PA4/failed_hash/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205304132","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 20 11:27:39 2019\r\n\r\n@author: navee\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\ndataset=pd.read_csv('Diabetes.csv')\r\nf=dataset.iloc[:,:-1].values\r\nf = pd.DataFrame(f)\r\nr=dataset.iloc[:,8].values\r\nr = pd.DataFrame(r)\r\nfrom sklearn.preprocessing import LabelEncoder\r\nlabelencoder=LabelEncoder()\r\nr.values[:,0]=labelencoder.fit_transform(r.values[:,0])\r\nfrom sklearn.cross_validation import train_test_split\r\nftrain,ftest,rtrain,rtest=train_test_split(f,r,test_size=0.2,random_state=1)\r\nfrom sklearn.preprocessing import StandardScaler\r\nscf=StandardScaler()\r\nftrain=scf.fit_transform(ftrain)\r\nftest=scf.transform(ftest)\r\nrtest=rtest.astype('int')\r\nftest=ftest.astype('int')\r\nftrain=ftrain.astype('int')\r\nrtrain=rtrain.astype('int')\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nclassifier=DecisionTreeClassifier(criterion='entropy',random_state=0)\r\nclassifier.fit(ftrain,rtrain)\r\nrpred=classifier.predict(ftest)\r\nfrom sklearn.metrics import confusion_matrix\r\nRusult=confusion_matrix(rtest,rpred)","sub_path":"DTC.py","file_name":"DTC.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432227392","text":"import json\n\nfrom rest_framework import permissions, viewsets, mixins\nfrom rest_framework.response import Response\nfrom utils.stringvalidator import ServiceError, isEmpty\nfrom authentication.permissions import IsLogin\nfrom wordsstatistics.models import WordsStatistics\nfrom words.models import Words\nfrom wordsstatistics.serializers import WordsStatisticsSerializer, WrongsStatisticsSerializer, RightStatisticsSerializer, NotTouchStatisticsSerializer ,StatisticsSerializer\nfrom utils.utils import access_token\n\nclass WordsStatisticsViewSet(mixins.ListModelMixin,\n\t\t\t\t\t\t\t\tmixins.CreateModelMixin,\n\t\t \t\t\tviewsets.GenericViewSet):\n\tqueryset = WordsStatistics.objects.all()\n\tserializer_class = WordsStatisticsSerializer\n\tpermission_classes = (IsLogin,)\n\n\tdef list(self, request):\n\t\tif not request.GET.get('wordlib', None) or not request.GET.get('type', None):\n\t\t\traise ServiceError(code=u'获取失败', detail=u'请求参数不正确')\n\t\telse: \n\t\t\taccount = access_token(request)\n\t\t\twordlib = request.GET.get('wordlib')\n\t\t\ttype = request.GET.get('type')\n\t\t\ttry:\n\t\t\t\tif (type=='0'):\n\t\t\t\t\treturn Response( StatisticsSerializer(WordsStatistics.objects.get(account=account.user, wordlib=wordlib)).data )\n\t\t\t\telif (type=='100'):\n\t\t\t\t\treturn Response( WrongsStatisticsSerializer(WordsStatistics.objects.get(account=account.user, wordlib=wordlib)).data )\n\t\t\t\telif(type=='200'):\n\t\t\t\t\treturn Response( RightStatisticsSerializer(WordsStatistics.objects.get(account=account.user, wordlib=wordlib)).data )\n\t\t\t\telif(type=='300'):\n\t\t\t\t\treturn Response( NotTouchStatisticsSerializer(WordsStatistics.objects.get(account=account.user, wordlib=wordlib)).data)\n\t\t\t\telse:\n\t\t\t\t\traise ServiceError(code=u'获取失败', detail=u'请求参数不正确')\n\t\t\texcept WordsStatistics.DoesNotExist:\n\t\t\t\treturn Response({})\n\tdef create(self, request):\n\t\tregister = json.loads(request.body.decode())\n\t\tfields = ['wordlib', 'right', 'wrong']\n\t\tif isEmpty(register, fields):\n\t\t\traise ServiceError(code=u'统计失败', detail=u'所发送统计数据不全')\n\t\telse:\n\t\t\taccount = access_token(request)\n\t\t\twordlib = register['wordlib']\n\t\t\tright = register['right']\n\t\t\twrong = register['wrong']\n\n\t\t\tif WordsStatistics.objects.get_or_create(account=account.user, wordlib=wordlib):\n\t\t\t\tpass\n\t\t\tstatistics = WordsStatistics.objects.get(account=account.user, wordlib=wordlib)\n\t\t\tif not statistics.statisticslist:\n\t\t\t\twordlist={}\n\t\t\telse:\n\t\t\t\twordlist = json.loads(statistics.statisticslist)\n\t\t\tstatistics.statisticslist = countStatistics(right, wrong, wordlist)\n\t\t\tstatistics.user = account.user\n\t\t\tstatistics.save()\n\t\t\treturn Response({'statistics': 'ok'})\n\ndef checkJSON(x, result):\n\tif not x in result:\n\t\tresult[x] = {\n\t\t\t\"right\": 0,\n\t\t\t\"wrong\": 0\n\t\t}\n\ndef countStatistics(right, wrong, wordlist):\n\tresult = wordlist\n\n\tfor x in right:\n\t\tword = Words.objects.get(pk=x)\n\t\tword.right += 1\n\t\tword.save()\n\t\tcheckJSON(x, result)\n\t\tresult[x][\"right\"] += 1\n\n\tfor x in wrong:\n\t\tword = Words.objects.get(pk=x)\n\t\tword.wrong += 1\n\t\tword.save()\n\t\tcheckJSON(x, result)\n\t\tresult[x][\"wrong\"] += 1\n\n\treturn json.dumps(result)\n\n","sub_path":"wordsstatistics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399037303","text":"# Cameron Pierce\n# CS 101 - Intro to Computing\n# Brickbreaker\n# Dec 12 2015\n\n'''\nNote the starting position and velocity of the ball is always the same, so it's \ndeterministic. Some randomness could be added to the ball's initial properties\nwith the random module.\n\nIdeas for future work: change the ball's speed as fewer bricks remain, change\nthe color and layout for the bricks with each iteration (i.e. add levels), add\npower-ups that might increase the size of the paddle, give an extra life, etc.\n'''\n\nfrom pyprocessing import *\nWIDTH = 600\nHEIGHT = 500\n\nclass Ball:\n '''\n A ball that bounces off obstacles, left and right walls, and \n ceiling, but passes through floor and disappears.\n '''\n def __init__(self, x, y, radius, color):\n '''\n Initializes the ball. The arguments x, y, radius, and color should be \n specified when creating an instance of type Ball, but its velocity \n given by vx and vy are assigned inside the function. Color should be \n specified as a tuple of RGBA value.\n '''\n self.x = x\n self.y = y\n self.radius = radius\n self.color = color\n \n # velocity in terms of how far ball moves per repeated call to special draw function\n self.vx = 8 # x component\n self.vy = -8 # y component\n \n def draw(self):\n '''\n Draws the ball.\n '''\n ellipseMode(CENTER) # x and y are at center of ball\n fill(self.color[0], self.color[1], self.color[2], self.color[3]) # built in function to specify color\n ellipse(self.x, self.y, self.radius*2, self.radius*2) # second two arguments give horizontal and vertical sizes, they are equal to create a circle\n \n def update(self, obstacles):\n '''\n Updates ball's position based on velocity (vx and vy). If ball is going \n to collide with wall, ceiling, or obstacle, direction is flipped to \n create a perfect bounce.\n '''\n self.x += self.vx # adjust x vector\n self.y += self.vy # adjust y vector\n \n # bounce off left or right wall and correct for the point of reference being in center of circle\n if self.x <= self.radius or self.x >= WIDTH-self.radius:\n self.vx = -self.vx\n # bounce off ceiling only\n if self.y <= self.radius:\n self.vy = -self.vy\n \n self.obs = [] # iterate over obstacles, call bounce method and the type of the obstacle determines which bounce method that runs (either Paddle and Brick), then append result to a list and use the contents of that list to change the direction of the ball\n for item in obstacles:\n self.obs += item.bounce(ball)\n \n if 't' in self.obs or 'b' in self.obs: # ball hits top or bottom of obstacle, y component of velocity flips\n self.vy = -self.vy\n if 'l' in self.obs or 'r' in self.obs: # ball hits either side of obstacle, x component of velocity flips\n self.vx = -self.vx\n \nclass Paddle:\n '''\n A paddle in which the center of the paddle moves with the mouse on screen. \n When ball comes into contact with the top of the paddle surface, it bounces \n off.\n '''\n def __init__(self, width, height, color):\n '''\n Initializes the paddle. The arguments width, height, and color should \n be specified when creating an instance of type Paddle, but its starting \n position given by x and y are assigned inside the function.\n '''\n self.width = width\n self.height = height\n self.color = color\n \n self.x = WIDTH-(self.width//2) # when update runs it effectively overwrites whatever is here\n self.y = HEIGHT-self.height # paddle at very bottom of screen\n \n def draw(self):\n '''\n Draws the paddle.\n '''\n fill(self.color[0], self.color[1], self.color[2], self.color[3])\n rect(self.x, self.y, self.width, self.height) # x and y coordinates are upper left corner of paddle, width and height are dimensions of rectangle\n \n def update(self):\n '''\n Updates paddle's position. The center of the paddle moves with the \n mouse.\n '''\n self.x = mouse.x-(self.width//2) # adjust for starting on left edge of rectangle\n \n if self.x < 0: # keep entire paddle in window\n self.x = 0\n if self.x > WIDTH-self.width:\n self.x = WIDTH-self.width\n \n def bounce(self, ball):\n '''\n Tests whether ball is in the same column as the paddle, then looks to \n see if lower edge of the ball is at or has passed the top of the paddle. \n Returns ['t'] if ball has bounced and [] otherwise.\n '''\n if self.x < ball.x+ball.radius < self.x+self.width+(ball.radius*2): # ball is inside vertical column of paddle\n if ball.y+ball.radius-ball.vy < self.y <= ball.y+ball.radius: # the bottom of the ball is at or below the top of the paddle, its old position is above the top of the paddle\n return ['t']\n else:\n return []\n else:\n return []\n \nclass Brick:\n '''\n A brick that disppears when the ball bounces off of it. \n '''\n def __init__(self, x, y, width, height, color):\n '''\n Initializes the brick. The arguments x, y, width, height, and color \n should be specified when creating an instance of type Brick, but its \n visibility given by the Boolean visible is assigned inside the function. \n '''\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.color = color\n \n self.visible = True # variable to change when ball hits brick\n \n def draw(self):\n '''\n Draws the brick, only if the ball has not already bounced off of the \n brick.\n '''\n if self.visible == True: # only drawn if not already hit by ball\n fill(self.color[0], self.color[1], self.color[2], self.color[3])\n rect(self.x, self.y, self.width, self.height) # same as with paddle\n \n def bounce(self, ball):\n '''\n Returns a list containing which side of the brick the ball bounced off \n of, which allows for the ball update method to change direction of the \n ball in response. Returns an empty list when brick has already been hit \n or when the ball occupied the same horizontal or vertical column as \n brick but made no contact. \n '''\n if self.visible == True:\n self.contact = [] # store points of contact \n if self.x < ball.x+ball.radius < self.x+self.width+(ball.radius*2): # ball is inside vertical column of brick\n if ball.y+ball.radius-ball.vy < self.y <= ball.y+ball.radius: # the bottom of the ball is at or below the top of the brick, its old position is above the top of the brick\n self.contact += ['t']\n if ball.y-ball.radius-ball.vy > self.y+self.height >= ball.y-ball.radius: # the top of the ball is at or above the bottom of the brick, its old position is below the bottom of the brick\n self.contact += ['b']\n \n if self.y < ball.y+ball.radius < self.y+self.height+(ball.radius*2): # ball is inside horizontal column of brick\n if ball.x+ball.radius-ball.vx < self.x <= ball.x+ball.radius: # the right side of the ball is at or past the left edge of the brick, its old position is to the left of the left side of the brick\n self.contact += ['l']\n if ball.x-ball.radius-ball.vx > self.x+self.width >= ball.x-ball.radius: # the left side of the ball is at or past the right edge of the brick, its old position is to the right of the right side of the brick\n self.contact += ['r']\n if self.contact != []: # if list is not empty, contact has been made, so made brick invisible\n self.visible = False\n return self.contact # always return list, even if empty, to avoid error of iterating over nonetype\n else:\n return []\n \nclass DubBrick:\n '''\n A brick that disppears when the ball bounces off of it twice. \n '''\n def __init__(self, x, y, width, height, color):\n '''\n Initializes the brick. The arguments x, y, width, height, and color \n should be specified when creating an instance of type Brick, but its \n visibility and the count variable are assigned inside the function. \n '''\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.color = color\n \n self.visible = True\n self.count = 0 # track number of times ball bounces\n \n def draw(self):\n '''\n Draws the brick, only if the brick is visible.\n '''\n if self.visible == True: # only drawn if not already hit by ball\n if self.count == 0:\n fill(self.color[0], self.color[1], self.color[2], self.color[3]) # looks regular until hit\n else:\n fill(self.color[0]//2, self.color[1]//2, self.color[2]//2, self.color[3]//2) # looks lighter after first hit\n rect(self.x, self.y, self.width, self.height) # same as with paddle\n \n def bounce(self, ball):\n '''\n Returns a list containing which side of the brick the ball bounced off \n of, which allows for the ball update method to change direction of the \n ball in response. Returns an empty list when brick is not visible or \n when the ball occupied the same horizontal or vertical column as brick \n but made no contact. \n '''\n\n if self.visible == True:\n self.contact = [] # store points of contact \n if self.x < ball.x+ball.radius < self.x+self.width+(ball.radius*2): # ball is inside vertical column of brick\n if ball.y+ball.radius-ball.vy < self.y <= ball.y+ball.radius: # the bottom of the ball is at or below the top of the brick, its old position is above the top of the brick\n self.contact += ['t']\n if ball.y-ball.radius-ball.vy > self.y+self.height >= ball.y-ball.radius: # the top of the ball is at or above the bottom of the brick, its old position is below the bottom of the brick\n self.contact += ['b']\n \n if self.y < ball.y+ball.radius < self.y+self.height+(ball.radius*2): # ball is inside horizontal column of brick\n if ball.x+ball.radius-ball.vx < self.x <= ball.x+ball.radius: # the right side of the ball is at or past the left edge of the brick, its old position is to the left of the left side of the brick\n self.contact += ['l']\n if ball.x-ball.radius-ball.vx > self.x+self.width >= ball.x-ball.radius: # the left side of the ball is at or past the right edge of the brick, its old position is to the right of the right side of the brick\n self.contact += ['r']\n if self.contact != []: # if list is not empty, contact has been made\n self.count += 1 # increase count\n if self.count == 2: # if brick has been hit twice, make it invisible\n self.visible = False\n return self.contact # always return list, even if empty, to avoid error of iterating over nonetype\n else:\n return []\n \nball = Ball(WIDTH//2-100, HEIGHT-50, 10, (178, 23, 101, 150)) # Ball instance\npaddle = Paddle(80, 15, (9, 99, 199, 150)) # Paddle instance\nobstacles = [paddle] # list to hold paddle and obstacles\ngameOn = False # boolean used for opening screen, see draw function\n\n\ndef PlayGame():\n '''\n Function that restores ball and obstacles to original positions and \n velocities so that the game can effectively be played again without closing \n the program and relaunching it.\n '''\n global obstacles\n obstacles = [paddle] # redundant at first, but allows game to reset when this function is called\n ball.x = WIDTH//2-100 # also redundant at first\n ball.vx = 8\n ball.y = HEIGHT-50\n ball.vy = -8\n paddle.width = 80\n for i in range(14): # create bricks and append to obstacles list\n for j in range(5):\n if j == 3 or j == 1:\n brick = DubBrick(i*40+20, j*15+100, 40, 15, (100, 100, 100, 255))\n else:\n brick = Brick(i*40+20, j*15+100, 40, 15, (150*(.15*i), 100, 50, 150))\n obstacles.append(brick)\n \ndef setup():\n '''\n Function known to pyprocessing. Called once at start of program. Use to \n initialize window and bricks.\n '''\n size(WIDTH, HEIGHT) # window size\n # noStroke() # turn off shape outlines\n\ndef draw():\n '''\n Another function known to pyprocessing that is called repeatedly so it \n allows for our ball to have some velocity, given by the rate of change of \n position with respect to direction specified by vectors. \n '''\n global gameOn\n global obstacles\n background(255, 255, 255) # white background\n if gameOn == False: \n textSize(14)\n fill(0, 0, 0, 255)\n text(\"Welcome to brickbreaker! Press 'g' to begin a new game\", 75, 200)\n else:\n if ball.y >= HEIGHT+ball.radius:\n textSize(14)\n fill(0, 0, 0, 255)\n text(\"The ball left the playing area. Press 'g' to restart.\", 120, 75)\n paddle.update() # update paddle according to mouse position\n for obs in obstacles: # iterate over the list of obstacles\n obs.draw() # draw each of them\n ball.update(obstacles) # move ball with respect to obstacles\n ball.draw() # redraw ball after movement\n gameWon = True\n for brick in obstacles[1:]: # check each brick\n if brick.visible == True: # if any are visible, game is not over\n gameWon = False\n if gameWon == True: # if game is over, show message\n paddle.width = WIDTH\n textSize(14)\n fill(0, 0, 0, 255)\n text(\"Congratulations! You won! Press 'g' to restart.\", 110, 100)\n keyPressed()\n \ndef keyPressed():\n '''\n Allows for user input to reset the game. \n '''\n if key.char == 'g':\n global gameOn\n gameOn = True\n key.char = None\n PlayGame()\n \nrun() # start processing\n","sub_path":"BrickBreaker.py","file_name":"BrickBreaker.py","file_ext":"py","file_size_in_byte":14577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136771815","text":"# pkgdata.py\n# Copyright (c) 2013-2020 Pablo Acosta-Serafini\n# See LICENSE for details\n# pylint: disable=C0111\n\n# Standard library imports\nimport os\n\n\n###\n# Global variables\n###\nVERSION_INFO = (1, 5, 12, \"final\", 0)\nSUPPORTED_INTERPS = [\"3.5\", \"3.6\", \"3.7\", \"3.8\"]\nCOPYRIGHT_START = 2013\nPKG_DESC = (\n \"Miscellaneous utility functions that can be applied in a variety of circumstances\"\n)\nPKG_LONG_DESC = (\n \"This module contains miscellaneous utility functions that can be applied in a \"\n + \"variety of circumstances; there are context managers, membership functions \"\n + \"(test if an argument is of a given type), numerical functions, string \"\n + \"functions and functions to aid in the unit testing of modules \"\n + \"\"\n + os.linesep\n + \"`Pytest`_ is the supported test runner\"\n)\nPKG_PIPELINE_ID = 3\n\n\n###\n# Functions\n###\ndef _make_version(major, minor, micro, level, serial):\n \"\"\"Generate version string from tuple (almost entirely from coveragepy).\"\"\"\n level_dict = {\"alpha\": \"a\", \"beta\": \"b\", \"candidate\": \"rc\", \"final\": \"\"}\n if level not in level_dict:\n raise RuntimeError(\"Invalid release level\")\n version = \"{0:d}.{1:d}\".format(major, minor)\n if micro:\n version += \".{0:d}\".format(micro)\n if level != \"final\":\n version += \"{0}{1:d}\".format(level_dict[level], serial)\n return version\n\n\n__version__ = _make_version(*VERSION_INFO)\n","sub_path":"pmisc/pkgdata.py","file_name":"pkgdata.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20456289","text":"#!/usr/bin/env python3\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectively.\nSee --help to see further details.\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\nCopyright 2018 Institute of Bioinformatics, JKU Linz\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport pathlib\n\nimport numpy as np\nimport torch\nfrom scipy import linalg\nfrom torch.nn.functional import adaptive_avg_pool2d\nfrom src.utils import read_config\nfrom src.Models.models import ImitateJoint\nimport matplotlib.pyplot as plt\nfrom torch.nn import functional as F\nfrom src.Models.models import ImitateJoint, ParseModelOutput\nfrom src.utils.train_utils import prepare_input_op, cosine_similarity, chamfer, beams_parser, validity, image_from_expressions, stack_from_expressions\nfrom src.utils.generators.wake_sleep_gen import WakeSleepGen\nfrom src.utils.generators.shapenet_generater import Generator\n\nclass FidGen:\n def __init__(self, images_path):\n self.images = torch.load(images_path)\n def get_test_data(self):\n while True:\n for i in range(0, 3000, 100):\n batch_images = self.images[i:i+100]\n yield batch_images\n\ndef get_nn(images1, images2):\n min_cds = []\n for i in range(len(images1)):\n repeated_i = np.repeat(images1[i:i+1], axis=0, repeats=len(images2))\n cd = chamfer(repeated_i, images2)\n min_cds.append(np.amin(cd))\n return sum(min_cds)/len(min_cds)\n\ndef get_bidir_nn(images1, images2):\n return get_nn(images1, images2) + get_nn(images2, images1)\n\n\ndef get_all_cad():\n cad_generator = Generator().test_gen(batch_size=100,\n path=\"data/cad/cad.h5\",\n if_augment=False)\n images = np.zeros((3000, 64, 64))\n for i in range(3000 // 100):\n images[i*100:i*100+100] = next(cad_generator)[-1, :, 0, :, :]\n return images[:500]\n\ndef get_all_val():\n cad_generator = Generator().val_gen(batch_size=100,\n path=\"data/cad/cad.h5\",\n if_augment=False)\n images = np.zeros((3000, 64, 64))\n for i in range(3000 // 100):\n images[i*100:i*100+100] = next(cad_generator)[-1, :, 0, :, :]\n return images[:500]\n\nif __name__ == '__main__':\n cad_images = get_all_cad()\n val_images = get_all_val()\n # random_images = torch.load(\"random_images.pt\")[:500]\n distance = get_bidir_nn(cad_images, val_images)\n print(distance)\n # distances = []\n # for i in range(39):\n # lest_images = torch.load(f\"fid_images2/{i}.pt\")[:500]\n # cad_images = get_all_cad()\n # distance = get_bidir_nn(random_images, cad_images)\n # distances.append(distance)\n # print(distance)\n # with open(\"distances.txt\", \"w\") as file:\n # for d in distances:\n # file.write(f\"{d}\\n\")\n","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380936785","text":"def pig_it(text):\n\tlst = []\n\tfor w in text.split(' '):\n\t\tif w in '!?':\n\t\t\tlst.append(w)\n\t\telse:\n\t\t\tlst.append(w[1:] + w[0] + 'ay')\n\treturn ' '.join(lst)\n\nprint(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay')\nprint(pig_it('This is my string'),'hisTay siay ymay tringsay')\nprint(pig_it('O tempora o mores !'),'Oay emporatay oay oresmay !')","sub_path":"5kyu_SimplePigLatin.py","file_name":"5kyu_SimplePigLatin.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624688672","text":"import json\nfrom time import time\nfrom random import random\nfrom flask import Flask, render_template, make_response\nimport serial\nfrom threading import Timer\nfrom time import sleep\n\napp = Flask(__name__)\nser = serial.Serial('/dev/ttyUSB0', 9600)\nvaluesA=[]\nvaluesB=[]\nvaluesC=[]\n\ndef getValues():\n global valuesA\n global valuesB\n global valuesC\n ser.write('1')\n value=ser.readline()\n if value[:1] is 'A':\n valuesA = [time() * 1000, float(value[2:])]\n sleep(2)\n ser.write('2')\n value=ser.readline()\n if value[:1] is 'B':\n valuesB = [time() * 1000, float(value[2:])]\n sleep(2)\n ser.write('3')\n value=ser.readline()\n if value[:1] is 'C':\n valuesC = [time() * 1000, float(value[2:])]\n sleep(2)\n t = Timer(10,getValues)\n t.start()\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html', data='test')\n\n@app.route('/random-data')\ndef random_data():\n # Create a PHP array and echo it as JSON\n data = [time() * 1000, random() * 100]\n response = make_response(json.dumps(data))\n response.content_type = 'application/json'\n return response\n\n@app.route('/data-a')\ndef livedatas():\n response = make_response(json.dumps(valuesA))\n response.content_type = 'application/json'\n return response\n\n@app.route('/data-b')\ndef dataB():\n responseB = make_response(json.dumps(valuesB))\n responseB.content_type = 'application/json'\n return responseB\n\n@app.route('/data-c')\ndef dataC():\n responseC = make_response(json.dumps(valuesC))\n responseC.content_type = 'application/json'\n return responseC\n\nif __name__ == '__main__':\n t = Timer(10, getValues)\n t.start()\n app.run(debug=True, host='0.0.0.0', port=5000)\n","sub_path":"flask-live-chart.py","file_name":"flask-live-chart.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"650812247","text":"import h2o\nimport os\nimport subprocess\nimport pandas as pd\nimport time\n\n\ndef get_ip_from_node_name(name):\n check_ip = subprocess.run(('getent hosts ' + name).split(' '), stdout=subprocess.PIPE)\n ip = check_ip.stdout.decode('utf-8').split(' ')[0]\n return ip\n\n\ndef setup_h2o_cluster_sge(cluster_name,\n memory=14,\n opt_dir_ssh='',\n do_not_use_sge=False,\n use_local=False):\n if use_local:\n h2o.init(max_mem_size_GB=memory)\n return\n\n if do_not_use_sge:\n current_nodes = pd.DataFrame(['node{:03d}'.format(n) for n in range(2, 13)])\n current_nodes.columns = ['node_name']\n # current_nodes = current_nodes.append(pd.DataFrame(['quark'], columns=['node_name']), ignore_index=True)\n\n else:\n temp_folder = os.getenv('TMPDIR')\n current_nodes = pd.read_csv(temp_folder + '/machines', sep=':', header=None)\n print(current_nodes)\n # current_nodes.columns = ['node_name']\n current_nodes = pd.DataFrame(current_nodes[0].unique(), columns=['node_name'])\n\n current_nodes['node_ip'] = current_nodes['node_name'].apply(get_ip_from_node_name)\n\n print(\"The following nodes were found: \")\n print(current_nodes.set_index('node_name'))\n print()\n\n h2o_location = h2o.__file__.split('h2o/__init__.py')[0] + 'h2o/backend/bin/h2o.jar'\n ip_list = ''\n print('h2o location: ' + h2o_location)\n\n for ip in current_nodes['node_ip']:\n ip_list = ip_list + ip + r'/32' + ','\n ip_list = ip_list[:-1]\n\n run_h2o_arg = \"java -Xmx\" + str(memory) + \"g -jar \" + h2o_location + \" -name \" + cluster_name \\\n + \" -network \" + ip_list\n print(\"The java call to start the server will be:\")\n print(run_h2o_arg)\n print()\n\n for ip, node in zip(current_nodes['node_ip'], current_nodes['node_name']):\n print('Creating server on node: ' + node)\n argument_ssh = \"ssh \" + ip + ' ' + run_h2o_arg\n argument_ssh = argument_ssh + r' &> '\n file_stdout = opt_dir_ssh + \"h2o_out_\" + cluster_name + '_' + node + \".txt\"\n argument_ssh = argument_ssh + file_stdout\n run = subprocess.Popen(argument_ssh, shell=True)\n print('ssh result: ' + str(run))\n time.sleep(2)\n\n print('Created h2o servers in all nodes')\n time.sleep(4)\n","sub_path":"dhfcorr/ml/setup_sge_h2o.py","file_name":"setup_sge_h2o.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270427280","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 15 21:42:00 2016\r\n\r\n@author: Clément\r\n\"\"\"\r\n\r\nfrom random import randint\r\nimport time\r\nfrom math import *\r\n\r\ndef potentiel(x,y,vitesse,ecosysteme):\r\n xp=x\r\n yp=y\r\n score=0\r\n for i in range(-vitesse,vitesse+1):\r\n for j in range (-vitesse,vitesse+1):\r\n coord=(x+i,y+j)\r\n s=0\r\n for an in ecosysteme:\r\n d=sqrt((an.x-coord[0])**2+(an.y-coord[1])**2)\r\n if d<2:\r\n if d!=0:\r\n s+=-1/d # fait baisser le score si le point testé est trop près d'autres animaux\r\n else:\r\n s+=1/d # augmente le score sinon\r\n if s>score:\r\n score=s\r\n xp=coord[0]\r\n yp=coord[1]\r\n return xp,yp\r\n\r\n\r\ndef signnourriture(x,y,d): #Fonction pour se rapprocher de la nourriture\r\n if x>map.limiteDN:\r\n if y>map.limiteHN:\r\n return -d,-d\r\n elif ymap.limiteHN:\r\n return d,-d\r\n elif ymap.limiteHN:\r\n return 0,-d\r\n elif ymap.limiteDE:\r\n if y>map.limiteHE:\r\n return -d,-d\r\n elif ymap.limiteHE:\r\n return d,-d\r\n elif ymap.limiteHE:\r\n return 0,-d\r\n elif ycH:\r\n return -d\r\n elif cCcC:\r\n return d\r\n elif cHself.limitex:\r\n self.__limiteGE=None\r\n elif e<-self.limitex:\r\n self.__limiteGE=-self.limitex\r\n else:\r\n self.__limiteGE=e\r\n\r\n @property\r\n def limiteDE(self):\r\n return self.__limiteDE\r\n\r\n @limiteDE.setter\r\n def limiteDE(self,e):\r\n if e>self.limitex:\r\n self.__limiteDE=self.limitex\r\n elif e<-self.limitex:\r\n self.__limiteDE=None\r\n else:\r\n self.__limiteDE=e\r\n\r\n @property\r\n def limiteHE(self):\r\n return self.__limiteHE\r\n\r\n @limiteHE.setter\r\n def limiteHE(self,e):\r\n if e>self.limitey:\r\n self.__limiteHE=self.limitey\r\n elif e<-self.limitey:\r\n self.__limiteHE=None\r\n else:\r\n self.__limiteHE=e\r\n\r\n @property\r\n def limiteBE(self):\r\n return self.__limiteBE\r\n\r\n @limiteBE.setter\r\n def limiteBE(self,e):\r\n if e>self.limitey:\r\n self.__limiteBE=None\r\n elif e<-self.limitey:\r\n self.__limiteBE=-self.limitey\r\n else:\r\n self.__limiteBE=e\r\n\r\n\r\n @property\r\n def limiteGN(self):\r\n return self.__limiteGN\r\n\r\n @limiteGN.setter\r\n def limiteGN(self,n):\r\n if n>self.limitex:\r\n self.__limiteGN=None\r\n elif n<-self.limitex:\r\n self.__limiteGN=-self.limitex\r\n else:\r\n self.__limiteGN=n\r\n\r\n @property\r\n def limiteDN(self):\r\n return self.__limiteDN\r\n\r\n @limiteDN.setter\r\n def limiteDN(self,n):\r\n if n>self.limitex:\r\n self.__limiteDN=self.limitex\r\n elif n<-self.limitex:\r\n self.__limiteDN=None\r\n else:\r\n self.__limiteDN=n\r\n\r\n @property\r\n def limiteHN(self):\r\n return self.__limiteHN\r\n\r\n @limiteHN.setter\r\n def limiteHN(self,n):\r\n if n>self.limitey:\r\n self.__limiteHN=self.limitey\r\n elif n<-self.limitey:\r\n self.__limiteHN=None\r\n else:\r\n self.__limiteHN=n\r\n\r\n @property\r\n def limiteBN(self):\r\n return self.__limiteBN\r\n\r\n @limiteBN.setter\r\n def limiteBN(self,n):\r\n if n>self.limitey:\r\n self.__limiteBN=None\r\n elif n<-self.limitey:\r\n self.__limiteBN=-self.limitey\r\n else:\r\n self.__limiteBN=n\r\n\r\n\r\n def position(self,x,y):\r\n if (self.limiteGE is not None) and (self.limiteDE is not None) and (self.limiteHE is not None) and (self.limiteBE is not None):\r\n if ((x >= self.limiteGE) and (x <= self.limiteDE)) and ((y >= self.limiteBE) and (y <= self.limiteHE)):\r\n return 1\r\n if (self.limiteGN is not None) and (self.limiteDN is not None) and (self.limiteHN is not None) and (self.limiteBN is not None):\r\n if ((x >= self.limiteGN) and (x <= self.limiteDN)) and ((y >= self.limiteBN) and (y <= self.limiteHN)):\r\n return 2\r\n return 0\r\n\r\n\r\n\r\n\r\n\r\nclass Animal(object):\r\n def __init__(self,abscisse,ordonnee,rapidite,cEau=30,cNourriture=30):\r\n self.x=abscisse\r\n self.y=ordonnee\r\n self.xp=abscisse # abscisse prévue, initialisée arbitrairement\r\n self.yp=ordonnee # ordonnée prévue, initialisée arbitrairement\r\n self.vitesse=rapidite\r\n self.eEau=randint(cEau//2, cEau) # état eau\r\n self.eNourriture=randint(cNourriture//2, cNourriture) # état nourriture\r\n self.maxEau=cEau\r\n self.maxNourriture=cNourriture\r\n \r\n @property\r\n def x(self):\r\n return self.__x\r\n \r\n @x.setter\r\n def x(self,abscisse):\r\n if abscisse>map.limitex:\r\n self.__x=map.limitex\r\n elif abscisse<-map.limitex:\r\n self.__x=-map.limitex\r\n else:\r\n self.__x=abscisse\r\n \r\n \r\n @property\r\n def y(self):\r\n return self.__y\r\n \r\n @y.setter\r\n def y(self,ordonnee):\r\n if ordonnee>map.limitey:\r\n self.__y=map.limitey\r\n elif ordonnee<-map.limitey:\r\n self.__y=-map.limitey\r\n else:\r\n self.__y=ordonnee\r\n \r\n @property\r\n def xp(self):\r\n return self.__xp\r\n \r\n @xp.setter\r\n def xp(self,abscisse):\r\n if abscisse>map.limitex:\r\n self.__xp=map.limitex\r\n elif abscisse<-map.limitex:\r\n self.__xp=-map.limitex\r\n else:\r\n self.__xp=abscisse\r\n \r\n @property\r\n def yp(self):\r\n return self.__yp\r\n \r\n @yp.setter\r\n def yp(self,ordonnee):\r\n if ordonnee>map.limitey:\r\n self.__yp=map.limitey\r\n elif ordonnee<-map.limitey:\r\n self.__yp=-map.limitey\r\n else:\r\n self.__yp=ordonnee\r\n \r\n def boire(self):\r\n self.eEau=self.maxEau\r\n \r\n def manger(self):\r\n self.eNourriture=self.maxNourriture\r\n \r\n def bouger(self,ecosysteme):\r\n for an in ecosysteme:\r\n if an.x!=self.x or an.y!=self.y or an.xp!=self.xp or an.yp!=self.yp or an.eEau!=self.eEau or an.eNourriture!=self.eNourriture:\r\n if self.xp==an.x and self.yp==an.y: \r\n if an.x==an.xp and an.y==an.yp: # on vérifie si l'animal dont on prend la place est à sa place finale\r\n if self.x<=an.x: # le cas d'égalité n'est normalement pas possible\r\n self.xp=self.xp-randint(0,2)\r\n if self.x>an.x:\r\n self.xp=self.xp+randint(0,2)\r\n if self.y<=an.y: # le cas d'égalité n'est normalement pas possible\r\n self.yp=self.yp-randint(0,2)\r\n if self.y>an.y:\r\n self.yp=self.yp+randint(0,2)\r\n self.bouger(ecosysteme)\r\n break\r\n else:\r\n self.x=self.xp\r\n self.y=self.yp\r\n \r\n def __str__(self):\r\n return \"%c : position (%i, %i) etat_eau %i/%i etat_nourriture %i/%i\"%(self.car(), self.x, self.y, self.eEau, self.maxEau, self.eNourriture, self.maxNourriture)\r\n \r\n\r\n def afaim(self):\r\n return self.eNourriture<=10\r\n \r\n def asoif(self):\r\n return self.eEau<=10\r\n \r\n def mort(self):\r\n return self.eEau <=0 or self.eNourriture <=0\r\n \r\nclass Herbivore(Animal):\r\n def __init__(self,abscisse,ordonnee,rapidite=4):\r\n super().__init__(abscisse,ordonnee,rapidite)\r\n \r\n def car(self):\r\n return ('H')\r\n \r\n def decider(self,ecosysH,ecosysC):\r\n self.eNourriture -= 1\r\n self.eEau-=1\r\n dHC=2*(2*map.limitex)^2\r\n #On regarde à quelle distance sont les carnivores\r\n if len(ecosysC)>0:#si il y'a au moins un carnivore, l'herbivore peut prendre la fuite \r\n xC=ecosysC[0].x\r\n yC=ecosysC[0].y\r\n for an in ecosysC:\r\n d=sqrt((an.x-self.x)**2+(an.y-self.y)**2)\r\n if d=0: # si il a plus soif que faim, il va boire\r\n self.xp = self.x + signeau(self.x,self.y,self.vitesse//2)[0] #j'ai mis self.vitesse//2 pour que si on a besoin de le faire \"courrir\", on ai juste à mettre self.vitesse, pour fuir un prédateur par exemple\r\n self.yp = self.y + signeau(self.x,self.y,self.vitesse//2)[1]\r\n else: # si il a plus faim que soif, il va manger\r\n self.xp = self.x + signnourriture(self.x,self.y,self.vitesse//2)[0]\r\n self.yp = self.y + signnourriture(self.x,self.y,self.vitesse//2)[1]\r\n if len(ecosysH)>1 and not self.afaim() and not self.asoif(): # si il a ni faim ni soif, il cherche à se rapprocher des autres herbivore\r\n self.xp,self.yp = potentiel(self.x,self.y,self.vitesse//2,ecosysH)\r\n\r\n # if coordTroupeau(ecosysH)[0]>self.x:\r\n # self.xp = self.x + self.vitesse//2\r\n # elif coordTroupeau(ecosysH)[0]self.y:\r\n # self.yp = self.y + self.vitesse//2\r\n # elif coordTroupeau(ecosysH)[1]0:#si il y'a au moins un herbivore, on cherche l'herbivore le plus proche\r\n proie=ecosysH[0]\r\n dHC=sqrt((ecosysH[0].x-self.x)**2+(ecosysH[0].y-self.y)**2)\r\n xH=ecosysH[0].x\r\n yH=ecosysH[0].y\r\n for an in ecosysH:\r\n d=sqrt((an.x-self.x)**2+(an.y-self.y)**2)\r\n if d=0: # si il a plus soif que faim, il regarde si il peut boire\r\n if map.position(self.x,self.y)==1: # si il est dans la zone ou il peut boire, il boit\r\n self.boire()\r\n print(\"J'ai bu\")\r\n else: #si il a plus faim que soif, il regarde si il peut manger\r\n if dHC<2: # si il est proche d'un herbivore, il le mange\r\n ecosys.remove(proie)\r\n self.manger()\r\n if self.afaim() or self.asoif(): # teste de nouveau si il a faim ou soif\r\n if self.eNourriture-self.eEau>=0: # si il a plus soif que faim, il va boire\r\n self.xp = self.x + signeau(self.x,self.y,self.vitesse//2)[0]\r\n self.yp = self.y + signeau(self.x,self.y,self.vitesse//2)[1]\r\n else:# si il a plus faim que soif, il va manger\r\n if dHC>4:\r\n self.xp = self.x + coordHerbivore(xH,self.x,self.vitesse//2)\r\n self.yp = self.y + coordHerbivore(yH,self.y,self.vitesse//2)\r\n else:\r\n self.xp = self.x + coordHerbivore(xH,self.x,self.vitesse)\r\n self.yp = self.y + coordHerbivore(yH,self.y,self.vitesse)\r\n if not self.afaim() and not self.asoif(): #si il n'a ni faim ni soif, il se déplace aléatoirement\r\n self.xp = self.x + randint(-self.vitesse//2, self.vitesse//2)\r\n self.yp = self.y + randint(-self.vitesse//2, self.vitesse//2)\r\n \r\n else: #il n'y a plus d'herbivore\r\n if self.asoif():\r\n if map.position(self.x,self.y)==1: # si il est dans la zone ou il peut boire, il boit\r\n self.boire()\r\n print(\"J'ai bu\")\r\n if self.asoif():\r\n self.xp = self.x + signeau(self.x,self.y,self.vitesse//2)[0]\r\n self.yp = self.y + signeau(self.x,self.y,self.vitesse//2)[1]\r\n else:\r\n self.xp = self.x + randint(-self.vitesse//2, self.vitesse//2)\r\n self.yp = self.y + randint(-self.vitesse//2, self.vitesse//2)\r\n\r\n# comme les deux types de carnivores auront des comportements assez différents, ça peut être bien d'avoir 2 classes ? \r\nclass Meute(Carnivore):\r\n def __init__(self,abscisse,ordonnee):\r\n super().__init__(abscisse,ordonnee)\r\n\r\n \r\nclass Solitaire(Carnivore):\r\n def __init__(self,abscisse,ordonnee):\r\n super().__init__(abscisse,ordonnee)\r\n \r\n \r\nclass Ecosysteme(list): #Affiche la carte, l'eau, la nourriture et les annimaux\r\n def __init__(self, nbanH, nbanC):\r\n for i in range(nbanH): #Liste avec d'abord tout les Herbivores\r\n self.append(Herbivore(randint(-map.limitex, map.limitex), randint(-map.limitey, map.limitey)))\r\n for i in range(nbanC): #La suite de la liste est composé des carnivores\r\n self.append(Carnivore(randint(-map.limitex, map.limitex), randint(-map.limitey, map.limitey)))\r\n \r\n def __str__(self):\r\n pos = {}\r\n for an in self:\r\n pos[(an.x, an.y)]=an.car()\r\n s = \"\"\r\n for j in range(map.limitey,-map.limitey-1, -1):\r\n for i in range(-map.limitex, map.limitex+1):\r\n if (i, j) in pos:\r\n s += pos[(i,j)]\r\n elif map.position(i,j)==1:\r\n s += \"~\"\r\n elif map.position(i,j)==2:\r\n s += '\"'\r\n else:\r\n s += \".\"\r\n s += \"\\n\"\r\n return s \r\n \r\n def enterrer(self):\r\n morts=[]\r\n for an in self:\r\n if an.mort():\r\n print('Enterré : '+str(an))\r\n morts.append(an)\r\n for an in morts:\r\n ecosys.remove(an)\r\n\r\n def nbAnnimaux(self):\r\n nbH = 0\r\n nbC = 0\r\n for an in self:\r\n if an.car()=='H':\r\n nbH += 1\r\n elif an.car()=='C':\r\n nbC += 1\r\n return nbH, nbC \r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n map=Terrain(30,20,(0,0),6,(0,0),12)\r\n ecosysH = []\r\n ecosysC = []\r\n nbH = 4\r\n nbC=0\r\n nbtour = 40\r\n ecosys=Ecosysteme(nbH,nbC)\r\n\r\n \r\n for t in range(nbtour):\r\n ecosysH = []\r\n ecosysC = []\r\n nbH, nbC = ecosys.nbAnnimaux()\r\n for i in range(nbH): #Liste avec que les Herbivores\r\n ecosysH.append(ecosys[i])\r\n for i in range(nbH,nbC+nbH): #Liste avec que les carnivores\r\n ecosysC.append(ecosys[i])\r\n \r\n print(\"### Tour %i ###\"%(t))\r\n \r\n for an in ecosysH: #On fait décider tout les Herbivores\r\n an.decider(ecosysH,ecosysC)\r\n for an in ecosysC: #On fait décider tout les Carnivores\r\n an.decider(ecosysH,ecosysC)\r\n ecosys.enterrer() #Verifie qui est mort et le supprime\r\n for an in ecosys: \r\n an.bouger(ecosys)\r\n print(an)\r\n \r\n print(ecosys)\r\n time.sleep(1)\r\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431650560","text":"#!/usr/bin/env python\n\n# Let's keep everything tested with python 2 and python 3\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport os\nimport numpy as np\n\n\n\ndef GetType(varid):\n size = varid.Sizeof()\n kind = varid.Type()\n\n # I'm just handling the common ones for now\n if kind.find('int') != -1:\n if size == 8:\n UserType = np.int64\n elif size == 4:\n UserType = np.int32\n elif size == 2:\n UserType = np.int16\n elif kind.find('double') != -1:\n UserType = np.float64\n elif (kind.find('float') != -1) or (kind.find('single') != -1):\n UserType = np.float32\n\n return UserType\n\n\ndef DotSplit(txt):\n if txt[0] == '{':\n EndIndex = '}'\n if EndIndex == -1:\n raise ValueError(\"Format for data can't be parsed correctly\")\n entry = txt[1:EndIndex]\n\n if len(txt) > EndIndex + 2:\n remaining = txt[EndIndex + 2:]\n else:\n remaining = \"\"\n\n else:\n EndIndex = txt.find('.')\n if EndIndex == -1:\n raise ValueError(\"Format for data can't be parsed correctly\")\n entry = txt[0:EndIndex]\n\n if len(txt) > EndIndex + 1:\n remaining = txt[EndIndex + 1:]\n else:\n remaining = \"\"\n\n return entry, remaining\n\n\ndef Namelist(*args):\n groups = []\n for arg in args:\n groups += [\"&{0}{2}{1}{2}/\\n\".format(arg[0], arg[1], '\\n\\n')]\n outstr = \"\\n\".join(groups)\n return outstr\n\n\ndef NMLFile(name, mainpath, outstr, codename=None, appname=None, launchmode=None):\n if launchmode == \"default\":\n outdir = os.path.join(mainpath, codename)\n else:\n outdir = mainpath\n\n if appname is None:\n outname = os.path.join(outdir, \".{0}.nml\".format(name))\n else:\n outname = os.path.join(outdir, \".{0}-{1}.nml\".format(name, appname))\n with open(outname, 'w') as out:\n out.write(outstr)\n\n","sub_path":"util/kittie_common.py","file_name":"kittie_common.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507400599","text":"#!/usr/bin/env python3\nimport argparse\nimport json\nimport os\nfrom time import time\n\nimport torch\n\nfrom models import *\nfrom loader import DataLoader\n\n\ndef main():\n torch.manual_seed(42)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('path', type=os.path.abspath)\n parser.add_argument('--dataset', default=\"div2k\", type=str)\n parser.add_argument('--transform', default=None, type=str)\n parser.add_argument('--gpu', default=0, type=int)\n\n args = parser.parse_args()\n\n torch.cuda.set_device(args.gpu)\n\n validation = DataLoader(os.path.join(\"data\", args.dataset, \"val\"), shuffle=False, num_workers=0)\n model = SteganoGAN.load(path=args.path)\n metrics = {field: list() for field in METRIC_FIELDS}\n model._validate(validation, metrics, transform=args.transform)\n metrics = {k: torch.tensor(v).mean().item() for k, v in metrics.items()}\n print(metrics)\n\nif __name__ == '__main__':\n main()\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276520225","text":"from .test import BaseTest\n\nclass Test_Cors(BaseTest):\n label = 'Cross Origin Headers'\n level = 1\n category = 7\n versions = [u'1.0', u'1.1', u'2.0']\n validationInfo = None\n\n def run(self, result):\n info = result.get_info();\n cors = result.last_headers.get('access-control-allow-origin', '')\n self.validationInfo.check('CORS', cors, '*', result)\n return result","sub_path":"implementations/validator/iiif_validator/tests/cors.py","file_name":"cors.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230800092","text":"# Time Complexity: O(N*M)\n# Space Complexity: O(N)\n# Leetcode all test cases passed: Yes\n# Any Difficulties: No\n\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n \n if not matrix:\n return None\n \n result = []\n \n startRow = 0\n startCol = 0\n endRow = len(matrix)\n endCol = len(matrix[0])\n \n while startRow < endRow and startCol < endCol:\n \n for i in range(startCol, endCol):\n result.append(matrix[startRow][i])\n \n for i in range(startRow+1, endRow-1):\n result.append(matrix[i][endCol-1])\n \n if startRow != endRow - 1:\n for i in range(endCol-1,startCol-1,-1):\n result.append(matrix[endRow-1][i])\n \n if startCol != endCol - 1:\n for i in range(endRow-2,startRow,-1):\n result.append(matrix[i][startRow])\n \n startRow += 1\n startCol += 1\n endRow -= 1\n endCol -= 1\n return result\n","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"326668041","text":"import json\nimport os\nimport glob\nimport shutil\nimport re\nimport datetime\nimport hashlib\n\nfrom parsers.base_log_parser import get_version_num\nfrom parsers.math_parser import MathSessionLogParser\n\n\nfrom loggers import log, logger\n\nDATA_ROOT='/Volumes/rhino_mount/data/eeg'\nDB_ROOT='/Volumes/db_root/'\n\nclass UnTransferrableException(Exception):\n pass\n\nclass Transferer(object):\n\n CURRENT_NAME = 'current_source'\n INDEX_NAME='index.json'\n\n\n def __init__(self, json_file, groups, destination, **kwargs):\n self.groups = groups\n self.destination_root = os.path.abspath(destination)\n self.destination_current = os.path.join(self.destination_root, self.CURRENT_NAME)\n self.label = datetime.datetime.now().strftime('%y%m%d.%H%M%S')\n log('Transferer {} created'.format(self.label))\n self.kwargs = kwargs\n self.transferred_files = {}\n self.transfer_dict = self.load_groups(json.load(open(json_file)), groups)\n self.old_symlink = None\n self.transfer_aborted = False\n self.previous_label = self.get_current_target()\n self._should_transfer = True\n\n def get_label(self):\n if self.transfer_aborted:\n return self.previous_label\n else:\n return self.label\n\n def build_transferred_index(self):\n md5_dict = {}\n destination_labeled = os.path.join(self.destination_root, self.label)\n for name, file in self.transferred_files.items():\n info = self.transfer_dict[name]\n if 'checksum_filename_only' in info and info['checksum_filename_only']:\n if not isinstance(file, list):\n file = [file]\n filenames_md5 = hashlib.md5()\n md5_dict[name] = {'files': []}\n for each_file in file:\n filenames_md5.update(os.path.basename(each_file))\n md5_dict[name]['files'].append(os.path.relpath(each_file, destination_labeled))\n md5_dict[name]['md5'] = filenames_md5.hexdigest()\n elif len(file) > 0:\n if not isinstance(file, list):\n file = [file]\n file_md5 = hashlib.md5()\n md5_dict[name] = {'files': []}\n for each_file in file:\n file_md5.update(open(each_file).read())\n md5_dict[name]['files'].append(os.path.relpath(each_file, destination_labeled))\n md5_dict[name]['md5'] = file_md5.hexdigest()\n\n return md5_dict\n\n def get_current_target(self):\n current = os.path.join(self.destination_current)\n if not os.path.exists(current):\n return None\n else:\n return os.path.basename(os.path.realpath(current))\n\n def load_previous_index(self):\n old_index_filename = os.path.join(self.destination_current, self.INDEX_NAME)\n if not os.path.exists(old_index_filename):\n return {}\n with open(old_index_filename, 'r') as old_index_file:\n return json.load(old_index_file)\n\n def write_index_file(self):\n index = self.build_transferred_index()\n with open(os.path.join(self.destination_current, self.INDEX_NAME), 'w') as index_file:\n json.dump(index, index_file, indent=2)\n\n @classmethod\n def load_groups(cls, full_dict, groups):\n if \"default\" in full_dict:\n out_dict = cls.load_groups(full_dict[\"default\"], groups)\n else:\n out_dict = dict()\n\n for key, value in full_dict.items():\n if not isinstance(value, dict):\n continue\n if value[\"type\"] == \"group\" and key in groups:\n out_dict.update(cls.load_groups(value, groups))\n elif value[\"type\"] != \"group\":\n out_dict[key] = value\n return out_dict\n\n def get_destination_path(self, info):\n if info['multiple']:\n destination_directory = info['destination']\n else:\n destination_directory = os.path.dirname(info['destination'])\n\n destination_path = os.path.join(self.destination_root, self.label, destination_directory)\n return destination_path\n\n @classmethod\n def get_origin_files(cls, info, **kwargs):\n try:\n origin_directory = info['origin_directory'].format(**kwargs)\n except:\n if info['required']:\n raise\n else:\n return []\n\n if info['type'] == 'link':\n origin_directory = os.path.relpath(os.path.realpath(origin_directory))\n\n origin_file_entry = info['origin_file']\n\n if not isinstance(origin_file_entry, list):\n origin_file_entry = [origin_file_entry]\n\n origin_files = []\n\n for origin_file in origin_file_entry:\n origin_filename = origin_file.format(**kwargs)\n origin_path = os.path.join(origin_directory, origin_filename)\n\n origin_files += glob.glob(origin_path)\n\n return origin_files\n\n def missing_required_files(self):\n for name, info in self.transfer_dict.items():\n origin_files = self.get_origin_files(info, **self.kwargs)\n\n if info['required'] and not origin_files:\n log(\"Could not locate file {} in {}\".format(name, info['origin_directory'].format(**self.kwargs)))\n return name\n\n if (not info['multiple']) and len(origin_files) > 1:\n log(\"multiple = {}, but {} files found\".format(info['multiple'],\n len(origin_files)))\n return name\n return False\n\n def check_checksums(self):\n old_index = self.load_previous_index()\n\n found_change = False\n for name, info in self.transfer_dict.items():\n log('Checking {}'.format(name))\n\n origin_files = self.get_origin_files(info, **self.kwargs)\n\n if info['required'] and not origin_files:\n raise UnTransferrableException(\"Could not locate file {}\".format(name))\n\n if (not info['multiple']) and len(origin_files) > 1:\n raise UnTransferrableException(\"multiple = {}, but {} files found\".format(info['multiple'],\n len(origin_files)))\n\n if not origin_files:\n continue\n\n if not name in old_index:\n log('Found new file: {}'.format(name))\n found_change = True\n break\n\n this_md5 = hashlib.md5()\n for origin_file in origin_files:\n if 'checksum_filename_only' in info and info['checksum_filename_only']:\n this_md5.update(os.path.basename(origin_file))\n else:\n this_md5.update(open(origin_file).read())\n\n if not old_index[name]['md5'] == this_md5.hexdigest():\n found_change = True\n log('Found differing file: {}'.format(name))\n break\n\n self._should_transfer = found_change\n return found_change\n\n def get_files_to_transfer(self):\n\n transferrable_files = []\n\n for name, info in self.transfer_dict.items():\n log('Checking {}'.format(name))\n\n origin_files = self.get_origin_files(info, **self.kwargs)\n\n if info['required'] and not origin_files:\n raise UnTransferrableException(\"Could not locate file {}\".format(name))\n\n if (not info['multiple']) and len(origin_files) > 1:\n raise UnTransferrableException(\"multiple = {}, but {} files found\".format(info['multiple'],\n len(origin_files)))\n\n if not origin_files:\n continue\n\n transferrable_files.append({'name': name,\n 'info': info,\n 'files': origin_files,\n 'directory': info['origin_directory'].format(**self.kwargs)})\n\n return transferrable_files\n\n def _transfer_files(self):\n if not os.path.exists(self.destination_root):\n os.makedirs(self.destination_root)\n\n log('Transferring into {}'.format(self.destination_root))\n\n file_dicts = self.get_files_to_transfer()\n if not file_dicts:\n log('No files to transfer.')\n self.transfer_aborted = True\n return None\n\n for file_dict in file_dicts:\n name = file_dict['name']\n info = file_dict['info']\n origin_files = file_dict['files']\n\n log('Transferring {}'.format(name))\n\n destination_path = self.get_destination_path(info)\n if not os.path.exists(destination_path):\n os.makedirs(destination_path)\n\n this_files_transferred = []\n\n for origin_file in origin_files:\n if info['multiple']:\n destination_file_path = origin_file.replace(file_dict['directory'], '')\n while destination_file_path[0] == '/':\n destination_file_path = destination_file_path[1:]\n destination_file = os.path.join(destination_path, destination_file_path)\n else:\n destination_file = os.path.join(self.destination_root, self.label, info['destination'])\n\n if info['type'] == 'file':\n if not os.path.exists(os.path.dirname(destination_file)):\n os.makedirs(os.path.dirname(destination_file))\n shutil.copyfile(origin_file, destination_file)\n log('Copied file {} to {}'.format(origin_file, destination_file))\n elif info['type'] == 'directory':\n shutil.copytree(origin_file, destination_file)\n log('Copied directory {} to {}'.format(origin_file, destination_file))\n elif info['type'] == 'link':\n if os.path.islink(destination_file):\n log('Removing link %s' % destination_file, 'WARNING')\n os.unlink(destination_file)\n link = os.path.relpath(origin_file, destination_path)\n os.symlink(link, destination_file)\n log('Linking {} to {}'.format(link, destination_file))\n else:\n raise UnTransferrableException(\"Type {} not known.\"+\\\n \"Must be 'file' or 'directory'\".format(info['type']))\n this_files_transferred.append(destination_file)\n\n self.transferred_files[name] = this_files_transferred if len(this_files_transferred) != 1 else \\\n this_files_transferred[0]\n\n\n if os.path.islink(self.destination_current):\n self.old_symlink = os.path.relpath(os.path.realpath(self.destination_current), self.destination_root)\n os.unlink(self.destination_current)\n os.symlink(self.label, self.destination_current)\n\n self.write_index_file()\n\n return self.transferred_files\n\n def transfer_with_rollback(self):\n try:\n return self._transfer_files()\n except Exception as e:\n log('Exception encountered: %s' % e.message)\n\n self.remove_transferred_files()\n raise\n\n def remove_transferred_files(self):\n new_transferred_files = {k:v for k,v in self.transferred_files.items()}\n for file in self.transferred_files:\n log('Removing Entry : {} '.format(file))\n info = self.transfer_dict[file]\n destination_path = self.get_destination_path(info)\n\n origin_file_entry = info['origin_file']\n if not isinstance(origin_file_entry, list):\n origin_file_entry = [origin_file_entry]\n\n for origin_file in origin_file_entry:\n if info['multiple']:\n destination_files = glob.glob(os.path.join(destination_path, origin_file.format(**self.kwargs)))\n for destination_file in destination_files:\n if info['type'] == 'file':\n log('removing %s' % destination_file)\n os.remove(destination_file)\n elif info['type'] == 'directory':\n log('removing %s' % destination_file)\n shutil.rmtree(destination_file)\n else:\n destination_file = os.path.join(self.destination_root, self.label, info['destination'])\n log('removing %s' % destination_file)\n if info['type'] == 'link':\n os.unlink(destination_file)\n else:\n os.remove(destination_file)\n\n\n del new_transferred_files[file]\n self.transferred_files = new_transferred_files\n\n index_file = os.path.join(self.destination_current, self.INDEX_NAME)\n if os.path.exists(index_file):\n os.remove(index_file)\n\n\n self.delete_if_empty(self.destination_root)\n if os.path.islink(self.destination_current):\n log('removing symlink: %s' % self.destination_current)\n os.unlink(self.destination_current)\n if self.old_symlink:\n os.symlink(self.old_symlink, self.destination_current)\n else:\n log('Could not find symlink %s' % self.destination_current)\n\n\n @classmethod\n def delete_if_empty(cls, path):\n try:\n for (subpath, _, _) in os.walk(path):\n if subpath == path:\n continue\n cls.delete_if_empty(subpath)\n os.rmdir(path)\n except Exception as e:\n pass\n #print 'Couldn\\'t remove {}: {}'.format(path, e)\n\n\n\ndef find_sync_file(subject, experiment, session):\n subject_dir = os.path.join(DATA_ROOT, subject)\n # Look in raw folder first\n raw_sess_dir = os.path.join(subject_dir, 'raw', '{exp}_{sess}'.format(exp=experiment, sess=session))\n sync_files = glob.glob(os.path.join(raw_sess_dir, '*.sync'))\n if len(sync_files) == 1:\n return raw_sess_dir, sync_files[0]\n # Now look in eeg.noreref\n noreref_dir = os.path.join(subject_dir, 'eeg.noreref')\n sync_pattern = os.path.join(noreref_dir, '*.{exp}_{sess}.sync.txt'.format(exp=experiment, sess=session))\n sync_files = glob.glob(sync_pattern)\n if len(sync_files) == 1:\n return noreref_dir, sync_files[0]\n else:\n raise UnTransferrableException(\"{} sync files found at {}, expected 1\".format(len(sync_files), sync_pattern))\n\n\ndef generate_ephys_transferer(subject, experiment, session, protocol='r1', groups=tuple(),\n code=None, original_session=None, new_experiment=None, **kwargs):\n json_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ephys_inputs.json')\n if new_experiment is None:\n new_experiment = experiment\n destination = os.path.join(DB_ROOT,\n 'protocols', protocol,\n 'subjects', subject,\n 'experiments', new_experiment,\n 'sessions', str(session),\n 'ephys')\n code = code or subject\n original_session = original_session if not original_session is None else session\n\n\n return Transferer(json_file, (experiment,) + groups, destination,\n protocol=protocol,\n subject=code, experiment=experiment, new_experiment=new_experiment, session=original_session,\n data_root=DATA_ROOT, db_root=DB_ROOT, code=code, original_session=original_session, **kwargs)\n\n\n\ndef generate_session_transferer(subject, experiment, session, protocol='r1', groups=tuple(), code=None,\n original_session=None, new_experiment=None, **kwargs):\n groups = groups+(re.sub('\\d', '', experiment),)\n json_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'behavioral_inputs.json')\n source_files = Transferer.load_groups(json.load(open(json_file)), groups)\n\n code = code or subject\n original_session = original_session if not original_session is None else session\n\n kwarg_inputs = dict(protocol=protocol,\n experiment=experiment, session=session,\n code=code, original_session=original_session,\n data_root=DATA_ROOT, db_root=DB_ROOT, **kwargs)\n\n try:\n session_log = Transferer.get_origin_files(source_files['session_log'], **kwarg_inputs)[0]\n if experiment != 'PS':\n is_sys2 = get_version_num(session_log) >= 2\n else:\n is_sys2 = False\n except KeyError:\n log('Could not find session log!','WARNING')\n is_sys2 = True\n\n\n\n kwarg_inputs['subject'] = subject\n if is_sys2:\n groups += ('system_2', )\n else:\n groups += ('system_1', )\n kwarg_inputs['sync_folder'], kwarg_inputs['sync_filename'] = find_sync_file(code, experiment, original_session)\n\n if not new_experiment:\n new_experiment = experiment\n\n destination = os.path.join(DB_ROOT,\n 'protocols', protocol,\n 'subjects', subject,\n 'experiments', new_experiment,\n 'sessions', str(session),\n 'behavioral')\n\n transferer= Transferer(json_file, (experiment,) + groups, destination, new_experiment=new_experiment,**kwarg_inputs)\n return transferer, groups\n\n\n\n\nclass TransferPipeline(object):\n\n CURRENT_PROCESSED_DIRNAME = 'current_processed'\n\n def __init__(self, transferer, *pipeline_tasks):\n self.transferer = transferer\n self.pipeline_tasks = pipeline_tasks\n self.exports = {}\n self.destination_root = self.transferer.destination_root\n self.destination = os.path.join(self.destination_root, self.processed_label)\n self.current_dir = os.path.join(self.destination_root, self.CURRENT_PROCESSED_DIRNAME)\n if not os.path.exists(self.destination):\n os.makedirs(self.destination)\n for task in self.pipeline_tasks:\n task.set_pipeline(self)\n self.log_filenames = [\n os.path.join(self.destination_root, 'log.txt'),\n os.path.join(self.destination, 'log.txt')\n ]\n\n\n @property\n def source_label(self):\n return self.transferer.get_label()\n\n @property\n def processed_label(self):\n return '{}_processed'.format(self.transferer.get_label())\n\n def start_logging(self):\n try:\n logger.add_log_files(*self.log_filenames)\n except:\n log('Could not set logging path.')\n\n def stop_logging(self):\n logger.remove_log_files(*self.log_filenames)\n\n def run(self, force=False):\n logger.set_label('Transfer initialization')\n self.start_logging()\n\n log('Transfer pipeline to {} started'.format(self.destination_root))\n missing_files = self.transferer.missing_required_files()\n if missing_files:\n log(\"Missing file {}. Deleting processed folder {}\".format(missing_files, self.destination), 'CRITICAL')\n self.stop_logging()\n shutil.rmtree(self.destination)\n raise UnTransferrableException('Missing file {}'.format(missing_files))\n\n should_transfer = self.transferer.check_checksums()\n if should_transfer != True:\n log('No changes to transfer...')\n if not os.path.exists(self.current_dir):\n log('{} does not exist! Continuing anyway!'.format(self.current_dir))\n else:\n self.transferer.transfer_aborted = True\n if not force:\n log('Removing processed folder {}'.format(self.destination))\n log('Transfer pipeline ended without transfer')\n self.stop_logging()\n shutil.rmtree(self.destination)\n return\n else:\n log('Forcing transfer to happen anyway')\n\n logger.set_label('Transfer in progress')\n transferred_files = self.transferer.transfer_with_rollback()\n pipeline_task = None\n try:\n for i, pipeline_task in enumerate(self.pipeline_tasks):\n\n log('Executing task {}: {}'.format(i+1, pipeline_task.name))\n pipeline_task.run(transferred_files, self.destination)\n log('Task {} finished successfully'.format(pipeline_task.name))\n\n if os.path.islink(self.current_dir):\n os.unlink(self.current_dir)\n os.symlink(self.processed_label, self.current_dir)\n\n except Exception as e:\n log('Task {} failed!!\\nRolling back transfer'.format(pipeline_task.name if pipeline_task else\n 'initialization'), 'CRITICAL')\n\n\n self.transferer.remove_transferred_files()\n log('Transfer pipeline errored: {}'.format(e.message), 'CRITICAL')\n log('Removing processed folder {}'.format(self.destination), 'CRITICAL')\n self.stop_logging()\n if os.path.exists(self.destination):\n shutil.rmtree(self.destination)\n raise\n\n log('Transfer pipeline ended normally')\n self.stop_logging()\n\n\ndef xtest_load_groups():\n from pprint import pprint\n transferer = Transferer('./behavioral_inputs.json', ('system_2', \"TH\"))\n pprint(transferer.transfer_dict)\n\ndef xtest_transfer_files():\n transferer = Transferer('./behavioral_inputs.json', ('system_2'), '../tests/test_output/test_transfer',\n data_root='../tests/test_data',\n db_root=DB_ROOT,\n subject='R1124J_1',\n experiment='FR3',\n session=1)\n transferer.transfer_with_rollback()\n\n","sub_path":"submission/transferer.py","file_name":"transferer.py","file_ext":"py","file_size_in_byte":22348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"443746964","text":"# Выведите строки, содержащие обратный слеш \"\\\".\nimport re\nimport sys\n\n\nfor string in sys.stdin:\n string = string.rstrip()\n pattern = r'\\b(\\w+)\\1\\b'\n if re.search(pattern, string):\n print(string)\n#'\\b(\\w+)\\1\\b' -- \\1 указывает на первую группу соответствующих символов\n# 1 потому что одна группа, которую образуют круглые скобки ","sub_path":"2_17_re_strings_with_double_word.py","file_name":"2_17_re_strings_with_double_word.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605313168","text":"from collections import Counter\ndef first_unique_char(string):\n dic = {}\n for s in string:\n if s not in dic:\n dic[s] = 1\n else:\n dic[s] += 1\n for key,value in enumerate(string):\n if dic[value] == 1:\n return key\n return -1\n\ndef first_unique_char_2(string):\n s = Counter(string)\n for key,value in enumerate(s):\n if s[value] == 1:\n return key\n return -1\n\ndef first_unique_char_3(string):\n letters = 'abcdefghijklmnopqrstuvwxyz'\n index = [s.index(l) for l in letters if s.count(l) == 1]\n return min(index) if len(index) > 0 else -1\n","sub_path":"strings/unique_character_387.py","file_name":"unique_character_387.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"200079389","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom unittest import TestCase\n\nfrom tests.utils import assert_equal_layers\n\nfrom polyaxon_schemas.ml.initializations import (\n GlorotNormalInitializerConfig,\n OrthogonalInitializerConfig,\n ZerosInitializerConfig\n)\nfrom polyaxon_schemas.ml.layers.convolutional_recurrent import (\n ConvLSTM2DConfig,\n ConvRecurrent2DConfig\n)\n\n\nclass TestConvolutionalRecurrentConfigs(TestCase):\n def test_conv_recurrent_2d_config(self):\n config_dict = {\n 'filters': 20,\n 'kernel_size': 3,\n 'strides': [1, 1],\n 'padding': 'valid',\n 'data_format': None,\n 'dilation_rate': [1, 1],\n 'return_sequences': False,\n 'go_backwards': False,\n 'stateful': False\n }\n config = ConvRecurrent2DConfig.from_dict(config_dict)\n assert_equal_layers(config, config_dict)\n\n def test_conv_lstm_2d_config(self):\n config_dict = {\n 'filters': 20,\n 'kernel_size': 3,\n 'strides': [1, 1],\n 'padding': 'valid',\n 'data_format': None,\n 'dilation_rate': [1, 1],\n 'activation': 'tanh',\n 'recurrent_activation': 'hard_sigmoid',\n 'use_bias': True,\n 'kernel_initializer': GlorotNormalInitializerConfig().to_schema(),\n 'recurrent_initializer': OrthogonalInitializerConfig().to_schema(),\n 'bias_initializer': ZerosInitializerConfig().to_schema(),\n 'unit_forget_bias': True,\n 'kernel_regularizer': None,\n 'recurrent_regularizer': None,\n 'bias_regularizer': None,\n 'activity_regularizer': None,\n 'kernel_constraint': None,\n 'recurrent_constraint': None,\n 'bias_constraint': None,\n 'return_sequences': False,\n 'go_backwards': False,\n 'stateful': False,\n 'dropout': 0.,\n 'recurrent_dropout': 0.\n }\n config = ConvLSTM2DConfig.from_dict(config_dict)\n assert_equal_layers(config, config_dict)\n","sub_path":"tests/test_ml/test_layers/test_convolutional_reccurrent.py","file_name":"test_convolutional_reccurrent.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468809617","text":"\nimport os\nfrom argparse import ArgumentParser\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom matplotlib import pyplot as plt\nimport attention as att\nfrom tensorflow.keras.layers.experimental.preprocessing import Rescaling\nfrom tensorflow.keras.layers import (\n Dense,\n Dropout\n)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0, 1, 2\"\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--logdir\", default=\"logs\")\n parser.add_argument(\"--image-size\", default=32, type=int)\n # parser.add_argument(\"--image-size\", default=28, type=int)\n parser.add_argument(\"--patch-size\", default=4, type=int)\n parser.add_argument(\"--num-layers\", default=4, type=int)\n parser.add_argument(\"--d-model\", default=64, type=int)\n parser.add_argument(\"--num-heads\", default=4, type=int)\n parser.add_argument(\"--mlp-dim\", default=128, type=int)\n parser.add_argument(\"--lr\", default=3e-4, type=float)\n parser.add_argument(\"--weight-decay\", default=1e-4, type=float)\n parser.add_argument(\"--batch-size\", default=2048, type=int)\n parser.add_argument(\"--epochs\", default=5, type=int)\n args = parser.parse_args()\n\n ds = tfds.load(\"imagenet_r\", as_supervised=True)\n # ds = tfds.load(\"mnist\", as_supervised=True)\n ds_train = (\n ds[\"train\"]\n .cache()\n .shuffle(5 * args.batch_size)\n .batch(args.batch_size)\n .prefetch(AUTOTUNE)\n )\n ds_test = (\n ds[\"test\"]\n .cache()\n .batch(args.batch_size)\n .prefetch(AUTOTUNE)\n )\n\n strategy = tf.distribute.MirroredStrategy()\n\n with strategy.scope():\n model = tf.keras.models.Sequential()\n\n model.add(Rescaling(1.0 / 255))\n\n model.add(att.VisionTransformer(\n image_size=args.image_size,\n patch_size=args.patch_size,\n num_layers=args.num_layers,\n num_classes=10,\n d_model=args.d_model,\n num_heads=args.num_heads,\n mlp_dim=args.mlp_dim,\n channels=1,\n dropout=0.1,\n ))\n\n model.add(Dense(args.mlp_dim, activation=tfa.activations.gelu))\n model.add(Dropout(0.1))\n model.add(Dense(10, activation='softmax'))\n\n model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True\n ),\n optimizer=tfa.optimizers.AdamW(\n learning_rate=args.lr, weight_decay=args.weight_decay\n ),\n metrics=[\"accuracy\"],\n )\n\n history = model.fit(\n ds_train,\n validation_data=ds_test,\n epochs=args.epochs,\n callbacks=[TensorBoard(log_dir=args.logdir, profile_batch=0), ],\n\n )\n\n test = model.predict(ds_test)\n\n acc = history.history['accuracy']\n val_acc = history.history['val_accuracy']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n\n epochs = range(1, len(acc) + 1)\n\n plt.plot(epochs, acc, 'bo', label='Training acc')\n plt.plot(epochs, val_acc, 'b', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n\n plt.figure()\n\n plt.plot(epochs, loss, 'bo', label='Training loss')\n plt.plot(epochs, val_loss, 'b', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n\n plt.show()\n\n model.save_weights(os.path.join(args.logdir, \"vit\"))\n","sub_path":"pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354917084","text":"# Routines for downsampling the level 2 data to wide band chunks for continuum data analysis\n# Data will be cleaned such that it is ready to enter the destriper:\n# 1) From Statistics : Remove atmosphere and baselines \n# 2) From astrocalibration : Apply Jupiter calibration to each feed\n\nimport numpy as np\nimport h5py\nfrom astropy import wcs\nfrom matplotlib import pyplot\nfrom tqdm import tqdm\nfrom scipy import linalg as la\nimport healpy as hp\nfrom comancpipeline.Tools.median_filter import medfilt\nfrom comancpipeline.Tools import binFuncs, stats, FileTools\n\nfrom comancpipeline.Analysis import BaseClasses\nfrom comancpipeline.Analysis.FocalPlane import FocalPlane\nfrom comancpipeline.Analysis import SourceFitting\nfrom comancpipeline.Analysis import Statistics\nfrom scipy import signal\n\nimport time\nimport os\n\nimport shutil\n\nfrom tqdm import tqdm\n\n__level3_version__='v062022'\n\ndef subtract_filters(tod,az,el,filter_tod, filter_coefficients, atmos, atmos_coefficient):\n \"\"\"\n Return the TOD with median filter and atmosphere model subtracted\n \"\"\"\n tod_out = tod - filter_tod*filter_coefficients -\\\n Statistics.AtmosGroundModel(atmos,az,el)*atmos_coefficient\n tod_out -= np.nanmedian(tod_out)\n return tod_out \n\nclass CreateLevel3(BaseClasses.DataStructure):\n def __init__(self,\n level2='level2',\n level3='level3',\n database=None, \n output_obsid_starts = [0],\n output_obsid_ends = [None],\n output_dirs = ['.'],\n cal_source='taua',\n set_permissions=True,\n permissions_group='comap',\n median_filter=True,\n atmosphere=True,\n cal_database=None,\n astro_cal=True, **kwargs):\n \"\"\"\n \"\"\"\n super().__init__(**kwargs)\n self.name = 'CreateLevel3'\n\n self.output_dirs = output_dirs\n self.output_obsid_starts = output_obsid_starts\n self.output_obsid_ends = output_obsid_ends\n\n self.database = database\n self.cal_database=cal_database\n\n self.level2=level2\n self.level3=level3\n self.cal_source=cal_source\n\n self.set_permissions = set_permissions\n self.permissions_group = permissions_group\n\n self.astro_cal=astro_cal\n self.median_filter = median_filter\n self.atmosphere = atmosphere\n\n def __str__(self):\n return \"Creating Level 3\"\n\n def __call__(self,data):\n \"\"\"\n \"\"\"\n\n assert isinstance(data, h5py._hl.files.File), 'Data is not a h5py file structure'\n fname = data.filename.split('/')[-1]\n data_dir = data.filename.split(fname)[0]\n\n # obtain obsid\n obsid = int(data.filename.split('/')[-1].split('-')[1])\n # determine output directory\n self.output_dir = self.getOutputDir(obsid,\n self.output_dirs,\n self.output_obsid_starts,\n self.output_obsid_ends)\n\n self.outfile = '{}/{}_{}'.format(self.output_dir,self.level3,fname)\n\n self.logger(f' ')\n self.logger(f'{fname}:{self.name}: Starting. (overwrite = {self.overwrite})')\n\n comment = self.getComment(data)\n\n if 'Sky nod' in comment:\n return data\n\n if not self.level2 in data.keys():\n self.logger(f'{fname}:{self.name}:Error: No {self.level2} data found?')\n return data\n\n if not 'Statistics' in data[self.level2].keys():\n self.logger(f'{fname}:{self.name}:Error: No {self.level2}/Statistics found?')\n return data\n\n if not 'scan_edges' in data[f'{self.level2}/Statistics'].keys():\n self.logger(f'{fname}:{self.name}:Error: No {self.level2}/Statistics/scan_edges found?')\n return data\n\n \n\n if os.path.exists(self.outfile) & (not self.overwrite):\n self.logger(f'{fname}:{self.name}: {self.level3}_{fname} exists, ignoring (overwrite = {self.overwrite})')\n return data\n \n\n self.logger(f'{fname}:{self.name}: Creating {self.level3} data.')\n self.run(data)\n\n # Want to ensure the data file is read/write\n data = self.setReadWrite(data)\n\n self.logger(f'{fname}:{self.name}: Writing to {self.outfile}')\n self.write(data)\n self.write_database(data)\n self.logger(f'{fname}:{self.name}: Done.')\n\n return data\n\n def create_simulation(self,data):\n \"\"\"\n \"\"\"\n\n self.all_tod = data['level2/averaged_tod'][...]\n self.all_tod = np.reshape(self.all_tod, (self.all_tod.shape[0],\n self.all_tod.shape[1]*self.all_tod.shape[2],\n self.all_tod.shape[3]))\n N = int(self.all_tod.shape[-1]//2*2)\n rms = np.nanstd(self.all_tod[:,:,:N:2] - self.all_tod[:,:,1:N:2],axis=-1)/np.sqrt(2)\n rms = rms[...,None]*np.ones(self.all_tod.shape[-1])[None,None,:]\n self.all_weights = 1./rms**2\n self.cal_factors = self.all_tod*0.+1\n self.all_frequency = data['level2/frequency'][...].flatten()\n\n\n def get_cal_gains(self,this_obsid):\n \"\"\"\n Get all of the gain factors associated with this calibration source\n \"\"\"\n\n db = FileTools.safe_hdf5_open(self.cal_database,'r')\n\n gains = {'Gains':np.zeros((20,8))} #N_feeds, N_bands\n\n obsids = {k:[] for k in range(19)}\n for obsid, grp in db.items():\n for ifeed in range(19):\n if grp['CalFeedMask'][ifeed]:\n obsids[ifeed] += [int(obsid)]\n\n obsids = obsids\n for ifeed in range(19):\n if len(np.array(obsids[ifeed])) == 0:\n continue\n idx = np.argmin(np.abs(np.array(obsids[ifeed])-this_obsid))\n self.nearest_calibrator = str(obsids[ifeed][idx])\n gains['Gains'][ifeed] = db[self.nearest_calibrator]['CalGains'][ifeed,:]\n\n db.close()\n\n return gains\n\n def get_channel_mask(self,this_obsid,feed):\n \"\"\"\n Get the updated channel mask for this obsid\n \"\"\"\n\n db = FileTools.safe_hdf5_open(self.database,'r')\n channel_mask = db[str(this_obsid)]['Vane/Level2Mask'][feed-1,...]\n db.close()\n return channel_mask\n\n def calibrate_tod(self,data, tod, weights, ifeed, feed):\n \"\"\"\n Calibrates data using a given calibration source\n \"\"\"\n this_obsid = int(self.getObsID(data))\n # Get Gain Calibration Factors\n gains = self.get_cal_gains(this_obsid)\n\n nbands, nchan, ntod = tod.shape\n if self.cal_source != 'none':\n idx = int(feed-1)\n cal_factors = gains['Gains'][idx,...]\n\n tod = tod/cal_factors[0,...,None]\n weights = weights*cal_factors[0,...,None]**2\n bad = ~np.isfinite(tod) | ~np.isfinite(weights)\n tod[bad] = 0\n weights[bad] = 0\n\n\n #channel_mask = self.get_channel_mask(this_obsid,feed)\n #tod[~channel_mask] = 0\n #weights[~channel_mask] = 0\n\n return tod, weights, cal_factors[0]\n\n def clean_tod(self,d,ifeed,feed):\n \"\"\"\n Subtracts the median filter and atmosphere from each channel per scan\n \"\"\"\n scan_edges = d[f'{self.level2}/Statistics/scan_edges'][...]\n nscans = scan_edges.shape[0]\n\n feed_tod = d[f'{self.level2}/averaged_tod'][ifeed,:,:,:]\n weights = np.zeros(feed_tod.shape)\n mask = np.zeros(feed_tod.shape[-1],dtype=bool)\n az = d['level1/spectrometer/pixel_pointing/pixel_az'][ifeed,:]\n el = d['level1/spectrometer/pixel_pointing/pixel_el'][ifeed,:]\n\n # Statistics for this feed \n medfilt_coefficient = d[f'{self.level2}/Statistics/filter_coefficients'][ifeed,...]\n atmos = d[f'{self.level2}/Statistics/atmos'][ifeed,...]\n atmos_coefficient = d[f'{self.level2}/Statistics/atmos_coefficients'][ifeed,...]\n wnoise_auto = d[f'{self.level2}/Statistics/wnoise_auto'][ifeed,...]\n fnoise_fits = d[f'{self.level2}/Statistics/fnoise_fits'][ifeed,...]\n\n # then the data for each scan\n last = 0\n scan_samples = []\n for iscan,(start,end) in enumerate(scan_edges):\n scan_samples = np.arange(start,end,dtype=int)\n median_filter = d[f'{self.level2}/Statistics/FilterTod_Scan{iscan:02d}'][ifeed,...]\n N = int((end-start))\n end = start+N\n tod = feed_tod[...,start:end]\n mask[start:end] = True\n # Subtract atmospheric fluctuations per channel\n for iband in range(4):\n for ichannel in range(64):\n #if self.channelmask[ifeed,iband,ichannel] == False:\n amdl = Statistics.AtmosGroundModel(atmos[iband,iscan],az[start:end],el[start:end]) *\\\n atmos_coefficient[iband,ichannel,iscan,0]\n if self.median_filter:\n tod[iband,ichannel,:] -= median_filter[iband,:N] * medfilt_coefficient[iband,ichannel,iscan,0]\n if self.atmosphere:\n tod[iband,ichannel,:] -= amdl\n tod[iband,ichannel,:] -= np.nanmedian(tod[iband,ichannel,:])\n\n\n wnoise = wnoise_auto[:,:,iscan,0]\n weights[...,start:end] = 1./wnoise[...,None]**2\n bad = np.isnan(weights) | np.isinf(weights) | ~np.isfinite(feed_tod)\n feed_tod[bad] = 0\n weights[bad] = 0\n\n return feed_tod, weights, mask\n\n def average_tod(self,d,feed_tod,feed_weights,mask):\n \"\"\"\n Average together to TOD \n \"\"\" \n\n frequency = d['level1/spectrometer/frequency'][...]\n # This becomes (nBands, 64) \n self.frequency = np.mean(np.reshape(frequency,(frequency.shape[0],frequency.shape[1]//16,16)) ,axis=-1)\n all_tod = np.zeros((8, feed_tod.shape[-1]))\n all_weights=np.zeros((8, feed_tod.shape[-1]))\n all_frequency=np.zeros((8))\n for ichan, (flow,fhigh) in enumerate(zip(np.arange(8)+26,np.arange(8)+27)):\n sel = ((self.frequency >= flow) & (self.frequency < fhigh))\n top = np.sum(feed_tod[sel,:]*feed_weights[sel,:],axis=0)\n bot = np.sum(feed_weights[sel,:],axis=0)\n all_tod[ichan,:] = top/bot\n all_weights[ichan,:] = bot\n all_frequency[ichan] = (fhigh+flow)/2.\n \n diff = all_tod[:,mask]\n N = int(diff.shape[1]//2*2)\n diff = (diff[:,:N:2]-diff[:,1:N:2])\n auto = stats.MAD(diff.T)\n\n amean_rms = np.sqrt(1./np.nanmedian(all_weights[:,mask],axis=1))\n\n # Add the weighted average uncertainties to the auto-rms uncertainties\n all_weights = 1./(1./all_weights + auto[:,None]**2)\n\n return all_tod, all_weights, auto, all_frequency\n \n def run(self, d):\n \"\"\"\n Expects a level2 file structure to be passed.\n \"\"\"\n\n feeds,feedidx,_ = self.getFeeds(d,'all')\n\n tod_shape = d[f'{self.level2}/averaged_tod'].shape\n \n scanedges = d[f'{self.level2}/Statistics/scan_edges'][...]\n nfeeds = 20\n nchannels = 8\n \n self.all_tod = np.zeros((20, nchannels, tod_shape[-1])) \n self.all_weights = np.zeros((20, nchannels, tod_shape[-1])) \n self.all_frequency = np.zeros((nchannels)) \n self.all_auto = np.zeros((20,nchannels)) \n self.all_mask = np.zeros((20,tod_shape[-1]))\n self.all_cal_factors = np.zeros((20,4,64))\n # Read in data from each feed\n for ifeed,feed in enumerate(tqdm(feeds,desc='Looping over feeds')):\n if feeds[ifeed] == 20:\n continue\n feed_tod,feed_weights,mask = self.clean_tod(d,ifeed,feed)\n\n if self.astro_cal:\n feed_tod,feed_weights,cal_factors = self.calibrate_tod(d,feed_tod,feed_weights,ifeed,feed)\n else:\n cal_factors = 1\n\n self.all_tod[feed-1],self.all_weights[feed-1], self.all_auto[feed-1], self.all_frequency = self.average_tod(d,feed_tod,feed_weights,mask) \n self.all_mask[feed-1] = mask\n self.all_cal_factors[feed-1] = cal_factors\n \n def write(self,data):\n \"\"\"\n Write out the averaged TOD to a Level2 continuum file with an external link to the original level 1 data\n \"\"\" \n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n\n # We will store these in a separate file and link them to the level2s\n fname = data.filename.split('/')[-1]\n \n if os.path.exists(self.outfile):\n output = h5py.File(self.outfile,'a')\n else:\n output = h5py.File(self.outfile,'w')\n\n # Set permissions and group\n if self.set_permissions:\n try:\n os.chmod(self.outfile,0o664)\n shutil.chown(self.outfile, group=self.permissions_group)\n except PermissionError:\n self.logger(f'{fname}:{self.name}: Warning, couldnt set the file permissions.')\n\n # Store datasets in root\n data_out = {'tod':self.all_tod,\n 'weights':self.all_weights,\n 'mask':self.all_mask,\n 'cal_factors':self.all_cal_factors,\n 'frequency':self.all_frequency,\n 'auto_rms':self.all_auto}\n\n for dname, dset in data_out.items():\n if dname in output:\n del output[dname]\n output.create_dataset(dname, data=dset)\n\n output.attrs['version'] = __level3_version__\n output['cal_factors'].attrs['source'] = self.cal_source\n output['cal_factors'].attrs['calibrator_obsid'] = self.nearest_calibrator\n\n output.close()\n \n if self.level3 in data.keys():\n del data[self.level3]\n data[self.level3] = h5py.ExternalLink(self.outfile,'/')\n\n def write_database(self,data):\n \"\"\"\n Write out the statistics to a common statistics database for easy access\n \"\"\"\n \n if not os.path.exists(self.database):\n output = FileTools.safe_hdf5_open(self.database,'w')\n else:\n output = FileTools.safe_hdf5_open(self.database,'a')\n\n obsid = self.getObsID(data)\n if obsid in output:\n grp = output[obsid]\n else:\n grp = output.create_group(obsid)\n\n grp.attrs['level3_filename'] = self.outfile\n\n if self.name in grp:\n del grp[self.name]\n lvl3 = grp.create_group(self.name)\n\n lvl3.attrs['version'] = __level3_version__\n lvl3.attrs['calibrator_obsid'] = self.nearest_calibrator\n lvl3.attrs['calibrator_source'] = self.cal_source\n output.close()\n","sub_path":"comancpipeline/Analysis/CreateLevel3.py","file_name":"CreateLevel3.py","file_ext":"py","file_size_in_byte":14988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"77649261","text":"import argparse\nimport os\nfrom tqdm import trange\n\n\ndef read_all(root, ham_only=False):\n if not os.path.exists(root):\n raise ValueError(\"Path Doesn't Exist\")\n\n out_path = root + \"/out\"\n if not os.path.exists(out_path):\n os.mkdir(out_path)\n if not os.path.exists(out_path + \"/ham\"):\n os.mkdir(out_path +\"/ham\")\n if not os.path.exists(out_path + \"/spam\"):\n os.mkdir(out_path +\"/spam\")\n\n spam_c = 0\n ham_c = 0\n\n err_c = 0\n\n with open(root + \"/full/index\", 'r') as index:\n\n counter = 0 # only count printed files, ie don't count skipped in case of ham only\n for c in trange(rawgencount(root + \"/full/index\")):\n iline = index.readline()\n (label, msg_path) = iline.split(\" ..\", 1)\n if label == 'spam' and ham_only:\n continue\n\n try:\n with open(root + msg_path.strip(), 'r') as msg:\n try:\n _, body = msg.read().split('\\n\\n', 1) # strip the header info\n except ValueError:\n err_c += 1\n continue\n except FileNotFoundError:\n err_c += 1\n continue\n except OSError:\n err_c += 1\n continue\n \n \n with open(out_path + f\"/{label}/{counter:06d}\", 'w+') as fout:\n fout.write(body)\n counter += 1\n\n if label == \"spam\":\n spam_c += 1\n else:\n ham_c += 1\n\n print(f\"Ham: {ham_c}\\nSpam: {spam_c}\\nErr: {err_c}\")\n\n \n\n\n# https://stackoverflow.com/questions/845058/how-to-get-line-count-of-a-large-file-cheaply-in-python?page=1&tab=votes#tab-top\ndef _make_gen(reader):\n b = reader(1024 * 1024)\n while b:\n yield b\n b = reader(1024*1024)\n\n# https://stackoverflow.com/questions/845058/how-to-get-line-count-of-a-large-file-cheaply-in-python?page=1&tab=votes#tab-top\ndef rawgencount(filename):\n f = open(filename, 'rb')\n f_gen = _make_gen(f.raw.read)\n return sum( buf.count(b'\\n') for buf in f_gen )\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--path\", type=str, required=True)\n parser.add_argument('--ham_only', action='store_true')\n\n args = parser.parse_args()\n\n read_all(args.path, args.ham_only)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"textGen/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51425844","text":"import pytest\n\nfrom . import factories\nfrom .. import views\n\n\npytestmark = pytest.mark.django_db\n\n\ndef test_index_view(rf):\n\n user1 = factories.UserFactory(username='test_user_1')\n user2 = factories.UserFactory(username='test_user_2')\n\n factories.ProfileFactory(user=user1)\n factories.ProfileFactory(user=user2)\n\n response = views.index(rf)\n\n assert response.status_code == 200\n assert b'test_user_1' in response.content\n assert b'test_user_2' in response.content\n\n\ndef test_profile_view(rf):\n user = factories.UserFactory(\n username='test_user',\n first_name='test_first_name',\n last_name='test_last_name',\n email='test_email_name',\n )\n factories.ProfileFactory(user=user)\n response = views.profile(rf, user.username)\n\n assert response.status_code == 200\n assert b'test_user' in response.content\n assert b'test_first_name' in response.content\n assert b'test_last_name' in response.content\n assert b'test_email' in response.content\n","sub_path":"oc_lettings_site/profiles/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472741876","text":"from __future__ import absolute_import\n\nimport numpy as np\nimport time\nfrom PIL import Image\n\nfrom ..utils.viz import show_frame\n\nclass Tracker(object):\n\n def __init__(self, name, is_deterministic=False):\n \n #self.name = name.split('/')[-1].split('.')[0]\n self.name='SiamFC'\n self.is_deterministic = is_deterministic\n \n def init(self, image, box):\n raise NotImplementedError()\n\n def update(self, image):\n raise NotImplementedError()\n\n def track(self, img_files, box, visualize=False):\n frame_num = len(img_files)\n boxes = np.zeros((frame_num, 4))\n boxes[0] = box\n times = np.zeros(frame_num)\n\n for f, img_file in enumerate(img_files):\n image = Image.open(img_file)\n if not image.mode == 'RGB':\n image = image.convert('RGB')\n\n start_time = time.time()\n if f == 0:\n self.init(image, box)\n else:\n boxes[f, :] = self.update(image)\n times[f] = time.time() - start_time\n\n if visualize:\n show_frame(image, boxes[f, :])\n\n return boxes, times\n\nfrom .identity_tracker import IdentityTracker\n","sub_path":"SiamDW/SiamDW-FC/got10k/trackers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601813666","text":"import requests\nimport urllib3\nfrom Xcharger.HomePage.login import Login\n\n#禁用安全警告\nurllib3.disable_warnings()\n\nurl1 = 'http://xcloud.dev.xcharger.net/service/api/promotion'\n\nclass Marketing_Activity(Login):\n def __init__(self,s):\n self.s = s\n def CreateActivity(self,title,startTime,endTime,scope,policy,description='',type=1):\n '''营销活动管理,添加活动,scope取值范围为wechat,idcard.all\n policy格式为[[],[],...]'''\n json_body = {\n 'title':title,\n 'startTime':startTime,\n 'endTime':endTime,\n 'scope':scope,\n 'setting':{\n 'policy':policy,\n },\n 'description':description,\n 'type':type\n }\n res = self.s.post(url1,json=json_body,verify=False)\n return res\n\n def DeleteActivity(self,ActivityId):\n '''营销活动管理,删除活动'''\n params_body = {\n 'id':ActivityId\n }\n res = self.s.delete(url1,params=params_body,verify=False)\n return res\n\n def ControlActivity(self,disabled,activityId):\n '''活动开关'''\n json_body = {\n 'id':activityId,\n 'disabled':disabled\n }\n res = self.s.post(url1,json=json_body,verify=False)\n return res\n\n\nif __name__ == '__main__':\n s = requests.session()\n activity = Marketing_Activity(s)\n activity.login('zhichong','xcharger88')\n policy = [[100,100]]\n res = activity.CreateActivity('活动','20180419000000','20180419235959','all',policy)\n activityId = res.json()['result']\n print(res.json())\n #activity.DeleteActivity(activityId)\n\n\n","sub_path":"Xcharger/MarketingActivityManagement/marketing_activity_management.py","file_name":"marketing_activity_management.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418317163","text":"import random\nimport cryptocode\n\n\nclass Board:\n def __init__(self, w, h, bomb_count, new=True, data=[]):\n self.w = w\n self.h = h\n self.cells = {}\n self.bomb_count = bomb_count\n self.count_flag = 0\n for x in range(w):\n self.cells[x] = {}\n self.open = 0\n if new:\n for x in range(w):\n for y in range(h):\n self.cells[x][y] = Cell(\"clear\", x, y, w, h)\n for i in range(bomb_count):\n x, y = random.choice(range(w)), random.choice(range(h))\n while self.cells[x][y].type == \"bomb\":\n x, y = random.choice(range(0, w)), random.choice(range(0, h))\n self.cells[x][y].type = \"bomb\"\n for j in self.cells[x][y].give_list_around_object():\n self.cells[j[0]][j[1]].digit += 1\n else:\n self.count_flag = int(data[0])\n self.open = int(data[1])\n for i in data[2:]:\n i = i.split(\"/\")\n objectt = Cell(i[0], int(i[1]), int(i[2]), self.w, self.h)\n objectt.digit = int(i[3])\n objectt.close = int(i[4])\n objectt.flag = int(i[5])\n self.cells[int(i[1])][int(i[2])] = objectt\n\n def save(self, password):\n s = f\"{self.w}/{self.h}/{self.bomb_count} {self.count_flag} {self.open} \"\n for i in list(self.cells.keys()):\n for j in list(self.cells[i].keys()):\n a = self.cells[i][j]\n s += a.type + \"/\" + str(a.x) + \"/\" + str(a.y) + \"/\" + str(a.digit) + \"/\" + str(a.close) + \"/\" + str(\n a.flag) + \" \"\n s += \"tisgfd\"\n return cryptocode.encrypt(s, password)\n\n def output(self):\n print(\"_\", end=\"\\t\")\n print(\"_\", end=\"\\t\")\n for i in range(self.w):\n print(i + 1, end=\"\\t\")\n print()\n for i in range(self.w + 2):\n print(\"_\", end=\"\\t\")\n print()\n for i in range(self.w):\n print(i + 1, end=\"\\t\")\n print(\"|\", end=\"\\t\")\n for j in range(self.h):\n if self.cells[i][j].close:\n print(\"f\" if self.cells[i][j].flag else \"*\", end=\"\\t\")\n else:\n print(self.cells[i][j].digit, end=\"\\t\")\n print()\n\n def update(self, what_do, x, y):\n x -= 1\n y -= 1\n if what_do.lower() == \"flag\":\n if self.cells[x][y].close:\n self.cells[x][y].flag = 0 if self.cells[x][y].flag else 1\n self.open += 1 if self.cells[x][y].flag else -1\n self.count_flag += 1 if self.cells[x][y].flag else -1\n return True\n else:\n print(\"Клетка уже открыта\")\n return True\n elif what_do.lower() == \"open\":\n if self.cells[x][y].type == \"bomb\":\n print(\"Вы пройграли\")\n return False\n elif not self.cells[x][y].close:\n print(\"Вы уже открыли\")\n return True\n elif self.cells[x][y].flag:\n print(\"Здесь флаг\")\n return True\n else:\n was = []\n what_check = [(x, y)]\n what_open = [(x, y)]\n while what_check:\n a = what_check.pop()\n was.append(a)\n if self.cells[a[0]][a[1]].digit == 0 and not (self.cells[a[0]][a[1]].flag) and self.cells[a[0]][\n a[1]].close:\n for j in self.cells[a[0]][a[1]].give_list_around_object():\n if j not in what_open and not (self.cells[j[0]][j[1]].flag) and self.cells[j[0]][\n j[1]].close:\n what_open.append(j)\n if j not in was:\n what_check.append(j)\n for i in what_open:\n self.cells[i[0]][i[1]].close = 0\n self.open += 1\n return True\n\n def check_win(self, flag):\n print(self.bomb_count, self.count_flag, self.open)\n if not (flag):\n return flag\n if self.w * self.h == self.open and self.bomb_count == self.count_flag:\n print(\"Победа\")\n return False\n return True\n\n def last_output(self):\n print(\"_\", end=\"\\t\")\n print(\"_\", end=\"\\t\")\n for i in range(self.w):\n print(i + 1, end=\"\\t\")\n print()\n for i in range(self.w + 2):\n print(\"_\", end=\"\\t\")\n print()\n for i in range(self.w):\n print(i + 1, end=\"\\t\")\n print(\"|\", end=\"\\t\")\n for j in range(self.h):\n if self.cells[i][j].type == \"bomb\":\n print(\"b\", end=\"\\t\")\n else:\n print(self.cells[i][j].digit, end=\"\\t\")\n print()\n\n\nclass Cell:\n def __init__(self, type, x, y, w, h):\n self.x = x\n self.y = y\n self.type = type\n self.digit = 0\n self.close = 1\n self.flag = 0\n self.list_around_object = [(x + i, y + j) for i in range(-1, 2) for j in range(-1, 2) if\n (i != 0 or j != 0) and -1 < x + i < w and -1 < y + j < h]\n\n def give_list_around_object(self):\n return self.list_around_object\n","sub_path":"boars.py","file_name":"boars.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626370961","text":"from flask import Flask, request, redirect, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:12345@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\n\nclass Blog(db.Model):\n\n id = db.Column(db.Integer, primary_key = True)\n name = db.Column(db.String(120))\n body = db.Column(db.String(255))\n posted = db.Column(db.Boolean)\n\n def __init__(self, name, body):\n self.name = name\n self.body = body\n self.posted = False\n\n\n@app.route(\"/newpost\", methods=['POST', 'GET'])\ndef newpost():\n \n blog_name_error = ''\n blog_body_error = ''\n \n if request.method == 'POST':\n blog_name = request.form.get('blog')\n if len(blog_name) < 1:\n blog_name_error = ('Please fill in the title')\n \n blog_body = request.form.get('blog-body')\n if len(blog_body) < 1:\n blog_body_error = ('Please fill in the body')\n \n if any([blog_name_error, blog_body_error]):\n return render_template('newpost.html', blog_name_error = blog_name_error, blog_body_error = blog_body_error, blog_name=blog_name, blog_body=blog_body)\n else:\n new_blog = Blog(blog_name, blog_body)\n db.session.add(new_blog)\n db.session.commit()\n new_blog_id = new_blog.id\n blog = Blog.query.get(new_blog_id)\n return render_template('/blog.html', blog = blog)\n\n return render_template('newpost.html', name = \"Add New Blog Post\")\n\ndef blog_checkoff():\n \n blog_id = int(request.form['blog-id'])\n blog = Blog.query.get(blog_id)\n blog.posted = True\n db.session.add(blog)\n db.session.commit()\n return redirect('/newpost')\n\n@app.route('/blog', methods = ['GET'])\ndef blog():\n \n blog_id = int(request.args.get('id'))\n blog = Blog.query.get(blog_id)\n \n return render_template('blog.html', blog=blog) \n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n posted_blogs = Blog.query.all()\n return render_template('index.html', posted_blogs = posted_blogs)\n\nif __name__ == '__main__':\n app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521652810","text":"import tensorflow as tf\nimport numpy as np\n\n\nclass Model():\n def __init__(self, args, training=True):\n self.args = args\n if not training:\n args.batch_size = 1\n args.seq_length = 1\n\n # Step 2-1: create placeholder\n self.input_data = tf.placeholder(\n tf.int32, [args.batch_size, args.seq_length])\n self.targets = tf.placeholder(\n tf.int32, [args.batch_size, args.seq_length])\n\n # Step 2-2: define multi-layer RNN\n cells = []\n for _ in range(args.num_layers):\n cell = tf.contrib.rnn.BasicLSTMCell(args.rnn_size)\n if training and (args.output_keep_prob < 1.0 or args.input_keep_prob < 1.0):\n cell = tf.contrib.rnn.DropoutWrapper(cell,\n input_keep_prob=args.input_keep_prob,\n output_keep_prob=args.output_keep_prob)\n cells.append(cell)\n\n self.cell = cell = tf.contrib.rnn.MultiRNNCell(cells)\n self.initial_state = cell.zero_state(args.batch_size, tf.float32)\n\n embedding = tf.get_variable(\"embedding\", [args.vocab_size, args.rnn_size])\n inputs = tf.nn.embedding_lookup(embedding, self.input_data)\n\n outputs, last_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=self.initial_state)\n outputs = tf.reshape(outputs, [-1, args.rnn_size])\n\n # Step 2-3: compute outputs and loss\n with tf.variable_scope('rnnlm'):\n softmax_w = tf.get_variable(\"softmax_w\",\n [args.rnn_size, args.vocab_size])\n softmax_b = tf.get_variable(\"softmax_b\", [args.vocab_size])\n\n self.logits = tf.matmul(outputs, softmax_w) + softmax_b\n self.probs = tf.nn.softmax(self.logits)\n loss = tf.contrib.seq2seq.sequence_loss(\n tf.reshape(self.logits, [-1, args.seq_length, args.vocab_size]),\n self.targets,\n tf.ones([args.batch_size, args.seq_length]))\n self.cost = tf.reduce_mean(loss)\n self.final_state = last_state\n\n def sample(self, sess, chars, vocab, num=200, prime='The ', sampling_type=1):\n state = sess.run(self.cell.zero_state(1, tf.float32))\n for char in prime[:-1]:\n x = np.zeros((1, 1))\n x[0, 0] = vocab[char]\n feed = {self.input_data: x, self.initial_state: state}\n [state] = sess.run([self.final_state], feed)\n\n def weighted_pick(weights):\n t = np.cumsum(weights)\n s = np.sum(weights)\n return(int(np.searchsorted(t, np.random.rand(1)*s)))\n\n ret = prime\n char = prime[-1]\n for n in range(num):\n x = np.zeros((1, 1))\n x[0, 0] = vocab[char]\n feed = {self.input_data: x, self.initial_state: state}\n [probs, state] = sess.run([self.probs, self.final_state], feed)\n p = probs[0]\n\n if sampling_type == 0:\n sample = np.argmax(p)\n elif sampling_type == 2:\n if char == ' ':\n sample = weighted_pick(p)\n else:\n sample = np.argmax(p)\n else: # sampling_type == 1 default:\n sample = weighted_pick(p)\n\n pred = chars[sample]\n ret += pred\n char = pred\n return ret\n","sub_path":"04_char_rnn/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"188629016","text":"\"\"\"\nSFU CMPT756 Final Project.\nThis service is used to log the events performed by various services based on customer_id\n\"\"\"\n\n# Standard library modules\nimport logging\nimport sys\nimport time\n\n# Installed packages\nfrom flask import Blueprint\nfrom flask import Flask\nfrom flask import request\nfrom flask import Response\nfrom datetime import datetime\n\nimport jwt\n\nfrom prometheus_flask_exporter import PrometheusMetrics\n\nimport requests\n\nimport simplejson as json\n\n# The application\n\napp = Flask(__name__)\n\nmetrics = PrometheusMetrics(app)\nmetrics.info('app_info', 'User process')\n\nbp = Blueprint('app', __name__)\n\n#172.17.0.1\n#host.docker.internal\n\ndb = {\n \"name\": \"http://172.17.0.1:30004/api/v1/datastore\",\n \"endpoint\": [\n \"read\",\n \"write\",\n \"delete\",\n \"update\"\n ]\n}\n\n\n@bp.route('/', methods=['GET'])\n@metrics.do_not_track()\ndef hello_world():\n return (\"If you are reading this in a browser, your service is \"\n \"operational. Switch to curl/Postman/etc to interact using the \"\n \"other HTTP verbs.\")\n\n\n@bp.route('/health')\n@metrics.do_not_track()\ndef health():\n return Response(\"\", status=200, mimetype=\"application/json\")\n\n\n@bp.route('/readiness')\n@metrics.do_not_track()\ndef readiness():\n return Response(\"\", status=200, mimetype=\"application/json\")\n\n\n@bp.route('/create', methods=['POST'])\ndef create_event():\n \"\"\"\n Insert every call the service into logger table .\n Each new entry will be tagged to a customer_id and based on timestamp.\n \"\"\"\n print(\"Test check inside the create event\") \n try:\n content = request.get_json()\n customer_id = content['customer_id']\n service_name = content['service_name']\n operation_name = content['operation_name']\n status_code = content['status_code']\n message = content['message']\n request_message = content['request_message']\n response_message = content['response_message']\n \n except Exception:\n return json.dumps({\"message\": \"error reading arguments\",\"status_code\":\"500\"})\n url = db['name'] + '/' + db['endpoint'][1]\n response = requests.post(\n url,\n json={\"objtype\": \"logger\",\n \"objkey\":\"customer_id\",\n \"customer_id\": customer_id,\n \"service_name\": service_name,\n \"operation_name\": operation_name,\n \"op_date\": datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),\n \"status_code\":status_code,\n \"message\":message,\n \"request_message\":request_message,\n \"response_message\":response_message\n })\n return (response.json())\n\n\n@bp.route('/list', methods=['GET'])\ndef list_event():\n \"\"\"\n List the logs based on customer_id and op_date.\n \"\"\"\n print(\"Test check inside the list events\") \n headers = request.headers\n # check header here\n try:\n content = request.get_json()\n customer_id = content[\"customer_id\"]\n beg_date = content[\"beg_date\"]\n end_date = content[\"end_date\"]\n except Exception:\n return json.dumps({\"message\": \"error reading arguments\",\"status_code\":\"500\"})\n\n payload = {\"objtype\": \"logger\", \"objkey\": 'customer_id'}\n url = db['name'] + '/' + db['endpoint'][0]\n response = requests.get(url, \n params=payload,\n json={\"sort_key\": \"op_date\",\n \"table_key\": customer_id,\n \"beg_date\": beg_date,\n \"end_date\": end_date}\n )\n return (response.json())\n\n\n# All database calls will have this prefix. Prometheus metric\n# calls will not---they will have route '/metrics'. This is\n# the conventional organization.\napp.register_blueprint(bp, url_prefix='/api/v1/logger/')\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n logging.error(\"Usage: app.py \")\n sys.exit(-1)\n\n p = int(sys.argv[1])\n # Do not set debug=True---that will disable the Prometheus metrics\n app.run(host='0.0.0.0', port=p, threaded=True)\n","sub_path":"code/logger/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422442999","text":"import math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nigfont = {'family': 'IPAexGothic'}\n\npi = math.pi # mathモジュールのπを利用\n\nx = np.linspace(0, 360, 100) # 0から360度までの範囲を100分割したnumpy配列\ny = (np.sin(x * pi / 180), np.cos(x * pi / 180))\n\nlbl = ['Sin', 'Cos']\n\n# グラフタイトル\nplt.title('Sin/Cos', **igfont, fontsize=16)\n# グラフの軸\nplt.xlabel('Angle', **igfont, fontsize=16)\nplt.ylabel('値', **igfont, fontsize=16)\n\nfor i in range(0, 2, 1):\n plt.plot(x, y[i], label=lbl[i])\n\n# グラフの凡例\n# plt.legend()\nplt.show()\n","sub_path":"LearnPython/DrawGraph/matplotlib-test20.py","file_name":"matplotlib-test20.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322372064","text":"n=int(input())\nl=list(map(int,input().split()))\na_ha=0\nb_ha=0\nl.sort(reverse=True)\nfor i in l:\n m=a_ha+i\n if b_ha>m:\n a_ha=m\n else:\n a_ha=b_ha\n b_ha=m\nprint(a_ha,b_ha)\n","sub_path":"pro46.py","file_name":"pro46.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203670515","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom datetime import datetime, date as dt, timedelta\nfrom collections import defaultdict\nimport pdb\n\n\nclass Attribute(models.Model):\n name = models.CharField(max_length=50)\n\n def __unicode__(self):\n return self.name\n\n\nclass Room(models.Model):\n name = models.CharField(max_length=100)\n capacity = models.IntegerField()\n description = models.TextField()\n attributes = models.ManyToManyField(Attribute, blank=True)\n\n def __unicode__(self):\n return self.name\n\n def get_unique_dates(self):\n dates = self.freeterm_set.values_list('date', flat=True).distinct().order_by()\n dates = [str(d) for d in dates]\n return dates\n\n def get_free_hours(self, date):\n terms = self.freeterm_set.filter(date=date)\n hours = []\n for t in terms:\n h = datetime.combine(dt.today(), t.begin_time)\n end = datetime.combine(dt.today(), t.end_time)\n while h < end:\n hours.append(h.time())\n h += timedelta(hours = 1)\n\n hours = [str(h)[0:2] for h in hours]\n return hours\n\n def as_json(self):\n my_dict = defaultdict(list)\n dates = self.get_unique_dates()\n\n for d in dates:\n for h in self.get_free_hours(d):\n my_dict[d].append(h)\n\n return dict(\n id = self.id,\n name = self.name,\n description = self.description,\n capacity = self.capacity,\n attributes = [ob.__unicode__() for ob in Attribute.objects.filter(room=self)],\n terms = my_dict\n )\n\n\n\nclass FreeTerm(models.Model):\n room = models.ForeignKey(Room)\n date = models.DateField()\n begin_time = models.TimeField()\n end_time = models.TimeField()\n\n def clean(self):\n if self.begin_time >= self.end_time:\n raise ValidationError('Invalid time interval')\n\n def save(self, *args, **kwargs):\n no_crossing = True\n for t in self.room.freeterm_set.filter(date=self.date):\n if t != self:\n if not (t.end_time < self.begin_time or \\\n self.end_time < t.begin_time):\n no_crossing = False\n\n if no_crossing:\n super(FreeTerm, self).save()\n else:\n term = FreeTerm(\n room=self.room,\n date=self.date,\n begin_time=min(self.begin_time, t.begin_time),\n end_time=max(self.end_time, t.end_time)\n )\n t.delete()\n term.save()\n\n def __unicode__(self):\n return self.begin_time.__str__()[:2] + u\"\\u2013\" + self.end_time.__str__()[:2]\n\n\n class Meta:\n ordering = ['date', 'begin_time']\n\n\nclass Reservation(models.Model):\n user = models.ForeignKey(User)\n room = models.ForeignKey(Room)\n date = models.DateField()\n begin_time = models.TimeField()\n end_time = models.TimeField()\n\n def clean(self):\n for r in self.room.reservation_set.filter(date=self.date):\n if r != self:\n if not (r.end_time <= self.begin_time or \\\n self.end_time <= r.begin_time):\n raise ValidationError('Someone alerady took this term')\n\n valid = False\n for t in self.room.freeterm_set.filter(date=self.date):\n if t.begin_time <= self.begin_time and \\\n t.end_time >= self.end_time:\n valid = True\n break\n\n if not valid:\n raise ValidationError('There is no fitting free term')\n\n\n\n def __unicode__(self):\n return self.user.__str__() + ': ' + self.room.__unicode__()","sub_path":"booking/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175695307","text":"from __future__ import absolute_import\n\nimport os\nimport re\nfrom xml.sax import ContentHandler\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element\nfrom xml.etree.ElementTree import SubElement\n\nimport defusedxml.sax as sax\n\n\ndef _copy_preserve(orig, preserve, merge=None):\n # return keys $preserve from $orig and merge with $merge\n res = {}\n for k in preserve:\n if k in orig:\n res[k] = orig[k]\n\n res.update(merge or {})\n\n return res\n\n\ndef _get_file_contents(p): # relative to this file path\n tp = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + u'' + p)\n with open(tp, \"rb\") as f:\n s = f.read()\n return s\n\n\n_ENCRYPTED_JS = \"\"\"\n\n\n// This is a set of scripts required for decrypting encrypted content. Please don't touch it.\n\n\nfunction evernote_decrypt(o) {\n var h = o.dataset.hint ? \" Hint: \" + o.dataset.hint : \"\";\n var p = prompt(\"Enter the passphrase.\" + h);\n try {\n o.outerHTML = decrypt(o.dataset.cipher || \"AES\", o.dataset.length, p, o.dataset.body);\n }\n catch(e) {\n alert(\"Failed: \" + e);\n }\n return false;\n}\n\n\"\"\" + _get_file_contents(\"js/decrypt.min.js\")\n\n_AN_PATTERN = re.compile(\"<(br|/?html|/?head|/?body|/title|/div)[^>]*>\")\n_BN_PATTERN = re.compile(\"<(/head|/body|title)[^>]*>\")\n\n_ENTITY_PATTERN = re.compile(\"&#?\\w+;\")\n\n\ndef _unescape_entities(text):\n def fixup(m):\n text = m.group(0)\n if text[:2] == \"&#\":\n # character reference\n try:\n if text[:3] == \"&#x\":\n return unichr(int(text[3:-1], 16))\n else:\n return unichr(int(text[2:-1]))\n except ValueError:\n pass\n return text # leave as is\n\n return _ENTITY_PATTERN.sub(fixup, text)\n\n\nclass _EWrapper:\n def __init__(self, e):\n self.e = e\n self.st = {}\n\n\nclass _EvernoteNoteParser(ContentHandler):\n def __init__(self, resources_base, title):\n ContentHandler.__init__(self)\n\n self.resources_base = resources_base\n\n self.hierarchy = []\n self.hierarchy.append(_EWrapper(Element(\"html\")))\n self.hierarchy[0].st['latest_child'] = None\n\n self._startElement(\"head\")\n self._startElement(\"meta\", attrib={'http-equiv': 'Content-Type', 'content': 'text/html; charset=UTF-8'})\n self._endElement()\n\n self._startElement(\"title\", text=title)\n self._endElement()\n\n self._endElement()\n\n self.body_started = False\n self.include_encrypted_js = False\n\n def _startElement(self, tag, text=None, attrib=None, **extraattrib):\n z = extraattrib.copy()\n z.update(attrib or {})\n\n se = _EWrapper(SubElement(self.hierarchy[-1].e, tag, attrib=z))\n se.st['latest_child'] = None\n self.hierarchy[-1].st['latest_child'] = se\n\n if text is not None:\n se.e.text = text\n\n self.hierarchy.append(se)\n\n def _endElement(self):\n self.hierarchy = self.hierarchy[:-1]\n\n def _text(self, t):\n if self.hierarchy[-1].st['latest_child'] is None:\n if self.hierarchy[-1].e.text is None:\n self.hierarchy[-1].e.text = t\n else:\n self.hierarchy[-1].e.text += t\n else:\n if self.hierarchy[-1].st['latest_child'].e.tail is None:\n self.hierarchy[-1].st['latest_child'].e.tail = t\n else:\n self.hierarchy[-1].st['latest_child'].e.tail += t\n\n def startElement(self, tag, attrs):\n # https://dev.evernote.com/doc/articles/enml.php\n\n attrs = attrs.copy()\n attrs = dict(attrs)\n\n # todo in-app note links https://dev.evernote.com/doc/articles/note_links.php\n\n if tag == \"en-note\":\n if 'style' not in attrs:\n attrs['style'] = 'word-wrap: break-word;' \\\n + ' -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;'\n\n attrs.pop('xmlns', 0)\n\n self._startElement(\"body\", attrib=attrs)\n self.body_started = True\n else:\n if not self.body_started:\n raise Exception('Malformed note: tag %s appeared before en-note' % tag)\n\n if tag == 'en-todo':\n a = {'type': \"checkbox\", 'disabled': \"disabled\"}\n\n if attrs['checked'].lower() in (\"true\", \"checked\"):\n a['checked'] = 'checked'\n self._startElement(\"input\", attrib=a)\n\n elif tag == 'en-media':\n # https://dev.evernote.com/doc/reference/Limits.html\n\n # \"image/gif\", \"image/jpeg\", \"image/png\"\n # \"audio/wav\", \"audio/mpeg\", \"audio/amr\", \"audio/aac\", \"audio/mp4\"\n # \"application/vnd.evernote.ink\"\n # \"application/pdf\"\n # \"video/mp4\"\n\n # \"application/msword\", \"application/mspowerpoint\", \"application/excel\"\n #\n # \"application/vnd.ms-word\", \"application/vnd.ms-powerpoint\", \"application/vnd.ms-excel\"\n #\n # \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n # \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n # \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"\n #\n # \"application/vnd.apple.pages\", \"application/vnd.apple.numbers\", \"application/vnd.apple.keynote\",\n # \"application/x-iwork-pages-sffpages\", \"application/x-iwork-numbers-sffnumbers\",\n # \"application/x-iwork-keynote-sffkey\"\n\n toptype, subtype = attrs['type'].split('/', 2)\n\n src = ''.join([self.resources_base, attrs['hash'], \".\", subtype])\n if toptype == \"image\":\n a = _copy_preserve(attrs, [\"alt\", \"style\", \"width\", \"height\"], {'src': src})\n self._startElement(\"img\", attrib=a)\n else:\n # TODO other types\n\n self._startElement(\"a\", text=\"Document of type \" + attrs['type'], href=src)\n\n elif tag == 'en-crypt':\n self.include_encrypted_js = True\n\n a = {\n 'href': '#',\n 'onclick': 'return evernote_decrypt(this);',\n 'data-body': ''\n }\n for k in ['cipher', 'length', 'hint']:\n if k in attrs:\n a['data-' + k] = attrs[k]\n\n self._startElement(\"a\", text=\"Encrypted content. Click here to decrypt.\", attrib=a)\n self.hierarchy[-1].st['en-crypt'] = True\n else:\n self._startElement(tag, attrib=attrs)\n\n def endElement(self, tag):\n self._endElement()\n\n def characters(self, content):\n if 'en-crypt' in self.hierarchy[-1].st and self.hierarchy[-1].st['en-crypt']:\n self.hierarchy[-1].e.attrib['data-body'] += content\n else:\n self._text(content)\n\n def getResult(self): # utf8-encoded\n if len(self.hierarchy) != 1:\n raise Exception(\"Note is not parsed yet: hierarchy size is %d\" % len(self.hierarchy))\n\n r = ElementTree.tostring(self.hierarchy[0].e)\n\n r = _AN_PATTERN.sub(lambda m: m.group(0) + \"\\n\", r)\n r = _BN_PATTERN.sub(lambda m: \"\\n\" + m.group(0), r)\n\n r = _unescape_entities(r)\n r = r.encode(\"utf8\")\n\n if self.include_encrypted_js:\n # avoid dealing with XML text escapes\n r = r.replace(\"\", \"\", 1)\n return r\n\n\ndef parse(resources_base_path, enbody, title):\n p = _EvernoteNoteParser(resources_base_path, title)\n sax.parseString(enbody, p, forbid_dtd=False, forbid_entities=False, forbid_external=False)\n\n return p.getResult()\n","sub_path":"synctogit/EvernoteNoteParser.py","file_name":"EvernoteNoteParser.py","file_ext":"py","file_size_in_byte":7931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164435382","text":"class Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n words = s.split()\n ans = []\n for word in words:\n ans.append(word[::-1])\n return \" \".join(ans)\n\n\nclass Solution(object):\n def reverseWords(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n words = s.split()\n ans = [word[::-1] for word in words]\n return \" \".join(ans)\n\n\nres = Solution().reverseWords(\"Let's take LeetCode contest\")\nprint(res) # \"s'teL ekat edoCteeL tsetnoc\"\n","sub_path":"leet/题目/e557.py","file_name":"e557.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165676627","text":"'''\n\nThe CDP module contains all the tools required to act on a Maker collateralized debt position or vault, such as increasing or decreasing its leverage (boost and repay), closing the vault to calculate its lifetime profit, adding collateral or drawing more debt. \n\nThe vault should be presented to the interface as a Python dictionary with the appropriate keys depending on the function called. The keys should be:\n\n\"collateral\": The collateral in the vault.\n\"debt\": The debt associated with the vault.\n\"repay from\": The collateralization threshold in % at which the vault should automatically be deleveraged.\n\"repay to\": The collateralization target in % after deleveraging.\n\"boost from\": The collateralization threshold in % at which the leverage of the vault should automatically be increased. \n\"boost to\": The collateralization target in % after increasing leverage.\n\"initial collateral\": The initial collateral in at the inception of the vault.\n\"initial debt\": The initial debt at the inception of the vault. \n\n'''\n\nimport numpy as np\n\ndef boost(vault, eth_price, gas_price, service_fee):\n '''\n Given a vault (dictionary), checks if the vault can be boosted, and if yes, boosts it and returns the new vault.\n\n Parameters: \n vault (dictionary): A dictionary representing an automated vault\n eth_price (float): A float representing the current price of ETH - or another collateral\n gas_price (float): A float representing the current *fast* gas price in gwei\n service_fee (float): A float representing the DeFi Saver service fee in %\n\n Returns: \n vault (dictionary): The new updated vault\n ''' \n collateral_value = vault[\"collateral\"]*eth_price\n gas_fee_in_eth = 800000*gas_price*1e-9\n gas_fee_in_usd = eth_price*gas_fee_in_eth\n #Conversion of service fee in decimal format\n s = service_fee/100\n #New variables for more readable math\n p = eth_price\n c = vault[\"collateral\"]\n g = gas_fee_in_usd\n t = vault[\"boost to\"]/100 #Must be in decimal format in the code\n d = vault[\"debt\"]\n boosted = False\n\n if d == 0:\n ratio = float(\"inf\")\n else:\n ratio = collateral_value/vault[\"debt\"]\n\n if ratio >= vault[\"boost from\"]/100:\n #Algebra to get required debt change to reach a target ratio\n debt_change = (p*c - (1-s)*g - t*d)/(t - (1-s))\n #If gas fee lower than 5% boost amount, convert newly generated debt, subtract gas fee and service fee, and add to collateral\n if g < 0.05*debt_change*(1-s)/(2-s) or ratio < 1.65: \n vault[\"collateral\"] += (1- s)*(debt_change-g)/p\n #Add newly generated debt\n vault[\"debt\"] += debt_change\n boosted = True\n\n return vault, boosted\n\ndef repay(vault, eth_price, gas_price, service_fee):\n '''\n Given a vault (dictionary), checks if the vault can be repayed, and if yes, repays it and returns the new vault.\n\n Parameters: \n vault (dictionary): A dictionary representing an automated vault\n eth_price (float): A float representing the current price of ETH \n gas_price (float): A float representing the current *fast* gas price in gwei\n service_fee (float): A float representing the DeFi Saver service fee in %\n\n Returns: \n vault (dictionary): The new updated vault\n ''' \n collateral_value = vault[\"collateral\"]*eth_price\n gas_fee_in_eth = 800000*gas_price*1e-9\n gas_fee_in_usd = eth_price*gas_fee_in_eth\n #Conversion of service fee in decimal format\n s = service_fee/100\n #New variables for more readable math\n p = eth_price\n c = vault[\"collateral\"]\n g = gas_fee_in_usd\n t = vault[\"repay to\"]/100 #Must be in decimal format in the code\n d = vault[\"debt\"]\n repaid = False\n\n if d == 0:\n ratio = float(\"inf\")\n else: \n ratio = collateral_value/vault[\"debt\"]\n \n if ratio <= vault[\"repay from\"]/100:\n #Algebra to get required collateral change to reach a target ratio\n collateral_change = (p*c + t*s*g - t*d - t*g)/(p - t*p + t*s*p)\n #If gas fee lower than 5% repay amount, convert extracted collateral and swap to repay debt\n if g < 0.05*p*collateral_change*(1-s)/(1.05 - 0.05*s) or ratio < 1.65:\n #Remove collateral\n vault[\"collateral\"] -= collateral_change\n #Convert collateral to DAI and substract from debt\n vault[\"debt\"] -= (1 - s)*(p*collateral_change - g)\n repaid = True\n\n return vault, repaid\n\ndef close(vault, eth_price):\n '''\n Given a vault (dictionary), returns the collateral that would be left by closing it using the collateral within the vault to repay the debt.\n\n Parameters: \n vault (dictionary): A dictionary representing an automated vault\n eth_price (float): A float representing the current price of ETH\n\n Returns: \n balance (float): The current vault's balance (what would be left after closing it)\n profit_in_collateral (float): The net profit of the vault, denominated in collateral. \n '''\n collateral_to_repay_debt = vault[\"debt\"]/eth_price\n balance = vault[\"collateral\"] - collateral_to_repay_debt\n profit_in_collateral = balance - vault[\"initial balance\"]\n\n return balance, profit_in_collateral","sub_path":"modules/cdp.py","file_name":"cdp.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"343783519","text":"\"\"\"\nAdd UUID column to dataset table\n\"\"\"\nfrom __future__ import print_function\n\nimport logging\n\nfrom sqlalchemy import Column, MetaData, Table\n\nfrom galaxy.model.custom_types import UUIDType\n\nlog = logging.getLogger(__name__)\ndataset_uuid_column = Column(\"uuid\", UUIDType, nullable=True)\n\n\ndef upgrade(migrate_engine):\n print(__doc__)\n metadata = MetaData()\n metadata.bind = migrate_engine\n metadata.reflect()\n\n # Add the uuid colum to the dataset table\n try:\n dataset_table = Table(\"dataset\", metadata, autoload=True)\n dataset_uuid_column.create(dataset_table)\n assert dataset_uuid_column is dataset_table.c.uuid\n except Exception:\n log.exception(\"Adding column 'uuid' to dataset table failed.\")\n\n\ndef downgrade(migrate_engine):\n metadata = MetaData()\n metadata.bind = migrate_engine\n metadata.reflect()\n\n # Drop the dataset table's uuid column.\n try:\n dataset_table = Table(\"dataset\", metadata, autoload=True)\n dataset_uuid = dataset_table.c.uuid\n dataset_uuid.drop()\n except Exception:\n log.exception(\"Dropping 'uuid' column from dataset table failed.\")\n","sub_path":"lib/galaxy/model/migrate/versions/0110_add_dataset_uuid.py","file_name":"0110_add_dataset_uuid.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"326171512","text":"from FFxivPythonTrigger.Logger import info\nfrom plugins.XivCraft.simulator import Manager\n\n\nclass Stage1:\n def __init__(self):\n self.count = 0\n\n def is_finished(self, craft, prev_skill=None):\n temp = craft.clone()\n temp.effects.clear()\n temp.status = Manager.mStatus.DEFAULT_STATUS()\n return temp.use_skill('制作').is_finished()\n\n def deal(self, craft, prev_skill=None):\n if prev_skill == '高速制作:fail':\n self.count += 1\n if self.count > 3 or craft.effects['内静'].param < 2 or craft.craft_round >= 20 or craft.current_cp < 300:\n return 'terminate'\n if craft.status == \"高效\":\n if not '掌握' in craft.effects: return '掌握'\n if craft.current_durability < 20: return '精修'\n if craft.status == \"高品质\":\n if craft.effects['内静'].param < 10 and craft.current_durability > 10:\n return '集中加工'\n return '秘诀'\n if craft.status == \"安定\":\n if craft.effects['内静'].param < 6 and craft.current_durability > 10:\n return '专心加工'\n for s in '制作','模范制作','高速制作':\n temp=craft.clone().use_skill(s)\n if temp.current_durability <= 0:\n return '精修'\n if self.is_finished(temp):\n if temp.is_finished():\n return '最终确认'\n else:\n return s\n if '崇敬' in craft.effects:\n return '高速制作'\n else:\n return '崇敬'\n","sub_path":"plugins/XivCraft/solvers/SkyBuilder23/Stage1.py","file_name":"Stage1.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116691649","text":"'''\nThis module us for utilty functions that take as input and / or return Container subclasses such as Index, Series, or Frame, and that need to be shared by multiple such Container classes.\n'''\n\nimport datetime\nimport typing as tp\nfrom collections import defaultdict\nfrom fractions import Fraction\nfrom functools import partial\nfrom itertools import zip_longest\n\nimport numpy as np\nfrom arraykit import column_2d_filter\nfrom arraykit import resolve_dtype_iter\nfrom numpy import char as npc\n\nfrom static_frame.core.container import ContainerOperand\nfrom static_frame.core.exception import AxisInvalid\nfrom static_frame.core.exception import ErrorInitIndex\nfrom static_frame.core.fill_value_auto import FillValueAuto\nfrom static_frame.core.rank import RankMethod\nfrom static_frame.core.rank import rank_1d\nfrom static_frame.core.util import BOOL_TYPES\nfrom static_frame.core.util import DEFAULT_SORT_KIND\nfrom static_frame.core.util import DTYPE_BOOL\nfrom static_frame.core.util import DTYPE_OBJECT\nfrom static_frame.core.util import DTYPE_STR\nfrom static_frame.core.util import DTYPE_STR_KINDS\nfrom static_frame.core.util import INT_TYPES\nfrom static_frame.core.util import NULL_SLICE\nfrom static_frame.core.util import STATIC_ATTR\nfrom static_frame.core.util import AnyCallable\nfrom static_frame.core.util import Bloc2DKeyType\nfrom static_frame.core.util import BoolOrBools\nfrom static_frame.core.util import DepthLevelSpecifier\nfrom static_frame.core.util import DtypeSpecifier\nfrom static_frame.core.util import DtypesSpecifier\nfrom static_frame.core.util import GetItemKeyType\nfrom static_frame.core.util import IndexConstructor\nfrom static_frame.core.util import IndexConstructors\nfrom static_frame.core.util import IndexInitializer\nfrom static_frame.core.util import ManyToOneType\nfrom static_frame.core.util import NameType\nfrom static_frame.core.util import UFunc\nfrom static_frame.core.util import WarningsSilent\nfrom static_frame.core.util import concat_resolved\nfrom static_frame.core.util import is_dtype_specifier\nfrom static_frame.core.util import is_mapping\nfrom static_frame.core.util import iterable_to_array_1d\nfrom static_frame.core.util import iterable_to_array_2d\nfrom static_frame.core.util import slice_to_ascending_slice\nfrom static_frame.core.util import ufunc_set_iter\nfrom static_frame.core.util import ufunc_unique1d\nfrom static_frame.core.util import ufunc_unique2d\n\nif tp.TYPE_CHECKING:\n import pandas as pd # pylint: disable=W0611 #pragma: no cover\n\n from static_frame.core.frame import Frame # pylint: disable=W0611,C0412 #pragma: no cover\n # from static_frame.core.index_auto import IndexDefaultFactory #pylint: disable=W0611,C0412 #pragma: no\n from static_frame.core.index_auto import IndexAutoFactory # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.index_auto import IndexAutoFactoryType # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.index_auto import IndexConstructorFactoryBase # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.index_auto import IndexInitOrAutoType # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.index_base import IndexBase # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.index_hierarchy import IndexHierarchy # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.quilt import Quilt # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.series import Series # pylint: disable=W0611,C0412 #pragma: no cover\n from static_frame.core.type_blocks import TypeBlocks # pylint: disable=W0611,C0412 #pragma: no cover\n\n\nExplicitConstructor = tp.Union[\n IndexConstructor,\n 'IndexConstructorFactoryBase',\n tp.Type['IndexConstructorFactoryBase'],\n None,\n ]\n\nFILL_VALUE_AUTO_DEFAULT = FillValueAuto.from_default()\n\nclass ContainerMap:\n\n _map: tp.Optional[tp.Dict[str, tp.Type[ContainerOperand]]] = None\n\n @classmethod\n def _update_map(cls) -> None:\n from static_frame.core.batch import Batch\n from static_frame.core.bus import Bus\n from static_frame.core.fill_value_auto import FillValueAuto # pylint: disable=W0404\n from static_frame.core.frame import Frame\n from static_frame.core.frame import FrameGO\n from static_frame.core.frame import FrameHE\n # not containers but neede for build_example.py\n from static_frame.core.hloc import HLoc\n from static_frame.core.index import ILoc\n from static_frame.core.index import Index\n from static_frame.core.index import IndexGO\n from static_frame.core.index_datetime import IndexDate\n from static_frame.core.index_datetime import IndexDateGO\n from static_frame.core.index_datetime import IndexHour\n from static_frame.core.index_datetime import IndexHourGO\n from static_frame.core.index_datetime import IndexMicrosecond\n from static_frame.core.index_datetime import IndexMicrosecondGO\n from static_frame.core.index_datetime import IndexMillisecond\n from static_frame.core.index_datetime import IndexMillisecondGO\n from static_frame.core.index_datetime import IndexMinute\n from static_frame.core.index_datetime import IndexMinuteGO\n from static_frame.core.index_datetime import IndexNanosecond\n from static_frame.core.index_datetime import IndexNanosecondGO\n from static_frame.core.index_datetime import IndexSecond\n from static_frame.core.index_datetime import IndexSecondGO\n from static_frame.core.index_datetime import IndexYear\n from static_frame.core.index_datetime import IndexYearGO\n from static_frame.core.index_datetime import IndexYearMonth\n from static_frame.core.index_datetime import IndexYearMonthGO\n from static_frame.core.index_hierarchy import IndexHierarchy\n from static_frame.core.index_hierarchy import IndexHierarchyGO\n from static_frame.core.memory_measure import MemoryDisplay\n from static_frame.core.quilt import Quilt\n from static_frame.core.series import Series\n from static_frame.core.series import SeriesHE\n from static_frame.core.yarn import Yarn\n\n cls._map = {k: v for k, v in locals().items() if v is not cls}\n\n @classmethod\n def str_to_cls(cls, name: str) -> tp.Type[ContainerOperand]:\n if cls._map is None:\n cls._update_map()\n return cls._map[name] #type: ignore #pylint: disable=unsubscriptable-object\n\ndef get_col_dtype_factory(\n dtypes: DtypesSpecifier,\n columns: tp.Optional[tp.Sequence[tp.Hashable]],\n ) -> tp.Callable[[int], DtypeSpecifier]:\n '''\n Return a function, or None, to get values from a DtypeSpecifier by integer column positions.\n\n Args:\n columns: In common usage in Frame constructors, ``columns`` is a reference to a mutable list that is assigned column labels when processing data (and before this function is called). Columns can also be an ``Index``.\n '''\n # dtypes are either a dtype initializer, mappable by name, or an ordered sequence\n # NOTE: might verify that all keys in dtypes are in columns, though that might be slow\n\n if is_mapping(dtypes):\n is_map = True\n is_element = False\n elif is_dtype_specifier(dtypes):\n is_map = False\n is_element = True\n else: # an iterable of types\n is_map = False\n is_element = False\n\n if columns is None and is_map:\n raise RuntimeError('cannot lookup dtypes by name without supplied columns labels')\n\n def get_col_dtype(col_idx: int) -> DtypeSpecifier:\n nonlocal dtypes # might mutate a generator into a tuple\n if is_element:\n return dtypes\n if is_map:\n # mappings can be incomplete\n return dtypes.get(columns[col_idx], None) #type: ignore\n # NOTE: dtypes might be a generator deferred until this function is called; if so, realize here; INVALID_ITERABLE_FOR_ARRAY (dict_values, etc) do not have __getitem__,\n if not hasattr(dtypes, '__len__') or not hasattr(dtypes, '__getitem__'):\n dtypes = tuple(dtypes) #type: ignore\n return dtypes[col_idx] #type: ignore\n\n return get_col_dtype\n\n\ndef get_col_fill_value_factory(\n fill_value: tp.Any,\n columns: tp.Optional[tp.Sequence[tp.Hashable]],\n ) -> tp.Callable[[int, np.dtype], tp.Any]:\n '''\n Return a function to get fill_vlaue.\n\n Args:\n columns: In common usage in Frame constructors, ``columns`` is a reference to a mutable list that is assigned column labels when processing data (and before this function is called). Columns can also be an ``Index``.\n '''\n # if all false it is an iterable\n is_fva = False\n is_map = False\n is_element = False\n\n if fill_value is FillValueAuto:\n is_fva = True\n fill_value = FILL_VALUE_AUTO_DEFAULT\n elif is_mapping(fill_value):\n is_map = True\n elif fill_value.__class__ is np.ndarray: # tuple is an element\n if fill_value.ndim > 1:\n raise ValueError('Fill values must be one-dimensional arrays.')\n elif isinstance(fill_value, tuple): # tuple is an element\n is_element = True\n elif hasattr(fill_value, '__iter__') and not isinstance(fill_value, str):\n # an iterable or iterator but not a string\n pass\n elif isinstance(fill_value, FillValueAuto):\n is_fva = True\n else: # can assume an element\n is_element = True\n\n if columns is None and is_map:\n raise RuntimeError('cannot lookup fill_value by name without supplied columns labels')\n\n def get_col_fill_value(col_idx: int, dtype: tp.Optional[np.dtype]) -> tp.Any:\n '''dtype can be used for automatic selection based on dtype kind\n '''\n nonlocal fill_value # might mutate a generator into a tuple\n if is_fva and dtype is not None: # use the mapping from dtype\n return fill_value[dtype]\n if is_fva and dtype is None:\n raise RuntimeError('Cannot use a FillValueAuto in a context where new blocks are being created.')\n if is_element:\n return fill_value\n if is_map:\n return fill_value.get(columns[col_idx], np.nan) #type: ignore\n # NOTE: the types trying to select here could be more explicit\n if not hasattr(fill_value, '__len__') or not hasattr(fill_value, '__getitem__'):\n fill_value = tuple(fill_value)\n return fill_value[col_idx]\n\n return get_col_fill_value\n\n\ndef is_element(value: tp.Any, container_is_element: bool = False) -> bool:\n '''\n Args:\n container_is_element: Boolean to show if SF containers are treated as elements.\n '''\n if isinstance(value, str) or isinstance(value, tuple):\n return True\n if container_is_element and isinstance(value, ContainerOperand):\n return True\n return not hasattr(value, '__iter__')\n\ndef is_fill_value_factory_initializer(value: tp.Any) -> bool:\n # NOTE: in the context of a fill-value, we will not accept SF containers for now; a Series might be used as a mapping, but more clear to just force that to be converted to a dict\n return (not is_element(value, container_is_element=True)\n or value is FillValueAuto\n or isinstance(value, FillValueAuto)\n )\n\ndef is_static(value: IndexConstructor) -> bool:\n try:\n # if this is a class constructor\n return getattr(value, STATIC_ATTR) #type: ignore\n except AttributeError:\n pass\n # assume this is a class method\n return getattr(value.__self__, STATIC_ATTR) #type: ignore\n\n\ndef pandas_version_under_1() -> bool:\n import pandas\n return not hasattr(pandas, 'NA') # object introduced in 1.0\n\ndef pandas_to_numpy(\n container: tp.Union['pd.Index', 'pd.Series', 'pd.DataFrame'],\n own_data: bool,\n fill_value: tp.Any = np.nan\n ) -> np.ndarray:\n '''Convert Pandas container to a numpy array in pandas 1.0, where we might have Pandas extension dtypes that may have pd.NA. If no pd.NA, can go back to numpy types.\n\n If coming from a Pandas extension type, will convert pd.NA to `fill_value` in the resulting object array. For object dtypes, pd.NA may pass on into SF; the only way to find them is an expensive iteration and `is` comparison, which we are not sure we want to do at this time.\n\n Args:\n fill_value: if replcaing pd.NA, what to replace it with. Ultimately, this can use FillValueAuto to avoid going to object in all cases.\n '''\n # NOTE: only to be used with pandas 1.0 and greater\n\n if container.ndim == 1: # Series, Index\n dtype_src = container.dtype\n ndim = 1\n elif container.ndim == 2: # DataFrame, assume contiguous dtypes\n dtypes = container.dtypes.unique()\n assert len(dtypes) == 1\n dtype_src = dtypes[0]\n ndim = 2\n else:\n raise NotImplementedError(f'no handling for ndim {container.ndim}') #pragma: no cover\n\n if isinstance(dtype_src, np.dtype):\n dtype = dtype_src\n is_extension_dtype = False\n elif hasattr(dtype_src, 'numpy_dtype'):\n # only int, uint dtypes have this attribute\n dtype = dtype_src.numpy_dtype\n is_extension_dtype = True\n else:\n dtype = None # resolve below\n is_extension_dtype = True\n\n if is_extension_dtype:\n isna = container.isna() # returns a NumPy Boolean type sometimes\n if not isinstance(isna, np.ndarray):\n isna = isna.values\n hasna = isna.any() # will work for ndim 1 and 2\n\n from pandas import BooleanDtype # pylint: disable=E0611\n from pandas import StringDtype # pylint: disable=E0611\n\n # from pandas import DatetimeTZDtype\n # from pandas import Int8Dtype\n # from pandas import Int16Dtype\n # from pandas import Int32Dtype\n # from pandas import Int64Dtype\n # from pandas import UInt16Dtype\n # from pandas import UInt32Dtype\n # from pandas import UInt64Dtype\n # from pandas import UInt8Dtype\n\n if isinstance(dtype_src, BooleanDtype):\n dtype = DTYPE_OBJECT if hasna else DTYPE_BOOL\n elif isinstance(dtype_src, StringDtype):\n # trying to use a dtype argument for strings results in a converting pd.NA to a string ''\n dtype = DTYPE_OBJECT if hasna else DTYPE_STR\n else:\n # if an extension type and it hasna, have to go to object; otherwise, set to None or the dtype obtained above\n dtype = DTYPE_OBJECT if hasna else dtype\n\n # NOTE: in some cases passing the dtype might raise an exception, but it appears we are handling all of those cases by looking at hasna and selecting an object dtype\n array = container.to_numpy(copy=not own_data, dtype=dtype)\n\n if hasna:\n # if hasna and extension dtype, should be an object array; replace pd.NA objects with fill_value (np.nan)\n assert array.dtype == DTYPE_OBJECT\n array[isna] = fill_value\n\n else: # not an extension dtype\n if own_data:\n array = container.values\n else:\n array = container.values.copy()\n\n array.flags.writeable = False\n return array\n\ndef df_slice_to_arrays(*,\n part: 'pd.DataFrame',\n column_ilocs: range,\n get_col_dtype: tp.Optional[tp.Callable[[int], np.dtype]],\n pdvu1: bool,\n own_data: bool,\n ) -> tp.Iterator[np.ndarray]:\n '''\n Given a slice of a DataFrame, extract an array and optionally convert dtypes. If dtypes are provided, they are read with iloc positions given by `columns_ilocs`.\n '''\n if pdvu1:\n array = part.values\n if own_data:\n array.flags.writeable = False\n else:\n array = pandas_to_numpy(part, own_data=own_data)\n\n if get_col_dtype:\n assert len(column_ilocs) == array.shape[1]\n for col, iloc in enumerate(column_ilocs):\n # use iloc to get dtype\n dtype = get_col_dtype(iloc)\n if dtype is None or dtype == array.dtype:\n yield array[NULL_SLICE, col]\n else:\n yield array[NULL_SLICE, col].astype(dtype)\n else:\n yield array\n\n#---------------------------------------------------------------------------\ndef index_from_optional_constructor(\n value: 'IndexInitOrAutoType',\n *,\n default_constructor: IndexConstructor,\n explicit_constructor: ExplicitConstructor = None,\n ) -> 'IndexBase':\n '''\n Given a value that is an IndexInitializer (which means it might be an Index), determine if that value is really an Index, and if so, determine if a copy has to be made; otherwise, use the default_constructor. If an explicit_constructor is given, that is always used.\n '''\n # NOTE: this might return an own_index flag to show callers when a new index has been created\n # NOTE: do not pass `name` here; instead, partial contstuctors if necessary\n from static_frame.core.index_auto import IndexAutoConstructorFactory\n from static_frame.core.index_auto import IndexAutoFactory\n from static_frame.core.index_auto import IndexConstructorFactoryBase\n from static_frame.core.index_base import IndexBase\n\n if isinstance(value, IndexAutoFactory):\n return value.to_index(\n default_constructor=default_constructor,\n explicit_constructor=explicit_constructor,\n )\n\n if explicit_constructor:\n if isinstance(explicit_constructor, IndexConstructorFactoryBase):\n return explicit_constructor(value,\n default_constructor=default_constructor,\n )\n elif explicit_constructor is IndexAutoConstructorFactory:\n # handle class-only case; get constructor, then call with values\n return explicit_constructor.to_index(value, # type: ignore\n default_constructor=default_constructor,\n )\n return explicit_constructor(value) #type: ignore\n\n # default constructor could be a function with a STATIC attribute\n if isinstance(value, IndexBase):\n # if default is STATIC, and value is not STATIC, get an immutable\n if is_static(default_constructor):\n if not value.STATIC:\n # v: ~S, dc: S, use immutable alternative\n return value._IMMUTABLE_CONSTRUCTOR(value)\n # v: S, dc: S, both immutable\n return value\n else: # default constructor is mutable\n if not value.STATIC:\n # v: ~S, dc: ~S, both are mutable\n return value.copy()\n # v: S, dc: ~S, return a mutable version of something that is not mutable\n return value._MUTABLE_CONSTRUCTOR(value)\n\n # cannot always determine static status from constructors; fallback on using default constructor\n return default_constructor(value)\n\ndef constructor_from_optional_constructor(\n default_constructor: IndexConstructor,\n explicit_constructor: ExplicitConstructor = None,\n ) -> IndexConstructor:\n '''Return a constructor, resolving default and explicit constructor .\n '''\n def func(\n value: tp.Union[np.ndarray, tp.Iterable[tp.Hashable]],\n ) -> 'IndexBase':\n return index_from_optional_constructor(value,\n default_constructor=default_constructor,\n explicit_constructor=explicit_constructor,\n )\n return func\n\ndef index_from_optional_constructors(\n value: tp.Union[np.ndarray, tp.Iterable[tp.Hashable]],\n *,\n depth: int,\n default_constructor: IndexConstructor,\n explicit_constructors: IndexConstructors = None,\n ) -> tp.Tuple[tp.Optional['IndexBase'], bool]:\n '''For scenarios here `index_depth` is the primary way of specifying index creation from a data source and the returned index might be an `IndexHierarchy`. Note that we do not take `name` or `continuation_token` here, but expect constructors to be appropriately partialed.\n '''\n if depth == 0:\n index = None\n own_index = False\n elif depth == 1:\n if not explicit_constructors:\n explicit_constructor = None\n elif callable(explicit_constructors):\n explicit_constructor = explicit_constructors\n else:\n if len(explicit_constructors) != 1:\n raise RuntimeError('Cannot specify multiple index constructors for depth 1 indicies.')\n explicit_constructor = explicit_constructors[0]\n\n index = index_from_optional_constructor(\n value,\n default_constructor=default_constructor,\n explicit_constructor=explicit_constructor,\n )\n own_index = True\n else:\n # if depth is > 1, the default constructor is expected to be an IndexHierarchy, and explicit constructors are optionally provided `index_constructors`\n if callable(explicit_constructors):\n explicit_constructors = [explicit_constructors] * depth\n # default_constructor is an IH type\n index = default_constructor(\n value,\n index_constructors=explicit_constructors\n )\n own_index = True\n return index, own_index\n\ndef constructor_from_optional_constructors(\n *,\n depth: int,\n default_constructor: IndexConstructor,\n explicit_constructors: IndexConstructors = None,\n ) -> tp.Callable[\n [tp.Union[np.ndarray, tp.Iterable[tp.Hashable]]],\n tp.Optional['IndexBase']]:\n '''\n Partial `index_from_optional_constructors` for all args except `value`; only return the Index, ignoring the own_index Boolean.\n '''\n def func(\n value: tp.Union[np.ndarray, tp.Iterable[tp.Hashable]],\n ) -> tp.Optional['IndexBase']:\n # drop the own_index Boolean\n index, _ = index_from_optional_constructors(value,\n depth=depth,\n default_constructor=default_constructor,\n explicit_constructors=explicit_constructors,\n )\n return index\n return func\n\n\ndef index_constructor_empty(\n index: 'IndexInitOrAutoType',\n ) -> bool:\n '''\n Determine if an index is empty (if possible) or an IndexAutoFactory.\n '''\n from static_frame.core.index_auto import IndexAutoFactory\n from static_frame.core.index_base import IndexBase\n\n if index is None or index is IndexAutoFactory:\n return True\n elif (not isinstance(index, IndexBase)\n and hasattr(index, '__len__')\n and len(index) == 0 #type: ignore\n ):\n return True\n return False\n\n#---------------------------------------------------------------------------\ndef matmul(\n lhs: tp.Union['Series', 'Frame', np.ndarray, tp.Sequence[float]],\n rhs: tp.Union['Series', 'Frame', np.ndarray, tp.Sequence[float]],\n ) -> tp.Any: #tp.Union['Series', 'Frame']:\n '''\n Implementation of matrix multiplication for Series and Frame\n '''\n from static_frame.core.frame import Frame\n from static_frame.core.series import Series\n\n # for a @ b = c\n # if a is 2D: a.columns must align b.index\n # if b is 1D, a.columns bust align with b.index\n # if a is 1D: len(a) == b.index (len of b), returns w columns of B\n\n if not isinstance(rhs, (np.ndarray, Series, Frame)):\n # try to make it into an array\n rhs = np.array(rhs)\n\n if not isinstance(lhs, (np.ndarray, Series, Frame)):\n # try to make it into an array\n lhs = np.array(lhs)\n\n if isinstance(lhs, np.ndarray):\n lhs_type = np.ndarray\n elif isinstance(lhs, Series):\n lhs_type = Series\n else: # normalize subclasses\n lhs_type = Frame\n\n if isinstance(rhs, np.ndarray):\n rhs_type = np.ndarray\n elif isinstance(rhs, Series):\n rhs_type = Series\n else: # normalize subclasses\n rhs_type = Frame\n\n if rhs_type == np.ndarray and lhs_type == np.ndarray:\n return np.matmul(lhs, rhs)\n\n\n own_index = True\n constructor = None\n\n if lhs.ndim == 1: # Series, 1D array\n # result will be 1D or 0D\n columns = None\n\n if lhs_type == Series and (rhs_type == Series or rhs_type == Frame):\n aligned = lhs._index.union(rhs._index)\n # if the aligned shape is not the same size as the originals, we do not have the same values in each and cannot proceed (all values go to NaN)\n if len(aligned) != len(lhs._index) or len(aligned) != len(rhs._index):\n raise RuntimeError('shapes not alignable for matrix multiplication') #pragma: no cover\n\n if lhs_type == Series:\n if rhs_type == np.ndarray:\n if lhs.shape[0] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = rhs.ndim - 1 # if 2D, result is 1D, of 1D, result is 0\n left = lhs.values\n right = rhs # already np\n if ndim == 1:\n index = None # force auto increment integer\n own_index = False\n constructor = lhs.__class__\n elif rhs_type == Series:\n ndim = 0\n left = lhs.reindex(aligned).values\n right = rhs.reindex(aligned).values\n else: # rhs is Frame\n ndim = 1\n left = lhs.reindex(aligned).values\n right = rhs.reindex(index=aligned).values\n index = rhs._columns\n constructor = lhs.__class__\n else: # lhs is 1D array\n left = lhs\n right = rhs.values\n if rhs_type == Series:\n ndim = 0\n else: # rhs is Frame, len(lhs) == len(rhs.index)\n ndim = 1\n index = rhs._columns\n constructor = Series # cannot get from argument\n\n elif lhs.ndim == 2: # Frame, 2D array\n\n if lhs_type == Frame and (rhs_type == Series or rhs_type == Frame):\n aligned = lhs._columns.union(rhs._index)\n # if the aligned shape is not the same size as the originals, we do not have the same values in each and cannot proceed (all values go to NaN)\n if len(aligned) != len(lhs._columns) or len(aligned) != len(rhs._index):\n raise RuntimeError('shapes not alignable for matrix multiplication')\n\n if lhs_type == Frame:\n if rhs_type == np.ndarray:\n if lhs.shape[1] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = rhs.ndim\n left = lhs.values\n right = rhs # already np\n index = lhs._index\n\n if ndim == 1:\n constructor = Series\n else:\n constructor = lhs.__class__\n columns = None # force auto increment index\n elif rhs_type == Series:\n # a.columns must align with b.index\n ndim = 1\n left = lhs.reindex(columns=aligned).values\n right = rhs.reindex(aligned).values\n index = lhs._index # this axis is not changed\n constructor = rhs.__class__\n else: # rhs is Frame\n # a.columns must align with b.index\n ndim = 2\n left = lhs.reindex(columns=aligned).values\n right = rhs.reindex(index=aligned).values\n index = lhs._index\n columns = rhs._columns\n constructor = lhs.__class__ # give left precedence\n else: # lhs is 2D array\n left = lhs\n right = rhs.values\n if rhs_type == Series: # returns unindexed Series\n ndim = 1\n index = None\n own_index = False\n constructor = rhs.__class__\n else: # rhs is Frame, lhs.shape[1] == rhs.shape[0]\n if lhs.shape[1] != rhs.shape[0]: # works for 1D and 2D\n raise RuntimeError('shapes not alignable for matrix multiplication')\n ndim = 2\n index = None\n own_index = False\n columns = rhs._columns\n constructor = rhs.__class__\n else:\n raise NotImplementedError(f'no handling for {lhs}')\n\n # NOTE: np.matmul is not the same as np.dot for some arguments\n data = np.matmul(left, right)\n\n if ndim == 0:\n return data\n\n assert constructor is not None\n\n data.flags.writeable = False\n if ndim == 1:\n return constructor(data,\n index=index,\n own_index=own_index,\n )\n return constructor(data,\n index=index,\n own_index=own_index,\n columns=columns\n )\n\n\ndef axis_window_items( *,\n source: tp.Union['Series', 'Frame', 'Quilt'],\n size: int,\n axis: int = 0,\n step: int = 1,\n window_sized: bool = True,\n window_func: tp.Optional[AnyCallable] = None,\n window_valid: tp.Optional[AnyCallable] = None,\n label_shift: int = 0,\n start_shift: int = 0,\n size_increment: int = 0,\n as_array: bool = False,\n ) -> tp.Iterator[tp.Tuple[tp.Hashable, tp.Any]]:\n '''Generator of index, window pairs. When ndim is 2, axis 0 returns windows of rows, axis 1 returns windows of columns.\n\n Args:\n as_array: if True, the window is returned as an array instead of a SF object.\n '''\n # see doc_str window for docs\n\n from static_frame.core.frame import Frame\n from static_frame.core.quilt import Quilt\n from static_frame.core.series import Series\n\n if size <= 0:\n raise RuntimeError('window size must be greater than 0')\n if step < 0:\n raise RuntimeError('window step cannot be less than than 0')\n\n source_ndim = source.ndim\n values: tp.Optional[np.ndarray] = None\n\n if source_ndim == 1:\n assert isinstance(source, Series) # for mypy\n labels = source._index\n if as_array:\n values = source.values\n else:\n labels = source._index if axis == 0 else source._columns #type: ignore\n\n if isinstance(source, Frame) and axis == 0 and as_array:\n # for a Frame, when collecting rows, it is more efficient to pre-consolidate blocks prior to slicing. Note that this results in the same block coercion necessary for each window (which is not the same for axis 1, where block coercion is not required)\n values = source._blocks.values\n\n if start_shift >= 0:\n count_window_max = len(labels)\n else: # add for iterations when less than 0\n count_window_max = len(labels) + abs(start_shift)\n\n idx_left_max = count_window_max - 1\n idx_left = start_shift\n count = 0\n\n while True:\n # idx_left, size can change over iterations\n idx_right = idx_left + size - 1\n\n # floor idx_left at 0 so as to not wrap\n idx_left_floored = idx_left if idx_left > 0 else 0\n idx_right_floored = idx_right if idx_right > -1 else -1 # will add one\n\n key = slice(idx_left_floored, idx_right_floored + 1)\n\n if source_ndim == 1:\n if as_array:\n window = values[key] #type: ignore\n else:\n window = source._extract_iloc(key)\n else:\n if axis == 0: # extract rows\n if as_array and values is not None:\n window = values[key]\n elif as_array:\n window = source._extract_array(key) #type: ignore\n else: # use low level iloc selector\n window = source._extract(row_key=key) #type: ignore\n else: # extract columns\n if as_array:\n window = source._extract_array(NULL_SLICE, key) #type: ignore\n else:\n window = source._extract(column_key=key) #type: ignore\n\n valid = True\n try:\n idx_label = idx_right + label_shift\n if idx_label < 0: # do not wrap around\n raise IndexError()\n #if we cannot get a label, the window is invalid\n label = labels.iloc[idx_label]\n except IndexError: # an invalid label has to be dropped\n valid = False\n\n if valid and window_sized and window.shape[axis] != size:\n valid = False\n if valid and window_valid and not window_valid(window):\n valid = False\n\n if valid:\n if window_func:\n window = window_func(window)\n yield label, window\n\n idx_left += step\n size += size_increment\n count += 1\n\n if count > count_window_max or idx_left > idx_left_max or size < 0:\n break\n\ndef get_block_match(\n width: int,\n values_source: tp.List[np.ndarray],\n ) -> tp.Iterator[np.ndarray]:\n '''Utility method for assignment. Draw from values to provide as many columns as specified by width. Use `values_source` as a stack to draw and replace values.\n '''\n # see clip().get_block_match() for one example of drawing values from another sequence of blocks, where we take blocks and slices from blocks using a list as a stack\n\n if width == 1: # no loop necessary\n v = values_source.pop()\n if v.ndim == 1:\n yield v\n else: # ndim == 2\n if v.shape[1] > 1: # more than one column\n # restore remained to values source\n values_source.append(v[NULL_SLICE, 1:])\n yield v[NULL_SLICE, 0]\n else:\n width_found = 0\n while width_found < width:\n v = values_source.pop()\n if v.ndim == 1:\n yield v\n width_found += 1\n continue\n # ndim == 2\n width_v = v.shape[1]\n width_needed = width - width_found\n if width_v <= width_needed:\n yield v\n width_found += width_v\n continue\n # width_v > width_needed\n values_source.append(v[NULL_SLICE, width_needed:])\n yield v[NULL_SLICE, :width_needed]\n break\n\ndef bloc_key_normalize(\n key: Bloc2DKeyType,\n container: 'Frame'\n ) -> np.ndarray:\n '''\n Normalize and validate a bloc key. Return a same sized Boolean array.\n '''\n from static_frame.core.frame import Frame\n\n if isinstance(key, Frame):\n bloc_frame = key.reindex(\n index=container._index,\n columns=container._columns,\n fill_value=False\n )\n bloc_key = bloc_frame.values # shape must match post reindex\n elif key.__class__ is np.ndarray:\n bloc_key = key\n if bloc_key.shape != container.shape:\n raise RuntimeError(f'bloc {bloc_key.shape} must match shape {container.shape}')\n else:\n raise RuntimeError(f'invalid bloc_key, must be Frame or array, not {key}')\n\n if not bloc_key.dtype == bool:\n raise RuntimeError('cannot use non-Boolean dtype as bloc key')\n\n return bloc_key\n\n\ndef key_to_ascending_key(key: GetItemKeyType, size: int) -> GetItemKeyType:\n '''\n Normalize all types of keys into an ascending formation.\n\n Args:\n size: the length of the container on this axis\n '''\n from static_frame.core.frame import Frame\n from static_frame.core.series import Series\n\n if key.__class__ is slice:\n return slice_to_ascending_slice(key, size=size) #type: ignore\n\n if isinstance(key, str) or not hasattr(key, '__len__'):\n return key\n\n if key.__class__ is np.ndarray:\n # array first as not truthy\n if key.dtype == bool: #type: ignore\n return key\n return np.sort(key, kind=DEFAULT_SORT_KIND)\n\n if not len(key): #type: ignore\n return key\n\n if isinstance(key, list):\n return sorted(key)\n\n if isinstance(key, Series):\n return key.sort_index()\n\n if isinstance(key, Frame):\n # for usage in assignment we need columns to be sorted\n return key.sort_columns()\n\n raise RuntimeError(f'unhandled key {key}')\n\n\ndef rehierarch_from_type_blocks(*,\n labels: 'TypeBlocks',\n depth_map: tp.Sequence[int],\n ) -> tp.Tuple['TypeBlocks', np.ndarray]:\n '''\n Given labels suitable for a hierarchical index, order them into a hierarchy using the given depth_map.\n\n Args:\n index_cls: provide a class, from which the constructor will be called.\n '''\n\n depth = labels.shape[1] # number of columns\n\n if depth != len(depth_map):\n raise RuntimeError('must specify new depths for all depths')\n if set(range(depth)) != set(depth_map):\n raise RuntimeError('all depths must be specified')\n\n labels_post = labels._extract(row_key=NULL_SLICE, column_key=list(depth_map))\n labels_sort = np.full(labels_post.shape, 0)\n\n # get ordering of values found in each level\n order: tp.List[tp.Dict[tp.Hashable, int]] = [defaultdict(int) for _ in range(depth)]\n\n for (idx_row, idx_col), label in labels.element_items():\n if label not in order[idx_col]:\n # Map label to an integer representing the observed order.\n order[idx_col][label] = len(order[idx_col])\n # Fill array for sorting based on observed order.\n labels_sort[idx_row, idx_col] = order[idx_col][label]\n\n # Reverse depth_map for lexical sorting, which sorts by rightmost column first.\n order_lex = np.lexsort(\n [labels_sort[NULL_SLICE, i] for i in reversed(depth_map)])\n\n labels_post = labels_post._extract(row_key=order_lex)\n\n return labels_post, order_lex\n\n\ndef rehierarch_from_index_hierarchy(*,\n labels: 'IndexHierarchy',\n depth_map: tp.Sequence[int],\n index_constructors: IndexConstructors = None,\n name: tp.Optional[tp.Hashable] = None,\n ) -> tp.Tuple['IndexBase', np.ndarray]:\n '''\n Alternate interface that updates IndexHierarchy cache before rehierarch.\n '''\n if labels._recache:\n labels._update_array_cache()\n\n rehierarched_blocks, index_iloc = rehierarch_from_type_blocks(\n labels=labels._blocks,\n depth_map=depth_map,\n )\n\n return labels.__class__._from_type_blocks(\n blocks=rehierarched_blocks,\n index_constructors=index_constructors,\n name=name,\n ), index_iloc\n\ndef array_from_value_iter(\n key: tp.Hashable,\n idx: int,\n get_value_iter: tp.Callable[[tp.Hashable, int], tp.Iterator[tp.Any]],\n get_col_dtype: tp.Optional[tp.Callable[[int], np.dtype]],\n row_count: int,\n ) -> np.ndarray:\n '''\n Return a single array given keys and collections.\n\n Args:\n get_value_iter: Iterator of a values\n dtypes: if an\n key: hashable for looking up field in `get_value_iter`.\n idx: integer position to extract from dtypes\n '''\n # for each column, try to get a dtype, or None\n # if this value is None we cannot tell if it was explicitly None or just was not specified\n dtype = None if get_col_dtype is None else get_col_dtype(idx)\n\n # NOTE: shown to be faster to try fromiter in some performance tests\n # values, _ = iterable_to_array_1d(get_value_iter(key), dtype=dtype)\n\n values = None\n if dtype is not None:\n try:\n values = np.fromiter(\n get_value_iter(key, idx),\n count=row_count,\n dtype=dtype)\n values.flags.writeable = False\n except (ValueError, TypeError):\n # the dtype may not be compatible, so must fall back on using np.array to determine the type, i.e., ValueError: cannot convert float NaN to integer\n pass\n if values is None:\n # returns an immutable array\n values, _ = iterable_to_array_1d(\n get_value_iter(key, idx),\n dtype=dtype\n )\n return values\n\n#-------------------------------------------------------------------------------\n# utilities for binary operator applications with type blocks\n\ndef apply_binary_operator(*,\n values: np.ndarray,\n other: tp.Any,\n other_is_array: bool,\n operator: UFunc,\n ) -> np.ndarray:\n '''\n Utility to handle binary operator application.\n '''\n if (values.dtype.kind in DTYPE_STR_KINDS or\n (other_is_array and other.dtype.kind in DTYPE_STR_KINDS)):\n operator_name = operator.__name__\n\n if operator_name == 'add':\n result = npc.add(values, other)\n elif operator_name == 'radd':\n result = npc.add(other, values)\n elif operator_name == 'mul' or operator_name == 'rmul':\n result = npc.multiply(values, other)\n else:\n with WarningsSilent():\n result = operator(values, other)\n else:\n with WarningsSilent():\n # FutureWarning: elementwise comparison failed\n result = operator(values, other)\n\n if result is False or result is True:\n if not other_is_array and (\n isinstance(other, str) or not hasattr(other, '__len__')\n ):\n # only expand to the size of the array operand if we are comparing to an element\n result = np.full(values.shape, result, dtype=DTYPE_BOOL)\n elif other_is_array and other.size == 1:\n # elements in arrays of 0 or more dimensions are acceptable; this is what NP does for arithmetic operators when the types are compatible\n result = np.full(values.shape, result, dtype=DTYPE_BOOL)\n else:\n raise ValueError('operands could not be broadcast together')\n # raise on unaligned shapes as is done for arithmetic operators\n\n result.flags.writeable = False\n return result\n\ndef apply_binary_operator_blocks(*,\n values: tp.Iterable[np.ndarray],\n other: tp.Iterable[np.ndarray],\n operator: UFunc,\n apply_column_2d_filter: bool,\n ) -> tp.Iterator[np.ndarray]:\n '''\n Application from iterators of arrays, to iterators of arrays.\n '''\n if apply_column_2d_filter:\n values = (column_2d_filter(op) for op in values)\n other = (column_2d_filter(op) for op in other)\n\n for a, b in zip_longest(values, other):\n yield apply_binary_operator(\n values=a,\n other=b,\n other_is_array=True,\n operator=operator,\n )\n\ndef apply_binary_operator_blocks_columnar(*,\n values: tp.Iterable[np.ndarray],\n other: np.ndarray,\n operator: UFunc,\n ) -> tp.Iterator[np.ndarray]:\n '''\n Application from iterators of arrays, to iterators of arrays. Will return iterator of all 1D arrays, as we will break down larger blocks in values into 1D arrays.\n\n Args:\n other: 1D array to be applied to each column of the blocks.\n '''\n assert other.ndim == 1\n for block in values:\n if block.ndim == 1:\n yield apply_binary_operator(\n values=block,\n other=other,\n other_is_array=True,\n operator=operator,\n )\n else:\n for i in range(block.shape[1]):\n yield apply_binary_operator(\n values=block[NULL_SLICE, i],\n other=other,\n other_is_array=True,\n operator=operator,\n )\n\n#-------------------------------------------------------------------------------\n\ndef arrays_from_index_frame(\n container: 'Frame',\n depth_level: tp.Optional[DepthLevelSpecifier],\n columns: GetItemKeyType\n ) -> tp.Iterator[np.ndarray]:\n '''\n Given a Frame, return an iterator of index and / or columns as 1D or 2D arrays.\n '''\n if depth_level is not None:\n # NOTE: a 1D index of tuples will be taken as a 1D array of tuples; there is no obvious way to treat this as 2D array without guessing that we are trying to match an IndexHierarchy\n # NOTE: if a multi-column selection, might be better to yield one depth at a time\n yield container.index.values_at_depth(depth_level)\n if columns is not None:\n column_key = container.columns._loc_to_iloc(columns)\n yield from container._blocks._slice_blocks(column_key=column_key)\n\n\ndef key_from_container_key(\n index: 'IndexBase',\n key: GetItemKeyType,\n expand_iloc: bool = False,\n ) -> GetItemKeyType:\n '''\n Unpack selection values from another Index, Series, or ILoc selection.\n '''\n # PERF: do not do comparisons if key is not a Container or SF object\n if not hasattr(key, 'STATIC'):\n return key\n\n from static_frame.core.index import ILoc\n from static_frame.core.index import Index\n from static_frame.core.series import Series\n from static_frame.core.series import SeriesHE\n\n if isinstance(key, Index):\n # if an Index, we simply use the values of the index\n key = key.values\n elif isinstance(key, Series) and key.__class__ is not SeriesHE:\n # Series that are not hashable are unpacked into an array; SeriesHE can be used as a key\n if key.dtype == DTYPE_BOOL:\n # if a Boolean series, sort and reindex\n if not key.index.equals(index):\n key = key.reindex(index,\n fill_value=False,\n check_equals=False,\n ).values\n else: # the index is equal\n key = key.values\n else:\n # For all other Series types, we simply assume that the values are to be used as keys in the IH. This ignores the index, but it does not seem useful to require the Series, used like this, to have a matching index value, as the index and values would need to be identical to have the desired selection.\n key = key.values\n elif expand_iloc and key.__class__ is ILoc:\n # realize as Boolean array\n array = np.full(len(index), False)\n array[key.key] = True #type: ignore\n key = array\n\n # detect and fail on Frame?\n return key\n\n\n#---------------------------------------------------------------------------\nclass IMTOAdapterSeries:\n __slots__ = ('values',)\n\n def __init__(self, values: np.ndarray) -> None:\n self.values = values\n\nclass IMTOAdapter:\n '''Avoid creating a complete Index, and instead wrap an array and associated metadata into an adapter object that can be used in index_many_to_one\n '''\n __slots__ = (\n 'values',\n 'name',\n 'depth',\n 'ndim',\n 'index_types',\n 'dtypes',\n )\n\n _map = object() # not None\n\n def __init__(self,\n values: np.ndarray,\n name: NameType,\n depth: int,\n ndim: int,\n ):\n self.values = values\n self.name = name\n self.depth = depth\n self.ndim = ndim\n\n if self.ndim > 1:\n # simply provide None so as not to match in any comparison\n self.index_types = IMTOAdapterSeries(\n np.array([None for _ in range(depth)],\n dtype=DTYPE_OBJECT,\n ))\n self.dtypes = IMTOAdapterSeries(\n np.array([self.values.dtype for _ in range(depth)],\n dtype=DTYPE_OBJECT,\n ))\n\n def __len__(self) -> int:\n return len(self.values)\n\ndef imto_adapter_factory(\n source: tp.Union['IndexBase', tp.Iterable[tp.Hashable]],\n depth: int,\n name: NameType,\n ndim: int,\n ) -> tp.Union['IndexBase', IMTOAdapter]:\n '''\n Factory function to let `IndexBase` pass through while wrapping other iterables (after array conversion) into `IMTOAdapter`s, such that they can be evaluated with other `IndexBase` in `index_many_to_one`.\n\n Args:\n depth: provide depth of root caller.\n name: provide name of root caller.\n '''\n from static_frame.core.index_base import IndexBase\n\n if isinstance(source, IndexBase):\n return source\n\n if source.__class__ is np.ndarray:\n if ndim != source.ndim: # type: ignore\n raise ErrorInitIndex(\n f'Index must have ndim of {ndim}, not {source.ndim}' # type: ignore\n )\n array = source\n elif depth == 1:\n array, assume_unique = iterable_to_array_1d(source)\n if not assume_unique:\n array = ufunc_unique1d(array)\n else:\n array = iterable_to_array_2d(source)\n array = ufunc_unique2d(array, axis=0) # TODO: check axis\n\n return IMTOAdapter(array,\n name=name,\n depth=depth,\n ndim=ndim,\n )\n\n\ndef index_many_to_one(\n indices: tp.Iterable['IndexBase'],\n cls_default: tp.Type['IndexBase'],\n many_to_one_type: ManyToOneType,\n explicit_constructor: tp.Optional[IndexInitializer] = None,\n ) -> 'IndexBase':\n '''\n Given multiple Index objects, combine them. Preserve name and index type if aligned, and handle going to GO if the default class is GO.\n\n Args:\n indices: can be a generator\n cls_default: Default Index class to be used if no alignment of classes; also used to determine if result Index should be static or mutable.\n explicit_constructor: Alternative constructor that will override normal evaluation.\n '''\n from static_frame.core.index import Index\n from static_frame.core.index_auto import IndexAutoFactory\n\n array_processor: tp.Callable[[tp.Iterable[np.ndarray]], np.ndarray]\n mtot_is_concat = many_to_one_type is ManyToOneType.CONCAT\n\n if mtot_is_concat:\n array_processor = concat_resolved\n else:\n array_processor = partial(ufunc_set_iter,\n many_to_one_type=many_to_one_type,\n assume_unique=True)\n\n indices_iter: tp.Iterable['IndexBase']\n if not mtot_is_concat and hasattr(indices, '__len__') and len(indices) == 2:\n # as the most common use case has only two indices given in a tuple, check for that and expose optimized exits\n index, other = indices\n if index.equals(other,\n compare_dtype=True,\n compare_name=True,\n compare_class=True,\n ):\n # compare dtype as result should be resolved, even if values are the same\n if (many_to_one_type is ManyToOneType.UNION\n or many_to_one_type is ManyToOneType.INTERSECT):\n return index if index.STATIC else index.__deepcopy__({}) # type: ignore\n elif many_to_one_type is ManyToOneType.DIFFERENCE:\n return index.iloc[:0] # type: ignore\n indices_iter = (other,)\n else:\n indices_iter = iter(indices)\n try:\n index = next(indices_iter)\n except StopIteration:\n if explicit_constructor is not None:\n return explicit_constructor(()) #type: ignore\n return cls_default.from_labels(())\n\n name_first = index.name\n name_aligned = True\n cls_first = index.__class__\n cls_aligned = True\n depth_first = index.depth\n\n # if union/intersect, can give back an index_auto\n index_auto_aligned = (not mtot_is_concat\n and index.ndim == 1\n and index._map is None #type: ignore\n and many_to_one_type is not ManyToOneType.DIFFERENCE\n )\n\n # collect initial values from `index`\n if index.ndim == 2:\n is_ih = True\n index_types_arrays = [index.index_types.values]\n\n if not mtot_is_concat:\n if len(index) > 0: # only store these if the index has length\n index_dtypes_arrays = [index.dtypes.values] #type: ignore\n else:\n index_dtypes_arrays = []\n\n if mtot_is_concat:\n # store array for each depth; unpack aligned depths with zip\n arrays = [[index.values_at_depth(d) for d in range(depth_first)]]\n else: # NOTE: we accept type consolidation for set operations for now\n arrays = [index.values]\n else:\n is_ih = False\n arrays = [index.values]\n\n # iterate through all remaining indices\n for index in indices_iter:\n if index.depth != depth_first:\n raise ErrorInitIndex(f'Indices must have aligned depths: {depth_first}, {index.depth}')\n\n if mtot_is_concat and depth_first > 1:\n arrays.append([index.values_at_depth(d) for d in range(depth_first)])\n else:\n arrays.append(index.values)\n\n # Boolean checks that all turn off as soon as they go to false\n if name_aligned and index.name != name_first:\n name_aligned = False\n if cls_aligned and index.__class__ != cls_first:\n cls_aligned = False\n if index_auto_aligned and (index.ndim != 1 or index._map is not None): #type: ignore\n index_auto_aligned = False\n\n # is_ih can only be True if we have all IH of same depth\n if is_ih:\n index_types_arrays.append(index.index_types.values)\n if not mtot_is_concat and len(index) > 0:\n index_dtypes_arrays.append(index.dtypes.values) #type: ignore\n\n name = name_first if name_aligned else None\n\n # return an index auto if we can; already filtered out difference and concat\n if index_auto_aligned:\n if many_to_one_type is ManyToOneType.UNION:\n size = max(a.size for a in arrays) #type: ignore\n elif many_to_one_type is ManyToOneType.INTERSECT:\n size = min(a.size for a in arrays) #type: ignore\n return IndexAutoFactory(size, name=name).to_index(\n default_constructor=cls_default,\n explicit_constructor=explicit_constructor,\n )\n\n if cls_aligned and explicit_constructor is None:\n if cls_default.STATIC and not cls_first.STATIC:\n constructor_cls = cls_first._IMMUTABLE_CONSTRUCTOR\n elif not cls_default.STATIC and cls_first.STATIC:\n constructor_cls = cls_first._MUTABLE_CONSTRUCTOR\n else:\n constructor_cls = cls_first\n constructor = (constructor_cls.from_values_per_depth if is_ih # type: ignore\n else constructor_cls.from_labels) # type: ignore\n elif explicit_constructor is not None:\n constructor = explicit_constructor\n elif is_ih:\n constructor = cls_default.from_values_per_depth # type: ignore\n else:\n constructor = cls_default.from_labels\n\n if is_ih:\n # collect corresponding index constructor per depth position if they match; else, supply a simple Index\n index_constructors = []\n for types in zip(*index_types_arrays):\n if all(types[0] == t for t in types[1:]):\n index_constructors.append(types[0])\n else:\n index_constructors.append(Index)\n\n if mtot_is_concat: # concat same-depth collections of arrays\n arrays_per_depth = [array_processor(d) for d in zip(*arrays)]\n else:\n # NOTE: arrays is a list of 2D arrays, where rows are labels\n array = array_processor(arrays)\n arrays_per_depth = []\n for d, dtypes in enumerate(zip(*index_dtypes_arrays)):\n dtype = resolve_dtype_iter(dtypes)\n # we explicit retype after `array_processor` forced type consolidation\n a = array[NULL_SLICE, d].astype(dtype)\n a.flags.writeable = False\n arrays_per_depth.append(a)\n\n return constructor(arrays_per_depth, #type: ignore\n name=name,\n index_constructors=index_constructors,\n depth_reference=depth_first,\n )\n\n # returns an immutable array\n array = array_processor(arrays)\n return constructor(array, name=name) #type: ignore\n\ndef index_many_concat(\n indices: tp.Iterable['IndexBase'],\n cls_default: tp.Type['IndexBase'],\n explicit_constructor: tp.Optional[IndexConstructor] = None,\n ) -> tp.Optional['IndexBase']:\n return index_many_to_one(indices,\n cls_default,\n ManyToOneType.CONCAT,\n explicit_constructor,\n )\n\n#-------------------------------------------------------------------------------\ndef apex_to_name(\n rows: tp.Sequence[tp.Sequence[tp.Hashable]],\n depth_level: tp.Optional[DepthLevelSpecifier],\n axis: int, # 0 is by row (for index), 1 is by column (for columns)\n axis_depth: int,\n ) -> NameType:\n '''\n Utility for translating apex values (the upper left corner created be index/columns) in the appropriate name.\n '''\n if depth_level is None:\n return None\n if axis == 0:\n if isinstance(depth_level, INT_TYPES):\n row = rows[depth_level]\n if axis_depth == 1: # return a single label\n return row[0] if row[0] != '' else None\n else:\n return tuple(row)\n else: # its a list selection\n targets = [rows[level] for level in depth_level]\n # combine into tuples\n if axis_depth == 1:\n return next(zip(*targets))\n else:\n return tuple(zip(*targets))\n elif axis == 1:\n if isinstance(depth_level, INT_TYPES):\n # depth_level refers to position in inner row\n row = [r[depth_level] for r in rows]\n if axis_depth == 1: # return a single label\n return row[0] if row[0] != '' else None\n else:\n return tuple(row)\n else: # its a list selection\n targets = (tuple(row[level] for level in depth_level) for row in rows) #type: ignore\n # combine into tuples\n if axis_depth == 1:\n return next(targets) #type: ignore\n else:\n return tuple(targets)\n\n raise AxisInvalid(f'invalid axis: {axis}')\n\n\ndef container_to_exporter_attr(container_type: tp.Type['Frame']) -> str:\n from static_frame.core.frame import Frame\n from static_frame.core.frame import FrameGO\n from static_frame.core.frame import FrameHE\n\n if container_type is Frame:\n return 'to_frame'\n elif container_type is FrameGO:\n return 'to_frame_go'\n elif container_type is FrameHE:\n return 'to_frame_he'\n raise NotImplementedError(f'no handling for {container_type}')\n\ndef frame_to_frame(\n frame: 'Frame',\n container_type: tp.Type['Frame'],\n ) -> 'Frame':\n if frame.__class__ is container_type:\n return frame\n func = getattr(frame, container_to_exporter_attr(container_type))\n return func() # type: ignore\n\ndef prepare_values_for_lex(\n *,\n ascending: BoolOrBools = True,\n values_for_lex: tp.Optional[tp.Iterable[np.ndarray]],\n ) -> tp.Tuple[bool, tp.Optional[tp.Iterable[np.ndarray]]]:\n '''Prepare values for lexical sorting; assumes values have already been collected in reverse order. If ascending is an element and values_for_lex is None, this function is pass through.\n '''\n asc_is_element = isinstance(ascending, BOOL_TYPES)\n if not asc_is_element:\n ascending = tuple(ascending) #type: ignore\n if values_for_lex is None or len(ascending) != len(values_for_lex): #type: ignore\n raise RuntimeError('Multiple ascending values must match number of arrays selected.')\n # values for lex are in reversed order; thus take ascending reversed\n values_for_lex_post = []\n for asc, a in zip(reversed(ascending), values_for_lex):\n # if not ascending, replace with an inverted dense rank\n if not asc:\n values_for_lex_post.append(\n rank_1d(a, method=RankMethod.DENSE, ascending=False))\n else:\n values_for_lex_post.append(a)\n values_for_lex = values_for_lex_post\n\n return asc_is_element, values_for_lex\n\ndef sort_index_for_order(\n index: 'IndexBase',\n ascending: BoolOrBools,\n kind: str,\n key: tp.Optional[tp.Callable[['IndexBase'], tp.Union[np.ndarray, 'IndexBase']]],\n ) -> np.ndarray:\n '''Return an integer array defing the new ordering.\n '''\n # cfs is container_for_sort\n if key:\n cfs = key(index)\n cfs_is_array = cfs.__class__ is np.ndarray\n if cfs_is_array:\n cfs_depth = 1 if cfs.ndim == 1 else cfs.shape[1]\n else:\n cfs_depth = cfs.depth\n if len(cfs) != len(index):\n raise RuntimeError('key function returned a container of invalid length')\n else:\n cfs = index\n cfs_is_array = False\n cfs_depth = cfs.depth\n\n asc_is_element: bool\n # argsort lets us do the sort once and reuse the results\n if cfs_depth > 1:\n if cfs_is_array:\n values_for_lex = [cfs[NULL_SLICE, i] for i in range(cfs.shape[1]-1, -1, -1)]\n else: # cfs is an IndexHierarchy\n values_for_lex = [cfs.values_at_depth(i)\n for i in range(cfs.depth-1, -1, -1)]\n\n asc_is_element, values_for_lex = prepare_values_for_lex( #type: ignore\n ascending=ascending,\n values_for_lex=values_for_lex,\n )\n order = np.lexsort(values_for_lex)\n else:\n # depth is 1\n asc_is_element = isinstance(ascending, BOOL_TYPES)\n if not asc_is_element:\n raise RuntimeError('Multiple ascending values not permitted.')\n\n v = cfs if cfs_is_array else cfs.values\n order = np.argsort(v, kind=kind)\n\n if asc_is_element and not ascending:\n # NOTE: if asc is not an element, then ascending Booleans have already been applied to values_for_lex\n order = order[::-1]\n return order\n\n#-------------------------------------------------------------------------------\n\nclass MessagePackElement:\n '''\n Handle encoding/decoding of elements found in object arrays not well supported by msgpack. Many of these cases were found through Hypothesis testing.\n '''\n\n @staticmethod\n def encode(\n a: tp.Any,\n packb: AnyCallable,\n ) -> tp.Tuple[str, tp.Any]:\n\n if isinstance(a, datetime.datetime): #msgpack-numpy has an issue with datetime\n year = str(a.year).zfill(4) #datetime returns inconsistent year string for <4 digit years on some systems\n d = year + ' ' + a.strftime('%a %b %d %H:%M:%S:%f')\n return ('DT', d)\n elif isinstance(a, datetime.date):\n year = str(a.year).zfill(4) #datetime returns inconsistent year string for <4 digit years on some systems\n d = year + ' ' + a.strftime('%a %b %d')\n return ('D', d)\n elif isinstance(a, datetime.time):\n return ('T', a.strftime('%H:%M:%S:%f'))\n elif isinstance(a, np.ndarray): #recursion not covered by msgpack-numpy\n return ('A', packb(a)) #recurse packb\n elif isinstance(a, Fraction): #msgpack-numpy has an issue with fractions\n return ('F', str(a))\n elif isinstance(a, int) and len(str(a)) >=19:\n #msgpack-python has an overflow issue with large ints\n return ('I', str(a))\n return ('', a)\n\n\n @staticmethod\n def decode(\n pair: tp.Tuple[str, tp.Any],\n unpackb: AnyCallable,\n ) -> tp.Any:\n dt = datetime.datetime\n\n (typ, d) = pair\n if typ == 'DT': #msgpack-numpy has an issue with datetime\n return dt.strptime(d, '%Y %a %b %d %H:%M:%S:%f')\n elif typ == 'D':\n return dt.strptime(d, '%Y %a %b %d').date()\n elif typ == 'T':\n return dt.strptime(d, '%H:%M:%S:%f').time()\n elif typ == 'F': #msgpack-numpy has an issue with fractions\n return Fraction(d)\n elif typ == 'I': #msgpack-python has an issue with very large int values\n return int(d)\n elif typ == 'A': #recursion not covered by msgpack-numpy\n return unpackb(d) #recurse unpackb\n return d\n\n\n\n\n\n\n","sub_path":"static_frame/core/container_util.py","file_name":"container_util.py","file_ext":"py","file_size_in_byte":64605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272542876","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the caesarCipher function below.\ndef caesarCipher(s, k):\n string = \"abcdefghijklmnopqrstuvwxyz\"\n ans = \"\"\n for char in s:\n flag = False\n if char.isalpha():\n if(char.isupper()):\n char = char.lower()\n flag = True\n temp = string[(string.index(char) + (k % 26)) % 26]\n if(flag):\n temp = temp.upper()\n ans += temp\n else:\n ans += char\n return ans\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n s = input()\n\n k = int(input())\n\n result = caesarCipher(s, k)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","sub_path":"Problem Solving/Algorithms/Strings/Caesar Cipher/Caesar_Cipher.py","file_name":"Caesar_Cipher.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216441221","text":"#!/usr/bin/env python\n\nimport numpy as np;\n\nfrom arch.unitroot import PhillipsPerron\n\nimport pprint; pp = pprint.PrettyPrinter(indent=4);\nimport statsmodels.tsa as tsa;\nimport sys;\n\n\nclass Statistics:\n \"\"\"Implementation of some statistical functions\"\"\"\n\n # x and y np arrays\n def rsquared(self, time, values, regression_func):\n values_mean = np.mean(values);\n\n ss_total = 0;\n ss_residuals = 0;\n\n for t, v in zip(time, values):\n ss_total += (v - values_mean) * (v - values_mean);\n ss_residuals += (v - regression_func(t)) * (v - regression_func(t));\n\n return 1 - (ss_residuals / ss_total);\n\n def covariance(self, data_a, data_b, bessel_correction=True):\n sum = 0;\n if len(data_a) != len(data_b):\n return None;\n\n mean_a = np.mean(data_a);\n mean_b = np.mean(data_b);\n\n for index in range(len(data_a)):\n sum += (data_a[index] - mean_a) * (data_b[index] - mean_b);\n\n if bessel_correction:\n return ((1/(len(data_a) - 1)) * sum);\n else:\n return ((1/(len(data_a))) * sum);\n\n def auto_covariance(self, data, lag):\n if lag == 0:\n return self.covariance(data, data, False)\n else:\n return self.covariance(data[lag:], data[:-lag], False);\n\n def auto_correlation(self, data, lag):\n return self.auto_covariance(data, lag) / self.auto_covariance(data, 0); \n\n def sample_auto_covariance(self, data, lag, bessel_correction=True):\n sum = 0;\n mean = np.mean(data);\n\n for index in range(len(data[lag:])):\n sum += (data[index + lag] - mean) * (data[index] - mean);\n\n return ((1/len(data)) * sum);\n\n def sample_auto_correlation(self, data, lag): \n return self.sample_auto_covariance(data, lag) / self.sample_auto_covariance(data, 0);\n\n def dicky_fuller(self, data):\n ret = tsa.stattools.adfuller(data)\n\n return { \\\n \"adf\": ret[0], \\\n \"p_value\": ret[1], \\\n \"usedlag\": ret[2], \\\n \"nobs\": ret[3], \\\n \"ciritucal_values\": ret[4], \\\n \"icbest\": ret[5], \\\n };\n\n def phillips_peron(self, data):\n return PhillipsPerron(data)\n\n # Kwiatkovski-Philips-Schmidt-Shin\n def kpss(self, data):\n ret = tsa.stattools.kpss(data);\n\n return { \\\n \"kpss_stat\": ret[0], \\\n \"p_value\": ret[1], \\\n \"lags\": ret[2], \\\n \"crit\": ret[3] \\\n };\n\n def mean_standard_error(self, actual_values, predicted_values):\n n = len(actual_values);\n sum = 0;\n\n for a, p in zip(actual_values, predicted_values):\n e = a - p;\n sum += e**2\n\n return (1/n) * sum;\n\n def mean_absolute_error(self, actual_values, predicted_values):\n n = len(actual_values)\n sum = 0;\n\n for a, p in zip(actual_values, predicted_values):\n e = a - p;\n sum += np.abs(e);\n\n return (1/n) * sum;\n\n def mean_absolute_percentage_error(self, actual_values, predicted_values):\n n = len(actual_values)\n sum = 0;\n\n for a, p in zip(actual_values, predicted_values):\n e = a - p;\n sum += np.abs(e/a);\n\n return (100 / n) * sum;\n\n def symmetric_mean_absolute_percentage_error(self, actual_values, predicted_values):\n n = len(actual_values);\n sum = 0;\n\n for a, p in zip(actual_values, predicted_values):\n e = a - p;\n sum += np.abs((e)/((a + p)/2)); \n\n return (100 / n) * sum;\n\n def mean_absolute_scaled_error(self, actual_values_validation, predicted_values_validation, train_values):\n sum = 0;\n \n n = len(train_values)\n denominator = 0;\n for i in range(1, len(train_values)):\n denominator += np.abs(train_values[i] - train_values[i - 1]);\n\n denominator = (1)/(len(train_values) - 1) * denominator\n\n for a, p in zip(actual_values_validation, predicted_values_validation):\n e = a - p;\n sum += e / denominator; \n\n return sum;\n\n def moving_average_smoothing(self, values, order):\n arr = [];\n\n start_index = 0;\n end_index = order;\n while end_index != (len(values) + 1):\n sum = 0;\n for i in range(start_index, end_index): \n sum += values[i];\n arr.append(sum/order);\n start_index += 1;\n end_index += 1;\n\n return arr;\n\nif __name__ == \"__main__\":\n stat = Statistics();\n\n a = np.array([1, 2, 3, 4, 5]);\n print(stat.sample_auto_correlation(a, 1));\n","sub_path":"Statistics.py","file_name":"Statistics.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84313845","text":"\"\"\"\n==================\nzt-plots.\n==================\n\nThis example shows how to create a zt-plot of a given DU and event ID.\n\"\"\"\n\n# Author: Tamas Gal \n# License: BSD-3\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport km3pipe as kp\nimport km3pipe.style\nkm3pipe.style.use('default')\n\n\nDU = 26\nEVENT_ID = 23\nfilename = \"data/km3net_jul13_90m_muatm50T655.km3_v5r1.JTE_r2356.root.0-499.h5\"\ngeometry = kp.Geometry(filename=\"data/km3net_jul13_90m_r1494_corrected.detx\")\n\nall_hits = pd.read_hdf(filename, 'hits')\nhits = all_hits[all_hits.event_id == EVENT_ID].copy()\ngeometry.apply(hits)\n\nfig, ax = plt.subplots()\n\nhits[hits['du'] == DU].plot('time', 'pos_z', style='.', ax=ax, label='hits')\ntriggered_hits = hits[(hits['du'] == DU) & (hits['triggered'] == True)]\ntriggered_hits.plot('time', 'pos_z', style='.', ax=ax, label='triggered hits')\n\nax.set_title(\"zt-plot of event {0} on DU{1}\".format(EVENT_ID, DU))\nax.set_xlabel(\"time [ns]\")\nax.set_ylabel(\"z [m]\")\n","sub_path":"examples/plot_zt.py","file_name":"plot_zt.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44446517","text":"#coding:utf-8\r\n\r\nimport random\r\nimport json #用于保存settings\r\nimport os #用于获取AppData目录和新建目录\r\n\r\ndef encode(num):\r\n\t#加密,接收int,返回str\r\n\taddNumber=random.randint(1,9)\r\n\tsubNumber=random.randint(1,9)\r\n\tmulNumber=random.randint(1,9)\r\n\tresult=str(num-subNumber*mulNumber+addNumber)+str(subNumber)+str(mulNumber)+str(addNumber)\r\n\treturn result\r\n\r\ndef decode(num):\r\n\t#解密,接收int,返回str\r\n\taddetunum=str(num)[-1]\r\n\tsubetunum=str(num)[-3]\r\n\tdivetunum=str(num)[-2]\r\n\tlennum=len(str(num))\r\n\tisNum=str(num)[0:lennum-3]\r\n\tresult=str(int(isNum)-int(addetunum)+int(subetunum)*int(divetunum))\r\n\treturn result\r\n\r\ndef getText(language = '中文'):\r\n\t#引用文字的字典\r\n\tzh = {\r\n\t'welcome': '====================\\n欢迎使用NUAEDC\\n版本号:v2.0.0\\n====================',\r\n\t'help': '命令列表:\\n1.enc - 加密\\n2.dec - 解密\\n3.lan - 切换语言(Change Language)\\n4.? - 帮助\\n5.exit - 退出',\r\n\t'numberInput': '输入数字:',\r\n\t'switchLanguage': '中文/en:',\r\n\t'codeError': '失败。请输入一个整数。',\r\n\t'languageNotFound': '未找到该语言。'\r\n\t}\r\n\ten = {\r\n\t'welcome': '====================\\nwelcome to NUAEDC\\nversion: v2.0.0\\n====================',\r\n\t'help': 'Command List:\\n 1.enc - Encode\\n2.dec - Decode\\n3.lan - Change Language(切换语言)\\n4.? - help\\n5.exit - exit',\r\n\t'numberInput': 'Input number: ',\r\n\t'switchLanguage': '中文/en: ',\r\n\t'codeError': 'FAILED. Please input a integer.',\r\n\t'languageNotFound': 'Failed to find this language.'\r\n\t}\r\n\tif language == 'en':\r\n\t\treturn en\r\n\telif language == '中文':\r\n\t\treturn zh\r\n\t#语言没对上就报错,回去except\r\n\traise NotImplementError(\"Language Not Found\")\r\n\r\ndef commandList():\r\n\t#命令表\r\n\treturn {\r\n\t'encode': ['1', '加密', 'enc'],\r\n\t'decode': ['2', '解密', 'dec'],\r\n\t'switchLanguage': ['3', '切换语言', 'lan', 'language'],\r\n\t'help': ['4', 'help', '?', '?', '帮助'],\r\n\t'exit': ['5', '退出', 'exit'],\r\n\r\n\t'languages': {\r\n\t'中文': ['zh', 'cn', '中文', 'Chinese', 'zhcn', 'zh-cn'],\r\n\t'en': ['en', 'English', '英文']\r\n\t}\r\n\r\n\t}\r\n\r\ndef getInput(command,Text):\r\n\t#从命令中获取参数,失败就提示输入\r\n\ttry:\r\n\t\targ = command[1]\r\n\texcept:\r\n\t\targ = input(Text)\r\n\treturn arg\r\n\r\ndef isNotCommand(command, language):\r\n\t#命令识别失败\r\n\tif language == '中文':\r\n\t\tprint('不存在命令“' + command + '”。')\r\n\telse:\r\n\t\tprint('Command \"' + command + '\" not found.')\r\n\r\ndef writeSettings(Setting,file):\r\n\tjson.dump(Setting, file)\r\n\r\ndef getSettings(Path):\r\n\t#从Path指定的文件读取设置\r\n\tdefautSetting = {\r\n\t'language': '中文'\r\n\t}\r\n\tif not os.path.exists(os.path.split(Path)[0]): #判断目录是否存在,用os.path.split分离路径中目录与文件名\r\n\t\tos.mkdir(os.path.split(Path)[0])\r\n\tfSetting = open(Path, 'a+')\r\n\tfSetting.seek(0, 0) #把文件指针放到文件开头\r\n\tsetting = fSetting.read()\r\n\tif setting == '':\r\n\t\twriteSettings(defautSetting, fSetting)\r\n\t\tfSetting.close()\r\n\t\treturn defautSetting\r\n\tfSetting.close()\r\n\treturn json.loads(setting)\r\n\r\n\r\nif __name__ == \"__main__\": #排除被import时\r\n\r\n\t#初始化文本,命令表和语言\r\n\tsettingsPath = os.getenv('APPDATA') + '\\\\NUAEDC\\\\settings.json'\r\n\tsettings = getSettings(settingsPath)\r\n\tcommands = commandList()\r\n\ttext = getText(settings['language']) \r\n\r\n\tprint(text['welcome']) #欢迎\r\n\tprint(text['help'])\r\n\r\n\twhile True:\r\n\t\tcommand = input('>>>').split(' ',1)\r\n\t\tcommand[0] = command[0].lower() #命令转为小写,便于匹配\r\n\r\n\t\t#识别命令\r\n\r\n\t\t#避免空行造成程序退出\r\n\t\tif command[0] == '':\r\n\t\t\tcontinue\r\n\r\n\t\telif command[0] in commands['encode']:\r\n\t\t\ttry:\r\n\t\t\t\tnum = getInput(command, text['numberInput'])\r\n\t\t\t\tprint(encode(int(num)))\r\n\t\t\texcept:\r\n\t\t\t\tprint(text['codeError'])\r\n\r\n\t\telif command[0] in commands['decode']:\r\n\t\t\ttry:\r\n\t\t\t\tnum = getInput(command, text['numberInput'])\r\n\t\t\t\tprint(decode(int(num)))\r\n\t\t\texcept:\r\n\t\t\t\tprint(text['codeError'])\r\n\r\n\t\telif command[0] in commands['switchLanguage']:\r\n\t\t\tTlanguage = getInput(command, text['switchLanguage'])\r\n\t\t\tsucceed = False\r\n\t\t\tfor lan in commands['languages']:\r\n\t\t\t\tif Tlanguage in commands['languages'][lan]:\r\n\t\t\t\t\ttext = getText(lan)\r\n\t\t\t\t\tsettings['language'] = lan\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tfSettings = open(settingsPath, 'w')\r\n\t\t\t\t\t\twriteSettings(settings, fSettings)\r\n\t\t\t\t\t\tfSettings.close()\r\n\t\t\t\t\texcept:\r\n\t\t\t\t\t\tpass\r\n\t\t\t\t\tsucceed = True\r\n\t\t\t\t\tbreak\r\n\t\t\tif succeed == False:\r\n\t\t\t\tprint(text['languageNotFound'])\r\n\r\n\r\n\t\telif command[0] in commands['help']:\r\n\t\t\tprint(text['help'])\r\n\r\n\t\telif command[0] in commands['exit']:\r\n\t\t\texit()\r\n\r\n\t\telse:\r\n\t\t\tif command[0] != '':\r\n\t\t\t\tisNotCommand(command[0], settings['language'])\r\n","sub_path":"NUAEDC.py","file_name":"NUAEDC.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638886861","text":"import re # 导入模块\r\n\r\n\r\nclass Stack(object):\r\n # 初始化栈为列表\r\n def __init__(self):\r\n self.stack = []\r\n\r\n # 判断栈是否为空\r\n def isEmpty(self):\r\n return self.stack == []\r\n\r\n # 返回栈顶元素\r\n def peek(self):\r\n return self.stack[-1]\r\n\r\n def peek1(self):\r\n return self.stack[-2]\r\n\r\n # 返回栈的大小\r\n def size(self):\r\n return len(self.stack)\r\n\r\n # 入栈\r\n def push(self, item):\r\n self.stack.append(item)\r\n\r\n # 出栈\r\n def pop(self):\r\n return self.stack.pop()\r\n\r\n # 查看栈内的元素\r\n def show(self):\r\n print(self.stack)\r\n\r\n\r\nst = Stack() # 定义栈\r\nt1 = 0 # t1计数switch\r\nt2 = 0 # t2计数case数\r\nt3 = 0 # t3计数if-else的数\r\nt4 = 0 # t4计数if-elseif-else的数\r\nflag = 0\r\ntotal = 0 # total计数关键词\r\nx = 0\r\narva = [0 for x in range(10000)] # 存放t2\r\n\r\nfilename = input() # 传入文件路径\r\ngrade = input() # 传���作业等级\r\n\r\nf = open(filename, \"r\") # 打开文件\r\ndata = f.read() # 读文件\r\n\r\ndata = re.sub(r\"\\\"[\\S\\s]*?\\\"\", \"\", data)\r\ndata = re.sub(r\"\\/\\*[\\S\\s]*?\\*\\/\", \"\", data)\r\n\r\nres = re.findall(r'\\bdo\\b', data) # 从data里面查do的列表\r\ntotal += len(res) # 用len算do的个数\r\nres = re.findall(r'\\bauto\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bbreak\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bcase\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bchar\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bconst\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bcontinue\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bdefault\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bdouble\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\belse\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\benum\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bextern\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bfloat\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bfor\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bgoto\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bif\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bint\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\blong\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bregister\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\breturn\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bshort\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bsigned\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bsizeof\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bstatic\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bstruct\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bswitch\\b', data)\r\ntotal += len(res)\r\nt1 = len(res)\r\nres = re.findall(r'\\btypedef\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bunion\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bunsigned\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bvoid\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bvolatile\\b', data)\r\ntotal += len(res)\r\nres = re.findall(r'\\bwhile\\b', data)\r\ntotal += len(res)\r\n\r\nf.seek(0) # 回到文件开头\r\ni = 0\r\nk = len(f.readlines()) # 总行数\r\nf.seek(0)\r\nfor i in range(k):\r\n data = f.readline().strip() # 一行一行读\r\n\r\n data = re.sub(r\"\\\"[\\S\\s]*?\\\"\", \"\", data)\r\n data = re.sub(r\"\\/\\*[\\S\\s]*?\\*\\/\", \"\", data)\r\n\r\n res = re.findall(r'\\bswitch\\b', data)\r\n if flag == 1 and len(res) > 0: # 遇到下一个switch结构\r\n flag = 2\r\n if len(res) > 0 and flag == 0: # 找到switch结构\r\n flag = 1\r\n if flag == 1: # switch结构内\r\n res = re.findall(r'\\bcase\\b', data)\r\n t2 = t2 + len(res)\r\n res = re.findall(r'\\bdefault\\b', data)\r\n if len(res) > 0: # 遇到default退出\r\n flag = 0\r\n arva[x] = t2 # 保存case数\r\n x = x + 1\r\n t2 = 0 # t2清零\r\n if flag == 2: # 遇到下一个switch结构\r\n flag = 1 # 准备计数下一个switch结构的case数\r\n arva[x] = t2 # 保存case数\r\n x = x + 1\r\n t2 = 0 # t2清零\r\n if i == k - 1 and t2 != 0: # 下面没有default和switch\r\n arva[x] = t2 # 保存case数\r\n x = x + 1\r\n t2 = 0 # t2清零\r\n\r\nf.seek(0)\r\nk = len(f.readlines())\r\nf.seek(0)\r\nfor i in range(k):\r\n data = f.readline().strip()\r\n\r\n data = re.sub(r\"\\\"[\\S\\s]*?\\\"\", \"\", data)\r\n data = re.sub(r\"\\/\\*[\\S\\s]*?\\*\\/\", \"\", data)\r\n\r\n res = re.findall(r'\\bif\\b', data)\r\n res1 = re.findall(r'\\belse\\b', data)\r\n res2 = re.findall(r'{', data)\r\n res3 = re.findall(r'}', data)\r\n # 入栈时1代表 if 2代表 else 3代表 {\r\n if (len(res) > 0) and (len(res1) == 0): # 此行只有if没else\r\n st.push(1) # 1入栈\r\n if (len(res) > 0) and (len(res1) > 0): # 既有if又有else\r\n st.push(2) # 2入栈\r\n if (len(res1) > 0) and (len(res) == 0): # 此行只有else没if\r\n if st.isEmpty() == False and st.peek() == 2: # 栈不为空且栈顶为2,是属于if-elseif-else的\r\n t4 = t4 + 1\r\n while st.peek() == 2: # 删除队列中所有的elseif\r\n st.pop()\r\n st.pop() # 删除if\r\n if st.isEmpty() == False and st.peek() == 1: # 是属于if-else的\r\n t3 = t3 + 1\r\n st.pop() # 删除if\r\n if (len(res2) > 0):\r\n st.push(3) # 3入栈\r\n if (len(res3) > 0): # 是}时\r\n if st.isEmpty() == False and st.peek() == 3:\r\n st.pop() # 消括号\r\n elif (st.isEmpty() == False and st.peek() == 2) or (st.isEmpty() == False and st.peek() == 1):\r\n while st.peek() != 3: # 一直删到与其匹配的{\r\n st.pop()\r\n st.pop() # 删掉该{\r\n\r\nkey = int(grade) # 作业等级\r\n\r\nif key == 1: # 基础要求\r\n print('total num:', end=' ')\r\n print(total)\r\n print('switch num:', end=' ')\r\n print(t1)\r\nif key == 2: # 进阶要求\r\n print('total num:', end=' ')\r\n print(total)\r\n print('switch num:', end=' ')\r\n print(t1)\r\n print('case num:', end=' ')\r\n for i in range(x):\r\n if arva[i] != 0:\r\n print(arva[i], end=' ')\r\n print()\r\nif key == 3: # 拔高要求\r\n print('total num:', end=' ')\r\n print(total)\r\n print('switch num:', end=' ')\r\n print(t1)\r\n print('case num:', end=' ')\r\n for i in range(x):\r\n if arva[i] != 0:\r\n print(arva[i], end=' ')\r\n print()\r\n print('if-else num:', end=' ')\r\n print(t3)\r\nif key == 4: # 终极要求\r\n print('total num:', end=' ')\r\n print(total)\r\n print('switch num:', end=' ')\r\n print(t1)\r\n print('case num:', end=' ')\r\n for i in range(x):\r\n if arva[i] != 0:\r\n print(arva[i], end=' ')\r\n print()\r\n print('if-else num:', end=' ')\r\n print(t3)\r\n print('if-elseif-else num:', end=' ')\r\n print(t4)\r\n\r\nf.close() # 关闭文件\r\n","sub_path":"第一次个人编程作业最终版.py","file_name":"第一次个人编程作业最终版.py","file_ext":"py","file_size_in_byte":6846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"561452714","text":"from sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy import Column, Integer, String, ForeignKey, Table, insert, select, and_\r\nfrom sqlalchemy.orm import relationship\r\nfrom oracledb import *\r\n\r\nBase = declarative_base()\r\ndb = OracleDb()\r\n\r\nclass Users(Base):\r\n\r\n __tablename__ = 'Users'\r\n id = Column(Integer, primary_key=True)\r\n username = Column(String(100), unique=True)\r\n password = Column(String(100), nullable=False)\r\n country_id = Column(Integer, ForeignKey('Country.id'))\r\n user = relationship(\"Note\", backref=\"Users\")\r\n \r\n @classmethod\r\n def add_user(self,u_username, u_password, u_country_name):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n idcountry = session.query(Country).filter(Country.name == u_country_name)\r\n id_country = [row.country_id for row in idcountry][0]\r\n new_user = Users(\r\n username=u_username,\r\n password=u_password,\r\n country_id = id_country\r\n )\r\n session.add(new_user)\r\n session.commit()\r\n\r\nclass Country(Base):\r\n\r\n __tablename__ = 'Country'\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String(100), nullable=False)\r\n user = relationship(\"Users\", backref=\"Country\")\r\n numbersAid = relationship(\"NumbersAid\", backref=\"Country\")\r\n hospital = relationship(\"Hospital\", backref=\"Country\")\r\n \r\n @classmethod\r\n def add_country(self,u_name):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n new_country = Country(\r\n name=u_name\r\n )\r\n session.add(new_country)\r\n session.commit()\r\n\r\nclass NumbersAid(Base):\r\n\r\n __tablename__ = 'NumbersAid'\r\n id = Column(Integer, primary_key=True)\r\n phone_number = Column(String(20), nullable=False)\r\n country_id = Column(Integer, ForeignKey('Country.id'))\r\n \r\n @classmethod\r\n def add_aidNumber(self, u_phone_number, u_country_name):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n idcountry = session.query(Country).filter(Country.name == u_country_name)\r\n id_country = [row.country_id for row in idcountry][0]\r\n new_aidNumber = NumbersAid(\r\n phone_number = u_phone_number,\r\n country_id = id_country\r\n )\r\n session.add(new_aidNumber)\r\n session.commit()\r\n\r\nclass Hospital(Base):\r\n\r\n __tablename__ = 'Hospital'\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String(100), nullable=False)\r\n adres = Column(String(100), nullable=False)\r\n country_id = Column(Integer, ForeignKey('Country.id'))\r\n \r\n @classmethod\r\n def add_hospital(self, u_name, u_adres, u_country):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n idcountry = session.query(Country).filter(Country.name == u_country)\r\n id_country = [row.country_id for row in idcountry][0]\r\n new_hospital = Hospital(\r\n name = u_name,\r\n adres = u_adres,\r\n country_id = id_country\r\n )\r\n session.add(new_hospital)\r\n session.commit()\r\n \r\nclass Symptom(Base):\r\n\r\n __tablename__ = 'Symptom'\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String(100), nullable=False)\r\n Description = Column(String, nullable=False)\r\n \r\n @classmethod\r\n def add_symptom(self, u_name, u_Description):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n new_symptom = Symptom(\r\n name = u_name,\r\n Description = u_Description\r\n )\r\n session.add(new_symptom)\r\n session.commit()\r\n \r\nclass Note(Base):\r\n\r\n __tablename__ = 'Note'\r\n id = Column(Integer, primary_key=True)\r\n name = Column(String(100), nullable=False)\r\n Description = Column(String(1000), nullable=False)\r\n user_id = Column(Integer, ForeignKey('Users.id'))\r\n \r\n @classmethod\r\n def add_note(self, u_name, u_Description, id_user):\r\n db = OracleDb()\r\n session = db.sqlalchemy_session\r\n idnotes = session.query(Note).filter(Note.user_id == id_user)\r\n id_notes = [row.user_id for row in idnotes]\r\n if(len(id_notes)<41):\r\n new_note = Note(\r\n name = u_name,\r\n Description = u_Description,\r\n user_id = id_user\r\n )\r\n session.add(new_note)\r\n session.commit()\r\n else:\r\n print(\"Total notes will be less 40\")\r\n \r\nBase.metadata.create_all(db.sqlalchemy_engine)","sub_path":"Samodryga_Oleg/workshop4/source/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458054854","text":"\"\"\"Peridynamics model.\"\"\"\nfrom .integrators import Integrator\nfrom .neighbour_list import (family, create_neighbour_list, break_bonds,\n create_crack)\nfrom .peridynamics import damage, bond_force\nfrom collections import namedtuple\nimport meshio\nimport numpy as np\nimport pathlib\nfrom tqdm import trange\n\n\n_MeshElements = namedtuple(\"MeshElements\", [\"connectivity\", \"boundary\"])\n_mesh_elements_2d = _MeshElements(connectivity=\"triangle\",\n boundary=\"line\")\n_mesh_elements_3d = _MeshElements(connectivity=\"tetra\",\n boundary=\"triangle\")\n\n\nclass Model(object):\n \"\"\"\n A peridynamics model.\n\n This class allows users to define a peridynamics system from parameters and\n a set of initial conditions (coordinates and connectivity).\n\n >>> from peridynamics import Model\n >>>\n >>> model = Model(\n >>> mesh_file=\"./example.msh\",\n >>> horizon=0.1,\n >>> critical_strain=0.005,\n >>> elastic_modulus=0.05\n >>> )\n\n To define a crack in the inital configuration, you may supply a list of\n pairs of particles between which the crack is.\n\n >>> initial_crack = [(1,2), (5,7), (3,9)]\n >>> model = Model(\n >>> mesh_file=\"./example.msh\",\n >>> horizon=0.1,\n >>> critical_strain=0.005,\n >>> elastic_modulus=0.05,\n >>> initial_crack=initial_crack\n >>> )\n\n If it is more convenient to define the crack as a function you may also\n pass a function to the constructor which takes the array of coordinates as\n its only argument and returns a list of tuples as described above. The\n :func:`peridynamics.model.initial_crack_helper` decorator has been provided\n to easily create a function of the correct form from one which tests a\n single pair of node coordinates and returns `True` or `False`.\n\n >>> from peridynamics import initial_crack_helper\n >>>\n >>> @initial_crack_helper\n >>> def initial_crack(x, y):\n >>> ...\n >>> if crack:\n >>> return True\n >>> else:\n >>> return False\n >>>\n >>> model = Model(\n >>> mesh_file=\"./example.msh\",\n >>> horizon=0.1,\n >>> critical_strain=0.005,\n >>> elastic_modulus=0.05,\n >>> initial_crack=initial_crack\n >>> )\n\n The :meth:`Model.simulate` method can be used to conduct a peridynamics\n simulation. For this an :class:`peridynamics.integrators.Integrator` is\n required, and optionally a function implementing the boundary conditions.\n\n >>> from peridynamics.integrators import Euler\n >>>\n >>> model = Model(...)\n >>>\n >>> euler = Euler(dt=1e-3)\n >>>\n >>> indices = np.arange(model.nnodes)\n >>> model.lhs = indices[\n >>> model.coords[:, 0] < 1.5*model.horizon\n >>> ]\n >>> model.rhs = indices[\n >>> model.coords[:, 0] > 1.0 - 1.5*model.horizon\n >>> ]\n >>>\n >>> def boundary_function(model, u, step):\n >>> u[model.lhs] = 0\n >>> u[model.rhs] = 0\n >>> u[model.lhs, 0] = -1.0 * step\n >>> u[model.rhs, 0] = 1.0 * step\n >>>\n >>> return u\n >>>\n >>> u, damage, *_ = model.simulate(\n >>> steps=1000,\n >>> integrator=euler,\n >>> boundary_function=boundary_function\n >>> )\n \"\"\"\n\n def __init__(self, mesh_file, horizon, critical_strain, elastic_modulus,\n initial_crack=[], dimensions=2):\n \"\"\"\n Construct a :class:`Model` object.\n\n :arg str mesh_file: Path of the mesh file defining the systems nodes\n and connectivity.\n :arg float horizon: The horizon radius. Nodes within `horizon` of\n another interact with that node and are said to be within its\n neighbourhood.\n :arg float critical_strain: The critical strain of the model. Bonds\n which exceed this strain are permanently broken.\n :arg float elastic_modulus: The appropriate elastic modulus of the\n material.\n :arg initial_crack: The initial crack of the system. The argument may\n be a list of tuples where each tuple is a pair of integers\n representing nodes between which to create a crack. Alternatively,\n the arugment may be a function which takes the (nnodes, 3)\n :class:`numpy.ndarray` of coordinates as an argument, and returns a\n list of tuples defining the initial crack. Default is []\n :type initial_crack: list(tuple(int, int)) or function\n :arg int dimensions: The dimensionality of the model. The\n default is 2.\n\n :returns: A new :class:`Model` object.\n :rtype: Model\n\n :raises DimensionalityError: when an invalid `dimensions` argument is\n provided.\n :raises FamilyError: when a node has no neighbours (other nodes it\n interacts with) in the initial state.\n \"\"\"\n # Set model dimensionality\n self.dimensions = dimensions\n\n if dimensions == 2:\n self.mesh_elements = _mesh_elements_2d\n elif dimensions == 3:\n self.mesh_elements = _mesh_elements_3d\n else:\n raise DimensionalityError(dimensions)\n\n # Read coordinates and connectivity from mesh file\n self._read_mesh(mesh_file)\n\n self.horizon = horizon\n self.critical_strain = critical_strain\n\n # Determine bond stiffness\n self.bond_stiffness = (\n 18.0 * elastic_modulus / (np.pi * self.horizon**4)\n )\n\n # Calculate the volume for each node\n self.volume = self._volume()\n\n # Calculate the family (number of bonds in the initial configuration)\n # for each node\n self.family = family(self.coords, horizon)\n if np.any(self.family == 0):\n raise FamilyError(self.family)\n\n # Create the neighbourlist\n self.max_neighbours = self.family.max()\n nlist, n_neigh = create_neighbour_list(\n self.coords, horizon, self.max_neighbours\n )\n\n # Initialise inital crack\n if initial_crack:\n if callable(initial_crack):\n initial_crack = initial_crack(self.coords, nlist, n_neigh)\n create_crack(\n np.array(initial_crack, dtype=np.int32), nlist, n_neigh\n )\n self.initial_connectivity = (nlist, n_neigh)\n\n def _read_mesh(self, filename):\n \"\"\"\n Read the model's nodes, connectivity and boundary from a mesh file.\n\n :arg str filename: Path of the mesh file to read\n\n :returns: None\n :rtype: NoneType\n \"\"\"\n mesh = meshio.read(filename)\n\n # Get coordinates, encoded as mesh points\n self.coords = np.array(mesh.points, dtype=np.float64)\n self.nnodes = self.coords.shape[0]\n\n # Get connectivity, mesh triangle cells\n self.mesh_connectivity = mesh.cells_dict[\n self.mesh_elements.connectivity\n ]\n\n # Get boundary connectivity, mesh lines\n self.mesh_boundary = mesh.cells_dict[self.mesh_elements.boundary]\n\n def write_mesh(self, filename, damage=None, displacements=None,\n file_format=None):\n \"\"\"\n Write the model's nodes, connectivity and boundary to a mesh file.\n\n :arg str filename: Path of the file to write the mesh to.\n :arg damage: The damage of each node. Default is None.\n :type damage: :class:`numpy.ndarray`\n :arg displacements: An array with shape (nnodes, dim) where each row is\n the displacement of a node. Default is None.\n :type displacements: :class:`numpy.ndarray`\n :arg str file_format: The file format of the mesh file to\n write. Inferred from `filename` if None. Default is None.\n\n :returns: None\n :rtype: NoneType\n \"\"\"\n meshio.write_points_cells(\n filename,\n points=self.coords,\n cells=[\n (self.mesh_elements.connectivity, self.mesh_connectivity),\n (self.mesh_elements.boundary, self.mesh_boundary)\n ],\n point_data={\n \"damage\": damage,\n \"displacements\": displacements\n },\n file_format=file_format\n )\n\n def _volume(self):\n \"\"\"\n Calculate the value of each node.\n\n :returns: None\n :rtype: NoneType\n \"\"\"\n volume = np.zeros(self.nnodes)\n dimensions = self.dimensions\n\n if dimensions == 2:\n # element is a triangle\n element_nodes = 3\n elif dimensions == 3:\n # element is a tetrahedron\n element_nodes = 4\n\n for nodes in self.mesh_connectivity:\n # Calculate volume/area or element\n if dimensions == 2:\n a, b, c = self.coords[nodes]\n\n # Area of a trianble\n i = b - a\n j = c - a\n element_volume = 0.5 * np.linalg.norm(np.cross(i, j))\n elif dimensions == 3:\n a, b, c, d = self.coords[nodes]\n\n # Volume of a tetrahedron\n i = a - d\n j = b - d\n k = c - d\n element_volume = abs(np.dot(i, np.cross(j, k))) / 6\n\n # Add fraction element volume to all nodes belonging to that\n # element\n volume[nodes] += element_volume / element_nodes\n\n return volume\n\n def _break_bonds(self, u, nlist, n_neigh):\n \"\"\"\n Break bonds which have exceeded the critical strain.\n\n :arg u: A (nnodes, 3) array of the displacements of each node.\n :type u: :class:`numpy.ndarray`\n :arg nlist: The neighbour list.\n :type nlist: :class:`numpy.ndarray`\n :arg n_neigh: The number of neighbours of each node.\n :type n_neigh: :class:`numpy.ndarray`\n \"\"\"\n break_bonds(self.coords+u, self.coords, nlist, n_neigh,\n self.critical_strain)\n\n def _damage(self, n_neigh):\n \"\"\"\n Calculate bond damage.\n\n :arg n_neigh: The number of neighbours of each node.\n :type n_neigh: :class:`numpy.ndarray`\n\n :returns: A (`nnodes`, ) array containing the damage for each node.\n :rtype: :class:`numpy.ndarray`\n \"\"\"\n return damage(n_neigh, self.family)\n\n def _bond_force(self, u, nlist, n_neigh):\n \"\"\"\n Calculate the force due to bonds acting on each node.\n\n :arg u: A (nnodes, 3) array of the displacements of each node.\n :type u: :class:`numpy.ndarray`\n :arg nlist: The neighbour list.\n :type nlist: :class:`numpy.ndarray`\n :arg n_neigh: The number of neighbours of each node.\n :type n_neigh: :class:`numpy.ndarray`\n\n :returns: A (`nnodes`, 3) array of the component of the force in each\n dimension for each node.\n :rtype: :class:`numpy.ndarray`\n \"\"\"\n f = bond_force(self.coords+u, self.coords, nlist, n_neigh,\n self.volume, self.bond_stiffness)\n\n return f\n\n def simulate(self, steps, integrator, boundary_function=None, u=None,\n connectivity=None, first_step=1, write=None, write_path=None):\n \"\"\"\n Simulate the peridynamics model.\n\n :arg int steps: The number of simulation steps to conduct.\n :arg integrator: The integrator to use, see\n :mod:`peridynamics.integrators` for options.\n :type integrator: :class:`peridynamics.integrators.Integrator`\n :arg boundary_function: A function to apply the boundary conditions for\n the simlation. It has the form\n boundary_function(:class:`peridynamics.model.Model`,\n :class:`numpy.ndarray`, `int`). The arguments are the model being\n simulated, the current displacements, and the current step number\n (beginning from 1). `boundary_function` returns a (nnodes, 3)\n :class:`numpy.ndarray` of the updated displacements\n after applying the boundary conditions. Default `None`.\n :type boundary_function: function\n :arg u: The initial displacements for the simulation. If `None` the\n displacements will be initialised to zero. Default `None`.\n :type u: :class:`numpy.ndarray`\n :arg connectivity: The initial connectivity for the simulation. A tuple\n of a neighbour list and the number of neighbours for each node. If\n `None` the connectivity at the time of construction of the\n :class:`Model` object will be used. Default `None`.\n :type connectivity: tuple(:class:`numpy.ndarray`,\n :class:`numpy.ndarray`)\n :arg int first_step: The starting step number. This is useful when\n restarting a simulation, especially if `boundary_function` depends\n on the absolute step number.\n :arg int write: The frequency, in number of steps, to write the system\n to a mesh file by calling :meth:`Model.write_mesh`. If `None` then\n no output is written. Default `None`.\n :arg write_path: The path where the periodic mesh files should be\n written.\n :type write_path: path-like or str\n\n :returns: A tuple of the final displacements (`u`), damage and\n connectivity.\n :rtype: tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`,\n tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`))\n \"\"\"\n (nlist,\n n_neigh,\n u,\n boundary_function,\n write_path) = self._simulate_initialise(\n integrator, boundary_function, u, connectivity, write_path\n )\n\n for step in trange(first_step, first_step+steps,\n desc=\"Simulation Progress\", unit=\"steps\"):\n\n # Calculate the force due to bonds on each node\n force = self._bond_force(u, nlist, n_neigh)\n\n # Conduct one integration step\n u = integrator(u, force)\n # Apply boundary conditions\n u = boundary_function(self, u, step)\n\n # Update neighbour list\n self._break_bonds(u, nlist, n_neigh)\n\n # Calculate the current damage\n damage = self._damage(n_neigh)\n\n if write:\n if step % write == 0:\n self.write_mesh(write_path/f\"U_{step}.vtk\", damage, u)\n\n return u, damage, (nlist, n_neigh)\n\n def _simulate_initialise(self, integrator, boundary_function, u,\n connectivity, write_path):\n \"\"\"\n Initialise simulation variables.\n\n :arg integrator: The integrator to use, see\n :mod:`peridynamics.integrators` for options.\n :type integrator: :class:`peridynamics.integrators.Integrator`\n :arg boundary_function: A function to apply the boundary conditions for\n the simlation. It has the form\n boundary_function(:class:`peridynamics.model.Model`,\n :class:`numpy.ndarray`, `int`). The arguments are the model being\n simulated, the current displacements, and the current step number\n (beginning from 1). `boundary_function` returns a (nnodes, 3)\n :class:`numpy.ndarray` of the updated displacements\n after applying the boundary conditions. Default `None`.\n :type boundary_function: function\n :arg u: The initial displacements for the simulation. If `None` the\n displacements will be initialised to zero. Default `None`.\n :type u: :class:`numpy.ndarray`\n :arg connectivity: The initial connectivity for the simulation. A tuple\n of a neighbour list and the number of neighbours for each node. If\n `None` the connectivity at the time of construction of the\n :class:`Model` object will be used. Default `None`.\n :type connectivity: tuple(:class:`numpy.ndarray`,\n :class:`numpy.ndarray`)\n :arg write_path: The path where the periodic mesh files should be\n written.\n :type write_path: path-like or str\n\n :returns: A tuple of initialised variables used for simulation.\n :type: tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`,\n :class:`numpy.ndarray`, function, :class`pathlib.Path`)\n \"\"\"\n if not isinstance(integrator, Integrator):\n raise InvalidIntegrator(integrator)\n\n # Create initial displacements is none is provided\n if u is None:\n u = np.zeros((self.nnodes, 3))\n\n # Use the initial connectivity (when the Model was constructed) if none\n # is provided\n if connectivity is None:\n nlist, n_neigh = self.initial_connectivity\n elif type(connectivity) == tuple:\n if len(connectivity) != 2:\n raise ValueError(\"connectivity must be of size 2\")\n nlist, n_neigh = connectivity\n else:\n raise TypeError(\"connectivity must be a tuple or None\")\n\n # Create dummy boundary conditions function is none is provided\n if boundary_function is None:\n def boundary_function(model, u, step):\n return u\n\n # If no write path was provided use the current directory, otherwise\n # ensure write_path is a Path object.\n if write_path is None:\n write_path = pathlib.Path()\n else:\n write_path = pathlib.Path(write_path)\n\n return nlist, n_neigh, u, boundary_function, write_path\n\n\ndef initial_crack_helper(crack_function):\n \"\"\"\n Help the construction of an initial crack function.\n\n `crack_function` has the form `crack_function(icoord, jcoord)` where\n `icoord` and `jcoord` are :class:`numpy.ndarray` s representing two node\n coordinates. crack_function returns a truthy value if there is a crack\n between the two nodes and a falsy value otherwise.\n\n This decorator returns a function which takes all node coordinates and\n returns a list of tuples of the indices pair of nodes which define the\n crack. This function can therefore be used as the `initial_crack` argument\n of the :class:`Model`\n\n :arg function crack_function: The function which determine whether there is\n a crack between a pair of node coordinates.\n\n :returns: A function which determines all pairs of nodes with a crack\n between them.\n :rtype: function\n \"\"\"\n def initial_crack(coords, nlist, n_neigh):\n crack = []\n\n # Get all pairs of bonded particles\n nnodes = nlist.shape[0]\n pairs = [(i, j) for i in range(nnodes) for j in nlist[i][0:n_neigh[i]]\n if i < j]\n\n # Check each pair using the crack function\n for i, j in pairs:\n if crack_function(coords[i], coords[j]):\n crack.append((i, j))\n return crack\n return initial_crack\n\n\nclass DimensionalityError(Exception):\n \"\"\"An invalid dimensionality argument used to construct a model.\"\"\"\n\n def __init__(self, dimensions):\n \"\"\"\n Construct the exception.\n\n :arg int dimensions: The number of dimensions passed as an argument to\n :meth:`Model`.\n\n :rtype: :class:`DimensionalityError`\n \"\"\"\n message = (\n \"The number of dimensions must be 2 or 3,\"\n f\" {dimensions} was given.\"\n )\n\n super().__init__(message)\n\n\nclass FamilyError(Exception):\n \"\"\"One or more nodes have no bonds in the initial state.\"\"\"\n\n def __init__(self, family):\n \"\"\"\n Construct the exception.\n\n :arg family: The family array.\n :type family: :class:`numpy.ndarray`\n\n :rtype: :class:`FamilyError`\n \"\"\"\n indicies = np.where(family == 0)[0]\n indicies = \" \".join([f\"{index}\" for index in indicies])\n message = (\n \"The following nodes have no bonds in the initial state,\"\n f\" {indicies}.\"\n )\n\n super().__init__(message)\n\n\nclass InvalidIntegrator(Exception):\n \"\"\"An invalid integrator has been passed to `simulate`.\"\"\"\n\n def __init__(self, integrator):\n \"\"\"\n Construct the exception.\n\n :arg integrator: The object passed to :meth:`Model.simulate` as the\n integrator argument.\n\n :rtype: :class:`InvalidIntegrator`\n \"\"\"\n message = (\n f\"{integrator} is not an instance of\"\n \"peridynamics.integrators.Integrator\"\n )\n\n super().__init__(message)\n","sub_path":"peridynamics/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"148581914","text":"\nimport copy\nimport math\nimport random\n\nfrom unittest import mock\n\nfrom the_tale.common.utils import testcase\n\nfrom the_tale.game.balance import constants as c\n\nfrom the_tale.game.jobs import objects as jobs_objects\n\nfrom the_tale.game import tt_api_impacts\n\nfrom .. import conf\nfrom .. import logic\n\n\nclass CalculatePowerFractionsTests(testcase.TestCase):\n\n def test_no_powers(self):\n self.assertEqual(logic.calculate_power_fractions({}), {})\n\n def test_no_negative_powers(self):\n self.assertEqual(logic.calculate_power_fractions({1: 10*2,\n 2: 20*2,\n 3: 70*2}),\n {1: 0.1,\n 2: 0.2,\n 3: 0.7})\n\n def test_with_negative_powers(self):\n self.assertEqual(logic.calculate_power_fractions({1: 10,\n 2: -20,\n 3: 70}),\n {1: (10+20)/(10+20+70+20),\n 2: 0,\n 3: (70+20)/(10+20+70+20)})\n\n\nclass SyncPowerTests(testcase.TestCase):\n\n def setUp(self):\n super().setUp()\n\n tt_api_impacts.debug_clear_service()\n\n logic.add_power_impacts([tt_api_impacts.PowerImpact.hero_2_person(type=tt_api_impacts.IMPACT_TYPE.INNER_CIRCLE,\n hero_id=1,\n person_id=10,\n amount=100),\n tt_api_impacts.PowerImpact.hero_2_person(type=tt_api_impacts.IMPACT_TYPE.OUTER_CIRCLE,\n hero_id=2,\n person_id=20,\n amount=200),\n tt_api_impacts.PowerImpact.hero_2_place(type=tt_api_impacts.IMPACT_TYPE.OUTER_CIRCLE,\n hero_id=1,\n place_id=30,\n amount=300),\n tt_api_impacts.PowerImpact.hero_2_place(type=tt_api_impacts.IMPACT_TYPE.INNER_CIRCLE,\n hero_id=3,\n place_id=40,\n amount=400)])\n\n def test_success(self):\n\n with mock.patch('the_tale.game.politic_power.storage.PlacesPowerStorage.reset') as reset_places:\n with mock.patch('the_tale.game.politic_power.storage.PersonsPowerStorage.reset') as reset_persons:\n logic.sync_power()\n\n self.assertTrue(reset_places.called)\n self.assertTrue(reset_persons.called)\n\n targets = [(tt_api_impacts.OBJECT_TYPE.PERSON, 10),\n (tt_api_impacts.OBJECT_TYPE.PERSON, 20),\n (tt_api_impacts.OBJECT_TYPE.PLACE, 30),\n (tt_api_impacts.OBJECT_TYPE.PLACE, 40)]\n\n impacts = tt_api_impacts.personal_impacts.cmd_get_targets_impacts(targets=targets)\n\n self.assertCountEqual([impact.amount for impact in impacts], [math.floor(100*c.PLACE_POWER_REDUCE_FRACTION),\n math.floor(400*c.PLACE_POWER_REDUCE_FRACTION)])\n\n impacts = tt_api_impacts.crowd_impacts.cmd_get_targets_impacts(targets=targets)\n\n self.assertCountEqual([impact.amount for impact in impacts], [math.floor(200*c.PLACE_POWER_REDUCE_FRACTION),\n math.floor(300*c.PLACE_POWER_REDUCE_FRACTION)])\n\n\nclass GetInnerCircleTests(testcase.TestCase):\n\n def setUp(self):\n super().setUp()\n\n tt_api_impacts.debug_clear_service()\n\n self.person_impacts = []\n self.place_impacts = []\n\n test_size = conf.settings.PLACE_INNER_CIRCLE_SIZE + conf.settings.PERSON_INNER_CIRCLE_SIZE\n\n self.person_id = 666\n self.place_id = 777\n\n for i in range(test_size):\n self.person_impacts.append(tt_api_impacts.PowerImpact.hero_2_person(type=tt_api_impacts.IMPACT_TYPE.INNER_CIRCLE,\n hero_id=100+i,\n person_id=self.person_id,\n amount=1000+i))\n self.person_impacts.append(tt_api_impacts.PowerImpact.hero_2_person(type=tt_api_impacts.IMPACT_TYPE.OUTER_CIRCLE,\n hero_id=200+i,\n person_id=self.person_id,\n amount=2000+i))\n\n for i in range(test_size):\n self.place_impacts.append(tt_api_impacts.PowerImpact.hero_2_place(type=tt_api_impacts.IMPACT_TYPE.INNER_CIRCLE,\n hero_id=300+i,\n place_id=self.place_id,\n amount=3000+i))\n self.place_impacts.append(tt_api_impacts.PowerImpact.hero_2_place(type=tt_api_impacts.IMPACT_TYPE.OUTER_CIRCLE,\n hero_id=400+i,\n place_id=self.place_id,\n amount=4000+i))\n\n logic.add_power_impacts(self.person_impacts)\n logic.add_power_impacts(self.place_impacts)\n\n def test_get_place_circle(self):\n circle = logic.get_inner_circle(place_id=self.place_id)\n self.assertEqual(circle.rating, [(309, 3009),\n (308, 3008),\n (307, 3007),\n (306, 3006),\n (305, 3005),\n (304, 3004),\n (303, 3003),\n (302, 3002),\n (301, 3001),\n (300, 3000)])\n\n def test_get_person_circle(self):\n circle = logic.get_inner_circle(person_id=self.person_id)\n self.assertEqual(circle.rating, [(109, 1009),\n (108, 1008),\n (107, 1007),\n (106, 1006),\n (105, 1005),\n (104, 1004),\n (103, 1003),\n (102, 1002),\n (101, 1001),\n (100, 1000)])\n\n def test_no_actor(self):\n self.assertRaises(NotImplementedError, logic.get_inner_circle)\n\n\nclass GetJobPowerTests(testcase.TestCase):\n\n def setUp(self):\n super().setUp()\n\n tt_api_impacts.debug_clear_service()\n\n impacts = []\n\n self.hero_id = 111\n self.person_id = 666\n self.place_id = 777\n\n impacts = [tt_api_impacts.PowerImpact(type=tt_api_impacts.IMPACT_TYPE.JOB,\n actor_type=tt_api_impacts.OBJECT_TYPE.HERO,\n actor_id=self.hero_id,\n target_type=tt_api_impacts.OBJECT_TYPE.JOB_PERSON_POSITIVE,\n target_id=self.person_id,\n amount=1000),\n tt_api_impacts.PowerImpact(type=tt_api_impacts.IMPACT_TYPE.JOB,\n actor_type=tt_api_impacts.OBJECT_TYPE.HERO,\n actor_id=self.hero_id,\n target_type=tt_api_impacts.OBJECT_TYPE.JOB_PERSON_NEGATIVE,\n target_id=self.person_id,\n amount=2000),\n tt_api_impacts.PowerImpact(type=tt_api_impacts.IMPACT_TYPE.JOB,\n actor_type=tt_api_impacts.OBJECT_TYPE.HERO,\n actor_id=self.hero_id,\n target_type=tt_api_impacts.OBJECT_TYPE.JOB_PLACE_POSITIVE,\n target_id=self.place_id,\n amount=3000),\n tt_api_impacts.PowerImpact(type=tt_api_impacts.IMPACT_TYPE.JOB,\n actor_type=tt_api_impacts.OBJECT_TYPE.HERO,\n actor_id=self.hero_id,\n target_type=tt_api_impacts.OBJECT_TYPE.JOB_PLACE_NEGATIVE,\n target_id=self.place_id,\n amount=4000)]\n\n foreign_impacts = copy.deepcopy(impacts)\n for impact in foreign_impacts:\n impact.target_id += 1\n impact.amount = random.randint(1, 10000)\n\n logic.add_power_impacts(impacts)\n logic.add_power_impacts(foreign_impacts)\n\n def test_get_for_place(self):\n self.assertEqual(logic.get_job_power(place_id=self.place_id),\n jobs_objects.JobPower(3000, 4000))\n\n def test_get_for_person(self):\n self.assertEqual(logic.get_job_power(person_id=self.person_id),\n jobs_objects.JobPower(1000, 2000))\n\n def test_no_actor(self):\n self.assertRaises(NotImplementedError, logic.get_job_power)\n\n\nclass AddPowerImpactsTests(testcase.TestCase):\n\n def setUp(self):\n super().setUp()\n tt_api_impacts.debug_clear_service()\n\n def test_success(self):\n impacts = []\n\n for type in tt_api_impacts.IMPACT_TYPE.records:\n impacts.append(tt_api_impacts.PowerImpact.hero_2_person(type=type,\n hero_id=random.randint(1, 100),\n person_id=random.randint(1, 100),\n amount=random.randint(1, 100)))\n impacts.append(tt_api_impacts.PowerImpact.hero_2_place(type=type,\n hero_id=random.randint(1, 100),\n place_id=random.randint(1, 100),\n amount=random.randint(1, 100)))\n logic.add_power_impacts(impacts)\n\n loaded_impacts = []\n\n for api in [tt_api_impacts.personal_impacts, tt_api_impacts.crowd_impacts, tt_api_impacts.job_impacts]:\n loaded_impacts.extend(api.cmd_get_last_power_impacts(limit=100))\n\n for impact in loaded_impacts:\n impact.time = None\n\n self.assertCountEqual([impact for impact in impacts if not impact.type.is_FAME], loaded_impacts)\n\n fame_impacts = tt_api_impacts.fame_impacts.cmd_get_last_power_impacts(limit=100,\n actor_type=None,\n actor_id=None,\n target_type=None,\n target_id=None)\n\n for impact in fame_impacts:\n impact.time = None\n\n self.assertCountEqual([impact for impact in impacts if impact.type.is_FAME], fame_impacts)\n\n\nclass GetLastPowerImpactsTests(testcase.TestCase):\n\n def setUp(self):\n super().setUp()\n tt_api_impacts.debug_clear_service()\n\n self.impacts = []\n\n for type in tt_api_impacts.IMPACT_TYPE.records:\n self.impacts.append(tt_api_impacts.PowerImpact.hero_2_person(type=type,\n hero_id=random.randint(1, 100),\n person_id=random.randint(1, 100),\n amount=random.randint(1, 100)))\n self.impacts.append(tt_api_impacts.PowerImpact.hero_2_place(type=type,\n hero_id=random.randint(1, 100),\n place_id=random.randint(1, 100),\n amount=random.randint(1, 100)))\n\n with mock.patch('the_tale.game.turn.number', lambda: random.randint(1, 10000)):\n for impact in self.impacts:\n logic.add_power_impacts([impact])\n\n def test_success(self):\n\n loaded_impacts = logic.get_last_power_impacts(100)\n\n for impact in loaded_impacts:\n impact.time = None\n\n self.assertCountEqual([impact for impact in self.impacts if not impact.type.is_JOB and not impact.type.is_FAME],\n loaded_impacts)\n\n def test_limit(self):\n loaded_impacts = logic.get_last_power_impacts(3)\n\n for impact in loaded_impacts:\n impact.time = None\n\n self.impacts.sort(key=lambda impact: (impact.turn, impact.time), reverse=True)\n\n self.assertEqual([impact for impact in self.impacts if not impact.type.is_JOB and not impact.type.is_FAME][:3],\n loaded_impacts)\n","sub_path":"src/the_tale/the_tale/game/politic_power/tests/test_logic.py","file_name":"test_logic.py","file_ext":"py","file_size_in_byte":14564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10010971","text":"#!/usr/bin/env python\n\nimport loco\nimport tinymath as tm\nimport numpy as np\nimport gc\n\ndef test_scenario_constructor() :\n scenario = loco.sim.Scenario()\n scenario.Initialize()\n scenario.PreStep()\n scenario.PostStep()\n scenario.Reset()\n assert ( scenario.HasSingleBodyNamed( 'foo' ) == False ), 'test_scenario_constructor >>> method \\'HasSingleBodyNamed\\' doesn\\'t return correct value'\n assert ( scenario.GetSingleBodyByName( 'foo' ) == None ), 'test_scenario_constructor >>> method \\'GetSingleBodyByName\\' doesn\\'t return correct value'\n assert ( len( scenario.GetSingleBodiesList() ) == 0 ), 'test_scenario_constructor >>> method \\'GetSingleBodiesList\\' doesn\\'t return correct value'\n assert ( scenario.GetNumSingleBodies() == 0 ), 'test_scenario_constructor >>> method \\'GetNumSingleBodies\\' doesn\\'t return correct value'\n print( scenario )\n\ndef test_scenario_primitives() :\n vis_data = loco.sim.VisualData()\n vis_data.type = loco.sim.ShapeType.CAPSULE\n vis_data.size = [ 0.1, 0.2, 0.1 ]\n col_data = loco.sim.CollisionData()\n col_data.type = loco.sim.ShapeType.CAPSULE\n col_data.size = [ 0.1, 0.2, 0.1 ]\n\n body_data = loco.sim.BodyData()\n body_data.dyntype = loco.sim.DynamicsType.DYNAMIC\n body_data.collision = col_data\n body_data.visual = vis_data\n\n body_obj = loco.sim.SingleBody( \"body_0\", body_data, [ 1.0, 1.0, 1.0 ], np.identity( 3 ) )\n scenario = loco.sim.Scenario()\n scenario.AddSingleBody( body_obj )\n assert ( len( gc.get_referrers( scenario ) ) == 1 ), 'test_scenario_primitives >>> num-referrers to scenario should have remain constant'\n assert ( scenario.HasSingleBodyNamed( 'body_0' ) == True ), 'test_scenario_primitives >>> issue with method \\'HasSingleBodyNamed\\''\n assert ( scenario.GetSingleBodyByName( 'body_0' ) != None ), 'test_scenario_primitives >>> issue with method \\'GetSingleBodyByName\\''\n assert ( len( scenario.GetSingleBodiesList() ) == 1 ), 'test_scenario_primitives >>> issue with method \\'GetSingleBodiesList\\''\n assert ( scenario.GetSingleBodiesList()[0].name == 'body_0' ), 'test_scenario_primitives >>> issue with values returned by \\'GetSingleBodiesList\\''\n assert ( scenario.GetNumSingleBodies() == 1 ), 'test_scenario_primitives >>> issue with method \\'GetNumSingleBodies\\''\n print( scenario )\n\nif __name__ == '__main__' :\n _ = input( 'Press ENTER to start test : test_scenario_constructor' )\n test_scenario_constructor()\n\n _ = input( 'Press ENTER to start test : test_scenario_primitives' )\n test_scenario_primitives()\n\n _ = input( 'Press ENTER to continue ...' )","sub_path":"tests/python/test_scenario.py","file_name":"test_scenario.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534842056","text":"from twilio.rest import Client\nfrom os import environ\nimport telegram_send\n\n\ndef sendMessageT(body):\n telegram_send.send(conf=\"telegramConf\",messages=[body] )\n\ndef sendMessageW(body, number):\n account_sid = environ.get('TWILIO_SID')\n auth_token = environ.get('TWILIO_TOKEN')\n number = str('whatsapp:+55'+number)\n client = Client(account_sid, auth_token)\n message = client.messages.create(body=body,from_='whatsapp:+16106162363',to=number)\n print(message.sid)\n","sub_path":"clientflow/app/messagingHandler.py","file_name":"messagingHandler.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"261482349","text":"# 1929 / find primes in M to N\nprimes = [0] * 1000001 # eratostenes`s seele\nprimes[0], primes[1] = 1, 1\nfor i in range(2, 1000001):\n num = 2 * i\n while num <= 1000000:\n primes[num] = 1\n num += i\n\nM, N = map(int, input().split())\n\nfor i in range(M, N + 1):\n if primes[i] == 0:\n print(i)\n","sub_path":"math/1929.py","file_name":"1929.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"98936252","text":"#!/usr/bin/env python3\n\n\"\"\"\nTranscribing DNA into RNA\n=========================\n\nGiven: A DNA string t corresponding to a coding strand (at most 1000 nt).\n\nReturn: The transcribed RNA string of t.\n\nSample Dataset\n--------------\n\nGATGGAACTTGACTACGTAAATT\n\nSample Output\n-------------\n\nGAUGGAACUUGACUACGUAAAUU\n\n\"\"\"\n\nimport sys\n\nwith open(sys.argv[1], 'r') as input_file: # to automagically close the file\n data = input_file.read() # when leaving the nested block\n\ndna = ''.join(data.split()) # the split/join trick to remove all whitespace\n\ntranscription_table = str.maketrans(\"Tt\",\"Uu\") # preserving case\nrna = dna.translate(transcription_table) # much confusement, very chaos!\n\nprint(rna)\n","sub_path":"stronghold/02-RNA/RNA.py","file_name":"RNA.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519403829","text":"# coding=utf-8\n__author__ = 'ChaoMing'\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport myprojects.deal_files\nimport traceback\n\ndef get_list():\n try:\n html_content = urllib.request.urlopen(\"http://waimai.baidu.com/waimai/shoplist/5bf7d82935c40bd3?taste=0&welfare=pay,xin,jian,preorder,payenjoy,mian,coupon,zeng,invoice,express,overtimepayment\")\n except:\n print(\"这个链接未打开!!\", end=\" \")\n content = html_content.read().decode(\"utf-8\")\n\n f = open(\"files/baidu_html_pages/test.html\", \"w\")\n f.write(content)\n f.close()\n\ndef get_soup(url):\n try:\n req = urllib.request.Request(url, headers = {\n 'Connection': 'Keep-Alive',\n 'Accept': 'text/html, application/xhtml+xml, */*',\n 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'})\n html_content = urllib.request.urlopen(req)\n content = html_content.read().decode(\"utf-8\").replace(\"\\n\", \"\").replace(\"¥\", \"\")\n soup = BeautifulSoup(content, \"html.parser\")\n return soup\n except:\n print(url)\n traceback.print_exc()\n return None\n\ndef crawl_shop_info(soup, url):\n try:\n shop = {}\n # 店铺名称\n name = soup.find(class_=\"all-show\").string\n shop[\"name\"] = name\n\n # 店铺类别、评分、接单时间、商户地址\n dls = soup.find_all(\"dl\")\n shop[\"category\"] = dls[0].dt.string\n shop['ordertime'] = dls[1].dd.contents[0]\n shop[\"address\"] = dls[2].dd.string\n\n # 评分\n shop[\"grade\"] = soup.find(\"div\", class_=\"rate-num\").string\n\n # 配送费、起送价、平均送达时间\n divs = soup.find_all(\"div\", class_=\"b-value\")\n shop[\"distributioncharge\"] = divs[0].strong.string\n shop[\"playprice\"] = divs[1].strong.string\n shop[\"deliverytime\"] = divs[2].strong.string\n\n # 支持\n spans = soup.find(\"ul\", id=\"premium-notice\").find_all(\"span\")\n shop[\"support\"] = \"\"\n for span in spans:\n shop[\"support\"] += span.string + \"|\"\n\n myprojects.deal_files.write_a_json(\"files/test_shop_1.json\", shop)\n\n return True\n except BaseException as e:\n print(e)\n print(url)\n traceback.print_exc()\n return False\n\ndef crawl_good_info(soup, good_num, url):\n try:\n # 餐厅\n restaurant = soup.find(class_=\"all-show\").string\n\n # 得到所有分类、及菜品\n spans = soup.find_all(\"span\", class_=\"title\")\n divs = soup.find_all(\"div\", class_=\"list clearfix\")\n\n # 热销菜品\n i = 0\n number = 0\n for div in divs:\n i += 1\n\n for detail_div in div.find_all(\"div\", class_=\"info fl\"):\n good = {}\n good[\"name\"] = detail_div.h3.string\n sub_spans = detail_div.find_all(\"span\", class_=\"sales-count\")\n good[\"recommend\"] = sub_spans[0].string\n good[\"salesvolume\"] = sub_spans[1].string\n price_div = detail_div.find_all(\"div\")[-1]\n good[\"price\"] = price_div.strong.string\n good[\"restaurant\"] = restaurant\n if i == 1:\n good[\"category\"] = \"热销菜品\"\n else:\n good[\"category\"] = spans[i - 2].string\n\n myprojects.deal_files.write_a_json(\"files/test_good_1.json\", good)\n number += 1\n good_num += 1\n print(\"完成了\" + str(good_num) + \"个菜品的信息爬取。\")\n\n return good_num\n except BaseException as e:\n print(e)\n print(url)\n traceback.print_exc()\n return good_num\n\n\ndef main():\n # 读取URL列表\n url_set = set()\n f = open(\"files/urls1.txt\", \"r\")\n for line in f:\n url_set |= {line.strip()}\n f.close()\n\n shop_num = 0\n good_num = 0\n for url in url_set:\n soup = get_soup(url)\n\n if soup != None:\n if crawl_shop_info(soup, url):\n shop_num += 1\n print(\"\\n\\n完成了\"+ str(shop_num) +\"个店铺的信息爬取。\")\n\n good_num = crawl_good_info(soup, good_num, url)\n\nmain()","sub_path":"InternetThinking/BaiDuWaiMai8.py","file_name":"BaiDuWaiMai8.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48979891","text":"#! coding=utf-8\n\"\"\"\nhigh-level toolbox for Chinese Word Segmentation\n\"\"\"\nfrom nlpir import get_instance as __get_instance__\nfrom nlpir import native, PACKAGE_DIR\nimport typing\nimport re\nimport os\n\n# class and class instance\n__cls__ = native.ictclas.ICTCLAS\n__instance__: typing.Optional[native.ictclas.ICTCLAS] = None\n# Location of DLL\n__lib__ = None\n# Data directory\n__data__ = None\n# license_code\n__license_code__ = None\n# encode\n__nlpir_encode__ = native.UTF8_CODE\n\n\n@__get_instance__\ndef get_native_instance() -> native.ictclas.ICTCLAS:\n \"\"\"\n 返回原生NLPIR接口,使用更多函数\n\n :return: The singleton instance\n \"\"\"\n return __instance__\n\n\nmatch_tag = re.compile(r\"(.+?)/([a-z0-9A-Z]+) \")\n\n\ndef process_to_list(txt: str, pos_tag: bool) -> list:\n \"\"\"\n Split string, get list of tuple if it has POS tag, or get list of words\n\n :param txt: Segmented string\n :param pos_tag: The segmented string has POS tag or not\n :return: list of tuple of list of word\n\n Without POS tag::\n\n [\n '法国', '启蒙', '思想家', '孟德斯', '鸠', '曾', '说', '过', ':', '“', '一切', '有', '权力',\n '的', '人', '都', '容易', '滥用', '权力', ',', '这', '是', '一', '条', '千古', '不', '变',\n '的', '经验', '。'\n ]\n\n With POS tag::\n\n [\n ('法国', 'nsf'), ('启蒙', 'vn'), ('思想家', 'n'), ('孟德斯', 'nrf'), ('鸠', 'n'), ('曾', 'd'),\n ('说', 'v'), ('过', 'uguo'), (':', 'wm'), ('“', 'wyz'), ('一切', 'rz'), ('有', 'vyou'),\n ('权力', 'n'), ('的', 'ude1'), ('人', 'n'), ('都', 'd'), ('容易', 'ad'), ('滥用', 'v'),\n ('权力', 'n'), (',', 'wd'), ('这', 'rzv'), ('是', 'vshi'), ('一', 'm'), ('条', 'q'), ('千古', 'n'),\n ('不', 'd'), ('变', 'v'), ('的', 'ude1'), ('经验', 'n'), ('。', 'wj'), ('有', 'vyou'), ('权力', 'n'),\n ('的', 'ude1'), ('人', 'n'), ('直到', 'v'), ('把', 'pba'), ('权力', 'n'), ('用到', 'v'),\n ('极限', 'n'), ('方可', 'd'), ('休止', 'vi'), ('。', 'wj')\n ]\n\n \"\"\"\n if pos_tag:\n return match_tag.findall(txt)\n else:\n return txt.split(\" \")\n\n\ndef process_to_generator(text: str, pos_tag: bool) -> typing.Generator:\n \"\"\"\n Same as :func:`process_to_list` ,return an iterator, save memory if the string is very large\n\n :param text:\n :param pos_tag:\n :return:\n \"\"\"\n if pos_tag:\n for i in match_tag.finditer(text):\n yield i.groups()\n else:\n re_split = re.compile(r\"[^ ]+\")\n for i in re_split.finditer(text):\n yield i.group()\n\n\n@__get_instance__\ndef import_dict(word_list: list) -> list:\n \"\"\"\n Temporary add word as dictionary, will loss it when restart the Program.\n Can use :func:`save_user_dict` to make persistence, :func:`clean_user_dict` to\n delete all temporary words or :func:`delete_user_word` to delete part of them.\n\n The persistent dict cannot be clean by using method above. :func:`clean_saved_user_dict`\n will be used in this situation. But it will delete all user dict include saved dict in the past.\n\n Every word in `word_list` can be a single word and the POS will be `n`. The custom POS can be added\n as `word pos` in `word_list`.\n\n :param word_list: list of words want to add to NLPIR\n :return: the word fail to add to the NLPIR\n \"\"\"\n fail_list = list()\n for word in word_list:\n if 0 != __instance__.add_user_word(word):\n fail_list.append(word_list)\n return fail_list\n\n\n@__get_instance__\ndef clean_user_dict() -> bool:\n \"\"\"\n Clean all temporary dictionary, more information shows in :func:`import_dict`\n\n :return: success or not\n \"\"\"\n return __instance__.clean_user_word() == 0\n\n\n@__get_instance__\ndef delete_user_word(word_list: list):\n \"\"\"\n Delete words in temporary dictionary, more information shows in :func:`import_dict`\n\n :param word_list: list of words want to delete\n \"\"\"\n for word in word_list:\n __instance__.del_usr_word(word)\n\n\n@__get_instance__\ndef save_user_dict() -> bool:\n \"\"\"\n Save temporary dictionary to Data, more information shows in :func:`import_dict`\n :return: Success or not\n \"\"\"\n return 1 == __instance__.save_the_usr_dic()\n\n\n@__get_instance__\ndef clean_saved_user_dict():\n \"\"\"\n Delete user dict from disk, which is :\n\n 1. ``Data/FieldDict.pdat``\n 2. ``Data/FieldDict.pos``\n 3. ``Data/FieldDict.wordlist``\n 4. ``Data/UserDefinedDict.lst``\n\n :return: Delete success or not\n \"\"\"\n try:\n with open(os.path.join(PACKAGE_DIR, \"Data/FieldDict.pdat\"), 'w') as f:\n f.write(\"\")\n with open(os.path.join(PACKAGE_DIR, \"Data/FieldDict.pos\"), 'w') as f:\n f.write(\"\")\n with open(os.path.join(PACKAGE_DIR, \"Data/FieldDict.wordlist\"), 'w') as f:\n f.write(\"\")\n with open(os.path.join(PACKAGE_DIR, \"Data/UserDefinedDict.lst\"), 'w') as f:\n f.write(\"\")\n return True\n except OSError:\n return False\n\n\n@__get_instance__\ndef segment(txt: str, pos_tagged: bool = False, post_process: callable = process_to_list) -> typing.Any:\n \"\"\"\n 中文分词函数,将字符串进行分词,支持多线程和多进程分词:\n\n Example::\n\n from multiprocessing import Pool\n test_str = \"法国启蒙思想家孟德斯鸠曾说过:“一切有权力的人都容易滥用权力,这是一条千古不变的经验。有权力的人直到把权力用到\" \\\n \"极限方可休止。”另一法国启蒙思想家卢梭从社会契约论的观点出发,认为国家权力是公民让渡其全部“自然权利”而获得的,\" \\\n \"他在其名著《社会契约论》中写道:“任何国家权力无不是以民众的权力(权利)让渡与公众认可作为前提的”。\"\n with Pool(16) as pool:\n result = pool.map(ictclas.segment, [data]*100)\n\n 默认只进行分词不进行分词标注,返回为list,可使用其他或者自行创建需要的post_process函数改变最终输出,\n post_process的输入为字符串,格式如下,分别为进行词性标注和不进行词性标注的::\n\n test_str_seg_pos = '法国/nsf 启蒙/vn 思想家/n 孟德斯/nrf 鸠/n 曾/d 说/v 过/uguo :/wm “/wyz 一切/rz 有/vyou 权力/n ' \\\n '的/ude1 人/n 都/d 容易/ad 滥用/v 权力/n ,/wd 这/rzv 是/vshi 一/m 条/q 千古/n 不/d 变/v 的/ude1 经' \\\n '验/n 。/wj 有/vyou 权力/n 的/ude1 人/n 直到/v 把/pba 权力/n 用到/v 极限/n 方可/d 休止/vi 。/wj ”/wyy' \\\n ' 另/rz 一/m 法国/nsf 启蒙/vn 思想家/n 卢/nr1 梭/ng 从/p 社会/n 契约/n 论/k 的/ude1 观点/n 出发/vi ' \\\n ',/wd 认为/v 国家/n 权力/n 是/vshi 公民/n 让/v 渡/v 其/rz 全部/m “/wyz 自然/n 权利/n ”/wyy 而/cc ' \\\n '获得/v 的/ude1 ,/wd 他/rr 在/p 其/rz 名著/n 《/wkz 社会/n 契约/n 论/v 》/wky 中/f 写道/v :/wm ' \\\n '“/wyz 任何/rz 国家/n 权力/n 无不/d 是/vshi 以/p 民众/n 的/ude1 权力/n (/wkz 权利/n )/wky 让/v ' \\\n '渡/v 与/p 公众/n 认可/vi 作为/p 前提/n 的/ude1 ”/wyy 。/wj '\n test_str_seg = '法国 启蒙 思想家 孟德斯 鸠 曾 说 过 : “ 一切 有 权力 的 人 都 容易 滥用 权力 , 这 是 一 条 千古 不 变 的' \\\n ' 经验 。 有 权力 的 人 直到 把 权力 用到 极限 方可 休止 。 ” 另 一 法国 启蒙 思想家 卢 梭 从 社会 契约' \\\n ' 论 的 观点 出发 , 认为 国家 权力 是 公民 让 渡 其 全部 “ 自然 权利 ” 而 获得 的 , 他 在 其 名' \\\n '著 《 社会 契约 论 》 中 写道 : “ 任何 国家 权力 无不 是 以 民众 的 权力 ( 权利 ) 让 渡 与 公众' \\\n ' 认可 作为 前提 的 ” 。 '\n\n 默认的post_process是直接将上述结果变成列表形式,若想获得字符串形式,可以使用简单的lambda表达式使post_process直接返回::\n\n segment(txt, pas_tagged, post_process=lambda t, _ : t)\n\n 默认使用的标注集为 :attr:`nlpir.native.ictclas.ICTCLAS.ICT_POS_MAP_SECOND` 计算所二级标注集\n\n 若需要进行标注集修改,使用 :func:`nlpir.native.ictclas.ICTCLAS.set_pos_map` 进行修改\n\n :param txt: The string want to be segmented\n :param pos_tagged: POS tagging or not\n :param post_process: The post process function, in order to get different result\n \"\"\"\n return post_process(__instance__.paragraph_process(txt, pos_tagged=1 if pos_tagged else 0), pos_tagged)\n\n\n@__get_instance__\ndef file_segment(src_path: str, tgt_path: str, pos_tagged: bool = False) -> float:\n \"\"\"\n\n :param src_path: path of txt file\n :param tgt_path: path of result\n :param pos_tagged: POS tagging or not\n :return: time to process\n \"\"\"\n return __instance__.file_process(source_filename=src_path, result_filename=tgt_path, pos_tagged=pos_tagged)\n","sub_path":"nlpir/ictclas.py","file_name":"ictclas.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291398207","text":"import os\nfrom django.http import Http404\nfrom django.shortcuts import render,redirect\nfrom django.views.generic import TemplateView\nfrom django.views.generic.base import RedirectView\nfrom django.conf import settings\nfrom django.db.models import Prefetch\nfrom django.db.models.functions import Lower\n\nfrom benchmark.models import BM_EFOTrait\nfrom .tables import *\n\n\ngeneric_attributes =[ 'curation_notes','publication__title','publication__PMID','publication__authors','publication__curation_status','publication__curation_notes','publication__date_released']\npgs_defer = {\n 'generic': generic_attributes,\n 'perf' : [*generic_attributes,'date_released','score__curation_notes','score__date_released']\n}\npgs_prefetch = {\n 'trait': Prefetch('trait_efo', queryset=EFOTrait.objects.only('id','label').all()),\n 'perf' : ['score__publication', 'phenotyping_efo', 'sampleset__samples', 'sampleset__samples__sampleset', 'sampleset__samples__sample_age', 'sampleset__samples__followup_time', 'sampleset__samples__cohorts', 'performance_metric'],\n 'publication_score': Prefetch('publication_score', queryset=Score.objects.only('id', 'publication').all()),\n 'publication_performance': Prefetch('publication_performance', queryset=Performance.objects.only('id', 'publication', 'score').all().prefetch_related(Prefetch('score', queryset=Score.objects.only('id', 'publication').all()))),\n}\n\ndef disclaimer_formatting(content):\n return '
Disclaimer: {}
'.format(content)\n\ndef performance_disclaimer():\n return disclaimer_formatting(\"\"\"The performance metrics are displayed as reported by the source studies.\n It is important to note that metrics are not necessarily comparable with\n each other. For example, metrics depend on the sample characteristics\n (described by the PGS Catalog Sample Set [PSS] ID), phenotyping, and\n statistical modelling. Please refer to the source publication for additional\n guidance on performance.\"\"\")\n\ndef score_disclaimer(publication_url):\n return disclaimer_formatting(\"\"\"The original published polygenic score is unavailable.\n The authors have provided an alternative polygenic for the Catalog.\n Please note some details and performance metrics may differ from the publication.\"\"\".format(publication_url))\n\n\ndef get_efo_traits_data():\n \"\"\" Generate the list of traits and trait categories in PGS.\"\"\"\n data = []\n # Use set() to avoid duplication when an entry belongs to several categories\n traits_list = set()\n for category in TraitCategory.objects.all().prefetch_related('efotraits__associated_scores','efotraits__traitcategory').order_by('label'):\n cat_scores_count = 0\n cat_id = category.parent.replace(' ', '_')\n\n cat_traits = []\n\n for trait in category.efotraits.all():\n trait_scores_count = trait.scores_count\n if trait_scores_count == 0:\n continue\n cat_scores_count += trait_scores_count\n trait_entry = {\n \"name\": trait.label,\n \"size\": trait_scores_count,\n \"id\": trait.id\n }\n cat_traits.append(trait_entry)\n # Traits table\n traits_list.add(trait)\n\n if cat_scores_count == 0:\n continue\n\n cat_traits.sort(key=lambda x: x[\"name\"].lower())\n\n cat_data = {\n \"name\": category.label,\n \"colour\" : category.colour,\n \"id\" : cat_id,\n \"size_g\": cat_scores_count,\n \"children\": cat_traits\n }\n data.append(cat_data)\n\n traits_list = list(traits_list)\n traits_list.sort(key=lambda x: x.label)\n\n return [traits_list, data]\n\n\ndef index(request):\n current_release = Release.objects.values('date').order_by('-date').first()\n\n traits_count = EFOTrait.objects.count()\n\n context = {\n 'release' : current_release,\n 'num_pgs' : Score.objects.count(),\n 'num_traits' : traits_count,\n 'num_pubs' : Publication.objects.count(),\n 'num_benchmarks': BM_EFOTrait.objects.using('benchmark').count(),\n 'has_ebi_icons' : 1\n }\n if settings.PGS_ON_CURATION_SITE=='True':\n released_traits = set()\n for score in Score.objects.filter(date_released__isnull=False).prefetch_related('trait_efo'):\n for efo in score.trait_efo.all():\n released_traits.add(efo.id)\n released_traits_count = len(list(released_traits))\n trait_diff = traits_count - released_traits_count\n if trait_diff != 0:\n context['num_traits_not_released'] = trait_diff\n context['num_pgs_not_released'] = Score.objects.filter(date_released__isnull=True).count()\n context['num_pubs_not_released'] = Publication.objects.filter(date_released__isnull=True).count()\n\n return render(request, 'catalog/index.html', context)\n\n\ndef browseby(request, view_selection):\n context = {}\n\n if view_selection == 'traits':\n efo_traits_data = get_efo_traits_data()\n table = Browse_TraitTable(efo_traits_data[0])\n context = {\n 'view_name': 'Traits',\n 'table': table,\n 'data_chart': efo_traits_data[1],\n 'has_chart': 1\n }\n elif view_selection == 'studies':\n publication_defer = ['authors','curation_status','curation_notes','date_released']\n publication_prefetch_related = [pgs_prefetch['publication_score'], pgs_prefetch['publication_performance']]\n publications = Publication.objects.defer(*publication_defer).all().prefetch_related(*publication_prefetch_related)\n table = Browse_PublicationTable(publications, order_by=\"num\")\n context = {\n 'view_name': 'Publications',\n 'table': table,\n 'has_chart': 1\n }\n elif view_selection == 'sample_set':\n context['view_name'] = 'Sample Sets'\n table = Browse_SampleSetTable(Sample.objects.filter(sampleset__isnull=False).prefetch_related('sampleset', 'cohorts'))\n context['table'] = table\n else:\n context['view_name'] = 'Polygenic Scores (PGS)'\n score_only_attributes = ['id','name','publication','trait_efo','trait_reported','variants_number','publication__id','publication__date_publication','publication__journal','publication__firstauthor']\n table = Browse_ScoreTable(Score.objects.only(*score_only_attributes).select_related('publication').all().prefetch_related(pgs_prefetch['trait']), order_by=\"num\")\n context['table'] = table\n\n context['has_table'] = 1\n\n return render(request, 'catalog/browseby.html', context)\n\n\ndef pgs(request, pgs_id):\n # If ID in lower case, redirect with the ID in upper case\n if not pgs_id.isupper():\n return redirect_with_upper_case_id(request, '/score/', pgs_id)\n\n template_html_file = 'pgs.html'\n\n try:\n score = Score.objects.defer(*pgs_defer['generic']).select_related('publication').prefetch_related('trait_efo','samples_variants','samples_training').get(id__exact=pgs_id)\n except Score.DoesNotExist:\n raise Http404(\"Polygenic Score (PGS): \\\"{}\\\" does not exist\".format(pgs_id))\n\n pub = score.publication\n citation = format_html(' '.join([pub.firstauthor, 'et al. %s'%pub.journal, '(%s)' % pub.date_publication.strftime('%Y')]))\n citation = format_html('{}', pub.doi, citation)\n context = {\n 'pgs_id' : pgs_id,\n 'score' : score,\n 'citation' : citation,\n 'performance_disclaimer': performance_disclaimer(),\n 'efos' : score.trait_efo.all(),\n 'num_variants_pretty' : '{:,}'.format(score.variants_number),\n 'has_table': 1\n }\n if not score.flag_asis:\n context['score_disclaimer'] = score_disclaimer(score.publication.doi)\n\n # Extract and display Sample Tables\n if score.samples_variants.count() > 0:\n table = SampleTable_variants(score.samples_variants.all())\n context['table_sample_variants'] = table\n if score.samples_training.count() > 0:\n table = SampleTable_training(score.samples_training.all())\n context['table_sample_training'] = table\n\n # Extract + display Performance + associated samples\n pquery = Performance.objects.defer(*pgs_defer['perf']).select_related('score', 'publication').filter(score=score).prefetch_related(*pgs_prefetch['perf'])\n table = PerformanceTable(pquery)\n table.exclude = ('score')\n context['table_performance'] = table\n\n pquery_samples = set()\n for q in pquery:\n for sample in q.samples():\n pquery_samples.add(sample)\n\n table = SampleTable_performance(pquery_samples)\n context['table_performance_samples'] = table\n\n return render(request, 'catalog/'+template_html_file, context)\n\n\ndef redirect_with_upper_case_id(request, dir, id):\n id = id.upper()\n response = redirect(dir+str(id), permanent=True)\n return response\n\n\ndef redirect_pgs_to_score(request, pgs_id):\n response = redirect_with_upper_case_id(request, '/score/', pgs_id)\n return response\n\n\ndef pgp(request, pub_id):\n # If ID in lower case, redirect with the ID in upper case\n if not pub_id.isupper():\n return redirect_with_upper_case_id(request, '/publication/', pub_id)\n\n template_html_file = 'pgp.html'\n try:\n pub = Publication.objects.prefetch_related('publication_score', 'publication_performance').get(id__exact=pub_id)\n except Publication.DoesNotExist:\n raise Http404(\"Publication: \\\"{}\\\" does not exist\".format(pub_id))\n context = {\n 'publication' : pub,\n 'performance_disclaimer': performance_disclaimer(),\n 'has_table': 1\n }\n\n # Display scores that were developed by this publication\n related_scores = pub.publication_score.defer(*pgs_defer['generic']).select_related('publication').all().prefetch_related(pgs_prefetch['trait'])\n if related_scores.count() > 0:\n table = Browse_ScoreTable(related_scores)\n context['table_scores'] = table\n\n #Get PGS evaluated by the PGP\n pquery = pub.publication_performance.defer(*pgs_defer['perf']).select_related('publication','score').all().prefetch_related(*pgs_prefetch['perf'], 'score__trait_efo')\n\n # Check if there any of the PGS are externally developed + display their information\n external_scores = set()\n for perf in pquery:\n perf_score = perf.score\n if perf_score not in related_scores:\n external_scores.add(perf_score)\n if len(external_scores) > 0:\n table = Browse_ScoreTable(external_scores)\n context['table_evaluated'] = table\n\n #Find + table the evaluations\n table = PerformanceTable(pquery)\n context['table_performance'] = table\n\n pquery_samples = set()\n for q in pquery:\n for sample in q.samples():\n pquery_samples.add(sample)\n\n table = SampleTable_performance(pquery_samples)\n context['table_performance_samples'] = table\n\n context['has_table'] = 1\n return render(request, 'catalog/'+template_html_file, context)\n\n\ndef efo(request, efo_id):\n # If ID in lower case, redirect with the ID in upper case\n # If ID with ':', redirect using the ID with '_'\n if not efo_id.isupper() or ':' in efo_id:\n efo_id = efo_id.replace(':','_')\n return redirect_with_upper_case_id(request, '/trait/', efo_id)\n\n exclude_children = False\n include_children = request.GET.get('include_children');\n if include_children:\n if include_children.lower() == 'false':\n exclude_children = True\n\n try:\n ontology_trait = EFOTrait_Ontology.objects.prefetch_related('scores_direct_associations','scores_child_associations','child_traits').get(id__exact=efo_id)\n except EFOTrait_Ontology.DoesNotExist:\n raise Http404(\"Trait: \\\"{}\\\" does not exist\".format(efo_id))\n\n # Get list of PGS Scores\n related_direct_scores = ontology_trait.scores_direct_associations.defer(*pgs_defer['generic']).select_related('publication').all().prefetch_related(pgs_prefetch['trait'])\n related_child_scores = ontology_trait.scores_child_associations.defer(*pgs_defer['generic']).select_related('publication').all().prefetch_related(pgs_prefetch['trait'])\n if exclude_children:\n related_scores = related_direct_scores\n else:\n related_scores = list(related_direct_scores) + list(related_child_scores)\n related_scores.sort(key=lambda x: x.id)\n\n context = {\n 'trait': ontology_trait,\n 'trait_id_with_colon': ontology_trait.id.replace('_', ':'),\n 'trait_scores_direct_count': len(related_direct_scores),\n 'trait_scores_child_count': len(related_child_scores),\n 'performance_disclaimer': performance_disclaimer(),\n 'table_scores': Browse_ScoreTable(related_scores),\n 'include_children': False if exclude_children else True,\n 'has_table': 1\n }\n\n # Check if there are multiple descriptions\n try:\n desc_list = eval(ontology_trait.description)\n if type(desc_list) == list:\n context['desc_list'] = desc_list\n except:\n pass\n\n\n # Find the evaluations of these scores\n pquery = Performance.objects.defer(*pgs_defer['perf']).select_related('publication','score').filter(score__in=related_scores).prefetch_related(*pgs_prefetch['perf'])\n\n table = PerformanceTable(pquery)\n context['table_performance'] = table\n\n pquery_samples = set()\n for q in pquery:\n for sample in q.samples():\n pquery_samples.add(sample)\n\n table = SampleTable_performance(pquery_samples)\n context['table_performance_samples'] = table\n\n return render(request, 'catalog/efo.html', context)\n\n\ndef gwas_gcst(request, gcst_id):\n # If ID in lower case, redirect with the ID in upper case\n if not gcst_id.isupper():\n return redirect_with_upper_case_id(request, '/gwas/', gcst_id)\n\n samples = Sample.objects.filter(source_GWAS_catalog__exact=gcst_id).distinct()\n if len(samples) == 0:\n raise Http404(\"No PGS Samples are associated with the NHGRI-GWAS Catalog Study: \\\"{}\\\"\".format(gcst_id))\n\n related_scores = Score.objects.defer(*pgs_defer['generic']).select_related('publication').filter(samples_variants__in=samples).prefetch_related(pgs_prefetch['trait']).distinct()\n if len(related_scores) == 0:\n raise Http404(\"No PGS Scores are associated with the NHGRI-GWAS Catalog Study: \\\"{}\\\"\".format(gcst_id))\n\n context = {\n 'gwas_id': gcst_id,\n 'performance_disclaimer': performance_disclaimer(),\n 'table_scores' : Browse_ScoreTable(related_scores),\n 'has_table': 1\n }\n\n pquery = Performance.objects.defer(*pgs_defer['perf']).select_related('publication','score').filter(score__in=related_scores).prefetch_related(*pgs_prefetch['perf'])\n table = PerformanceTable(pquery)\n context['table_performance'] = table\n\n pquery_samples = set()\n for q in pquery:\n for sample in q.samples():\n pquery_samples.add(sample)\n\n table = SampleTable_performance(pquery_samples)\n context['table_performance_samples'] = table\n\n return render(request, 'catalog/gwas_gcst.html', context)\n\n\ndef pss(request, pss_id):\n # If ID in lower case, redirect with the ID in upper case\n if not pss_id.isupper():\n return redirect_with_upper_case_id(request, '/sampleset/', pss_id)\n\n try:\n sample_set = SampleSet.objects.prefetch_related('samples', 'samples__cohorts', 'samples__sample_age', 'samples__followup_time').get(id__exact=pss_id)\n except SampleSet.DoesNotExist:\n raise Http404(\"Sample Set: \\\"{}\\\" does not exist\".format(pss_id))\n\n table_cohorts = []\n samples_list = sample_set.samples.all()\n for sample in samples_list:\n # Cohort\n if sample.cohorts.count() > 0:\n table = CohortTable(sample.cohorts.all(), order_by=\"name_short\")\n table_cohorts.append(table)\n else:\n table_cohorts.append('')\n\n sample_set_data = zip(samples_list, table_cohorts)\n context = {\n 'pss_id': pss_id,\n 'sample_count': range(len(samples_list)),\n 'sample_set_data': sample_set_data,\n 'has_table': 1,\n 'has_chart': 1\n }\n\n related_performance = Performance.objects.defer(*pgs_defer['perf']).select_related('score', 'publication').filter(sampleset=sample_set).prefetch_related('score__publication', 'score__trait_efo', 'sampleset', 'phenotyping_efo', 'performance_metric')\n if related_performance.count() > 0:\n # Scores\n related_scores = [x.score for x in related_performance]\n table_scores = Browse_ScoreTable(related_scores)\n context['table_scores'] = table_scores\n # Display performance metrics associated with this sample set\n table_performance = PerformanceTable(related_performance)\n table_performance.exclude = ('sampleset')\n context['table_performance'] = table_performance\n context['performance_disclaimer'] = performance_disclaimer()\n\n return render(request, 'catalog/pss.html', context)\n\ndef releases(request):\n\n release_data = []\n pub_per_year_data = { 'all': [] }\n\n total_score = 0\n total_perf = 0\n total_publi = 0\n max_score = 0\n max_publi = 0\n max_perf = 0\n max_width = 100\n\n ## Publications distribution\n # All publications\n pub_per_year = {}\n publications = Publication.objects.all()\n for publication in publications:\n year = publication.pub_year\n if year in pub_per_year:\n pub_per_year[year] += 1\n else:\n pub_per_year[year] = 1\n\n for p_year in sorted(pub_per_year.keys()):\n pub_per_year_item = { 'year': p_year, 'count': pub_per_year[p_year] }\n pub_per_year_data['all'].append(pub_per_year_item)\n\n # Sepatate the \"Released\" and \"Not released\" Publications\n nr_publications = Publication.objects.filter(date_released__isnull=True)\n if len(nr_publications) > 0:\n nr_pub_per_year = {}\n for nr_publication in nr_publications:\n year = nr_publication.pub_year\n if year in nr_pub_per_year:\n nr_pub_per_year[year] += 1\n else:\n nr_pub_per_year[year] = 1\n pub_per_year_data['nr'] = []\n for p_year in sorted(nr_pub_per_year.keys()):\n pub_per_year_item = { 'year': p_year, 'count': nr_pub_per_year[p_year] }\n pub_per_year_data['nr'].append(pub_per_year_item)\n\n r_publications = Publication.objects.exclude(date_released__isnull=True)\n if len(r_publications) > 0:\n r_pub_per_year = {}\n for r_publication in r_publications:\n year = r_publication.pub_year\n\n if year in r_pub_per_year:\n r_pub_per_year[year] += 1\n else:\n r_pub_per_year[year] = 1\n pub_per_year_data['r'] = []\n for p_year in sorted(r_pub_per_year.keys()):\n pub_per_year_item = { 'year': p_year, 'count': r_pub_per_year[p_year] }\n pub_per_year_data['r'].append(pub_per_year_item)\n\n # Get max data\n releases_list = Release.objects.order_by('date')\n for release in releases_list:\n score = release.score_count\n perf = release.performance_count\n publi = release.publication_count\n if score > max_score:\n max_score = score\n if publi > max_publi:\n max_publi = publi\n if perf > max_perf:\n max_perf = perf\n\n for release in releases_list:\n score = release.score_count\n perf = release.performance_count\n publi = release.publication_count\n date = release.date\n\n release_item = {\n 'date': date.strftime('%d/%m/%y'),\n 'score_count': score,\n 'performance_count': perf,\n 'publication_count': publi,\n 'total_score_count': total_score,\n 'total_performance_count': total_perf,\n 'total_publication_count': total_publi,\n }\n total_score += score\n total_perf += perf\n total_publi += publi\n\n release_data.append(release_item)\n\n context = {\n 'releases_list': releases_list.order_by('-date'),\n 'releases_data': release_data,\n 'pub_per_year_data': pub_per_year_data,\n 'max_score': max_score,\n 'max_publi': max_publi,\n 'max_perf': max_perf,\n 'has_table': 1,\n 'has_chart_js': 1\n }\n return render(request, 'catalog/releases.html', context)\n\n\ndef upload_metadata(request):\n context = {}\n from django.core.files.storage import default_storage\n if request.method == 'POST' and request.FILES['myfile']:\n file_name = request.FILES['myfile'].name\n file_content = request.FILES['myfile'].read()\n file = default_storage.open(file_name, 'w')\n file.write(file_content)\n file.close()\n context['uploaded_file'] = True\n context['filename'] = file_name\n\n return render(request, 'catalog/upload.html', context)\n\n\nclass AboutView(TemplateView):\n template_name = \"catalog/about.html\"\n\nclass DocsView(TemplateView):\n template_name = \"catalog/docs.html\"\n\nclass DownloadView(TemplateView):\n template_name = \"catalog/download.html\"\n\nclass ReportStudyView(TemplateView):\n template_name = \"catalog/report_study.html\"\n\nclass CurrentTemplateView(RedirectView):\n url = settings.USEFUL_URLS['TEMPLATEGoogleDoc_URL']\n\nclass CurationDocView(RedirectView):\n url = settings.USEFUL_URLS['CurationGoogleDoc_URL']\n\n\n# Method used for the App Engine warmup\ndef warmup(request):\n \"\"\"\n Provides default procedure for handling warmup requests on App\n Engine. Just add this view to your main urls.py.\n \"\"\"\n import importlib\n from django.http import HttpResponse\n for app in settings.INSTALLED_APPS:\n for name in ('urls', 'views', 'models'):\n try:\n importlib.import_module('%s.%s' % (app, name))\n except ImportError:\n pass\n content_type = 'text/plain; charset=utf-8'\n return HttpResponse(\"Warmup done.\", content_type=content_type)\n","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396713517","text":"# coding: utf-8\r\n\r\nimport time,sys,os\r\nsys.path.append(os.getcwd())\r\nsys.path.append(os.getcwd()+'/../')\r\n\r\nfrom HPSocket import TcpPack\r\nfrom HPSocket import helper\r\nimport HPSocket.pyhpsocket as HPSocket\r\n\r\nclass Client(TcpPack.HP_TcpPackClient):\r\n counter = 0\r\n EventDescription = TcpPack.HP_TcpPackServer.EventDescription\r\n\r\n @EventDescription\r\n def OnSend(self, Sender, ConnID, Data):\r\n print('[%d, OnSend] < %s' % (ConnID, repr(Data)))\r\n\r\n @EventDescription\r\n def OnConnect(self, Sender, ConnID):\r\n print('[%d, OnConnect] Success.' % ConnID)\r\n\r\n @EventDescription\r\n def OnReceive(self, Sender, ConnID, Data):\r\n print('[%d, OnReceive] < %s' % (ConnID, repr(Data)))\r\n self.SendTest()\r\n\r\n def SendTest(self):\r\n self.counter += 1\r\n self.Send(self.Client, 'text to be sent - %d' % self.counter)\r\n\r\n\r\nif __name__ == '__main__':\r\n cnt = Client()\r\n cnt.Start(host='127.0.0.1', port=5555, head_flag=0x169)\r\n cnt.SendTest()\r\n while True:\r\n time.sleep(1)","sub_path":"Demo/TcpPackClient.py","file_name":"TcpPackClient.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114628136","text":"#!/usr/bin/python\nimport re\n\ndef func():\n lst = input(\"1st list: \")\n lst1 = set(re.findall(\"\\d+\", lst))\n lst = input(\"2nd list: \")\n lst2 = set(re.findall(\"\\d+\", lst))\n\n print(\"=> union\")\n print(sorted(list(map(int,list(lst1 | lst2)))))\n \n print(\"=> intersection\")\n print(sorted(list(map(int,list(lst1 & lst2)))))\n \n","sub_path":"py_lab2/my_pkg/unionInteger.py","file_name":"unionInteger.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446305353","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description' : 'Simple dummy project',\n 'author' : 'gitnik',\n 'url' : 'there is no url',\n 'download_url' : 'nowhere',\n 'author_email' : 'none',\n 'version' : '0.1',\n 'install_requires' : ['nose'],\n 'packages' : ['dummy'],\n 'scripts' : ['bin/bmi.py'],\n 'name' : 'dummy'\n}\n\nsetup(**config)\n","sub_path":"learn-python-the-hard-way-exercises/exercise-46/projects/dummy_project/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"57203635","text":"\"\"\"Sector Alarm Sensor.\"\"\"\nimport asyncio\nimport logging\nimport hearth\nimport sectoralarm\n\n__all__ = ['SectorAlarm']\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass SectorAlarm(hearth.Device):\n \"\"\"Sector Alarm Sensor.\"\"\"\n\n async def __init__(self, id_, username, password, panel):\n \"\"\"Init.\"\"\"\n await super().__init__(id_)\n await self.init_state({\n 'armed': \"disarmed\",\n 'armed_time': \"\",\n 'armed_by': \"\",\n 'temperatures': []\n })\n self.username = username\n self.password = password\n self.panel = panel\n self.session = None\n self.sleeptime = 600\n self.temperature_devices = {}\n await self.connect()\n asyncio.ensure_future(self.syncer())\n\n async def connect(self):\n \"\"\"Connect.\"\"\"\n self.session = await sectoralarm.Session(self.username,\n self.password,\n self.panel)\n\n async def sync(self):\n \"\"\"Sync data.\"\"\"\n try:\n new_state = {}\n armstate = await self.session.get_arm_state()\n new_state['armed'] = armstate['message']\n new_state['armed_time'] = armstate['timeex']\n new_state['armed_by'] = armstate['user']\n temps = (await self.session.get_temperature())['temperatureComponentList']\n new_state['temperatures'] = [\n {key: temp[key] for key in ['serialNo', 'label', 'temperature']}\n for temp in temps]\n if 'armed' in new_state and new_state['armed'] != self.state['armed']:\n LOGGER.debug(\"Got SA state: %s\", new_state)\n await self.update_state(new_state)\n except Exception as e:\n LOGGER.warning(\"SectorAlarm exception: %s\", e)\n await self.update_state({\"reachable\": False}, False)\n await self.connect()\n\n async def syncer(self):\n \"\"\"Stay in sync.\"\"\"\n while True:\n await self.sync()\n await asyncio.sleep(self.sleeptime)\n\n def ui(self):\n \"\"\"Return ui representation.\"\"\"\n uix = {\"ui\": [\n {\"class\": \"Text\",\n \"props\": {\"label\": \"Armed\"},\n \"state\": \"armed\"},\n {\"class\": \"Text\",\n \"props\": {\"label\": \"Armed at\"},\n \"state\": \"armed_time\"},\n {\"class\": \"Text\",\n \"props\": {\"label\": \"Armed by\"},\n \"state\": \"armed_by\"},\n ],\n \"state\": {}}\n for therm in self.state.get('temperatures', []):\n uix['ui'].append(\n {\"class\": \"Text\",\n \"props\": {\"label\": therm['label'], \"format\": \"{} °C\"},\n \"state\": 'temp' + therm['serialNo']},\n )\n uix['state'].update({'temp' + therm['serialNo']: therm['temperature']})\n return uix\n","sub_path":"hearth/devices/sectoralarm.py","file_name":"sectoralarm.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29059897","text":"from __future__ import print_function\n\n\nfrom MMTK import *\nfrom PIGSHarmonicOscillatorFF import PIGSHarmonicOscillatorForceField\n\nfrom MMTK.ForceFields.ForceFieldTest import gradientTest, forceConstantTest\nfrom MMTK_PIGSNormalModeIntegrator import PIGSLangevinNormalModeIntegrator\nfrom MMTK.Environment import PathIntegrals\nfrom MMTK.Trajectory import Trajectory, TrajectoryOutput\nfrom MMTK.Dynamics import VelocityVerletIntegrator\n\n\n# neil\nimport numpy as np\nimport sys\n\n############################# IMPORT THE TRAJECTORY ##########################\ndef run(P = 129.0, beta = 8.0, tau = (0.0625 / Units.K), outdir = None, outfile = None):\n #if (outdir == None) or (outfile == None) :\n # sys.exit(\"outdir or outfile not provided, can't run() estimator.py\")\n\n for P in [np.power(2, x) + 1 for x in range(2, 10)]:\n beta = ((P-1) * tau) if (P != 129) else float(8.0)\n # gather our information and prepare files to write to\n try:\n print(str(P))\n trajectory_file = Trajectory(None, \"./workspace/betaho\" + str(P) + \".nc\")\n universe = trajectory_file.universe\n plotting_file = open(\"./workspace/betaho\" + str(P) + \".plt\",\"w\")\n except IOError as e:\n print(\"ERROR could not open file: \\'\" + str(outfile) + \"\\'\", file = sys.stderr)\n else:\n semi_classical_array = np.empty(len(trajectory_file)) # store the results in this array\n middle_point = (len(trajectory_file) / 2) # calculate the 'middle point' of our data sample, \n # this value is ACTUALLY half the size of the data sample, it is refered to as the 'middle point' because\n # it is used as an index when claculating values from either the first or second half of semi_classical_array\n\n\n # operate over the whole trajectory\n for index in xrange(len(trajectory_file)):\n universe.setFromTrajectory(trajectory_file, index)\n # for the first half of our data we need are calculating the numerator \n # for the second half of our data we need are calculating the denominator\n denominator = (False) if (index < middle_point) else (True) \n semi_classical_array[index] = estimator_semi_classical(universe, index, denominator, P, beta, tau) # this is where the estimation happens\n \n # find the mean of the numerator and denominator\n numerator_mean = np.mean(semi_classical_array[0:middle_point:1], axis = 0)\n denominator_mean = np.mean(semi_classical_array[middle_point::1], axis = 0)\n\n # the actual result of our estimator\n estimator_result = np.divide(numerator_mean, denominator_mean)\n \n # calculate the standard error of the numerator, denominator and the combined standard error\n numerator_std_err = np.std(semi_classical_array[0:middle_point:1], axis = 0, ddof = 1) / np.sqrt(middle_point)\n denominator_std_err = np.std(semi_classical_array[middle_point::1], axis = 0, ddof = 1) / np.sqrt(middle_point)\n combined_std_err = (numerator_std_err / denominator_mean) + ((numerator_mean * denominator_std_err) / np.power(denominator_mean, 2))\n\n \n # print for debugging purposes\n #print(estimator_result)\n #print(numerator_std_err)\n #print(denominator_std_err)\n #print(combined_std_err)\n\n # write them to a file\n outstring = \"\"\n for x in [ str(beta),\n str(estimator_result), \n str(numerator_mean), \n str(denominator_mean), \n str(numerator_std_err),\n str(denominator_std_err),\n str(combined_std_err) ]:\n outstring.join(x).join(\"\\n\")\n\n print(outstring, file=plotting_file)\n print(\"Finished writing to file\" + \" Numerator mean: \" + str(numerator_mean) + \" Denominator mean: \" + str(denominator_mean))\n \n \n plotting_file.close()\n trajectory_file.close()\n del universe\n del trajectory_file\n\n\n # done\n\n######################### SEMI CLASSICAL ESTIMATOR ##########################\ndef estimator_semi_classical(u_verse, i, denominator, P, beta, tau):\n\n # we use these two parameters in our equation\n omega = ((1.0 * Units.K * Units.k_B)/Units.hbar) # in THz\n w_2 = np.power(omega, 2) # we use this often enough\n\n # for now we only care about one particle\n atom = 0\n\n # define the middle bead\n M = (P-1) / 2\n\n # fetches one dimension of the position of a specific bead\n left = lambda dimension_index: u_verse.atomList()[0].beadPositions()[M-1][dimension_index]\n middle = lambda dimension_index: u_verse.atomList()[0].beadPositions()[M][dimension_index]\n right = lambda dimension_index: u_verse.atomList()[0].beadPositions()[M+1][dimension_index]\n\n # this function 'fetches' one dimension of the momentum of an atom \n m = u_verse.atomList()[0].mass()\n p = lambda dimension_index: u_verse.velocities()[M][dimension_index] * m / (P-1)\n\n # the q's\n q = lambda dimension_index, denominator: 1 if (denominator is True) else (left(dimension_index) * right(dimension_index))\n\n # meat and potatoes, equation version three\n fn = lambda d, denominator: (\n (np.sqrt(2.0) / (P-1))\n * q(d, denominator)\n * np.exp( (m * Units.k_B * np.power((right(d) - left(d)), 2) / (4.0 * Units.hbar * Units.hbar * tau))\n + ((beta * (P-1) * np.power(p(d),2)) / (2.0 * Units.k_B * m))\n ) \n * np.cos( (p(d) * (left(d) - right(d))) / Units.hbar ))\n\n return (fn(0, denominator) + fn(1, denominator) + fn(2, denominator)) / 3\n\n######################### RUNNING ESTIMATOR DIRECTLY ##########################\nif(__name__ == \"__main__\"):\n import argparse\n parser = argparse.ArgumentParser(prog='estimator.py', description='Preforms black magic rituals developed by Dimitry', \n usage = '%(prog)s [-h] [-d DIRECTORYNAME] [-f FILENAME] [-p BEADSVALUE' \n + '\\n%(prog)s [--help] [--outputdirectory DIRECTORYNAME] [--outputfile FILENAME] [--beads BEADSVALUE]',\n epilog='Extra information can be displayed here, such as a riddle: \"What walks on four legs in the morning, two legs in the afternoon, and three legs in the evening\" ')\n parser.add_argument(\"-d\", \"--outputdirectory\", action=\"store\", help=\"Provide a name for the directory that the output file is written to\")\n parser.add_argument(\"-f\", \"--outputfile\", action=\"store\", help=\"Provide a name for the file that output is written to\")\n parser.add_argument(\"-p\", \"--beads\", type=int, action=\"store\", help=\"Provide the number of beads to replace the default of 129\")\n parser_args = parser.parse_args() # prepare the argument parser\n\n # get the input paramaters\n #if (parser_args.outputfile == False) or (parser_args.beads == False):\n # print(\"You must provide a trajectory filename and a number of beads\")\n # sys.exit()\n\n directoryname = (parser_args.outputdirectory) if (parser_args.outputdirectory) else (\"./workspace/\")\n\n # run the job\n run(P = parser_args.beads, outdir = directoryname, outfile = parser_args.outputfile)\n\n\n\n\n","sub_path":"Resources/old code/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":7531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"257520611","text":"elements = []\r\nsum = 0\r\nlimit = int(input(\"Enter the number of elements: \"))\r\nprint(\"Enter a number: \")\r\nfor i in range(0,limit):\r\n number = int(input())\r\n elements.append(number) \r\n\r\nprint(elements)\r\n\r\nfor element in elements:\r\n sum+=element\r\n\r\nresult = \"Sum of all elements from list {}\"\r\nprint(result.format(sum))","sub_path":"Python/Activities/Activity7.py","file_name":"Activity7.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393946505","text":"import math\ndef func1(a):\n if(a>0):\n b = math.floor(a)\n if (a<0):\n b = math.ceil(a)\n return b\n\n\na = float(input(\"Enter some number \"))\nprint(a)\n\nd = func1(a)\nprint(d)","sub_path":"Python/שבוע 7/מעבדה/LAB6Q2.py","file_name":"LAB6Q2.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180935949","text":"from math import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\nfrom tkinter import *\n\n\nclass Cylinder:\n def __init__(self, radius, height):\n self.radius = radius\n self.height = height\n a = int(input(\"Enter the accuracy of circle: \"))\n self.appr = a\n self.longs = a\n self.userTheta = 0\n self.userHeight = 0\n self.light = [1.0, 1.0, 1.25]\n b = float(input(\"Enter the lighting level: \"))\n self.intensity = [b, b, b]\n self.ambient_intensity = [0.1, 0.1, 0.1]\n # Поверхность (SMOTH или FLAT)\n self.surface = GL_SMOOTH\n\n def init(self):\n # Цвет бэкграунда\n glClearColor(0.0, 0.0, 0.0, 0.0)\n self.compute_location()\n # Закрытие объектами друг друга\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_LIGHTING)\n # Модель освещения (включение отражение окружения)\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, self.ambient_intensity)\n # Начало работы со светильником 0\n glEnable(GL_LIGHT0)\n # Установка светильника и его уровня освещения\n glLightfv(GL_LIGHT0, GL_POSITION, self.light)\n glLightfv(GL_LIGHT0, GL_DIFFUSE, self.intensity)\n # Включеие окрашивания поверхности\n glEnable(GL_COLOR_MATERIAL)\n # Окраска передней части\n glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE)\n\n def compute_location(self):\n x = 2 * cos(self.userTheta)\n y = 2 * sin(self.userTheta)\n z = self.userHeight\n d = sqrt(x * x + y * y + z * z) * 0.5\n # Установка режима матрицы\n glMatrixMode(GL_PROJECTION)\n # Замена матрицы\n glLoadIdentity()\n glFrustum(-d, d, -d, d, d, 5)\n # Начальное положение видимости\n gluLookAt(x, y, z, 0, 0, 0, 0, 0, 1)\n\n def drawCylinder(self):\n circle_pts = []\n for i in range(self.appr + 1):\n angle = 2 * pi * (i / float(self.appr))\n x = self.radius * cos(angle)\n y = self.radius * sin(angle)\n pt = (x, y)\n circle_pts.append(pt)\n\n glBegin(GL_TRIANGLE_FAN) # drawing the back circle\n glNormal(0, 0, self.height / 2.0)\n glVertex(0, 0, self.height / 2.0)\n for (x, y) in circle_pts:\n z = self.height / 2.0\n glVertex(x, y, z)\n glEnd()\n\n glBegin(GL_TRIANGLE_FAN) # drawing the front circle\n glNormal(0, 0, self.height / 2.0)\n glVertex(0, 0, self.height / 2.0)\n for (x, y) in circle_pts:\n z = -self.height / 2.0\n glVertex(x, y, z)\n glEnd()\n\n glBegin(GL_TRIANGLE_STRIP) # draw the tube\n for (x, y) in circle_pts:\n z = self.height / 2.0\n glNormal(x, y, z)\n glVertex(x, y, z)\n glNormal(x, y, -z)\n glVertex(x, y, -z)\n glEnd()\n\n def display(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n # Цвет оокрашивания\n glColor3f(0.5, 0.0, 0.0)\n # Модель шейдеров\n glShadeModel(self.surface)\n self.drawCylinder()\n self.draw_coordinate_system()\n self.draw_light()\n # Замена буфера на другое окно\n glutSwapBuffers()\n\n def draw_coordinate_system(self):\n glBegin(GL_LINES)\n # oX\n glColor3f(1.0, 0.0, 0.0);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(3.0, 0.0, 0.0);\n # oY\n glColor3f(0.0, 1.0, 0.0);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(0.0, 3.0, 0.0);\n # oZ\n glColor3f(0.0, 0.0, 1.0);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(0.0, 0.0, 3.0);\n glEnd()\n\n def draw_light(self):\n glPointSize(10)\n glBegin(GL_POINTS)\n # Светильник\n glColor3f(1.0, 1.0, 1.0)\n glVertex3f(0.0, 0.0, 2.0)\n glEnd()\n\n def special(self, key, x, y):\n # камера up/down\n if key == GLUT_KEY_UP:\n self.userHeight += 0.1\n if key == GLUT_KEY_DOWN:\n self.userHeight -= 0.1\n # Кручение камеры\n if key == GLUT_KEY_LEFT:\n self.userTheta += 0.1\n if key == GLUT_KEY_RIGHT:\n self.userTheta -= 0.1\n # Изменение поверхности\n if key == GLUT_KEY_HOME:\n if self.surface == GL_FLAT:\n self.surface = GL_SMOOTH\n else:\n self.surface = GL_FLAT\n # Изменение освещения\n if key == GLUT_KEY_PAGE_UP:\n b = max(self.intensity)\n for i in range(0, 3):\n self.intensity.pop()\n self.intensity += [b + 0.2, b + 0.2, b + 0.2]\n glLightfv(GL_LIGHT0, GL_DIFFUSE, self.intensity)\n if key == GLUT_KEY_PAGE_DOWN:\n b = max(self.intensity)\n for i in range(0, 3):\n self.intensity.pop()\n if b <= 0.2:\n self.intensity += [0.0, 0.0, 0.0]\n else:\n self.intensity += [b - 0.2, b - 0.2, b - 0.2]\n glLightfv(GL_LIGHT0, GL_DIFFUSE, self.intensity)\n self.compute_location()\n glutPostRedisplay()\n\n\ndef main():\n glutInit(sys.argv)\n glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)\n glutInitWindowSize(600, 600)\n glutInitWindowPosition(400, 100)\n glutCreateWindow(b\"Cylinder\")\n s = Cylinder(0.7, 1.2)\n s.init()\n glutDisplayFunc(s.display)\n glutSpecialFunc(s.special)\n glutMainLoop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"CG/lab4/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337882093","text":"import unittest\nfrom hamcrest import assert_that, is_, has_entries\nfrom backdrop.core.bucket import BucketConfig\nfrom backdrop.core.database import Database\nfrom backdrop.core.repository import BucketConfigRepository, UserConfigRepository\nfrom backdrop.core.user import UserConfig\n\nHOST = ['localhost']\nPORT = 27017\nDB_NAME = 'performance_platform_test'\nBUCKET = 'buckets'\n\n\nclass TestBucketRepositoryIntegration(unittest.TestCase):\n\n def setUp(self):\n self.db = Database(HOST, PORT, DB_NAME)\n self.db._mongo.drop_database(DB_NAME)\n self.mongo_collection = self.db.get_collection(BUCKET)\n self.repository = BucketConfigRepository(self.db)\n\n def test_saving_a_config_with_default_values(self):\n config = BucketConfig(\"some_bucket\", data_group=\"group\", data_type=\"type\")\n\n self.repository.save(config)\n\n results = list(self.mongo_collection._collection.find())\n\n assert_that(len(results), is_(1))\n assert_that(results[0], has_entries({\n \"name\": \"some_bucket\",\n \"raw_queries_allowed\": False,\n \"bearer_token\": None,\n \"upload_format\": \"csv\"\n }))\n\n def test_saving_a_realtime_config_creates_a_capped_collection(self):\n config = BucketConfig(\"realtime_bucket\", data_group=\"group\", data_type=\"type\", realtime=True)\n\n self.repository.save(config)\n\n assert_that(self.db.mongo_database[\"realtime_bucket\"].options(), is_({\"capped\": True, \"size\": 5040}))\n\n def test_retrieves_config_by_name(self):\n self.repository.save(BucketConfig(\"not_my_bucket\", data_group=\"group\", data_type=\"type\"))\n self.repository.save(BucketConfig(\"my_bucket\", data_group=\"group\", data_type=\"type\"))\n self.repository.save(BucketConfig(\"someones_bucket\", data_group=\"group\", data_type=\"type\"))\n\n config = self.repository.retrieve(name=\"my_bucket\")\n\n assert_that(config.name, is_(\"my_bucket\"))\n\n def test_retrieves_config_for_service_and_data_type(self):\n self.repository.save(BucketConfig(\"b1\", data_group=\"my_service\", data_type=\"my_type\"))\n self.repository.save(BucketConfig(\"b2\", data_group=\"my_service\", data_type=\"not_my_type\"))\n self.repository.save(BucketConfig(\"b3\", data_group=\"not_my_service\", data_type=\"my_type\"))\n\n config = self.repository.get_bucket_for_query(data_group=\"my_service\", data_type=\"my_type\")\n\n assert_that(config.name, is_(\"b1\"))\n\n\nclass TestUserRepositoryIntegration(object):\n def setUp(self):\n self.db = Database(HOST, PORT, DB_NAME)\n self.db._mongo.drop_database(DB_NAME)\n self.mongo_collection = self.db.get_collection(\"users\")._collection\n self.mongo_collection.drop()\n self.repository = UserConfigRepository(self.db)\n\n def test_saving_a_config_with_no_buckets(self):\n config = UserConfig(email=\"test@example.com\")\n\n self.repository.save(config)\n\n results = list(self.mongo_collection.find())\n\n assert_that(len(results), is_(1))\n assert_that(results[0], has_entries({\n \"email\": \"test@example.com\",\n \"buckets\": [],\n }))\n","sub_path":"tests/core/integration/test_repository.py","file_name":"test_repository.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366035786","text":"#!/usr/bin/env python3\n\ndef random_NA(matrix_complete, remove_level):\n \"\"\"Introduce random NA's in matrix\"\"\"\n import random, copy\n random.seed(13)\n\n matrix = copy.deepcopy(matrix_complete)\n N_matrix_rows = len(matrix)\n N_matrix_cols = len(matrix[0])\n\n N = N_matrix_rows * N_matrix_cols # Calculate total number of cells in matrix\n N_remove = int(N * remove_level)\n\n removed_dict = dict()\n\n for i in range(N_remove):\n row_remove = random.randrange(0,N_matrix_rows) # Select random row for removal\n col_avail = set((range(N_matrix_cols)))\n\n if row_remove in removed_dict:\n # Remove already selected columns (found in dict)\n col_avail = col_avail.difference(removed_dict[row_remove])\n if col_avail: # Skipping if all columns for row have already been selected (NEEDS FIXING)\n col_remove = random.choice(tuple(col_avail))\n removed_dict[row_remove].add(col_remove)\n else:\n col_remove = random.choice(tuple(col_avail))\n removed_dict[row_remove] = set()\n removed_dict[row_remove] = {col_remove}\n\n matrix[row_remove][col_remove] = 'NA'\n\n return(matrix)\n","sub_path":"random_remove.py","file_name":"random_remove.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141999654","text":"from django.shortcuts import render\nfrom rest_framework import viewsets\nfrom .models import Masjid\nfrom .serializers import MasjidSerializer\nfrom . import tablecontext\nfrom .forms import MasjidForm\nfrom django.shortcuts import redirect\n# Create your views here.\n\ndef home(request):\n t_context = tablecontext.index()\n t_context[\"navbar\"] =True\n return render(request,\"masjid/home.html\",t_context)\n\ndef add(request):\n if request.method == \"POST\":\n masjidform = MasjidForm(request.POST)\n if masjidform.is_valid():\n masjidform.save()\n else:\n print(masjidform.errors)\n else:\n masjidform = MasjidForm()\n\n context = {\n \"form\":masjidform,\n \"navbar\":True,\n \"formtitle\":\"Add new mazjid\",\n \"url\":\"/masjid/add/\"\n }\n return render(request,\"masjid/forms.html\",context)\n\ndef edit(request,id):\n masjid = Masjid.objects.get(id=id)\n if request.method == \"POST\":\n masjidform = MasjidForm(request.POST,instance=masjid)\n if masjidform.is_valid():\n masjidform.save()\n else:\n print(masjidform.errors)\n else:\n masjidform = MasjidForm(instance= masjid)\n\n context = {\n \"form\":masjidform,\n \"navbar\":True,\n \"formtitle\":\"Add new mazjid\",\n \"url\":\"/masjid/edit/\"+str(id)\n }\n return render(request,\"masjid/forms.html\",context)\n\ndef delete(request,id):\n masjid = Masjid.objects.get(id=id)\n deleted = False\n if request.method == \"POST\":\n #masjidform = MasjidForm(data=request.POST,instance=masjid)\n masjid.delete()\n deleted = True\n else:\n masjidform = MasjidForm(instance= masjid)\n\n context = {\n \"form\":masjidform,\n \"navbar\":True,\n \"formtitle\":\"Delete mazjid\",\n \"url\":\"/masjid/delete/\"+str(id),\n \"delete_form\": \"true\",\n }\n if deleted:\n return redirect('/masjid/',permanent=True)\n else:\n return render(request,\"base/forms.html\",context)\n\ndef details(request,id):\n data = Masjid.objects.get(id=id)\n context = {\n 'data':data,\n 'details':\"Mazjid Details\",\n \"navbar\":True,\n }\n return render(request,'masjid/details.html',context)\n\n\n\nclass MasjidViewSet(viewsets.ModelViewSet):\n queryset = Masjid.objects.all()\n serializer_class = MasjidSerializer","sub_path":"mezan/masjid/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265564036","text":"#!/usr/bin/env python3\n\n\n\"\"\"\nSession03 - Part I\n\n\nhttps://uwpce-pythoncert.github.io/PythonCertDevel/exercises/mailroom.html#exercise-mailroom\n\nWrite a small command-line script called mailroom.py. This script should be executable.\nThe script should accomplish the following goals:\n\n It should have a data structure that holds a list of your donors and a history of the\n amounts they have donated. This structure should be populated at first with at least\n five donors, with between 1 and 3 donations each.\n\n You can store that data structure in the global namespace.\n\n The script should prompt the user (you) to choose from a menu of 3 actions:\n “Send a Thank You”, “Create a Report” or “quit”)\n\n\n\n### Finally, use only functions and the basic Python data types you’ve learned about so far.\nThere is no need to go any farther than that for this assignment.\n\n/*\nDonor Name | Total Given | Num Gifts | Average Gift\n------------------------------------------------------------------\nWilliam Gates, III $ 653784.49 2 $ 326892.24\nMark Zuckerberg $ 16396.10 3 $ 5465.37\nJeff Bezos $ 877.33 1 $ 877.33\nPaul Allen $ 708.42 3 $ 236.14\n*/\n\n/*\n\n\n*/\n\"\"\"\n\n# donor_db = {\"William Gates, III\":[326888.82, 326895.67],\n# \"Mark Zuckerberg\":[5565.37, 5465.37, 5365.36],\n# \"Jeff Bezos\":[877.33],\n# \"paul allen\":[236.14, 236.14, 236.14],\n# \"jose gonzalez\" : [123.45, 678.90, 101.11]\n# }\n\ndonor_db = {\"william gates, iii\":[326888.82, 326895.67],\n \"mark zuckerberg\":[5565.37, 5465.37, 5365.36],\n \"jeff bezos\":[877.33],\n \"paul allen\":[236.14, 236.14, 236.14],\n \"jose gonzalez\" : [123.45, 678.90, 101.11]\n }\n\n\ndef format_donor_name(donor_names):\n if ',' in donor_names:\n name_title=donor_names.split(',')\n i_var=name_title[0].title() + ','\n donor_names=i_var.replace(',', \",\" + name_title[1].upper())\n return(donor_names)\n else:\n name_title=donor_names\n return(donor_names.title())\n\n\ndef print_donor_name(donor_db):\n \"\"\"\n Output the donor name(s)\n :param: donor_db dict\n :returns: zero for success\n \"\"\"\n print(\"Donor list: \\n\")\n for donor_names in donor_db.keys():\n if ',' in donor_names:\n name_title=donor_names.split(',')\n i_var=name_title[0].title() + ','\n donor_names=i_var.replace(',', \",\" + name_title[1].upper())\n print(donor_names)\n else:\n name_title=donor_names\n print(donor_names.title())\n return 0\n\n\ndef get_donor(name):\n \"\"\"\n get a donor out of the donor \"structure\"\n :params: name/\n :return: donor\n \"\"\"\n for donor in donor_db:\n if name.strip().lower() == donor[0].lower():\n \"\"\" get the name in lowercase, makes matching names easier later\"\"\"\n return donor\n\n return None # or should this be donor?\n\n\ndef send_thank_you():\n \"\"\"\n Record a donation, create a thank you letter.\n \"\"\"\n\n # use a while loop to get the user input and execute a function\n # basic input checking, strip whitespace\n while True:\n name = input(\"Enter a donor's name \"\n \"(or 'list' to see all donors or 'menu' to exit)> \").strip()\n if name == \"list\":\n print_donor_name(donor_db)\n elif name == \"menu\":\n return\n else:\n if name.lower() in donor_db.keys():\n print(\"name: \", format_donor_name(name), \"found.\")\n print(create_letter(name, donor_db))\n else:\n if name.lower() not in donor_db.keys():\n print(\"name: \", format_donor_name(name), \"is NOT found.\")\n print(\"debug: adding a function call to add donor.\")\n add_donor_info(name, donor_db)\n break\n\n\ndef print_menu():\n getInputVar=(input('''Choose an action:\n\n 1 - Send a Thank You\n 2 - Create a Report\n 3 - Send letters to everyone\n 4 - Quit\n 5 - Add additional contribution\n '''))\n\n return getInputVar.strip()\n\n\ndef report_sort_key(item):\n \"\"\"list.sort(key=\"\") thing must be a function\n \"\"\"\n return item[1]\n\n\ndef print_donor_report(donor_database):\n \"\"\"\n Output report of donors\n \"\"\"\n # First, reduce the raw data into a summary list view\n report_rows = []\n for (name, gifts) in donor_database.items():\n name = format_donor_name(name)\n total_gifts = sum(gifts)\n num_gifts = len(gifts)\n avg_gift = total_gifts / num_gifts\n report_rows.append((name, total_gifts, num_gifts, avg_gift))\n\n # sort the report data\n report_rows.sort(key=report_sort_key)\n # print it out in with a nice format.\n print(\"{:25s} | {:11s} | {:9s} | {:12s}\".format(\n \"Donor Name\", \"Total Given\", \"Num Gifts\", \"Average Gift\"))\n print(\"-\" * 66) # Make 66 little '-'s\n for row in report_rows:\n print(\"{:25s} {:11.2f} {:9d} {:12.2f}\".format(*row))\n\n\ndef create_letter(donor, donor_db):\n \"\"\"\n Create a thank you letter for the donor\n :param: donor/string, donor_db dict/string:tuple\n :returns: string with letter\n \"\"\"\n return '''\\n\n Dear {},\n\n Thank you for your very kind donation of ${:.2f}.\n It will be put to very good use.\n Your generous contributions to date totaling ${:.2f}\n allow us continue our mission and achive our joint goals.\n\n Sincerely,\n -The Team\n '''.format(format_donor_name(donor), donor_db[donor][-1], sum(donor_db[donor]))\n\n\ndef send_letters_to_all(donor_db):\n \"\"\"\n\n :params: donor_db/dict,\n :returns: 0 if completes\n\n :description:\n In this version, add a function (and a menu item to invoke it),\n that goes through all the donors in your donor data structure,\n generates a thank you letter, and writes it to disk as a text file.\n\n menu_item, menu #3\n\n \"\"\"\n\n for k in donor_db.keys():\n\n file_name=format_donor_name(k).replace(',','').replace(\" \",\"_\") + \".txt\"\n with open(file_name, 'w') as fh1:\n fh1.write(create_letter(k, donor_db))\n\n print(create_letter(k, donor_db))\n\n return 0\n\n\ndef add_donor_info(name, donor_db):\n \"\"\" Add donor info or add a new donor\n :params: name/string/name of donor db key, donor_db: dictionary of donor names/amts.\n :return:\n \"\"\"\n if name == \"list\" or name == \"menu\":\n print('Please select a name other than list or menu.')\n return 15\n if name not in donor_db:\n \"create a name in the donor_db if it does not already exist\"\n donor_db.update({name.lower():[]})\n\n\n try:\n amount = input(\"Enter amount of donor's contribution \"\n \"(or 'list' to see all donors or 'menu' to exit)> \").strip()\n donor_db[name].append(float(amount))\n except ValueError:\n print(\"\\nPlease resubmit a the donor amount information in dollars and cents with a format matching: 10.11\\n\")\n return\n\n\n print(create_letter(name, donor_db))\n\n\ndef add_new_donor(donor_db):\n name = input(\"Enter a donor's name \"\n \"(or 'list' to see all donors or 'menu' to exit)> \").strip()\n\n add_donor_info(name, donor_db)\n\n\n\n\n\nif __name__ == '__main__':\n print(\"this is the main section\")\n\n ### code below works, need work on called functions (works)\n running = True\n while running:\n selection=print_menu()\n if selection == \"1\":\n send_thank_you()\n elif selection == \"2\":\n print_donor_report(donor_db)\n elif selection == \"3\":\n send_letters_to_all(donor_db)\n elif selection == \"4\":\n running = False\n elif selection == \"5\":\n add_new_donor(donor_db)\n else:\n print(\"Please select an option 1-5 from the menu\")\n","sub_path":"students/mark/Session05/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":8079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"349324704","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport re\nimport os\nimport sys\n\n\n# 定义获取version.json中的版本方法\ndef get_version(jsonfile):\n config_data = open(jsonfile)\n config = json.load(config_data)\n config_data.close()\n return config['version']\n\n\n# 定义替换ExportOptions.plist方法\ndef replace(file, value):\n with open(file, 'r') as content, open(\"%s.bak\" % file, 'w') as content2:\n for line in content:\n content2.write(re.sub(r'/.{3,4}/v\\d.{4,7}/', value, line))\n os.remove(file)\n os.rename(\"%s.bak\" % file, file)\n\n\nif __name__ == \"__main__\":\n json_path = sys.argv[2] + '/src/version.json' # 配置version.json的文件位置\n env = sys.argv[1] # 配置环境(test,pre,prd)\n if sys.argv[1] == 'test':\n ExportOptions = '/Users/jenkins/workspace/dist/yq/testExportOptions.plist' # 配置ExportOptions.plist文件位置\n replace(ExportOptions, '/%s/%s/' % (env, get_version(json_path)))\n elif sys.argv[1] == 'pre':\n ExportOptions = '/Users/jenkins/workspace/dist/yq/preExportOptions.plist' # 配置ExportOptions.plist文件位置\n replace(ExportOptions, '/%s/%s/' % (env, get_version(json_path)))\n elif sys.argv[1] == 'prd':\n ExportOptions = '/Users/jenkins/workspace/dist/yq/prdExportOptions.plist' # 配置ExportOptions.plist文件位置\n replace(ExportOptions, '/%s/%s/' % (env, get_version(json_path)))\n","sub_path":"test/replacefile.py","file_name":"replacefile.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592812378","text":"\"\"\"Classes and functions for unit tetsing the mmlib molecule module.\"\"\"\n\nimport unittest\n\nclass Test(unittest.TestCase):\n \"\"\"Unit tests for mmlib. method.\"\"\"\n\n\ndef suite():\n \"\"\"Builds a test suite of all unit test in _test module.\"\"\"\n test_classes = (\n Test)\n\n suite = unittest.TestSuite()\n for test_class in test_classes:\n tests = unittest.TestLoader().loadTestsFromTestCase(test_class)\n suite.addTests(tests)\n return suite\n","sub_path":"scripts/molecular_mechanics/mmlib/simulate_test.py","file_name":"simulate_test.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456244527","text":"#!/usr/bin/env python3\n\n# spotlight_fetcher.py - Utility to download wallpapers from Microsoft Spotlight.\n# Version: 0.1\n# (c) 2016 Piotr Grzeszczak\n# http://www.grzeszczak.it\n# Based on https://github.com/liu-yun/spotlight/blob/master/spotlight.py\n# License: GPLv3\n\nimport json\nimport os\nimport random\nimport uuid\nimport requests\nimport hashlib\nimport signal\n\nfrom datetime import datetime\n\ndest = os.path.join(os.path.expanduser('~'), \"Pictures\",\"Wallpapers\", \"Spotlight\")\nfile_blacklist = []\n\n# Catch Ctrl + C signal\ndef ctrlc_handler(signal, frame):\n print('\\nSIGINT signal received!\\nExiting now...')\n exit(0)\n\ndef random_id():\n return str(uuid.uuid4()).replace('-', '')\n\ndef read_md5(file):\n hasher = hashlib.md5()\n with open(file, 'rb') as f:\n buf = f.read()\n hasher.update(buf)\n return hasher.hexdigest()\n\ndef update_hash_db(path):\n md5_list = []\n for file in os.listdir(path):\n md5_list.append(read_md5(path + '/' + file))\n return md5_list\n\ndef downloader(url, session, dest_path):\n d = session.get(url)\n if d.status_code == 200:\n with open(dest_path, 'wb+') as f:\n for chunk in d:\n f.write(chunk)\n md5sum = read_md5(dest_path)\n print('Downloading {} ({})'.format(dest_path.split('/')[-1:][0], md5sum))\n return md5sum\n else:\n print('Download failed! ({})'.format(d.status_code))\n return False\n\ndef worker():\n print(\"Updating MD5 hash file list... \", end='')\n hash_db = update_hash_db(dest)\n print(\"items: {}\".format(len(hash_db)))\n\n # Magical request\n print('Requesting json...')\n cache_url = 'https://arc.msn.com/v3/Delivery/Cache'\n data = {'pid': random.choice([209562, 209567, 279978]),\n 'fmt': 'json', # Output format\n 'ctry': 'PL', # Country\n 'time': datetime.now().strftime('%Y%m%dT%H%M%SZ'), # Current time\n 'lc': 'pl-pl', # https://msdn.microsoft.com/pl-pl/windows/uwp/publish/supported-languages\n 'pl': 'pl-pl,en-US',\n 'idtp': 'mid',\n 'uid': uuid.uuid4(),\n 'aid': '00000000-0000-0000-0000-000000000000',\n 'ua': 'WindowsShellClient/9.0.40929.0 (Windows)',\n 'asid': random_id(),\n 'ctmode': 'ImpressionTriggeredRotation',\n 'arch': 'x64',\n 'cdmver': '10.0.14936.1000',\n 'devfam': 'Windows.Desktop',\n 'devform': 'Unknown',\n 'devosver': '10.0.14936.1000',\n 'disphorzres': 1920,\n 'dispsize': 15.5,\n 'dispvertres': 1080,\n 'fosver': 14352,\n 'isu': 0,\n 'lo': 510893,\n 'metered': False,\n 'nettype': 'wifi',\n 'npid': 'LockScreen',\n 'oemid': 'VMWARE',\n 'ossku': 'Professional',\n 'prevosver': 14257,\n 'smBiosDm': 'VMware Virtual Platform',\n 'smBiosManufacturerName': 'VMware, Inc.',\n 'tl': 4,\n 'tsu': 6788\n }\n\n # Get image urls\n r = requests.get(cache_url, params=data)\n urls = []\n\n try:\n for item in r.json()['batchrsp']['items']:\n d = json.loads(item['item'])\n urls.append(d['ad']['image_fullscreen_001_landscape']['u'])\n except:\n print(\"Broken data...\")\n\n print(\"Found {} images...\".format(len(urls)))\n\n # Download them\n # TODO: Cleanup this part.\n with requests.Session() as s:\n for url in urls:\n local_path = os.path.join(dest, url.split('/')[3] + '.jpg')\n if os.path.exists(local_path) is False and not local_path in file_blacklist:\n md5sum = downloader(url, s, local_path)\n\n if md5sum in hash_db:\n print(\"Exist (md5 sum), added to cache blacklist.\")\n os.remove(local_path)\n file_blacklist.append(local_path)\n else:\n hash_db.append(md5sum)\n else:\n print(\"Exist\")\n\ndef main():\n print(\"Ultimate Spotlight Fetcher!\")\n\n # Signals handlers\n signal.signal(signal.SIGINT, ctrlc_handler)\n print(\"Press Ctrl + C for exit\")\n\n if not os.path.exists(dest):\n print(\"Destination folder {} not found, creating it...\".format(dest))\n os.mkdir(dest)\n else:\n print(\"Destination: {}\".format(dest))\n\n while(1):\n worker()\n\nif __name__ == '__main__':\n main()\n","sub_path":"spotlight_fetcher.py","file_name":"spotlight_fetcher.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197259","text":"# -*- coding: utf-8 -*-\n#\n# satcfe/resposta/consultarstatusoperacional.py\n#\n# Copyright 2015 Base4 Sistemas Ltda ME\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#\n\nimport base64\nimport errno\nimport os\nimport tempfile\n\nfrom satcomum.util import forcar_unicode\n\nfrom ..excecoes import ExcecaoRespostaSAT\nfrom ..util import as_date\nfrom ..util import as_datetime\nfrom ..util import normalizar_ip\nfrom .padrao import RespostaSAT\nfrom .padrao import analisar_retorno\n\n\nDESBLOQUEADO = 0\nBLOQUEADO_SEFAZ = 1\nBLOQUEADO_CONTRIBUINTE = 2\nBLOQUEADO_AUTO = 3\nBLOQUEADO_PARA_DESATIVACAO = 4\n\nESTADOS_OPERACAO = (\n (DESBLOQUEADO, u'Desbloqueado'),\n (BLOQUEADO_SEFAZ, u'Bloqueado pelo SEFAZ'),\n (BLOQUEADO_CONTRIBUINTE, u'Bloqueado pelo contribuinte'),\n (BLOQUEADO_AUTO, u'Bloqueado autonomamente'),\n (BLOQUEADO_PARA_DESATIVACAO, u'Bloqueado para desativação'),\n )\n\n\nclass RespostaConsultarStatusOperacional(RespostaSAT):\n\n @property\n def status(self):\n \"\"\"Nome amigável do campo ``ESTADO_OPERACAO``, conforme a \"Tabela de\n Informações do Status do SAT\".\n \"\"\"\n for valor, rotulo in ESTADOS_OPERACAO:\n if self.ESTADO_OPERACAO == valor:\n return rotulo\n return u'(desconhecido: {})'.format(self.ESTADO_OPERACAO)\n\n\n @staticmethod\n def analisar(retorno):\n resposta = analisar_retorno(forcar_unicode(retorno),\n funcao='ConsultarStatusOperacional',\n classe_resposta=RespostaConsultarStatusOperacional,\n campos=RespostaSAT.CAMPOS + (\n ('NSERIE', unicode),\n ('TIPO_LAN', unicode),\n ('LAN_IP', normalizar_ip),\n ('LAN_MAC', unicode),\n ('LAN_MASK', normalizar_ip),\n ('LAN_GW', normalizar_ip),\n ('LAN_DNS_1', normalizar_ip),\n ('LAN_DNS_2', normalizar_ip),\n ('STATUS_LAN', unicode),\n ('NIVEL_BATERIA', unicode),\n ('MT_TOTAL', unicode), # int ?\n ('MT_USADA', unicode), # int ?\n ('DH_ATUAL', as_datetime),\n ('VER_SB', unicode),\n ('VER_LAYOUT', unicode),\n ('ULTIMO_CF_E_SAT', unicode),\n ('LISTA_INICIAL', unicode),\n ('LISTA_FINAL', unicode),\n ('DH_CFE', as_datetime),\n ('DH_ULTIMA', as_datetime),\n ('CERT_EMISSAO', as_date),\n ('CERT_VENCIMENTO', as_date),\n ('ESTADO_OPERACAO', int),\n )\n )\n if resposta.EEEEE not in ('10000',):\n raise ExcecaoRespostaSAT(resposta)\n return resposta\n","sub_path":"satcfe/resposta/consultarstatusoperacional.py","file_name":"consultarstatusoperacional.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294033194","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\nimport socket\n\ncnx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ncnx.bind(('', 12800))\ncnx.listen(5)\nclientCnx, clientInfo = cnx.accept()\n\nprint(clientInfo)\n\nprint(clientCnx.send(b\"Je viens d'accepter la connexion\"));\n\nclientCnx.close();\n\n","sub_path":"src/tcp/socket1.py","file_name":"socket1.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552671809","text":"#\n#introdução a programação de computadores\n#Professor: Jucimar JR\n#EQUIPE 2\n#\n#Ana Beatriz Frota - 1615310027 \n#Ariel Guilherme Rocha Capistrano - 1615310029\n#Frankilin Yuri Gonçaves dos santos - 1615310033\n#Kylciane Cristiny Lopes Freitas - 1615310052\n#Lucas Ferreira Soares - 1615310014\n#Luiz Alexandre Oliveira de Souza - 1615310057\n#Luiz Gustavo Rocha Melo - 1615310015\n#Nahan Trindade Passos - 1615310021\n#Samuel Silva França - 1615310049\n#\n\nmorango = float(input(\"Quanto Kg de morango?\\n\"))\nmaca = float(input(\"Quanto Kg de maca?\\n\"))\n\npeso_total = (morango + maca)\n\nif(0 < morango <= 5):\n preco_morango = (2.50*morango)\n if(0 < maca <= 5):\n preco_maca = (1.80*maca)\n preco_total = (preco_maca + preco_morango)\n if(peso_total > 8 or preco_total > 25):\n preco_total_desconto = (preco_total-(preco_total*10/100))\n print(\"O valor a ser pago e: R$\"%preco_total_desconto)\n else:\n print(\"O valor a ser pago e: R$\",preco_total)\n if(maca > 5):\n preco_maca = (1.50*maca)\n preco_total = (preco_maca + preco_morango)\n if(peso_total > 8 or preco_total > 25):\n preco_total_desconto = (preco_total-(preco_total*10/100))\n print(\"O valor a ser pago e: R$\",preco_total_desconto)\n else:\n print(\"O valor a ser pago e: R$\",preco_total)\n if(maca == 0):\n print(\"O valor a ser pago e: R$\",preco_morango)\nif(morango > 5):\n preco_morango = (2.20*morango)\n if(maca <= 5):\n preco_maca = (1.80*maca)\n preco_total = (preco_maca + preco_morango)\n if(peso_total > 8 or preco_total > 25):\n preco_total_desconto = (preco_total-(preco_total*10/100))\n print(\"O valor a ser pago e: R$\",preco_total_desconto)\n else:\n print(\"O valor a ser pago e: R$\",preco_total)\n if(maca > 5):\n preco_maca = (1.50*maca)\n preco_total = (preco_maca + preco_morango)\n if(peso_total > 8 or preco_total > 25):\n preco_total_desconto = (preco_total-(preco_total*10/100))\n print(\"O valor a ser pago e: R$\",preco_total_desconto)\n else:\n print(\"O valor a ser pago e: R$\",preco_total)\n if(morango > 8 and maca == 0 ):\n desconto_morango = (preco_morango-(preco_morango*10/100))\n print(\"O valor a ser pago e: R$\",desconto_morango)\n if(maca == 0):\n print(\"O valor a ser pago e: R$\",preco_morango)\nelif(maca <= 5 and morango == 0 ):\n preco_maca = (1.80*maca)\n print(\"O valor a ser pago e: R$\",preco_maca)\nelif(maca > 5 and morango == 0):\n preco_maca = (maca*1.50)\n if(maca > 8):\n desconto_maca = (preco_maca-(preco_maca*10/100))\n print(\"O valor a ser pago: R$\",desconto_maca)\n else:\n print(\"O valor a ser pago: R$\",preco_maca)\n","sub_path":"lista2/ipc_lista2.27.py","file_name":"ipc_lista2.27.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370789099","text":"# https://app.diagrams.net/?page-id=4pcr6fxJhgjnMUNqEWlp#G1eKp2W5wpHgpv28qTq0SMU-f0MtLq0pst\n# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.\n# Например, если введено число 3486, надо вывести 6843.\n\nnum = int(input('Введите число: '))\nl = len(str(num))\ns = ''\nwhile l != 0:\n l -= 1\n z = num % 10\n s += str(z)\n num = num // 10\nprint(s)\n","sub_path":"lesson2/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"516162613","text":"import requests\n\n\ndef get_data(url: str):\n with open('img.jpg', 'bw') as file:\n file.write(requests.get(url).content)\n\n\nif __name__ == '__main__':\n get_data('https://dummyimage.com/600x400/000/fff')\n","sub_path":"week3/lesson1-python-standart-library/homework/EugeneZabolotny/utils/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79389140","text":"#!/usr/bin/env python3.3\n# -*- coding: utf-8 -*-\n#\n# Simple web interface to cve-search to display the last entries\n# and view a specific CVE.\n#\n# Software is free software released under the \"Modified BSD license\"\n#\n\n# Copyright (c) 2013-2014 Alexandre Dulaunoy - a@foo.be\n# Copyright (c) 2014 Pieter-Jan Moreels - pieterjan.moreels@gmail.com\nfrom flask import Flask\nfrom flask import render_template, url_for\nfrom flask.ext.pymongo import PyMongo\nimport sys\nsys.path.append(\"../lib/\")\nimport cves\nimport redis\nimport pymongo\nfrom datetime import datetime\nfrom dateutil import tz\nimport dateutil.parser\nimport os\nimport base64\nimport re\nimport argparse\nsys.path.append(\"..\")\nfrom db_whitelist import importList\nfrom db_whitelist import dropDb\nfrom db_whitelist import countItems\n\n# parse command line arguments\nargparser = argparse.ArgumentParser(description='populate/update the whitelist used in webviews')\nargparser.add_argument('-v', action='store_true', help='verbose output')\nargs = argparser.parse_args()\n\napp = Flask(__name__, static_folder='static', static_url_path='/static')\napp.config['MONGO_DBNAME'] = 'cvedb'\nmongo = PyMongo(app)\n\n@app.route('/cve/')\ndef cve(cveid):\n cvesp = cves.last(rankinglookup = True, namelookup = True, vfeedlookup = True)\n cve = cvesp.getcve(cveid=cveid)\n if cve is None:\n return page_not_found(404)\n return render_template('cve.html', cve=cve)\n\n@app.route('/')\ndef last():\n cvesp = cves.last(rankinglookup = True, namelookup = True, vfeedlookup = True)\n cve = cvesp.get(limit=50)\n\n return render_template('index.html', cve=cve, r=0)\n\n@app.route('/r/')\ndef lastrange(r):\n if not r:\n r = 0\n cvesp = cves.last(rankinglookup = True, namelookup = True, vfeedlookup = True)\n cve = cvesp.get(limit=50, skip=r)\n return render_template('index.html', cve=cve, r=r)\n\n@app.route('/browse//')\n@app.route('/browse/')\n@app.route('/browse/')\ndef browse(vendor=None,product=None):\n r = redis.StrictRedis(host='localhost', port=6379, db=10)\n if vendor is None:\n v1 = r.smembers(\"t:/o\")\n v2 = r.smembers(\"t:/a\")\n v3 = r.smembers(\"t:/h\")\n vendor = sorted(list(set(list(v1)+list(v2)+list(v3))))\n cpe=None\n else:\n cpenum = r.scard(\"v:\"+vendor)\n if cpenum < 1:\n return page_not_found(404)\n p = r.smembers(\"v:\"+vendor)\n cpe = sorted(list(p))\n\n return render_template('browse.html', cpe=cpe, vendor=vendor, product=product)\n\ndef whitelist_logic(cve):\n # get the whitelist\n connect = pymongo.Connection()\n db = connect.cvedb\n collection = db.mgmt_whitelist\n whitelist = collection.find()\n whitelistitems = []\n for whitelistid in whitelist:\n whitelistitems.append(whitelistid['id'])\n\n # check the cpes (full or partially) in the whitelist\n for cveid in cve:\n cpes=cveid['vulnerable_configuration']\n if len([i for e in whitelistitems for i in cpes if e in i])>0:\n cve[cve.index(cveid)]['whitelisted'] = 'yes'\n return cve\n\n@app.route('/whitelist')\ndef whitelist():\n cvesp = cves.last(rankinglookup = True, namelookup = True, vfeedlookup = True)\n cve = cvesp.get(limit=50)\n cve=whitelist_logic(cve)\n return render_template('whitelist.html', cve=cve, r=0)\n\n@app.route('/whitelist/r/')\ndef whitelistlast(r):\n if not r:\n r = 0\n cvesp = cves.last(rankinglookup = True, namelookup = True, vfeedlookup = True)\n cve = cvesp.get(limit=50, skip=r)\n cve=whitelist_logic(cve)\n return render_template('whitelist.html', cve=cve, r=r)\n\n@app.route('/admin')\ndef admin():\n return render_template('admin.html', status=\"default\")\n\n@app.route('/admin/updatedb')\ndef updatedb():\n os.system(\"cd ..; python3 db_updater.py -civ\")\n return render_template('admin.html', status=\"db_updated\")\n\n@app.route('/admin/whitelist/import//')\ndef whitelistImport(force=None, path=None):\n path = base64.b64decode(path).decode('utf-8')\n pattern = re.compile('^([a-z/ 0-9._-])+$')\n if pattern.match(path):\n count = countItems()\n if (count == 0) | (force == \"f\"):\n dropDb()\n importList(path)\n status=\"wl_imported\"\n else:\n status=\"wl_already_filled\"\n else:\n status=\"invalid_path\"\n return render_template('admin.html', status=status)\n\n@app.route('/search//')\ndef search(vendor=None,product=None):\n\n connect = pymongo.Connection()\n db = connect.cvedb\n collection = db.cves\n search = vendor+\":\"+product\n cve = collection.find({\"vulnerable_configuration\": {'$regex': search}}).sort(\"Modified\",-1)\n return render_template('search.html', cve=cve)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n@app.template_filter('currentTime')\ndef currentTime(utc):\n timezone = tz.tzlocal()\n utc = dateutil.parser.parse(utc)\n output = utc.astimezone(timezone)\n output = output.strftime('%d-%m-%Y - %H:%M')\n return output \n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"web/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419959318","text":"'''\n35. Search Insert Position\n\nBinary search\n\nGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n'''\nclass Solution(object):\n def searchInsert(self, nums, n):\n left, right = 0, len(nums)\n while right > left:\n mid = (right - left) // 2 + left\n if n == nums[mid]:\n return mid\n elif n > nums[mid]:\n left = mid + 1\n else:\n right = mid\n if n < nums[mid]:\n return mid\n return mid + 1\nif __name__ == '__main__':\n nums, target = [1], 0\n res = Solution().searchInsert(nums, target)\n print(res)\n","sub_path":"35_searchInsert.py","file_name":"35_searchInsert.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"46158061","text":"'''10. Faça um Programa que pergunte em que turno você estuda. \nPeça para digitar M-matutino ou V-Vespertino ou N- Noturno. \nImprima a mensagem \"Bom Dia!\", \"Boa Tarde!\" ou \"Boa Noite!\" \nou \"Valor Inválido!\", conforme o caso.'''\n\nturno = input('Em que turno você estuda ? M-matutino ou V-Vespertino ou N-Noturno: ')\n\nresposta = ''\nif turno == 'M':\n resposta = 'Bom Dia!'\nelif turno == 'V':\n resposta = 'Boa Tarde!'\nelif turno == 'N':\n resposta = 'Boa Noite!'\nelse:\n resposta = 'Valor Inválido'\n\nprint(resposta)\n","sub_path":"EstruturaDeDecisao/exercise_10.py","file_name":"exercise_10.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466221583","text":"class Subdivider:\n # To survive noise non-stationarity,\n # we subdivide the filtering into 1024 second\n # subsections, or windows, which we will\n # then fit together.\n # Grant David Meadors\n # 02012-07-29 (JD 2456139)\n # g m e a d o r s @ u m i c h . e d u\n\n def __init__(self, tSegment):\n # Because they will overlap for 512 seconds\n # with the subsection before and 512 seconds\n # with the subsection after,\n # the start of a given science segment is 'tA',\n # the end 'tB'\n tA = tSegment.tA\n tB = tSegment.tB\n \n # tStart is a list of start times of the \n # 1024 second subsections,\n # tEnd the end times\n import math\n self.tStart = [tA] +\\\n [tA + 512*x for x in range(1, int(math.floor(tB-tA)/512)+1)]\n self.tEnd = [tA + 2*512*x for x in range(1, int(math.floor(tB-tA)/512)+1)] +\\\n [tB]\n \n # Check to see if the science segment ends before the last\n # 1024 seconds subsection. If so, cut the subsection short.\n self.tEnd = [tB if (x > tB) else x for x in self.tEnd]\n \n # Obliterate subsections with zero duration\n self.tStart = [-1 if (x == self.tEnd[i]) else x \\\n for i, x in enumerate(self.tStart)]\n self.tEnd = [[] if (self.tStart[i] == -1) else x \\\n for i, x in enumerate(self.tEnd)]\n self.tStart = [[] if (x == -1) else x \\\n for i,x in enumerate(self.tStart)]\n\n # Obliterate subsections with duration less than 32 s\n self.tStart = [-1 if (self.tEnd[i] - x < 32) else x \\\n for i, x in enumerate(self.tStart)]\n self.tEnd = [[] if (self.tStart[i] == -1) else x \\\n for i, x in enumerate(self.tEnd)]\n self.tStart = [[] if (self.tStart[i] == -1) else x \\\n for i, x in enumerate(self.tStart)]\n\n self.tStart = [x for x in self.tStart if x != []]\n self.tEnd = [x for x in self.tEnd if x != []]","sub_path":"Subdivider.py","file_name":"Subdivider.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436231433","text":"import os\nimport json\nimport csv\nimport re\nimport unicodedata\n\n\ndef cleaning_doi(doi_raw):\n doi_clean = doi_raw.strip(\"DOI: \").strip(\"HTTPS://DX.DOI.ORG/\").strip(\"#\").replace(\" \", \"\")\n\n return doi_clean\n\n\ndef cleaning_title(title_raw):\n\n title_clean = u\"\".join([c for c in unicodedata.normalize(\"NFKD\", title_raw) if not unicodedata.combining(c)]) # remove accents\n title_clean = title_clean.lower()\n title_clean = re.sub(r\" p$\", '', title_clean)\n title_clean = re.sub(r\"[^\\w\\d\\s]\", ' ', title_clean)\n title_clean = re.sub(r\"\\s+\", ' ', title_clean)\n\n return title_clean\n\n\ndef matching_pubbs(list_pubbs, new):\n value = 0\n n = len(list_pubbs)\n idx = 0\n while idx < n:\n if \"doi\" in new.keys() and \"doi\" in list_pubbs[idx].keys():\n if new[\"doi\"] == list_pubbs[idx][\"doi\"]:\n list_pubbs[idx][\"cv_id\"][\"pubbs\"] = new[\"cv_id\"][\"pubbs\"]\n value = 1\n idx = n\n elif \"title\" in new.keys() and \"title\" in list_pubbs[idx].keys():\n if (new[\"title\"].replace(\" \", \"\") == list_pubbs[idx][\"title\"].replace(\" \", \"\")\n and new[\"year\"] == list_pubbs[idx][\"year\"]):\n list_pubbs[idx][\"cv_id\"][\"pubbs\"] = new[\"cv_id\"][\"pubbs\"]\n value = 1\n idx = n\n idx += 1\n\n if value == 0:\n list_pubbs.append(new)\n\n return list_pubbs\n\n\ndef extracting_metadata_cand(path, cand_dd):\n\n with os.scandir(path) as asn_years:\n\n for asn_year in asn_years:\n asn_year_name = asn_year.name\n cand_dd[asn_year_name] = dict()\n asn_year_path = os.path.join(path, asn_year_name)\n with os.scandir(asn_year_path) as terms:\n\n for term in terms:\n term_name = term.name[-1]\n cand_dd[asn_year_name][term_name] = dict()\n term_path = os.path.join(asn_year_path, term.name)\n with os.scandir(term_path) as roles:\n\n for role in roles:\n role_name = role.name\n cand_dd[asn_year_name][term_name][role_name] = dict()\n role_path = os.path.join(term_path, role.name)\n with os.scandir(role_path) as fields:\n\n for field in fields:\n field_name = field.name\n cand_dd[asn_year_name][term_name][role_name][field_name] = dict()\n field_path = os.path.join(role_path, field_name)\n with os.scandir(field_path) as cvs:\n\n for cv in cvs:\n cv_name = cv.name[:-5]\n cand_id = cv_name.split(\"_\", 1)[0]\n cv_dir = os.path.join(field_path, cv.name)\n\n cand_dd[asn_year_name][term_name][role_name][field_name][cand_id] = dict()\n ddict = cand_dd[asn_year_name][term_name][role_name][field_name][cand_id]\n\n with open(cv_dir, 'r') as json_file:\n data = json.load(json_file)\n ddict[\"pubbs\"] = []\n\n for pub in data[\"pubbs_ind\"]:\n d1 = dict()\n d1[\"cv_id\"] = dict()\n d1[\"cv_id\"][\"pubbs_ind\"] = pub[\"id\"]\n d1[\"year\"] = int(pub[\"anno\"])\n d1[\"type\"] = pub[\"type\"].lower()\n if pub[\"parsed\"] is not None:\n if \"doi\" in pub[\"parsed\"].keys():\n d1[\"doi\"] = cleaning_doi(pub[\"parsed\"][\"doi\"][0].upper())\n if \"titolo\" in pub[\"parsed\"].keys():\n d1[\"title\"] = cleaning_title(pub[\"parsed\"][\"titolo\"])\n if \"journal\" in pub[\"parsed\"].keys():\n d1[\"journal\"] = pub[\"parsed\"][\"journal\"]\n if \"ISBN\" in pub[\"parsed\"].keys():\n d1[\"ISBN\"] = pub[\"parsed\"][\"ISBN\"]\n if \"ISSN\" in pub[\"parsed\"].keys():\n d1[\"ISSN\"] = pub[\"parsed\"][\"ISSN\"]\n ddict[\"pubbs\"].append(d1)\n\n for pub in data[\"pubbs\"]:\n d2 = dict()\n d2[\"cv_id\"] = dict()\n d2[\"cv_id\"][\"pubbs\"] = pub[\"id\"]\n d2[\"type\"] = pub[\"type\"].lower()\n d2[\"year\"] = int(pub[\"anno\"])\n if pub[\"parsed\"] is not None:\n if \"doi\" in pub[\"parsed\"].keys():\n d2[\"doi\"] = cleaning_doi(pub[\"parsed\"][\"doi\"][0].upper())\n if \"titolo\" in pub[\"parsed\"].keys():\n d2[\"title\"] = cleaning_title(pub[\"parsed\"][\"titolo\"])\n if \"journal\" in pub[\"parsed\"].keys():\n d2[\"journal\"] = pub[\"parsed\"][\"journal\"]\n if \"ISBN\" in pub[\"parsed\"].keys():\n d2[\"ISBN\"] = pub[\"parsed\"][\"ISBN\"]\n if \"ISSN\" in pub[\"parsed\"].keys():\n d2[\"ISSN\"] = pub[\"parsed\"][\"ISSN\"]\n\n copy = matching_pubbs(ddict[\"pubbs\"], d2)\n ddict[\"pubbs\"] = copy\n\n return cand_dd\n\n\ndef extracting_metadata_comm(path):\n\n comm_dd = dict()\n\n with open(path, 'r', encoding='utf-8') as csvfile:\n comm_csv = csv.reader(csvfile)\n\n for row in comm_csv:\n if row[0] and row[0] != \"asn_session\":\n if row[0] not in comm_dd.keys():\n comm_dd[row[0]] = dict()\n\n if row[1] not in comm_dd[row[0]].keys():\n comm_dd[row[0]][row[1]] = dict()\n\n if row[2] not in comm_dd[row[0]][row[1]].keys():\n comm_dd[row[0]][row[1]][row[2]] = dict()\n\n if \"fullname\" not in comm_dd[row[0]][row[1]][row[2]].keys():\n comm_dd[row[0]][row[1]][row[2]][\"fullname\"] = [row[3], row[4]]\n\n if \"pubbs\" not in comm_dd[row[0]][row[1]][row[2]].keys():\n comm_dd[row[0]][row[1]][row[2]][\"pubbs\"] = []\n\n pub = dict()\n pub[\"id\"] = row[5]\n pub[\"title\"] = cleaning_title(row[6])\n pub[\"year\"] = int(row[7])\n if row[8]:\n pub[\"doi\"] = cleaning_doi(row[8])\n comm_dd[row[0]][row[1]][row[2]][\"pubbs\"].append(pub)\n\n return comm_dd\n\n\ndef extracting_metadata(jsons_path, csv_path):\n\n dd = dict()\n dd[\"cand\"] = dict()\n cand_dict = extracting_metadata_cand(jsons_path, dd[\"cand\"])\n dd[\"cand\"] = cand_dict\n\n dd[\"comm\"] = dict()\n comm_dict = extracting_metadata_comm(csv_path)\n dd[\"comm\"] = comm_dict\n\n return dd\n","sub_path":"data_collection/meta_extraction.py","file_name":"meta_extraction.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197729988","text":"import logging\nfrom numpy import random,meshgrid,power,sin,pi\ndef grv(lat,lon=None,shape_wanted=None):\n \"\"\"\n purpose:give gravity cste depending of the latitude\n note: grv module returns vector if lat is a vector, to force the output to be a matrix of the same shape\n than over input fields, one can provide the lon vector as well or directly the shape of the matrix wanted.\n Args:\n lat (float ndarray): latitudes\n lon (float ncarray): longitudes [optional]\n shape_wanted (tuple): shape of the matrix wanted [optional]\n Returns:\n gg (float ndarray): gravity constant\n \n 2/12/2020 removed long which was a python 2.7 code\n \"\"\"\n gamma = 9.7803267715\n c1 = 0.0052790414\n c2 = 0.0000232718\n c3 = 0.0000001262\n c4 = 0.0000000007\n \n logging.debug('grv | lat:%s',lat.shape)\n if lon is not None:\n lon_m,lat_m = meshgrid(lon,lat)\n elif shape_wanted is not None and isinstance(lat, (int, float, complex))==False and len(shape_wanted)>1:\n randy = random.rand(shape_wanted[1])\n# lat_m = tile(lat,shape_wanted[1])\n lon_m,lat_m = meshgrid(randy,lat)\n# lat_m = lat_m.T\n logging.debug('grv | shape_wanted :%s lat_m:%s',shape_wanted,lat_m.shape)\n else:\n lat_m = lat\n phi = lat_m*pi/180.\n xx = sin(phi)\n gg = gamma*(1+c1*power(xx,2)+c2*power(xx,4)+c3*power(xx,6)+c4*power(xx,8))\n return gg","sub_path":"2020_fluxsat/error_propogation/cerform/gravity_constant.py","file_name":"gravity_constant.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353670179","text":"from app import app\nfrom flask import render_template,flash, redirect, url_for,jsonify, request\nfrom datetime import datetime as dt\nfrom datetime import timedelta\nimport datetime\n\n@app.route('/')\n@app.route('/index')\ndef index():\n \n return render_template('index.html') \n\n\n@app.route('/compute', methods=['POST'])\ndef compute():\n # import ipdb; ipdb.set_trace()\n \n form_data = request.form\n\n # All the data are expected to be serialized\n device_start_dates = form_data.getlist('device_start')\n device_end_dates = form_data.getlist('device_end')\n stop_watch_starts = form_data.getlist('stop_watch_start')\n stop_watch_ends = form_data.getlist('stop_watch_end')\n\n date_format = \"%Y-%m-%d %H:%M:%S\"\n\n difference = []\n\n # Loop in all the above list \n # All the above list has same length\n for index in range(len(device_start_dates)):\n d_start = device_start_dates[index]\n d_end = device_end_dates[index]\n s_start = stop_watch_starts[index]\n s_end = stop_watch_ends[index]\n\n each_node = {}\n d_start_obj = dt.strptime(d_start,date_format)\n d_end_obj = dt.strptime(d_end, date_format)\n \n timedelta = d_end_obj - d_start_obj\n # print(\"For Device \",timedelta)\n\n d_diff = timedelta.total_seconds()\n\n s_start_obj = dt.strptime(s_start,date_format)\n s_end_obj = dt.strptime(s_end, date_format)\n timedelta = s_end_obj - s_start_obj\n # print(\"For StopWatch \", timedelta)\n\n s_diff = timedelta.total_seconds()\n\n # Total Difference between the StopWatch and Device Time\n if s_diff > d_diff:\n total_diff = s_diff - d_diff\n else:\n total_diff = d_diff - s_diff\n\n each_node['name'] = \"Device \"+ str(index+1)\n each_node['diff'] = str(datetime.timedelta(seconds=total_diff))\n each_node['d_start'] = d_start\n each_node['d_end'] = d_end\n each_node['s_start'] = s_start\n each_node['s_end'] = s_end\n\n print(\"For {0}, the time difference is {1}\".format(each_node['name'],each_node['diff'] ))\n difference.append(each_node)\n\n \n return render_template('thanks.html',\n diff =difference, \n )","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163053192","text":"from dataclasses import dataclass\nfrom typing import List, Optional\n\nimport numba\nimport numpy as np\nimport pandas as pd\nfrom pandas.tseries.offsets import BDay\n\nfrom cns_analytics.entities import Duration\nfrom cns_analytics.timeseries import TimeSeries\n\n\n@numba.njit()\ndef running_max(x):\n _max = x[0]\n y = np.empty_like(x)\n for i, val in enumerate(x):\n if val > _max:\n _max = val\n y[i] = _max\n return y\n\n\n@numba.njit()\ndef running_min(x):\n _min = x[0]\n y = np.empty_like(x)\n for i, val in enumerate(x):\n if val < _min:\n _min = val\n y[i] = _min\n return y\n\n\n@numba.njit\ndef _get_loss_points(arr: np.ndarray, width: float):\n exited_max = (running_max(arr) - arr) > width\n exited_min = (arr - running_min(arr)) > width\n exited_max[-1] = 1\n exited_min[-1] = 1\n arg_max = np.argmax(exited_max)\n arg_min = np.argmax(exited_min)\n return arg_max, arg_min\n\n\n@dataclass\nclass TimeTillLossReport:\n timestamp: pd.Timestamp\n days_buy: float\n days_sell: float\n past_days_buy: float\n past_days_sell: float\n spread_value: float\n\n @property\n def days_both(self):\n return min(self.days_buy, self.days_sell)\n\n @property\n def past_days_both(self):\n return min(self.past_days_buy, self.past_days_sell)\n\n\ndef get_next_loss_time(df, width, reverse=False):\n if reverse:\n df = df.iloc[::-1]\n\n loss_idx_buy, loss_idx_sell = _get_loss_points(df.values, width)\n loss_idx_buy = df.index[loss_idx_buy]\n loss_idx_sell = df.index[loss_idx_sell]\n\n if reverse:\n # past has reversed buy and sell values\n days_buy = len(pd.date_range(loss_idx_sell, df.index[0], freq=BDay()))\n days_sell = len(pd.date_range(loss_idx_buy, df.index[0], freq=BDay()))\n else:\n days_buy = len(pd.date_range(df.index[0], loss_idx_buy, freq=BDay()))\n days_sell = len(pd.date_range(df.index[0], loss_idx_sell, freq=BDay()))\n\n return days_buy, days_sell\n\n\ndef get_time_till_loss(\n ts: TimeSeries,\n width: float,\n max_days: int = 500,\n framed=False,\n symbol='SPREAD',\n step: Duration = '7d',\n calc_past: bool = False,\n past_width: Optional[float] = None\n) -> List[TimeTillLossReport]:\n results = []\n\n all_df = ts.get_raw_df()[symbol]\n\n max_ = pd.Timedelta(f'{max_days}d')\n past_window = pd.Timedelta('7d')\n\n past_width = past_width or width\n\n past_days_buy = 0\n past_days_sell = 0\n\n skip_start = '30d' if calc_past else '0m'\n\n for point in ts.get_datetime_iterator(step=step, framed=framed, skip_start=skip_start):\n if calc_past:\n past_df = all_df[point - max_: point]\n past_days_buy, past_days_sell = get_next_loss_time(past_df, past_width, reverse=True)\n\n df = all_df[point: point + max_]\n days_buy, days_sell = get_next_loss_time(df, width)\n\n results.append(TimeTillLossReport(\n timestamp=point,\n days_buy=days_buy,\n days_sell=days_sell,\n past_days_buy=past_days_buy,\n past_days_sell=past_days_sell,\n spread_value=df.iloc[0]))\n\n return results\n","sub_path":"cns_analytics/statistics/time_till_loss.py","file_name":"time_till_loss.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615756974","text":"import os\nimport operator\nimport time\nimport math\nimport urllib\nimport json\nimport urllib.request\nimport unittest\nfrom PIL import Image\nfrom pandas.compat import reduce\nfrom selenium import webdriver\n#from baoxian.TestCase import SearchTestCase\n#https://baoxian.0033.com/web/products/gh_0007/index.html?id=50\n\nstarttime = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))\n#print('starttime:'+ starttime )\n\njs_heigh = \"var a=document.body.scrollHeight ;return(a)\"\njs_heigh_2 = \"var b=document.documentElement.clientHeight ;return(b)\"\njs_2 = 'window.scrollBy(0,document.documentElement.clientHeight)'\n\n#通过url请求接口,并将返回的内容存入字典并返回字典内容\nkind = {0:'1',1:'2',2:'3',3:'4'}\nurl_head = 'https://baoxian.0033.com/insurance/v1/products?type=product&page=1&limit=20&kind=1%7C2%7C3%7C4%7C6&price_order=&tag_types=%22%22'\n\nclass ClassMethon(object):\n '''\n 存放一些公共方法,方便后续进行调用\n '''\n imglist = []\n # 进入浏览器设置\n\n def setUp(self):\n options = webdriver.ChromeOptions()\n # 设置中文\n options.add_argument('lang=zh_CN.UTF-8')\n options.add_argument(\n 'user-agent=\"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1/userid/366693514 isChrome/1')\n self.driver = webdriver.Chrome(chrome_options=options)\n self.driver.set_window_size(375, 812) # 设置浏览器窗口大小\n self.driver.get('https://baoxian.0033.com/web/product-center.html')\n self.driver.implicitly_wait(20)#隐形等待二十\n if self.driver.find_element_by_xpath('/html/body/div[2]/div[1]/ul/li[1]'):\n time.sleep(1)\n self.driver.find_element_by_xpath('/html/body/div[2]/div[1]/ul/li[1]').click()\n #self.same_as('健康_')\n if self.driver.find_element_by_xpath('/html/body/div[3]/div/ul/li[1]/ul/li[10]'):\n time.sleep(1)\n self.driver.find_element_by_xpath('/html/body/div[3]/div/ul/li[1]/ul/li[10]').click()\n #self.same_as('平安e生保·住院医疗_')\n time.sleep(2)\n\n def creat_file(self,path):\n #t1 = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) # 获取当前的时间\n #print('当前时间:' + t1)\n #day = t1[0:8]\n #img_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")) + '/screenshot'\n # 设定文件保存的路径,存放到当前目录下是screenshots文件夹中\n #print('当前的路径:' + img_folder)\n #path = img_folder + '/'\n\n # 去除首位空格\n path = path.strip()\n # 去除尾部 \\ 符号\n path = path.rstrip(\"\\\\\")\n\n # 判断路径是否存在\n # 存在 True\n # 不存在 False\n isExists = os.path.exists(path)\n\n # 判断结果\n if not isExists:\n # 如果不存在则创建目录\n print(path + ' 创建成功')\n open('result', 'a', encoding='utf8').writelines(path + ' 创建成功' + '\\n')\n # 创建目录操作函数\n os.makedirs(path)\n return True\n else:\n # 如果目录存在则不创建,并提示目录已存在\n print(path + ' 目录已存在')\n open('result', 'a', encoding='utf8').writelines(path + ' 目录已存在' + '\\n')\n return False\n\n def same_as(self, na):\n # 截图\n fw = open('screenshot_path', 'w', encoding='utf8') # 打开文件写入\n fr = open('screenshot_path', 'r', encoding='utf8') # 打开文件读取\n t1 = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) # 获取当前的时间\n print('当前时间:' + t1)\n open('result', 'a', encoding='utf8').writelines('当前时间:' + t1 + '\\n')\n # #day = t1[0:8]\n day = t1\n img_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")) + '\\\\baoxian\\\\pajk_22_平安e生保_住院医疗'\n # # 设定文件保存的路径,存放到当前目录下是screenshots文件夹中\n # print('当前的路径:' + img_folder)\n #open('result', 'a', encoding='utf8').writelines('当前的路径:' + img_folder + '\\n')\n cre_file = ClassMethon()\n cre_file.creat_file(img_folder)\n screen_save_path = img_folder + '/' + na + t1 + '.png' # 截屏图片命名方式\n #print('当前截图路径已经名称为:' + screen_save_path)\n open('result', 'a', encoding='utf8').writelines('当前截图路径已经名称为:' + screen_save_path + '\\n')\n time.sleep(10) # 休眠十秒等待页面加载完成\n self.driver.get_screenshot_as_file(screen_save_path) # 截屏并存在指定的路径下\n #print('截图已存')\n open('result', 'a', encoding='utf8').writelines('截图已存 \\n')\n #self.pic_save()\n imglist = self.imglist\n if len(imglist) > 1:\n #这里的 screen_save_path 和 imglist[i] 是同一个张图片\n image1 = Image.open(imglist[-2])\n image2 = Image.open(imglist[-1])\n # 把图像对象转换为直方图数据,存在list h1、h2 中s\n h1 = image1.histogram()\n h2 = image2.histogram()\n result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1)) #通过方差大小进行计算\n print(result)\n if result > 5:\n # 图像不一致,继续执行下一个下拉截图\n print(imglist[-1] + '与' + imglist[-2] + '张图像不一致,继续执行。')\n open('result', 'a', encoding='utf8').writelines(imglist[-1] + '与' + imglist[-2] + '张图像不一致,继续执行。' + '\\n')\n else:\n # 图像一致,判断一致原因\n print(imglist[-1] + '与' + imglist[-2] + '图像一致')\n open('result', 'a', encoding='utf8').writelines(imglist[-1] + '与' + imglist[-2] + '图像一致' + '\\n')\n if self.driver.title != '同花顺保险':\n print('跳转地址有误,返回上一张图的位置重新截图')\n open('result', 'a', encoding='utf8').writelines('跳转地址有误,返回上一张图的位置重新截图 \\n')\n\n def find_by_id(self,id):\n t = 0\n try:\n while t < 5:\n if self.driver.find_elements_by_id(id):\n self.driver.find_element_by_id(id).click()\n return 1\n else:\n time.sleep(1)\n t = t + 1\n else:\n print('5s内未找到id')\n open('result', 'a', encoding='utf8').writelines('5s内未找到id \\n')\n return 0\n except Exception as e:\n print(e)\n #open('error', 'a', encoding='utf-8').writelines(e)\n\n def find_by_xpath(self,xpath):\n t = 0\n try:\n while t < 5:\n if self.driver.find_elements_by_xpath(xpath):\n time.sleep(1)\n self.driver.find_element_by_xpath(xpath).click()\n return 1\n else:\n time.sleep(1)\n t = t + 1\n else:\n print('5s内未找到xpath')\n open('result', 'a', encoding='utf-8').writelines('5s内未找到xpath \\n')\n return 0\n except Exception as e:\n print(e)\n #open('error', 'a', encoding='utf-8').writelines(e)\n\n def find_by_class(self, class_name, type):\n t = 0\n try:\n while t < 5:\n if self.driver.find_elements_by_class_name(class_name)and type =='click':\n time.sleep(1)\n self.driver.find_element_by_class_name(class_name).click()\n return 1\n elif self.driver.find_elements_by_class_name(class_name)and type == None:\n\n return 1\n\n else:\n time.sleep(1)\n t = t + 1\n else:\n print('5s内未找到id')\n open('result', 'a', encoding='utf8').writelines('5s内未找到class \\n')\n return 0\n except Exception as e:\n print(e)\n #open('error', 'a', encoding='utf-8').writelines(e)\n\n def find_by_title(self,title):\n t = 0\n try:\n while t < 5:\n if self.driver.title == title:\n return 1\n else:\n time.sleep(1)\n t = t + 1\n else:\n #print('5s内未找到id')\n open('result', 'a', encoding='utf8').writelines('未找到该标题 \\n')\n return 0\n except Exception as e:\n print(e)\n open('error', 'a', encoding='utf-8').writelines(e)\n\n def get_bx_dic(self,url):\n request = urllib.request.Request(url) # 请求目标url\n response = urllib.request.urlopen(request) # 获取返回的结果\n data = response.read().decode('utf-8') # 读取返回的结果并以utf-8进行编码\n data_dic = json.loads(data) # 将返回的结果变成json读取,作为字典保存\n return data_dic\n\n def tearDown(self):\n self.driver.quit()\n\n\n\n\nclass baoxianxiangqing_pa_22(unittest.TestCase):\n classmethod = ClassMethon()\n classmethod.setUp()\n # 进入保险详情页面的操作\n def baoxianxiangqing_pa_22(self):\n\n if self.classmethod.find_by_class('typeChoose', None):\n # 这里的代码需要优化一下,查下自定义查找标签的方法,这里存在3个种类,可以用个循环\n\n for i in range(1,4):\n self.classmethod.find_by_xpath('/html/body/div[2]/div[2]/li['+ str(i)+']')\n self.classmethod.same_as('第'+str(i)+'选择_')\n time.sleep(1)\n #这里进行一下页面上课点击的操作的处理,先查看保障详情\n if self.classmethod.find_by_class('product_detail','click'):\n for i in range(1,4):#也是有三种选择\n self.classmethod.find_by_xpath('/html/body/div/div[1]/li[1'+ str(i)+']/span')\n self.classmethod.same_as('第'+str(i)+'选择_')\n time.sleep(1)\n\n # 滑动页面(计算页面高度和设备高度,一次滑动一屏幕,直至滑到底部)\n t = math.ceil(\n self.classmethod.driver.execute_script(js_heigh) // self.classmethod.driver.execute_script(\n js_heigh_2)) + 1 # 向上取整\n for i in range(1, t):\n # 截图并进行图像对比\n self.classmethod.same_as('滑动第' + str(i) + '次_')\n self.classmethod.driver.execute_script(js_2)\n # 滑到底部之后点击其他的按钮并进行截图\n if self.classmethod.find_by_class('zixun', 'click'):\n # self.classmethod.driver.find_element_by_class_name('zixun').click() # 点击咨询按钮\n time.sleep(1)\n self.classmethod.same_as('咨询页面')\n self.classmethod.driver.back() # 回到保险产品页面\n time.sleep(1)\n # 点击判断是否存在投保按钮,有的话点击\n self.classmethod.driver.back()\n self.classmethod.driver.quit()\n\n\n\nclass shisuanbaofei_pa_22(unittest.TestCase):\n classmethod = ClassMethon()\n classmethod.setUp()\n # 保费试算的操作内容\n def shisuanbaofei_pa_22(self):\n two_y = ['911 元', '349 元', '277 元', '174 元', '249 元', '307 元', '392 元', '484 元', '563 元', '915 元', '1123 元', '1438 元']\n six_y = ['999 元', '407 元', '321 元', '202 元', '271 元', '335 元', '427 元', '529 元', '617 元', '1004 元', '1232 元', '1579 元']\n two_n = ['1929 元', '641 元', '491 元', '329 元', '474 元', '659 元', '921 元', '1215 元', '1397 元', '2251 元', '3648 元', '3697 元']\n baofei = ['two_y', 'six_y', 'two_n']\n a = 0\n if self.classmethod.find_by_id('toubao'): # 点击保费试算按钮\n # self.classmethod.driver.find_element_by_id('toubao').click() # 点击弹窗展示\n time.sleep(0.5)\n # 选择不同的类型进行点击操作\n for s in range(1,4):\n self.classmethod.find_by_xpath('/html/body/div[2]/div[8]/div/p[2]/em[' + str(s) + ']')\n for n in range(2, 14): # 总共是13个价格选项\n self.classmethod.find_by_xpath('/html/body/div[2]/div[8]/div/p[5]/select') # 点击展开年龄的选项\n time.sleep(1.5)\n self.classmethod.find_by_xpath('/html/body/div[2]/div[8]/div/p[5]/select/option[' + str(n) + ']') # 选择指定的价格\n time.sleep(1.5)\n if self.classmethod.find_by_class('price', None):\n price = self.classmethod.driver.find_element_by_class_name('price').text\n if self.classmethod.driver.find_element_by_class_name('price').text == baofei[a][n - 2]:\n print(str(s) + '_'+str(price) + '价格相同' + '\\n')\n else:\n self.classmethod.same_as(str(s) + '_'+str(price)+'产品价格有误')\n a = a + 1\n\n self.classmethod.driver.quit()\n\n\nclass xiadan_pa_22(unittest.TestCase):\n classmethod = ClassMethon()\n classmethod.setUp()\n #下单流程的操作内容\n def xiadan_pa_22(self):\n name = '同花顺测试'\n telephone = '18868888588'\n idcard = '330724199401226219'\n bankno = '6228480323239098219'\n\n if self.classmethod.find_by_id('toubao'): # 点击保费试算按钮\n # self.classmethod.driver.find_element_by_id('toubao').click() # 点击弹窗展示\n time.sleep(1)\n self.classmethod.driver.find_element_by_id('toubao').click() # 点击跳转下单流程页面\n self.classmethod.same_as('进入保单流程_')\n if self.classmethod.find_by_xpath('/html/body/div[1]/div/span[2]'):\n # 点击健康告知页面的【以上全否,继续投保】,进入保单填写页面\n #self.classmethod.driver.find_element_by_xpath('/html/body/div[1]/div/span[2]').click()\n print('点击健康告知页面的按钮')\n time.sleep(1)\n # screenshot(screenshot_dir, '继续投保按钮')\n # 填写保单信息\n if self.classmethod.find_by_title('保单填写'):\n # 输入姓名,手机号,身份证号码\n self.classmethod.driver.find_element_by_id('name').clear()\n self.classmethod.driver.find_element_by_id('name').send_keys(name)\n time.sleep(1)\n print('输入名字')\n self.classmethod.driver.find_element_by_id('telephone').clear()\n self.classmethod.driver.find_element_by_id('telephone').send_keys(telephone)\n time.sleep(1)\n print('输入手机号')\n self.classmethod.driver.find_element_by_id('idcard').clear()\n self.classmethod.driver.find_element_by_id('idcard').send_keys(idcard)\n print('输入身份证号码')\n #选择银行进行输入\n #不同的银行进行遍历一次\n self.classmethod.find_by_xpath('/html/body/div[2]/div[4]/li[2]/select') # 点击展开银行的选项\n time.sleep(1.5)\n self.classmethod.find_by_xpath('/html/body/div[2]/div[4]/li[2]/select/option[3]') # 选择指定的银行(这里银行有很多种,2-16,银行名称和卡号要一一对应起来)\n #输入银行卡号\n self.classmethod.driver.find_element_by_class_name('bankno').clear()\n self.classmethod.driver.find_element_by_class_name('bankno').send_keys(bankno)\n print('输入银行卡号')\n time.sleep(1)\n # 投保人选择自己\n # self.driver.find_element_by_xpath('/html/body/div[2]/div[3]/li[2]/div/nav[1]').click()\n # print('投保人为本人')\n # 勾选协议\n time.sleep(1)\n self.classmethod.same_as('投保本人保单_')\n # driver.swipe(200,700,200,300)\n js = 'window.scrollTo(0,document.body.scrollHeight)'\n self.classmethod.driver.execute_script(js) # 滑动页面到底部\n print('滑动页面到底部')\n time.sleep(1)\n self.classmethod.find_by_xpath('/html/body/div[2]/div[6]/p')\n #self.classmethod.driver.find_element_by_class_name('iconfont').click() #\n print('点击勾选按钮')\n time.sleep(1)\n # 点击立即投保按钮,进去保险公司页面\n self.classmethod.driver.find_element_by_class_name('toubao').click()\n self.classmethod.same_as('保险公司_')\n time.sleep(2)\n self.classmethod.driver.quit()\n\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n\n","sub_path":"TestCase_pajk_22.py","file_name":"TestCase_pajk_22.py","file_ext":"py","file_size_in_byte":17242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512923915","text":"from math import factorial\n\nn, m = map(int, input().split())\n\n\ndef f(n):\n if n == 1:\n return 1\n else:\n return n * f(n-1)\n\n\nif abs(n - m) >= 2:\n print(0)\n\nelif abs(n - m) == 1:\n print((factorial(min(n, m)) ** 2 * max(n, m)) % (10 ** 9 + 7))\n\nelse:\n print((2 * factorial(n) ** 2) % (10 ** 9 + 7))\n","sub_path":"kakomon/ABC065-C.py","file_name":"ABC065-C.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226316256","text":"from django.core.management.base import BaseCommand\nfrom django.db import transaction\n\nimport timetable.models\n\n\nclass Command(BaseCommand):\n \"\"\"\n Split group into multiple groups of the size 1.\n \"\"\"\n\n args = \"group_id\"\n help = \"Split group. Group should be assigned to exactly 1 activity. New group will be assigned to the same activity.\"\n\n @transaction.atomic\n def handle(self, *args, **options):\n assert len(args) == 1, \"Expected at least one argument.\"\n group = timetable.models.Group.objects.get(pk=args[0])\n assert (\n group.activities.count() == 1\n ), \"Group should be assigned to exactly one activity.\"\n activity = group.activities.get()\n last_underscore = group.short_name.rfind(\"_\")\n basename = group.short_name[:last_underscore]\n last_space = group.name.rfind(\" \")\n baselongname = group.name[:last_space]\n group_number = 1\n groups = activity.groups.filter(short_name__contains=basename)\n start = max([int(g.groupnum) for g in groups]) + 1\n parent = group.parent\n groupset = group.groupset\n for i in range(group.size - 1):\n short_name = \"{0}_{1:02}\".format(basename, start + i)\n name = \"{0} {1}\".format(baselongname, start + i)\n g = timetable.models.Group(\n name=name,\n short_name=short_name,\n parent=parent,\n groupset=groupset,\n size=1,\n )\n g.save()\n g.activities.add(*group.activities.all())\n group.size = 1\n group.save()\n","sub_path":"friprosveta/management/commands/split_group.py","file_name":"split_group.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465306868","text":"# -*- coding:utf-8 -*-\r\n# By tostq \r\n# Reference to hmmlearn.examples.plot_hmm_stock_analysis.py\r\n# 博客: blog.csdn.net/tostq\r\nfrom matplotlib import cm, pyplot as plt\r\nfrom matplotlib.dates import YearLocator, MonthLocator\r\nfrom hmm import GaussianHMM\r\nfrom sklearn.preprocessing import scale\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\n###############################################################################\r\n# 导入Yahoo金融数据\r\nquotes = pd.read_csv(\"../data/yahoofinance-INTC-19950101-20040412.csv\")\r\n\r\ndates = quotes.index.values\r\nclose_v = quotes[[\"Close\"]].values.flatten()\r\nvolume = quotes[[\"Volume\"]].values.flatten()\r\n# diff:out[n] = a[n+1] - a[n] 得到价格变化\r\ndiff = np.diff(close_v)\r\ndates = dates[1:]\r\nclose_v = close_v[1:]\r\nvolume = volume[1:]\r\n\r\n# scale归一化处理:均值为0和方差为1\r\n# 将价格和交易数组成输入数据\r\nX = np.column_stack([scale(diff), scale(volume)])\r\n\r\n# 训练高斯HMM模型,这里假设隐藏状态4个\r\nmodel = GaussianHMM(4, 2, 20)\r\nmodel.train(X)\r\n\r\n# 预测隐状态\r\nhidden_states = model.decode(X)\r\n\r\n# 打印参数\r\nprint(\"Transition matrix: \", model.transmat_prob)\r\nprint(\"Means and vars of each hidden state\")\r\nfor i in range(model.n_state):\r\n print(\"{0}th hidden state\".format(i))\r\n print(\"mean = \", model.emit_means[i])\r\n print(\"var = \", model.emit_covars[i])\r\n print()\r\n\r\n# 画图描述\r\nfig, axs = plt.subplots(model.n_state, sharex=True, sharey=True)\r\ncolours = cm.rainbow(np.linspace(0, 1, model.n_state))\r\nfor i, (ax, colour) in enumerate(zip(axs, colours)):\r\n # Use fancy indexing to plot data in each state.\r\n mask = hidden_states == i\r\n ax.plot_date(dates[mask], close_v[mask], \".-\", c=colour)\r\n ax.set_title(\"{0}th hidden state\".format(i))\r\n\r\n # Format the ticks.\r\n ax.xaxis.set_major_locator(YearLocator())\r\n ax.xaxis.set_minor_locator(MonthLocator())\r\n\r\n ax.grid(True)\r\n\r\nplt.show()\r\n","sub_path":"easyhmm/Stock_03.py","file_name":"Stock_03.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599143687","text":"from PIL import Image\nimport glob\nimport numpy as np\nfilenames = glob.glob('Gray/*.png')\nprint(filenames)\n\nfor file in filenames:\n\tarr = np.array(Image.open(file))[:, :, 0]\n\tfor i in range(16):\n\t\tfor j in range(16):\n\t\t\tarr[i][j] = 255 if arr[i][j] > 128 else 0\n\n\timg = Image.fromarray(arr)\n\t# img.show()\n\timg.save(file)","sub_path":"assignment1/make_imgs/Gray2Bin.py","file_name":"Gray2Bin.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528156152","text":"from DataService.TwitterService.TwitterStreamer import TwitterStreamProvider\nfrom DataService.TwitterService.TwitterConsumer import RouterManager\nimport datetime\nfrom pymongo import ASCENDING\nimport logging\n\n\nclass TwitterSource(object):\n logger = logging.getLogger(__name__)\n\n def __init__(self, dbm, cfg, n_routers_init=2):\n self.streamer = TwitterStreamProvider(cfg[\"auth\"])\n self.router = RouterManager(dbm, n_routers_init)\n self.pipes = []\n self.dbm = dbm\n\n def delete(self, dataset_meta):\n\n db_col = dataset_meta.db_col\n if db_col in self.dbm.data_db.collection_names():\n self.dbm.data_db.get_collection(db_col).drop()\n\n def setup_collection(self, name):\n\n self.dbm.data_db.get_collection(name).create_index([(\"ISO_created_at\",ASCENDING)])\n self.dbm.data_db.get_collection(name).create_index([(\"id\", ASCENDING)], unique=True)\n\n def get_status(self):\n\n return self.streamer.status.get()\n\n def add(self, dataset_info):\n\n db_col = dataset_info.db_col\n logging.info(\"Adding twitter sourced dataset %s\", dataset_info.db_col)\n if db_col not in self.dbm.data_db.collection_names():\n self.logger.info(\"Setting up new collection for %s\", db_col)\n self.setup_collection(db_col)\n\n\n self.pipes.append(dataset_info)\n self.streamer.run(self.get_tracking_terms())\n self.router.add_filter(dataset_info)\n\n logging.info(\"Filters: %d Consumers %d\", self.router.n_filters, self.router.p_counter)\n\n dataset_info.status = \"RUNNING\"\n dataset_info.save()\n\n def stop(self, dataset_info):\n\n logging.info(\"Stopping twitter sourced dataset %s\", dataset_info.description)\n\n try:\n\n self.pipes.remove(dataset_info)\n\n except ValueError:\n\n logging.info(\"Attempting to stop twitter sourced dataset %s that does not exist\", dataset_info.description)\n dataset_info.status = \"STOPPED\"\n dataset_info.collection_size = self.dbm.data_db.get_collection(dataset_info.db_col).count()\n dataset_info.end_time = datetime.datetime.now()\n dataset_info.save()\n return\n\n self.router.remove_filter(dataset_info)\n\n if len(self.pipes) == 0:\n self.streamer.stop()\n else:\n self.streamer.run(self.get_tracking_terms())\n\n dataset_info.status = \"STOPPED\"\n dataset_info.collection_size = self.dbm.data_db.get_collection(dataset_info.db_col).count()\n dataset_info.end_time = datetime.datetime.now()\n dataset_info.save()\n\n def get_tracking_terms(self):\n\n terms = []\n for pipe in self.pipes:\n terms += pipe.tags\n\n return list(set(terms))\n","sub_path":"server/src/DataService/TwitterService/TwitterSource.py","file_name":"TwitterSource.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524898365","text":"\r\nimport cv2\r\nimport math\r\nimport time\r\nimport numpy as np\r\nclass Exhaustive_Search:\r\n def __init__(self,ref_image,test_image):\r\n self.ref_img = ref_image\r\n self.tst_img = test_image\r\n self.row_ref = self.ref_img.shape[0]\r\n self.col_ref = self.ref_img.shape[1]\r\n self.mismatch_row = self.tst_img.shape[0]-self.row_ref+1\r\n self.mismatch_col = self.tst_img.shape[1]-self.col_ref+1\r\n\r\n def minimization(self, D_mis):\r\n index = []\r\n index.append(-1)\r\n index.append(-1)\r\n minimum = 1.7976931348623157e+308\r\n\r\n i = 0\r\n while i 0 and m[0] < 800:\n Data.hero.x = m[0]\n if m[1] > 350 and m[1] < 600:\n Data.hero.y = m[1]\n if e.type == pygame.MOUSEBUTTONDOWN:\n if e.button == 1:\n if Data.hero.push == False and Data3.arrowCounter > 0:\n Music.pushSoundPlay(0)\n Data.playerArrow.x = Data.hero.x\n Data.playerArrow.y = Data.hero.y\n Data.hero.push = True\n Data3.arrowCounter -= 1\n Data.enemy.y = 20\n Data.enemy2.y = 220\n\n if Bumps.checkBump(Data.playerArrow.x, Data.enemy.x, Data.playerArrow.y, Data.enemy.y, 10, 35) == True:\n Data.enemyArrow.x = Data.enemy.x\n Data.enemyArrow.y = Data.enemy.y\n Data.enemy.push = True\n if Data.enemy.x > 0 and Data.enemy.x < 700:\n if Data.enemy.push == False:\n Data.enemyArrow.x = Data.enemy.x\n Data.enemyArrow.y = Data.enemy.y\n Data.enemy.push = True\n\n if Bumps.checkBump(Data.playerArrow.x, Data.enemy2.x, Data.playerArrow.y, Data.enemy2.y, 10, 35) == True:\n Data.enemyArrow.x = Data.enemy.x\n Data.enemyArrow.y = Data.enemy.y\n Data.enemy.push = True\n if Data.enemy2.x > 0 and Data.enemy2.x < 700:\n if Data.enemy2.push == False:\n Data.enemy2Arrow.x = Data.enemy2.x\n Data.enemy2Arrow.y = Data.enemy2.y\n Data.enemy2.push = True\n\n if Data.enemy.right == True:\n Data.enemy.x -= Data.enemy.step\n if Data.enemy.x < 0:\n Data3.score += 1\n Data.enemy.right = False\n else:\n Data.enemy.x += Data.enemy.step\n if Data.enemy.x > 750:\n Data3.score += 1\n Data.enemy.right = True\n if Data.playerArrow.y < 0:\n Data.hero.push = False\n Data3.score -= Data.enemy.step + Data.enemy2.step\n if Data.hero.push == False:\n Data.playerArrow.y = 700\n Data.playerArrow.x = -20\n else:\n Data.playerArrow.y -= 4\n if Data.enemyArrow.y > 800:\n Data.enemy.push = False\n if Data.enemy.push == False:\n Data.enemyArrow.y = -700\n Data.enemyArrow.x = 20\n else:\n Data.enemyArrow.y += 12\n\n if Data.enemy2.right == True:\n Data.enemy2.x -= Data.enemy2.step\n if Data.enemy2.x < 0:\n Data3.score += 1\n Data.enemy2.right = False\n else:\n Data.enemy2.x += Data.enemy2.step\n if Data.enemy2.x > 750:\n Data3.score += 1\n Data.enemy2.right = True\n if Data.playerArrow.y < 0:\n Data.hero.push = False\n Data3.score -= Data.enemy.step\n if Data.hero.push == False:\n Data.playerArrow.y = 700\n Data.playerArrow.x = -20\n else:\n Data.playerArrow.y -= 4\n if Data.enemy2Arrow.y > 800:\n Data.enemy2.push = False\n if Data.enemy2.push == False:\n Data.enemy2Arrow.y = -700\n Data.enemy2Arrow.x = 20\n else:\n Data.enemy2Arrow.y += 12\n\n if Bumps.checkBump(Data.playerArrow.x, Data.enemy.x, Data.playerArrow.y, Data.enemy.y, 10, 35) == True:\n Data.hero.push = False\n Data.enemy.step += 0.6\n Data3.score += Data.enemy.step\n Data.enemy.health -= 5\n Data.hero.health += 5\n Data3.arrowCounter += 2\n\n if Bumps.checkBump(Data.playerArrow.x, Data.enemy2.x, Data.playerArrow.y, Data.enemy2.y, 10, 35) == True:\n Data.hero.push = False\n Data.enemy2.step += 0.6\n Data3.score += Data.enemy2.step\n Data.enemy2.health -= 5\n Data.hero.health += 5\n Data3.arrowCounter += 2\n\n if Bumps.checkBump(Data.enemyArrow.x, Data.hero.x, Data.enemyArrow.y, Data.hero.y, 10, 35) == True:\n Data.enemy.push = False\n Data3.score -= 2\n Data.hero.health -= 5\n Data.enemy.health += 5\n\n if Bumps.checkBump(Data.enemy2Arrow.x, Data.hero.x, Data.enemy2Arrow.y, Data.hero.y, 10, 35) == True:\n Data.enemy2.push = False\n Data3.score -= 2\n Data.hero.health -= 5\n Data.enemy2.health += 5\n\n Data.screen.blit(Data3.background_image, [0, 0])\n Data.info_string.fill((100, 0, 100))\n Data.playerArrow.render(Data.screen)\n Data.enemy.render(Data.screen)\n Data.enemy2.render(Data.screen)\n Data.hero.render(Data.screen)\n Data.enemyArrow.render(Data.screen)\n Data.enemy2Arrow.render(Data.screen)\n Data.info_string.blit(\n Data.speed_font.render(u'Speed: ' + str(round(Data.enemy.step + Data.enemy2.step, 2)), 1, (210, 120, 200)),\n (280, 5))\n Data.info_string.blit(Data.label_font.render(u'Blocks ' + str(Data3.arrowCounter), 1, (210, 120, 200)),\n (150, 5))\n Data.info_string.blit(Data.inf_font.render(u'Score: ' + str(round(Data3.score, 2)), 1, (0, 250, 200)), (2, 5))\n Data.info_string.blit(Data.hero_health_font.render(u'Hero health: ' + str(Data.hero.health), 1, (0, 250, 200)),\n (410, 5))\n Data.info_string.blit(\n Data.hero_health_font.render(u'Enemy health: ' + str(Data.enemy.health + Data.enemy2.health), 1,\n (0, 250, 200)), (600, 5))\n Data.window.blit(Data.info_string, (0, 0))\n Data.window.blit(Data.screen, (0, 30))\n pygame.display.flip()\n pygame.time.delay(1)\n print(Data.enemy.x)\n if Data.enemy.health <= 0:\n print(\"Victory!!!\")\n Music.main_sound.stop()\n Music.victorySoundPlay(0)\n end_puncts_win = [(80, 40, u'Congratulations!You completed the game!', (250, 250, 30), (250, 30, 250), 0),\n (250, 100, u'Your score is ' + str(round(Data3.score, 2)), (250, 250, 30), (250, 30, 250),\n 1),\n (250, 270, u'Start game again', (250, 250, 30), (250, 30, 250), 5),\n (350, 320, u'Quit', (250, 250, 30), (250, 30, 250), 6)]\n end = CAndM.Caption(end_puncts_win)\n end.menu(Data.info_string, Data.screen, Data.window)\n\n elif Data3.score <= 0 or Data.hero.health <= 0 or Data3.arrowCounter <= 0:\n Music.main_sound.stop()\n Music.lose_sound.play(0)\n\n end_puncts_lost = [(220, 40, u'You have lost!Try again! ', (250, 250, 30), (250, 30, 250), 0),\n (\n 250, 100, u'Your score is ' + str(round(Data3.score, 2)), (250, 250, 30), (250, 30, 250),\n 1),\n (250, 270, u'Try again this level', (250, 250, 30), (250, 30, 250), 4),\n (250, 320, u'Go to the first level', (250, 250, 30), (250, 30, 250), 5),\n (350, 370, u'Quit', (250, 250, 30), (250, 30, 250), 6)]\n Data3.arrowCounter = Data2.arrowCounter\n Data3.score = Data2.score\n Data.enemy.step = 1\n Data.enemy2.step = 1\n Data.enemy.health = 100\n Data.hero.health = 100\n end = CAndM.Caption(end_puncts_lost)\n end.menu(Data.info_string, Data.screen, Data.window)\n\n\nlevel3()","sub_path":"by/bntu/fitr/yan_sleptsov/gr_10702217/game/ThirdLevel.py","file_name":"ThirdLevel.py","file_ext":"py","file_size_in_byte":8570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197174833","text":"import math\nimport random\n\n\ndef calculate_euclidean_distance(coord1, coord2, magnifier=1):\n \"\"\"\n Computes the \"coordinate\" Euclidean distance between two points.\n :param coord1: the coordinates of the first point as a tuple (long, lat)\n :param coord2: the coordinates of the second point as a tuple (long, lat)\n :param magnifier: a factor to magnify the result\n :return: the \"coordinate\" Euclidean distance between the given points\n \"\"\"\n return sum([(x - y) ** 2 for x, y, in zip(coord1, coord2)]) * magnifier\n\n\ndef calculate_metric_distance(coord1, coord2):\n \"\"\"\n Computes the distance (in meters) between two points.\n Taken from: http://www.johndcook.com/blog/python_longitude_latitude/\n :param coord1: the coordinates of the first point as a tuple (long, lat)\n :param coord2: the coordinates of the second point as a tuple (long, lat)\n :return: the distance (in meters) between the given points\n \"\"\"\n # unpack the coordinates\n (long1, lat1) = coord1\n (long2, lat2) = coord2\n\n threshold = 1e-5\n if abs(long1 - long2) <= threshold or abs(lat1 - lat2) <= threshold:\n return 0\n\n # The radius of the Earth in meters\n earth_radius = 6371e3\n\n # Convert latitude and longitude to spherical coordinates in radians\n degrees_to_radians = math.pi / 180.0\n\n # phi = 90 - latitude\n phi1 = (90.0 - lat1) * degrees_to_radians\n phi2 = (90.0 - lat2) * degrees_to_radians\n\n # theta = longitude\n theta1 = long1 * degrees_to_radians\n theta2 = long2 * degrees_to_radians\n\n # Compute spherical distance from spherical coordinates\n cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) +\n math.cos(phi1) * math.cos(phi2))\n arc = math.acos(cos)\n\n return arc * earth_radius\n\n\ndef perform_clustering(points, centroids, magnifier):\n \"\"\"\n Assigns each of the given points to a cluster based on the distance from the respective centroid points.\n :param points: a list of n points to be clustered\n :param centroids: a list of m centroid points identifying the clusters\n :param magnifier: a factor to pass to the euclidean distance calculator\n :return: a list of n indexes, each defining the cluster that the respective point was assigned to\n \"\"\"\n clusters = []\n for p in points:\n distances = [calculate_euclidean_distance(p, c, magnifier) for c in centroids]\n min_distance = min(distances)\n clusters.append(distances.index(min_distance))\n\n return clusters\n\n\ndef recalculate_centroids(points, clusters, num_centroids):\n \"\"\"\n Recalculates the positions of the centroid points as the means of the points that belong to each cluster.\n :param points: a list of n clustered points\n :param clusters: a list of n indexes, each defining the cluster that the respective point was assigned to\n :param num_centroids: the number of centroids / clusters\n :return: a list of the new centroid points for the given clusters\n \"\"\"\n new_centroids = []\n for cluster_index in range(num_centroids):\n # if a cluster is empty, choose a random point to be used as a centroid\n point_indexes = [i for i in range(len(clusters)) if clusters[i] == cluster_index]\n if point_indexes:\n new_centroid_long = round(sum([points[j][0] for j in point_indexes]) / len(point_indexes), 4)\n new_centroid_lat = round(sum([points[j][1] for j in point_indexes]) / len(point_indexes), 4)\n new_centroids.append((new_centroid_long, new_centroid_lat))\n else:\n new_centroids.append(random.choice(points))\n\n return new_centroids\n\n\ndef calculate_average_distance(points, clusters, centroids):\n \"\"\"\n Computes the average distance (in meters) between a point and the centroid of its cluster.\n :param points: a list of n clustered points\n :param clusters: a list of n indexes, each defining the cluster that the respective point was assigned to\n :param centroids: a list of m centroid points identifying the clusters\n :return: the average distance (in meters) between a point and the centroid of its cluster\n \"\"\"\n total_dist = 0\n for i in range(len(points)):\n total_dist += calculate_metric_distance(points[i], centroids[clusters[i]])\n return round(total_dist / len(points))\n\n\ndef run_k_means(points, num_centroids, num_iterations, magnifier):\n \"\"\"\n Runs the K-means clustering algorithm.\n :param points: a list of points to be clustered\n :param num_centroids: the number of centroids / clusters\n :param num_iterations: the number of iterations to run the algorithm\n :param magnifier: a factor to pass to the euclidean distance calculator\n :return: the final list of centroid points and the average distance based on this clustering\n \"\"\"\n clusters = []\n centroids = random.sample(points, num_centroids)\n\n for _ in range(num_iterations):\n clusters = perform_clustering(points, centroids, magnifier)\n centroids = recalculate_centroids(points, clusters, num_centroids)\n\n average_distance = calculate_average_distance(points, clusters, centroids)\n return centroids, average_distance\n","sub_path":"process_geo_points/k_means_clustering.py","file_name":"k_means_clustering.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"190599686","text":"import networkx as nx\nimport random\nimport sys\nsize=int(sys.argv[-1])\nname=str(sys.argv[-2])\nG=nx.gnp_random_graph(size,0.5,directed=True, seed=random.seed())\nDAG = nx.DiGraph([(u,v,{'weight':random.randint(1,10)}) for (u,v) in G.edges() if u 1:\n flg_pairwise = False\n break\n\nif flg_pairwise:\n print('pairwise coprime')\nelse:\n for i in range(n-1):\n if i==0:\n tmp = gcd(lis[i],lis[i+1])\n else:\n tmp = gcd(tmp,lis[i+1])\n\n if tmp==1:\n print('setwise coprime')\n else:\n print('not coprime')","sub_path":"Python_codes/p02574/s896009974.py","file_name":"s896009974.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101350350","text":"import requests\nimport time\nimport sys\n\ndebit = json.loads(\n storage['card_debit_dispute']['response']\n)\n\ntimeout = 12 * 60\ninterval = 10\nbegin = time.time()\n\nwhile True:\n debit = requests.get(ctx.storage['api_location'] + debit['debits'][0]['href'],\n headers={'Accept-Type': ctx.storage.get('accept_type', '*/*')},\n auth=(ctx.storage['secret'], '')).json()\n if debit['debits'][0]['links']['dispute'] != None:\n break\n time.sleep(interval)\n elapsed = time.time() - begin\n if elapsed > timeout:\n exit()\n\nrequest = {\n 'uri': debit['links']['debits.dispute'].replace('{debits.dispute}', debit['debits'][0]['links']['dispute']),\n 'debit_href': debit['debits'][0]['href']\n}\n","sub_path":"clients/rev1/curl/debit_dispute_show/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321447072","text":"#defines the function that extracts relevant information from a pair of .json files. This function is imported in chatview.py\n\nimport json\n\ndef getChat(path):\n \"\"\"Parses the pair of json files in a directory (label.json and log.json) \n and returns a list of strings that makes up the chat transcription. The \n list starts with two strings containing meta information, and then uses \n one string for each turn.\"\"\"\n \n userList = []\n sysList = []\n\n # read user log\n with open(path + '/label.json', 'r') as myfile:\n data=myfile.read()\n obj = json.loads(data) # parse\n \n #extract transcript\n for x in range(len(obj['turns'])):\n userList.append(str(obj['turns'][x]['transcription']))\n \n # read system log\n with open(path + '/log.json', 'r') as myfile2:\n data2=myfile2.read()\n obj2 = json.loads(data2) #parse\n #extract transcript\n for y in range(len(obj2['turns'])):\n sysList.append(str(obj2['turns'][y]['output']['transcript']))\n\n #combine data into chat summary\n chat = []\n chat.append('session-id: ' + str(obj2['session-id']))\n chat.append(str(obj['task-information']['goal']['text']))\n for x in range(len(sysList)):\n chat.append('system: ' + sysList[x])\n chat.append('user: ' + userList[x])\n\n\n return chat\n","sub_path":"assignment-1b/read_json.py","file_name":"read_json.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"185484689","text":"from django.shortcuts import render,get_object_or_404,redirect\r\nfrom django.http import Http404\r\nfrom django.views.generic import TemplateView,CreateView,DetailView,ListView,RedirectView,DeleteView\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.contrib.auth.mixins import LoginRequiredMixin\r\nfrom django.urls import reverse_lazy,reverse\r\nfrom django.contrib.auth import authenticate,login\r\nfrom django.http import HttpResponseRedirect,HttpResponse\r\nfrom django.contrib.auth.models import User\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.forms import AuthenticationForm\r\nfrom speed.forms import DoctorProfileForm,PatientUserForm,PatientProfileForm,PhoneVerificationForm\\\r\n ,CityForm,Virtual,Usercreateform,MapForm,SlotForm\r\nfrom speed.models import Doctor,Clinic,Patient,Appointment,GroupMember,MapDetail,TimeSlot\r\nfrom .authy_api import send_verfication_code, verify_sent_code\r\nfrom .calender import main\r\nimport json\r\nimport datetime\r\nimport pickle\r\nfrom django_ical.views import ICalFeed\r\nfrom django.core.serializers import serialize\r\nfrom django.conf import settings\r\nfrom paypal.standard.forms import PayPalPaymentsForm\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nimport requests\r\n\r\n\r\n# Create your views here.\r\nclass Google(TemplateView):\r\n template_name =\"registration/google_login.html\"\r\ndef doctor_register(request,username):\r\n registered=False\r\n user=User.objects.get(username=username)\r\n if request.method==\"POST\":\r\n #user_form=DoctorUserForm(data=request.POST)\r\n reg_form=DoctorProfileForm(data=request.POST)\r\n if reg_form.is_valid():\r\n #user=user_form.save()\r\n #user.set_password(user.password)\r\n #user.save()\r\n reg=reg_form.save(commit=False)\r\n reg.user=user\r\n reg.save()\r\n registered=True\r\n return render(request,\"doctor/doctor_detail.html\",{'doctor':reg,'registered':registered})\r\n else:\r\n messages.error(request, 'Change the username!')\r\n else:\r\n #user_form=DoctorUserForm()\r\n reg_form=DoctorProfileForm()\r\n return render(request,\"registration/doctor_registration.html\",{'reg_form':reg_form,'registered':registered})\r\ndef doctor_signup(request):\r\n if request.method==\"POST\":\r\n user_form=Usercreateform(data=request.POST)\r\n user_form.save()\r\n return reverse(\"doc_user_login\")\r\n else:\r\n user_form=Usercreateform()\r\n return render(request,\"registration/google_login.html\",{'user_form':user_form})\r\n\r\n\r\n\r\ndef doctor_user_login(request):\r\n if request.method==\"POST\":\r\n form = AuthenticationForm(request, request.POST)\r\n username=request.POST.get('username')\r\n password= request.POST.get('password')\r\n\r\n user=authenticate(username=username,password=password)\r\n\r\n if user:\r\n login(request,user)\r\n return HttpResponseRedirect(reverse('speed:list_home',kwargs={'username':username}))\r\n else:\r\n messages.error(request, 'Invalid username and password')\r\n else:\r\n form = AuthenticationForm(request)\r\n return render(request,\"registration/doctor_login.html\",{'form':form})\r\n\r\ndef patient_register(request):\r\n registered=False\r\n if request.method==\"POST\":\r\n base_form=PatientUserForm(data=request.POST)\r\n pat_form=PatientProfileForm(data=request.POST)\r\n if base_form.is_valid() and pat_form.is_valid():\r\n user = base_form.save()\r\n user.set_password(user.password)\r\n user.save()\r\n pat=pat_form.save(commit=False)\r\n pat.user=user\r\n pat.save()\r\n registered=True\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n else:\r\n messages.error(request, '')\r\n\r\n else:\r\n base_form=PatientUserForm()\r\n pat_form=PatientProfileForm()\r\n return render(request,\"registration/patient_registration.html\",{'base_form':base_form,'pat_form':pat_form,'registered':registered})\r\n\r\ndef patient_user_login(request):\r\n\r\n if request.method==\"POST\":\r\n form=AuthenticationForm(request,request.POST)\r\n username = request.POST.get('username')\r\n if not User.objects.filter(username=username):\r\n messages.error(request, 'User with the mobile number does not exist!')\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n user = User.objects.get(username=username)\r\n user.backend = 'django.contrib.auth.backends.ModelBackend'\r\n patient = Patient.objects.get(user__username=user.username)\r\n patient.phone_number = user.username\r\n user.backend = 'django.contrib.auth.backends.ModelBackend'\r\n\r\n # print(user.two_factor_auth)\r\n if user:\r\n \"\"\"login(request,user)\r\n return render(request, \"patient/show_detail.html\", {'appointment': patient})\"\"\"\r\n\r\n try:\r\n response = send_verfication_code(patient)\r\n pass\r\n except Exception as e:\r\n messages.add_message(request, messages.ERROR,\r\n 'verification code not sent. \\n'\r\n 'Please retry logging in.')\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n data = json.loads(response.text)\r\n\r\n if data['success'] == False:\r\n messages.add_message(request, messages.ERROR,\r\n data['message'])\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n\r\n if data['success'] == True:\r\n request.method = \"GET\"\r\n print(request.method)\r\n kwargs = {'patient': patient}\r\n return PhoneVerificationView(request, **kwargs)\r\n else:\r\n messages.add_message(request, messages.ERROR,\r\n data['message'])\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n else:\r\n messages.error(request, 'User with the mobile number does not exist!')\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n else:\r\n form = AuthenticationForm(request)\r\n return render(request, \"registration/patient_login.html\", {'form': form})\r\n\r\ndef PhoneVerificationView(request, **kwargs):\r\n template_name = 'registration/phone_confirm.html'\r\n\r\n if request.method == \"POST\":\r\n username = request.POST['username']\r\n user = User.objects.get(username=username)\r\n user.backend = 'django.contrib.auth.backends.ModelBackend'\r\n patient=Patient.objects.get(user__username=user.username)\r\n patient.phone_number=user.username\r\n patient.save()\r\n form = PhoneVerificationForm(request.POST)\r\n if form.is_valid():\r\n verification_code = request.POST['one_time_password']\r\n response = verify_sent_code(verification_code, patient)\r\n print(response.text)\r\n data = json.loads(response.text)\r\n\r\n if data['success'] == True:\r\n login(request, user)\r\n if patient.phone_number_verified is False:\r\n patient.phone_number_verified = True\r\n patient.save()\r\n return render(request,\"patient/show_detail.html\",{'appointment':patient})\r\n else:\r\n messages.add_message(request, messages.ERROR,\r\n data['message'])\r\n return render(request, template_name, {'patient':patient})\r\n else:\r\n context = {\r\n 'patient': patient,\r\n 'form': form,\r\n }\r\n return render(request, template_name, context)\r\n\r\n elif request.method == \"GET\":\r\n patient = kwargs['patient']\r\n return render(request, template_name, {'patient': patient})\r\n\r\n## DOCTOR VIEWS\r\n\r\nclass DoctorListView(ListView):\r\n context_object_name =\"listdoc\"\r\n model=Doctor\r\n template_name =\"doctor/doctor_list.html\"\r\n\r\nclass DoctorDetailView(DetailView):\r\n model=Doctor\r\n template_name=\"doctor/doctor_detail.html\"\r\n def get_queryset(self):\r\n queryset=super().get_queryset()\r\n return queryset.filter(user__username__iexact=self.kwargs.get('username'))\r\n\r\nclass DoctorDetailView2(DetailView):\r\n model=Doctor\r\n template_name=\"doctor/doctor_detail2.html\"\r\n def get_queryset(self):\r\n queryset=super().get_queryset()\r\n return queryset.filter(user__username__iexact=self.kwargs.get('username'))\r\n\r\n\r\ndef Meet(request,pk):\r\n if request.method=='POST':\r\n v_form=Virtual(request.POST)\r\n p_form=AuthenticationForm(request,request.POST)\r\n username = request.POST.get('username')\r\n if v_form.is_valid():\r\n subject=request.POST.get('subject')\r\n user=User.objects.get(username=username)\r\n user.backend ='django.contrib.auth.backends.ModelBackend'\r\n if user:\r\n p=User.objects.get(pk=user.pk)\r\n date=request.POST.get('day')\r\n time=request.POST.get('time')\r\n appointment_pat=v_form.save(commit=False)\r\n appointment_pat.patient=Patient.objects.get(user__id=p.id)\r\n appointment_pat.save()\r\n appointment_doc=v_form.save(commit=False)\r\n appointment_doc.doctor=Doctor.objects.get(pk=pk)\r\n appointment_doc.save()\r\n patient = Patient.objects.get(user__username=user.username)\r\n patient.phone_number = user.username\r\n patient.save()\r\n #print(appointment_doc.doctor.user.email)\r\n main(appointment_doc.doctor.user.email,date,time)\r\n \"\"\"login(request,user)\r\n return render(request, \"patient/show_detail.html\", {'appointment': patient})\"\"\"\r\n try:\r\n response = send_verfication_code(patient)\r\n pass\r\n except Exception as e:\r\n messages.add_message(request, messages.ERROR,\r\n 'verification code not sent. \\n'\r\n 'Please retry logging in.')\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n data = json.loads(response.text)\r\n\r\n if data['success'] == False:\r\n messages.add_message(request, messages.ERROR,\r\n data['message'])\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n\r\n if data['success'] == True:\r\n request.method = \"GET\"\r\n print(request.method)\r\n kwargs = {'patient': patient}\r\n return PhoneVerificationView(request, **kwargs)\r\n else:\r\n messages.add_message(request, messages.ERROR,\r\n data['message'])\r\n return HttpResponseRedirect(reverse('pat_user_login'))\r\n\r\n else:\r\n v_form=Virtual()\r\n p_form=AuthenticationForm(request)\r\n return render(request,\"appointment/appointment_form.html\",{'v_form':v_form,'p_form':p_form})\r\nclass sample(TemplateView):\r\n template_name =\"patient/show_app.html\"\r\nclass another(TemplateView):\r\n template_name =\"patient/show_detail.html\"\r\n\r\nclass ConfirmView(TemplateView):\r\n template_name=\"appointment/confirm_app.html\"\r\n\r\n\r\nclass DoctorHomeView(TemplateView,RedirectView):\r\n template_name=\"doctor/doctor_base.html\"\r\n def get_redirect_url(self, pk):\r\n doctor=Doctor.objects.get(pk=pk)\r\n username=doctor.user.username\r\n return reverse('speed:detail_doctor',args=(username,pk))\r\nclass ClinicListView(ListView):\r\n model=Clinic\r\n template_name=\"clinic/clinic_list.html\"\r\n\r\n\r\ndef ClinicSearch(request):\r\n if request.method==\"POST\":\r\n form=CityForm(request.POST)\r\n context={}\r\n if form.is_valid():\r\n query=form.cleaned_data.get('city')\r\n res=Clinic.objects.filter(city__iexact=query)\r\n context.update({'res':res})\r\n return render(request,'clinic/clinic_list.html',context)\r\n else:\r\n return HttpResponse(\"Not valid\")\r\n else:\r\n form=CityForm()\r\n return render(request,\"clinic/clinic_search.html\",{'form':form})\r\n\r\nclass ClinicDetailView(DetailView):\r\n model=Clinic\r\n template_name =\"clinic/clinic_detail.html\"\r\n\r\nclass ListDoctor(ListView):\r\n model=Doctor\r\n template_name=\"doctor/home_list.html\"\r\n def get_queryset(self):\r\n self.people=Doctor.objects.get(user__username__iexact=self.kwargs.get('username'))\r\n def get_context_data(self,**kwargs):\r\n context=super().get_context_data(**kwargs)\r\n context['people']=self.people\r\n return context\r\n\r\n\r\n\r\n\r\nclass AppointmentList(ListView):\r\n model=Appointment\r\n template_name=\"appointment/appointment_list.html\"\r\nclass UserAppointments(ListView):\r\n model=Appointment\r\n template_name=\"appointment/user_appointment_list.html\"\r\n\r\n def get_queryset(self):\r\n try:\r\n self.appointment_user=Patient.objects.prefetch_related('appointments').get(user__username__iexact=self.kwargs.get('username'))\r\n except Patient.DoesNotExist:\r\n raise Http404\r\n else:\r\n return self.appointment_user.appointments.all()\r\n def get_context_data(self,**kwargs):\r\n context=super().get_context_data(**kwargs)\r\n context['appointment_user']=self.appointment_user\r\n return context\r\nclass AppointmentDetail(DetailView):\r\n model=Appointment\r\n def get_queryset(self):\r\n queryset=super().get_queryset()\r\n return queryset.filter(user__username__iexact=self.kwargs.get('username'))\r\n template_name=\"appointment/appointment_detail.html\"\r\n\r\nclass PatientHomeView(TemplateView):\r\n template_name =\"patient/patient_base.html\"\r\n\r\nclass PatientListView(ListView):\r\n model = Patient\r\n template_name = \"patient/home_patient.html\"\r\n\r\n def get_queryset(self):\r\n self.person= User.objects.prefetch_related('patient_profile').get(username__iexact=self.kwargs.get('username'))\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super().get_context_data(**kwargs)\r\n context['person'] = self.person\r\n return context\r\n\r\nclass PatientDetailView(DetailView):\r\n model=Patient\r\n def get_queryset(self):\r\n queryset=super().get_queryset()\r\n return queryset.filter(user__username__iexact=self.kwargs.get('username'))\r\n\r\n template_name = \"patient/patient_detail.html\"\r\n\r\nclass CancelAppointment(DeleteView):\r\n model=Appointment\r\n def get_success_url(self):\r\n p=self.kwargs.get('username')\r\n return reverse_lazy('for_patient',kwargs={'username':p})\r\n def get_queryset(self):\r\n queryset=super().get_queryset()\r\n return queryset.filter(patient__user__username=self.kwargs.get('username'))\r\n def delete(self, request, *args, **kwargs):\r\n return super().delete(request, *args, **kwargs)\r\n template_name=\"appointment/appointment_confirm_cancel.html\"\r\nclass DeleteAppointmentPatient(DeleteView):\r\n model=Appointment\r\n def get_success_url(self):\r\n p=self.kwargs.get('username')\r\n return reverse_lazy('speed:for_patient',kwargs={'username':p})\r\n def delete(self, request, *args, **kwargs):\r\n pk=self.kwargs.get('pk')\r\n name=self.kwargs.get('username')\r\n k=get_object_or_404(Appointment,pk=pk)\r\n #name=k.patient.user.username\r\n k.delt=False\r\n k.save()\r\n context = Patient.objects.prefetch_related(\"appointments\").get(user__username=self.kwargs.get('username'))\r\n return render(request,\"appointment/user_appointment_list.html\",{'appointment_user':context})\r\n template_name = \"appointment/appointment_confirm_delete.html\"\r\n\r\nclass DeleteAppointmentDoctor(DeleteView):\r\n model=Appointment\r\n def get_success_url(self):\r\n p=self.request.user.username\r\n k=Doctor.objects.get(user__username=p)\r\n pk=k.pk\r\n return reverse_lazy('speed:detail_doctor',kwargs={'username':p,'pk':pk})\r\n def delete(self, request, *args, **kwargs):\r\n pk=self.kwargs.get('pk')\r\n name=self.kwargs.get('username')\r\n k=get_object_or_404(Appointment,pk=pk)\r\n #name=k.patient.user.username\r\n k.deldoc=False\r\n k.save()\r\n context = Doctor.objects.prefetch_related(\"doc_appointments\").get(user__username=self.kwargs.get('username'))\r\n return render(request,\"doctor/doctor_detail.html\",{'doctor':context})\r\n template_name=\"appointment/appointment_confirm_deletedoc.html\"\r\n\r\ndef searchmap(request):\r\n #is_cached = ('geodata' in request.session)\r\n\r\n if not False:\r\n ip_address = request.META.get('HTTP_X_FORWARDED_FOR', '')\r\n params = {'access_key': settings.GOOGLE_MAPS_API_KEY}\r\n response = requests.get('https://www.google.com/maps/embed/v1/place', params=params)\r\n #data=json.loads(response.text)\r\n\r\n #geodata = request.session['geodata']\r\n if request.method==\"POST\":\r\n patient=MapForm(request.POST)\r\n if patient.is_valid:\r\n address=request.POST.get('address')\r\n #data=json.dumps(clinic)\r\n data=serialize('json',MapDetail.objects.all())\r\n y=json.loads(data)\r\n return render(request,\"clinic/maps.html\",{'address':address,'data':data,'y':y})\r\n else:\r\n patient=MapForm()\r\n return render(request,\"clinic/address_form.html\",{'patient':patient})\r\n\r\ndef TimeView(request):\r\n if request.method==\"POST\":\r\n form=Calendar(request.POST)\r\n if form.is_valid:\r\n return HttpResponseRedirect('home')\r\n else:\r\n form=Calendar()\r\n return render(request,\"patient/timings.html\",{'form':form})\r\n\r\n\r\nclass EventFeed(ICalFeed):\r\n\r\n #A simple event calender\r\n product_id = '-//example.com//Example//EN'\r\n timezone = 'UTC'\r\n file_name = \"event.ics\"\r\n\r\n def __call__(self, request, *args, **kwargs):\r\n self.request = request\r\n return super(EventFeed, self).__call__(request, *args, **kwargs)\r\n def items(self):\r\n return Event.objects.all().order_by('-date')\r\n\r\n def item_guid(self, item):\r\n return \"{}{}\".format(item.id, \"global_name\")\r\n\r\n def item_title(self, item):\r\n return \"{}\".format(item.name)\r\n\r\n def item_description(self, item):\r\n return item.description\r\n\r\n def item_start_datetime(self, item):\r\n return item.date\r\n\r\n def item_link(self, item):\r\n return \"http://www.google.de\"\r\n\r\n#Payment Gateway Interface\r\nclass pay_firstpage(TemplateView):\r\n template_name=\"first_page.html\"\r\n\r\ndef process_payment(request,pk):\r\n d=Appointment()\r\n #od_id =Order.get_id(obj)\r\n #print(od_id)\r\n d.doctor=Doctor.objects.prefetch_related(\"doc_appointments\").get(user_id=pk)\r\n d.order_id=d.get_id()\r\n d.save()\r\n print(d.order_id)\r\n\r\n host=request.get_host()\r\n od_name=\"Appointment with\"+d.doctor.name\r\n paypal_dict = {\r\n \"business\":settings.PAYPAL_RECEIVER_EMAIL,\r\n \"order_id\":d.order_id,\r\n \"amount\":d.doctor.fees,\r\n \"item_name\":od_name,\r\n 'notify_url': 'http://{}{}'.format(host,\r\n reverse('paypal-ipn')),\r\n 'return_url': 'http://{}{}'.format(host,\r\n reverse('done',args=[d.order_id])),\r\n 'cancel_return': 'http://{}{}'.format(host,\r\n reverse('cancel',args=[d.doctor_id])),\r\n #\"custom\": \"premium_plan\", # Custom command to correlate to some function later (optional)\r\n\r\n }\r\n form=PayPalPaymentsForm(initial=paypal_dict)\r\n return render(request,\"payment/payment.html\",{'form':form})\r\n\r\n@csrf_exempt\r\ndef ret_view(request,pk):\r\n obj = Appointment.objects.get(order_id__iexact=pk)\r\n obj.pay_status = True\r\n return render(request,\"payment/payment_done.html\",{'obj':obj})\r\n\r\n@csrf_exempt\r\ndef cancel_view(request,pk):\r\n obj=Appointment.objects.get(order_id__iexact=pk)\r\n obj.pay_status=False\r\n return render(request,\"payment/payment_cancel.html\",{'obj':obj})\r\n\r\n#TIME SLOT VIEWS\r\n\"\"\"class SlotList(ListView):\r\n model=TimeSlot\r\n template_name=\"slot/slot_list.html\" \"\"\"\r\n\r\nclass CreateSlot(CreateView):\r\n form_class=SlotForm\r\n template_name=\"slot/doctor_slot.html\"\r\n\r\nclass Doctor_slot(ListView):\r\n model=TimeSlot\r\n template_name=\"slot/slot_list.html\"\r\n def get_queryset(self):\r\n try:\r\n self.slots_of_doctor=Doctor.objects.prefetch_related(\"slots\").get(user__username__iexact=self.kwargs.get('username'))\r\n except:\r\n raise Http404\r\n else:\r\n return self.slots_of_doctor.slots.all()\r\n\r\n def get_context_data(self,**kwargs):\r\n context=super().get_context_data(**kwargs)\r\n context['slot_doc']=self.slots_of_doctor\r\n return context\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"online/speed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179704899","text":"\nclass Stack(object):\n\n def __init__(self, size=5):\n self.arr = [None] * size\n self.top = len(self.arr) * 2\n\n def is_full(self):\n # check if end is at the last index\n return self.top + 1 == len(self.arr)\n\n def is_empty(self):\n return self.top == len(self.arr) * 2\n \n def push(self, data):\n # if array is full raise exception\n\n if self.is_full():\n raise Exception(\"Stack is full\")\n\n # if stack is empty set the end and top to 0\n elif self.is_empty():\n self.top = 0\n # normal case: increment end\n else:\n self.top += 1\n\n # write data at the updated end\n self.arr[self.top] = data\n print(\"After push\")\n print(\"top : {}\".format(self.top))\n print(self.arr)\n\n def pop(self):\n data = None\n # if stack is empty raise exception\n if self.is_empty():\n raise Exception(\"stack is empty\")\n\n # if end == top, reset both to illegal index\n # this means only one element left in the\n elif self.top == 0:\n data = self.arr[self.top]\n self.top = len(self.arr) * 2\n print(\"After take\")\n print(\"top : {}\".format(self.top))\n print(self.arr)\n #self.stackprint()\n return data\n\n # normal case: take the element from the top of the stack and increment top\n else:\n data = self.arr[self.top]\n self.top -= 1\n print(\"After take\")\n print(\"top : {}\".format(self.top))\n print(self.arr)\n self.stackprint()\n return data\n\n def top(self):\n if self.is_empty():\n raise Exception(\"stack is empty cannot peek\")\n return self.arr[self.top]\n\n def clear(self):\n self.top = len(self.arr) * 2\n\n def stackprint(self):\n if self.is_empty():\n raise Exception(\"Stack is empty cannot print\")\n stack = []\n for i in range(self.top + 1):\n stack.append(self.arr[i])\n print(stack)\n\nq = Stack()\n\nfor i in range(1):\n for i in range(5):\n q.push(i)\n print(\"Popping 3\")\n for i in range(3):\n q.pop()\n print(\"Pushing 3\")\n for i in range(2, 5):\n q.push(i)\nwhile not q.is_empty():\n print(q.pop())\n q.stackprint()\n\n #print(q.peek())\n#q.put(2)\n#q.put(3)\n#q.put(4)\n#q.put(5)\n#q.take()\n\n","sub_path":"Stack/arraystack.py","file_name":"arraystack.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"193368091","text":"# MIT License\n# \n# Copyright (c) 2017-2018 Minato Sato\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nfrom collections import OrderedDict\nimport pickle\nimport numpy as np\n\nimport nnabla as nn\nimport nnabla.functions as F\nimport nnabla.parametric_functions as PF\nimport nnabla.solvers as S\nfrom nnabla.utils.data_iterator import data_iterator_simple\n\nfrom tqdm import tqdm\n\nfrom layers import SimpleRNN\nfrom layers import TimeDistributed\nfrom layers import TimeDistributedSoftmaxCrossEntropy\n\n\"\"\"cuda setting\"\"\"\nfrom nnabla.contrib.context import extension_context\nctx = extension_context('cuda.cudnn', device_id=0)\nnn.set_default_context(ctx)\n\"\"\"\"\"\"\n\nfrom utils import load_data\nfrom utils import wordseq2charseq\nfrom utils import w2i, i2w, c2i, i2c, word_length\n\nfrom keras.preprocessing import sequence\n\ntrain_data = load_data('./ptb/train.txt')\ntrain_data = sequence.pad_sequences(train_data, padding='post')\n\nvalid_data = load_data('./ptb/valid.txt')\nvalid_data = sequence.pad_sequences(valid_data, padding='post')\n\nvocab_size = len(w2i)\nsentence_length = 20\nembedding_size = 128\nhidden = 128\nbatch_size = 256\nmax_epoch = 100\n\nx_train = train_data[:, :sentence_length].astype(np.int32)\ny_train = train_data[:, 1:sentence_length+1].astype(np.int32)\n\nx_valid = valid_data[:, :sentence_length].astype(np.int32)\ny_valid = valid_data[:, 1:sentence_length+1].astype(np.int32)\n\nnum_train_batch = len(x_train)//batch_size\nnum_valid_batch = len(x_valid)//batch_size\n\ndef load_train_func(index):\n return x_train[index], y_train[index]\n\ndef load_valid_func(index):\n return x_valid[index], y_valid[index]\n\ntrain_data_iter = data_iterator_simple(load_train_func, len(x_train), batch_size, shuffle=True, with_file_cache=False)\nvalid_data_iter = data_iterator_simple(load_valid_func, len(x_valid), batch_size, shuffle=True, with_file_cache=False)\n\nx = nn.Variable((batch_size, sentence_length))\nt = nn.Variable((batch_size, sentence_length, 1))\nh = PF.embed(x, vocab_size, embedding_size)\nh = SimpleRNN(h, hidden, return_sequences=True)\nh = TimeDistributed(PF.affine)(h, hidden, name='hidden')\ny = TimeDistributed(PF.affine)(h, vocab_size, name='output')\n\nmask = F.sum(F.sign(t), axis=2) # do not predict 'pad'.\nentropy = TimeDistributedSoftmaxCrossEntropy(y, t) * mask\ncount = F.sum(mask, axis=1)\nloss = F.mean(F.div2(F.sum(entropy, axis=1), count))\n\n# Create solver.\nsolver = S.Momentum(1e-2, momentum=0.9)\nsolver.set_parameters(nn.get_parameters())\n\n# Create monitor.\nfrom nnabla.monitor import Monitor, MonitorSeries, MonitorTimeElapsed\nmonitor = Monitor('./tmp-rnnlm')\nmonitor_perplexity = MonitorSeries('perplexity', monitor, interval=1)\nmonitor_perplexity_valid = MonitorSeries('perplexity_valid', monitor, interval=1)\n\n\nfor epoch in range(max_epoch):\n train_loss_set = []\n for i in tqdm(range(num_train_batch)):\n x_batch, y_batch = train_data_iter.next()\n y_batch = y_batch.reshape(list(y_batch.shape) + [1])\n\n x.d, t.d = x_batch, y_batch\n\n loss.forward(clear_no_need_grad=True)\n train_loss_set.append(loss.d.copy())\n solver.zero_grad()\n loss.backward(clear_buffer=True)\n solver.update()\n\n valid_loss_set = []\n for i in range(num_valid_batch):\n x_batch, y_batch = valid_data_iter.next()\n y_batch = y_batch.reshape(list(y_batch.shape) + [1])\n\n x.d, t.d = x_batch, y_batch\n\n loss.forward(clear_no_need_grad=True)\n valid_loss_set.append(loss.d.copy())\n\n monitor_perplexity.add(epoch+1, np.e**np.mean(train_loss_set))\n monitor_perplexity_valid.add(epoch+1, np.e**np.mean(valid_loss_set))\n\n\n\n\n\n\n","sub_path":"rnnlm.py","file_name":"rnnlm.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578494626","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_mail import Mail\n\ndb = SQLAlchemy()\nmail = Mail()\n\n\ndef create_app():\n \"\"\" Initialize app. \"\"\"\n app = Flask(__name__, instance_relative_config=False)\n app.config.from_object(\"config.Config\")\n db.init_app(app)\n mail.init_app(app)\n\n with app.app_context():\n from application import routes # noqa: F401\n db.create_all()\n return app\n","sub_path":"application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168362755","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 2 22:26:30 2020\r\n\r\n@author: hrith\r\n\"\"\"\r\n\r\n\r\nn = int(input(\"Enter The Number: \"))\r\nsum = 0\r\n\r\nfor i in range(1,n+1):\r\n if n%i == 0:\r\n print(\"Factor\",i,\"Is: \",i)\r\n sum = sum+i\r\n \r\nprint(\"The Sum Of Factors Is: \",sum)\r\n\r\nif(sum == n*2):\r\n print(n,\"Is A Perfect Number\")\r\nelse:\r\n print(n,\"Is Not A Perfect Number\")\r\n \r\n ","sub_path":"PerfectNumber.py","file_name":"PerfectNumber.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194061209","text":"# Copyright (C) 2021 Jørgen S. Dokken and Sarah Roggendorf\n#\n# SPDX-License-Identifier: MIT\n\nimport argparse\n\nimport dolfinx\nimport dolfinx.io\nimport numpy as np\nimport ufl\nfrom mpi4py import MPI\n\nfrom create_mesh import create_disk_mesh, create_sphere_mesh, convert_mesh\nfrom nitsche_one_way import nitsche_one_way\nfrom snes_against_plane import snes_solver\n\n\nif __name__ == \"__main__\":\n description = \"Compare Nitsche's method for contact against a straight plane with PETSc SNES\"\n parser = argparse.ArgumentParser(description=description,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--theta\", default=1, type=np.float64, dest=\"theta\",\n help=\"Theta parameter for Nitsche, 1 symmetric, -1 skew symmetric, 0 Penalty-like\")\n parser.add_argument(\"--gamma\", default=1000, type=np.float64, dest=\"gamma\",\n help=\"Coercivity/Stabilization parameter for Nitsche condition\")\n _solve = parser.add_mutually_exclusive_group(required=False)\n _solve.add_argument('--linear', dest='linear_solver', action='store_true',\n help=\"Use linear solver\", default=False)\n _3D = parser.add_mutually_exclusive_group(required=False)\n _3D.add_argument('--3D', dest='threed', action='store_true',\n help=\"Use 3D mesh\", default=False)\n _strain = parser.add_mutually_exclusive_group(required=False)\n _strain.add_argument('--strain', dest='plane_strain', action='store_true',\n help=\"Use plane strain formulation\", default=False)\n _dirichlet = parser.add_mutually_exclusive_group(required=False)\n _dirichlet.add_argument('--dirichlet', dest='dirichlet', action='store_true',\n help=\"Use strong Dirichlet formulation\", default=False)\n _E = parser.add_argument(\"--E\", default=1e3, type=np.float64, dest=\"E\",\n help=\"Youngs modulus of material\")\n _nu = parser.add_argument(\n \"--nu\", default=0.1, type=np.float64, dest=\"nu\", help=\"Poisson's ratio\")\n _disp = parser.add_argument(\"--disp\", default=0.08, type=np.float64, dest=\"disp\",\n help=\"Displacement BC in negative y direction\")\n _ref = parser.add_argument(\"--refinements\", default=1, type=np.int32,\n dest=\"refs\", help=\"Number of mesh refinements\")\n _gap = parser.add_argument(\n \"--gap\", default=0.02, type=np.float64, dest=\"gap\", help=\"Gap between plane and y=0\")\n\n # Parse input arguments or set to defualt values\n args = parser.parse_args()\n\n # Current formulation uses unilateral contact\n nitsche_parameters = {\"gamma\": args.gamma, \"theta\": args.theta}\n nitsche_bc = not args.dirichlet\n physical_parameters = {\"E\": args.E, \"nu\": args.nu, \"strain\": args.plane_strain}\n vertical_displacement = -args.disp\n num_refs = args.refs + 1\n gap = args.gap\n top_value = 1\n threed = args.threed\n bottom_value = 2\n\n # Load mesh and create identifier functions for the top (Displacement condition)\n # and the bottom (contact condition)\n if threed:\n fname = \"sphere\"\n create_sphere_mesh(filename=f\"{fname}.msh\")\n convert_mesh(fname, \"tetra\")\n with dolfinx.io.XDMFFile(MPI.COMM_WORLD, f\"{fname}.xdmf\", \"r\") as xdmf:\n mesh = xdmf.read_mesh(name=\"Grid\")\n #mesh = dolfinx.UnitCubeMesh(MPI.COMM_WORLD, 10, 10, 20)\n\n # def top(x):\n # return x[2] > 0.99\n\n # def bottom(x):\n # return x[2] < 0.5\n def top(x):\n return x[2] > 0.9\n\n def bottom(x):\n return x[2] < 0.15\n\n else:\n fname = \"disk\"\n create_disk_mesh(filename=f\"{fname}.msh\")\n convert_mesh(fname, \"triangle\", prune_z=True)\n with dolfinx.io.XDMFFile(MPI.COMM_WORLD, f\"{fname}.xdmf\", \"r\") as xdmf:\n mesh = xdmf.read_mesh(name=\"Grid\")\n # mesh = dolfinx.UnitSquareMesh(MPI.COMM_WORLD, 30, 30)\n\n # def top(x):\n # return x[1] > 0.99\n\n def top(x):\n return x[1] > 0.5\n\n def bottom(x):\n return x[1] < 0.2\n\n e_abs = []\n e_rel = []\n dofs_global = []\n rank = MPI.COMM_WORLD.rank\n refs = np.arange(0, num_refs)\n for i in refs:\n if i > 0:\n # Refine mesh\n mesh.topology.create_entities(mesh.topology.dim - 2)\n mesh = dolfinx.mesh.refine(mesh)\n\n # Create meshtag for top and bottom markers\n tdim = mesh.topology.dim\n top_facets = dolfinx.mesh.locate_entities_boundary(mesh, tdim - 1, top)\n bottom_facets = dolfinx.mesh.locate_entities_boundary(\n mesh, tdim - 1, bottom)\n top_values = np.full(len(top_facets), top_value, dtype=np.int32)\n bottom_values = np.full(\n len(bottom_facets), bottom_value, dtype=np.int32)\n indices = np.concatenate([top_facets, bottom_facets])\n values = np.hstack([top_values, bottom_values])\n facet_marker = dolfinx.MeshTags(mesh, tdim - 1, indices, values)\n mesh_data = (facet_marker, top_value, bottom_value)\n\n # Solve contact problem using Nitsche's method\n u1 = nitsche_one_way(mesh=mesh, mesh_data=mesh_data, physical_parameters=physical_parameters,\n vertical_displacement=vertical_displacement, nitsche_parameters=nitsche_parameters,\n refinement=i, g=gap, nitsche_bc=nitsche_bc)\n # Solve contact problem using PETSc SNES\n u2 = snes_solver(mesh=mesh, mesh_data=mesh_data, physical_parameters=physical_parameters,\n vertical_displacement=vertical_displacement, refinement=i, g=gap)\n\n # Compute the difference (error) between Nitsche and SNES\n V = u1.function_space\n dx = ufl.Measure(\"dx\", domain=mesh)\n error = ufl.inner(u1 - u2, u1 - u2) * dx\n E_L2 = np.sqrt(MPI.COMM_WORLD.allreduce(dolfinx.fem.assemble_scalar(error), op=MPI.SUM))\n u2_norm = ufl.inner(u2, u2) * dx\n u2_L2 = np.sqrt(MPI.COMM_WORLD.allreduce(dolfinx.fem.assemble_scalar(u2_norm), op=MPI.SUM))\n if rank == 0:\n print(f\"abs. L2-error={E_L2:.2e}\")\n print(f\"rel. L2-error={E_L2/u2_L2:.2e}\")\n e_abs.append(E_L2)\n e_rel.append(E_L2 / u2_L2)\n dofs_global.append(V.dofmap.index_map.size_global * V.dofmap.index_map_bs)\n\n # Output absolute and relative errors of Nitsche compared to SNES\n if rank == 0:\n print(f\"Num dofs {dofs_global}\")\n print(f\"Absolute error {e_abs}\")\n print(f\"Relative error {e_rel}\")\n for i in refs:\n nitsche_timings = dolfinx.cpp.common.timing(f'{i} Solve Nitsche')\n snes_timings = dolfinx.cpp.common.timing(f'{i} Solve SNES')\n if rank == 0:\n print(f\"{dofs_global[i]}, Nitsche: {nitsche_timings[1]: 0.2e}\"\n + f\" SNES: {snes_timings[1]:0.2e}\")\n assert(e_rel[-1] < 1e-3)\n assert(e_abs[-1] < 1e-4)\n","sub_path":"implementation/compare_nitsche_snes.py","file_name":"compare_nitsche_snes.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"269076844","text":"import sys\nfrom pyspark import SparkConf, SparkContext\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"wordCount\")\nsc = SparkContext(conf = conf)\n\ninputFile = sys.argv[1]\ninput = sc.textFile(inputFile)\n\nwords = input.flatMap(lambda line: line.split(\" \"))\ncount = words.map(lambda word: (word, 1)).reduceByKey(lambda x,y: x+y)\n\noutputFile = sys.argv[2]\ncount.saveAsTextFile(outputFile)\n","sub_path":"chap01/my_script.py","file_name":"my_script.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395623884","text":"from flask import Flask,render_template,url_for,request\nfrom flask_bootstrap import Bootstrap\nfrom tweepy import OAuthHandler, API, Stream\nimport flaskr.functions.Tokens as t\nimport csv\nimport pandas as pd\nimport sys\nimport os\n#import wget\ndef tm_main():\n\t#Authentication\n\tapi = authenticate()\n\tif request.method == 'GET':\n username = request.args.get['username']\n max_tweets = int(request.args.get['count'])\n all_tweets = getTweetsFromUser(username,max_tweets,api)\n media_URLs = getTweetMediaURL(all_tweets)\n downloadFiles(media_URLs,username)\n return \"\"\ndef getTweetsFromUser(username,max_tweets,api):\n\tlast_tweet_id, num_images = 0,0\n\ttry:\n\t raw_tweets = api.user_timeline(screen_name=username,include_rts=False,exclude_replies=True)\n\texcept Exception as e:\n\t\tprint (e)\n\t\tsys.exit()\n\tlast_tweet_id = int(raw_tweets[-1].id-1)\n\tif max_tweets == 0:\n\t\tmax_tweets = 3500\n\twhile len(raw_tweets)0):\n\t\t\ttweets_with_media.add(media[0]['media_url'])\n\t\t\tsys.stdout.write(\"\\rMedia Links fetched: %d\" % len(tweets_with_media))\n\t\t\tsys.stdout.flush()\n\treturn tweets_with_media\ndef downloadFiles(media_url,username):\n\ttry:\n\t os.mkdir('twitter_images')\n\t os.chdir('twitter_images')\n\texcept:\n os.chdir('twitter_images')\n\ttry:\n\t os.mkdir(username)\n\t os.chdir(username)\n\texcept:\n\t\tos.chdir(username)\n\tfor url in media_url:\n\t\twget.download(url)\ndef authenticate():\n\tauth = OAuthHandler(t.CONSUMER_KEY, t.CONSUMER_SECRET)\n\tauth.set_access_token(t.ACCESS_TOKEN,t.ACCESS_TOKEN_SECRET)\n\tapi = API(auth)\n\treturn api\n\n","sub_path":"flaskr/functions/getm.py","file_name":"getm.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232124957","text":"\"\"\"\ncircuit_simulation.py\n\nAuthor:\n Sequoia Ploeg\n\nDependencies:\n- tkinter\n- SiEPIC._globals\n- SiEPIC.ann.graph, SiEPIC.ann.simulation\n- scipy\n- numpy\n- os\n- matplotlib\n\nThis file mainly provides the GUI for running simulations. It creates a \nSimulation object, runs it, and provides controls and windows for displaying\nand exporting the results.\n\"\"\"\n\nimport tkinter as tk\nfrom tkinter import filedialog\n\nfrom SiEPIC.ann.graph import Graph, DataSet, MenuItem\nimport SiEPIC._globals as glob\nfrom SiEPIC.ann.simulation import Simulation\n\nimport scipy.io as sio\nimport numpy as np\nimport os\n\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.figure import Figure\n\nclass TkRoot(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n self.withdraw()\n self.after(0, self.deiconify)\n self.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n \n def on_closing(self):\n self.withdraw()\n self.quit()\n self.destroy()\n\nclass CircuitAnalysisGUI():\n\n # Some constants\n tera = 1e12\n nano = 1e9\n\n def __init__(self, parent):\n self.parent = parent\n\n # Hide the parent until the whole window has loaded.\n self.parent.withdraw()\n\n # Set the window title and size\n self.parent.title('Circuit Simulation')\n\n # Initialize the menu and figures\n self.create_menu()\n self.init_figures()\n\n self.simulation = Simulation()\n\n self.plotFrequency = True\n\n # Update magnitude and phase generates the netlist, and therefore\n # need to be placed before generate_schematic\n self.set_controls()\n self.generate_schematic()\n\n # Now that everything is in place, show the window.\n self.parent.after(0, self.parent.deiconify)\n\n def create_menu(self):\n # Create the toplevel menubar\n menubar = tk.Menu(self.parent)\n \n # Add the pulldown menus with their options, then add it to the menubar\n filemenu = tk.Menu(menubar, tearoff=0)\n # filemenu.add_command(label=\"Open\")\n # filemenu.add_command(label=\"Save\")\n filemenu.add_command(label=\"Open folder\", command=self.open_folder)\n filemenu.add_command(label=\"Export s-matrix\", command=self.export_s_matrix)\n filemenu.add_command(label=\"Exit\", command=self.parent.on_closing)\n menubar.add_cascade(label=\"File\", menu=filemenu)\n \n # Configure the menubar\n self.parent.config(menu=menubar)\n\n def init_figures(self):\n # Port selection menu\n self.controls = tk.Frame(self.parent, bd=1)\n self.controls.grid(row=0, column=0)\n # Schematic figure initialization\n self.schematic = tk.Frame(self.parent)\n self.schematic.grid(row=1, column=0)\n\n def set_controls(self):\n options = self.simulation.external_port_list\n self.first = tk.StringVar(self.parent)\n self.first.set(options[0])\n self.second = tk.StringVar(self.parent)\n self.second.set(options[0])\n\n tk.Label(self.controls, text=\"From: \").grid(row=0, column=0)\n thing2 = tk.OptionMenu(self.controls, self.first, *options)\n thing2.grid(row=0, column=1)\n\n tk.Label(self.controls, text=\" to: \").grid(row=0, column=2)\n\n thing4 = tk.OptionMenu(self.controls, self.second, *options)\n thing4.grid(row=0, column=3)\n\n gobtn = tk.Button(self.controls, text=\"Plot\", command=self.selection_changed).grid(row=0, column=4)\n tk.Label(self.controls, text=\" Charts: \").grid(row=0, column=5)\n tk.Button(self.controls, text=\"Magnitude\", command=self.open_magnitude).grid(row=0, column=6)\n tk.Button(self.controls, text=\"Phase\", command=self.open_phase).grid(row=0, column=7)\n\n self.magnitude = None\n self.phase = None\n\n def generate_schematic(self):\n \"\"\"\n This function creates a figure object and places it within the \n schematic slot in the parent tkinter window. It then calls 'draw' to \n plot the layout points on the canvas.\n \"\"\"\n # The only real objects we'll need to interact with to plot and unplot\n self.components = self.simulation.external_components\n self.fig = Figure(figsize=(5, 4), dpi=100)\n\n # Objects needed simply for the sake of embedding the graph in tk\n self.canvas = FigureCanvasTkAgg(self.fig, master=self.schematic)\n self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n self.fig.clear()\n self.ax = self.fig.add_subplot(111)\n self.draw()\n\n def draw(self):\n for comp in self.components:\n self.ax.plot(comp.lay_x, comp.lay_y, 'ro')\n externals = [int(x) for x in comp.nets if int(x) < 0 ]\n self.ax.text(comp.lay_x, comp.lay_y, \" Port \" + str(-externals[0]) + \": \" + comp.__class__.__name__)\n self.ax.axis('off')\n self.canvas.draw()\n\n\n def export_s_matrix(self, ext=0):\n fileTypes = [(\"MATLAB file\",\"*.mat\"), (\"NumPy file\",\"*.npz\")]\n options = {}\n options['initialdir'] = os.path.expanduser('~')\n options['filetypes'] = fileTypes\n options['parent'] = self.parent\n filename = filedialog.asksaveasfilename(**options)\n if filename:\n _, ext = os.path.splitext(filename)\n s_mat, freq = self.simulation.exportSMatrix()\n if ext == \".mat\":\n sio.savemat(filename, {'s_mat' : s_mat, 'freq' : freq})\n elif ext == \".npz\":\n np.savez(filename, s_mat, freq)\n \n def plotByFrequency(self):\n if not self.plotFrequency:\n self.plotFrequency = True\n lines = self.magnitude.get_lines()\n for line in lines.values():\n x = line.x\n line.x = self.wavelengthToFrequency(x / CircuitAnalysisGUI.nano) / CircuitAnalysisGUI.tera\n line.objectID.set_xdata(line.x)\n self.magnitude.refresh()\n self.magnitude.xlabel('Frequency (THz)')\n lines = self.phase.get_lines()\n for line in lines.values():\n x = line.x\n line.x = self.wavelengthToFrequency(x / CircuitAnalysisGUI.nano) / CircuitAnalysisGUI.tera\n line.objectID.set_xdata(line.x)\n self.phase.refresh()\n self.phase.xlabel('Frequency (THz)')\n\n\n def plotByWavelength(self):\n if self.plotFrequency:\n self.plotFrequency = False\n lines = self.magnitude.get_lines()\n for line in lines.values():\n x = line.x\n line.x = self.frequencyToWavelength(x * CircuitAnalysisGUI.tera) * CircuitAnalysisGUI.nano\n line.objectID.set_xdata(line.x)\n self.magnitude.refresh()\n self.magnitude.xlabel('Wavelength (nm)')\n lines = self.phase.get_lines()\n for line in lines.values():\n x = line.x\n line.x = self.frequencyToWavelength(x * CircuitAnalysisGUI.tera) * CircuitAnalysisGUI.nano\n line.objectID.set_xdata(line.x)\n self.phase.refresh()\n self.phase.xlabel('Wavelength (nm)')\n\n def additional_menus(self):\n functions = [MenuItem(\"Plot by frequency\", self.plotByFrequency), MenuItem(\"Plot by wavelength\", self.plotByWavelength)]\n addon_menu = {\"Data\": functions}\n return addon_menu\n\n def open_magnitude(self):\n if self.magnitude is None:\n self.magnitude = Graph(self.parent, \"Magnitude\", additional_menus=self.additional_menus(), onCloseCallback=self._magnitude_closed)\n self.magnitude.ylabel(r'$|E| ^2$')\n self.magnitude.title('Magnitude-Squared')\n else:\n self.magnitude.raise_window()\n\n def _magnitude_closed(self):\n self.magnitude = None\n\n def open_phase(self):\n if self.phase is None:\n self.phase = Graph(self.parent, \"Phase\", additional_menus=self.additional_menus(), onCloseCallback=self._phase_closed)\n self.phase.ylabel('Phase (rad)')\n self.phase.title('Phase')\n else:\n self.phase.raise_window()\n\n def _phase_closed(self):\n self.phase = None\n\n # def open_layout(self):\n # comp = self.simulation.external_components\n # fig = SchematicDrawer(self.parent, comp)\n # fig.draw()\n\n def frequencyToWavelength(self, frequencies):\n c = 299792458\n return c / frequencies\n\n def wavelengthToFrequency(self, wavelengths):\n c = 299792458\n return c / wavelengths\n\n def update_magnitude(self, fromPort=0, toPort=0, name=None):\n if self.plotFrequency == True:\n self.magnitude.plot(*self.simulation.getMagnitudeByFrequencyTHz(fromPort, toPort), name=name)\n self.magnitude.xlabel('Frequency (THz)')\n else:\n self.magnitude.plot(*self.simulation.getMagnitudeByWavelengthNm(fromPort, toPort), name=name)\n self.magnitude.xlabel('Wavelength (nm)')\n \n def update_phase(self, fromPort=0, toPort=0, name=None):\n if self.plotFrequency == True:\n self.phase.plot(*self.simulation.getPhaseByFrequencyTHz(fromPort, toPort), name)\n self.phase.xlabel('Frequency (THz)')\n else:\n self.phase.plot(*self.simulation.getPhaseByWavelengthNm(fromPort, toPort), name)\n self.phase.xlabel('Wavelength (nm)')\n\n def open_folder(self):\n import webbrowser\n path = glob.TEMP_FOLDER\n webbrowser.open(path)\n \n def selection_changed(self):\n fromPort = self.first.get()\n toPort = self.second.get()\n try:\n self.update_magnitude(int(self.first.get()) - 1, int(self.second.get()) - 1, str(fromPort) + \"_to_\" + str(toPort))\n self.magnitude.tight_layout()\n except:\n pass\n try:\n self.update_phase(int(self.first.get()) - 1, int(self.second.get()) - 1, str(fromPort) + \"_to_\" + str(toPort))\n self.phase.tight_layout()\n except:\n pass\n \n def _quit(self):\n self.parent.withdraw()\n self.parent.quit()\n self.parent.destroy()\n \ndef circuit_analysis():\n root = TkRoot()\n app = CircuitAnalysisGUI(root)\n root.mainloop()\n\nclass TimeANN:\n def __init__(self):\n self.root = TkRoot()\n\n def time_circuit_analysis(self):\n self.app = CircuitAnalysisGUI(self.root)\n \nif __name__ == \"__main__\":\n import timeit \n setup=\"\"\"\\\nimport os\nprint(os.getcwd())\nfrom SiEPIC.ann.circuit_simulation import TimeANN\nobj = TimeANN()\n\"\"\"\n time = timeit.timeit('obj.time_circuit_analysis()', setup=setup, number=1)\n print(time)\n","sub_path":"klayout_dot_config/python/SiEPIC/ann/circuit_simulation.py","file_name":"circuit_simulation.py","file_ext":"py","file_size_in_byte":10810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229529835","text":"from Model.EventTemplate import EventTemplate\n\n\nclass LogEvent:\n \"\"\"Log Event\"\"\"\n\n def __init__(self):\n self.date = None\n self.time = None\n self.log_level = None\n self.class_name = None\n self.log_number = None\n self.category = ''\n self.message = None\n # Prepare an EventTemplate object\n self.event_template = EventTemplate()\n self.event_vars_dict = {'Case1': None, 'Case2': None, 'Case3': None, 'Case4': None, 'Case5': None}\n","sub_path":"Model/LogEvent.py","file_name":"LogEvent.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"527398903","text":"# -*- coding: utf-8 -*-\n__author__ = 'yusongmin'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom A_Settings.a_Base_parameter import *\nfrom E_Functions.Database.a_Result_read import get_data_matrix\nfrom E_Functions.Figure.Technology import tech_shadow\nfrom D_Result_analysis.Scenario.Scenario_figure import *\n\n\n\"\"\"\n数据库选择\n\"\"\"\n# conn_result = conn_4 # GF allocation\nconn_result = conn_5 # GF allocation\n\n\"\"\"\n读取\n\"\"\"\ntech_matrix = np.zeros((num_sim, num_period + 1, num_tech))\nfor sim in xrange(0, num_sim):\n\n tech_accumulated = get_data_matrix(\"tech_adoption_accumulated_Sim\" + str(sim), conn_result)\n tech_matrix[sim][:][:] = tech_accumulated\n\ninitial_array = tech_matrix[0][0][:]\nfinal_array_temp = np.zeros((num_tech, ))\naccumulated_matrix_temp = np.zeros((num_period + 1, num_tech))\nadoption_period = np.zeros((num_sim, num_period + 1))\nfor sim in xrange(0, num_sim):\n final_array_temp += tech_matrix[sim][num_period][:]\n accumulated_matrix_temp += tech_matrix[sim][:][:]\n adoption_period[sim][:] = tech_matrix[sim].sum(axis=1)\n\naccumulated_matrix = accumulated_matrix_temp / float(num_sim)\nadoption_mean = accumulated_matrix.sum(axis=1)\n\nadoption_max = np.zeros((num_period + 1, ))\nadoption_min = np.zeros((num_period + 1, ))\nfor t in xrange(0, num_period + 1):\n adoption_max[t] = adoption_period.transpose()[t].max()\n adoption_min[t] = adoption_period.transpose()[t].min()\n\n\"\"\"\n输出\n\"\"\"\nBase_scenario_figure_plot(adoption_mean - Total_tech_adoption_initial,\n adoption_max - Total_tech_adoption_initial,\n adoption_min - Total_tech_adoption_initial,\n \"technology\")\n","sub_path":"ThirdPaper/D_Result_analysis/Scenario/Base_scenario/Technology.py","file_name":"Technology.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325393401","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport abc\n\nimport six\n\nfrom oslo_log import log\n\nfrom watcher._i18n import _\nfrom watcher.decision_engine.strategy.strategies import base\n\nLOG = log.getLogger(__name__)\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass ParallelMigrationStrategy(base.BaseStrategy):\n\n VM = \"vm\"\n VOLUME = \"volume\"\n ACTIVE = \"active\"\n SHUTOFF = \"shutoff\"\n AVAILABLE = \"available\"\n IN_USE = \"in-use\"\n LIVE_MIGRATION = \"live_migration\"\n COLD_MIGRATION = \"cold_migration\"\n VOLUME_MIGRATION = \"volume_migration\"\n VOLUME_RETYPE = \"volume_retype\"\n VOLUME_UPDATE = \"volume_update\"\n STATUS = \"status\"\n DST_HOSTNAME = \"dst_hostname\"\n DST_TYPE = \"dst_type\"\n\n def __init__(self, config, osc=None):\n super(ParallelMigrationStrategy, self).__init__(config, osc)\n\n def pre_execute(self):\n pass\n\n def do_execute(self):\n params = self.input_parameters.params\n for key, value in params.iteritems():\n for resource_id, dict in value.items():\n resource_status = dict.get(self.STATUS)\n dst_hostname = dict.get(self.DST_HOSTNAME)\n dst_type = dict.get(self.DST_TYPE)\n if key == self.VM:\n if resource_status == self.ACTIVE:\n # do live migration\n self._live_migration(resource_id, dst_hostname)\n elif resource_status == self.SHUTOFF:\n # do cold migration\n # cold migration can not specify dest_hostname\n self._cold_migration(resource_id)\n else:\n raise Exception(\"Wrong status: %s.\" % resource_status)\n elif key == self.VOLUME:\n if resource_status == self.IN_USE:\n # do novavolume update\n self._volume_update(resource_id, dst_type)\n elif resource_status == self.AVAILABLE:\n # detached volume with no snapshots\n # do cinder migrate\n self._volume_retype(resource_id, dst_type)\n else:\n raise Exception(\"Wrong status: %s.\" % resource_status)\n else:\n raise Exception(\"Wrong key: %s.\" % key)\n\n def _live_migration(self, resource_id, dst_hostname):\n parameters = {self.DST_HOSTNAME: dst_hostname}\n self.solution.add_action(\n action_type=self.LIVE_MIGRATION,\n resource_id=resource_id,\n input_parameters=parameters)\n\n def _cold_migration(self, resource_id):\n self.solution.add_action(\n action_type=self.COLD_MIGRATION,\n resource_id=resource_id,\n input_parameters={})\n\n def _volume_update(self, resource_id, dst_type):\n parameters = {self.DST_TYPE: dst_type}\n self.solution.add_action(\n action_type=self.VOLUME_UPDATE,\n resource_id=resource_id,\n input_parameters=parameters)\n\n def _volume_migrate(self, resource_id, dst_hostname):\n parameters = {self.DST_HOSTNAME: dst_hostname}\n self.solution.add_action(\n action_type=self.VOLUME_MIGRATION,\n resource_id=resource_id,\n input_parameters=parameters)\n\n def _volume_retype(self, resource_id, dst_type):\n parameters = {self.DST_TYPE: dst_type}\n self.solution.add_action(\n action_type=self.VOLUME_RETYPE,\n resource_id=resource_id,\n input_parameters=parameters)\n\n def post_execute(self):\n pass\n\n @classmethod\n def get_goal_name(cls):\n return \"zone_migration\"\n\n @classmethod\n def get_name(cls):\n return \"parallel_migration\"\n\n @classmethod\n def get_display_name(cls):\n return _(\"Parallel migration strategy\")\n\n @classmethod\n def get_translatable_display_name(cls):\n return \"Parallel migration strategy\"\n\n @classmethod\n def get_schema(cls):\n return {\n \"properties\": {\n \"params\": {\n \"description\": \"\",\n \"type\": \"object\",\n \"default\":\n {\"vm\":\n {\"instance_id1\":\n {\"status\": \"active\",\n \"dst_hostname\": \"vm_dest_hostname1\"},\n \"instance_id2\":\n {\"status\": \"shutoff\"}},\n \"volume\":\n {\"cinder_id1\":\n {\"status\": \"available\",\n \"dst_type\": \"volume_dst_type\"},\n \"cinder_id2\":\n {\"status\": \"in-use\",\n \"dst_type\": \"volume_dst_type\"}}}\n }\n }\n }\n","sub_path":"zone_migration/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":5489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645319372","text":"from prac_08.silver_service_taxi import SilverServiceTaxi\n\n\ndef main():\n hummer = SilverServiceTaxi('Hummer', 100, 4)\n print(hummer)\n\n limo = SilverServiceTaxi('Limo', 100, 2)\n print(limo)\n limo.drive(18)\n print(limo)\n print(\"Current Fare: ${:.2f}\".format(limo.get_fare()))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"prac_08/silver_service_taxi_test.py","file_name":"silver_service_taxi_test.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119424728","text":"# Embedded file name: scripts/client/gui/battle_control/arena_info/listeners.py\r\nimport weakref\r\nimport BigWorld\r\nfrom debug_utils import LOG_DEBUG, LOG_NOTE, LOG_ERROR\r\nfrom gui.battle_control.arena_info import getClientArena\r\nfrom gui.battle_control.arena_info import IArenaController\r\nfrom messenger.m_constants import USER_ACTION_ID, USER_TAG\r\nfrom messenger.proto.events import g_messengerEvents\r\n\r\nclass _Listener(object):\r\n\r\n def __init__(self):\r\n super(_Listener, self).__init__()\r\n self._controllers = set()\r\n\r\n def __del__(self):\r\n LOG_DEBUG('Deleted:', self)\r\n\r\n def addController(self, battleCtx, controller):\r\n result = True\r\n if isinstance(controller, IArenaController):\r\n controllerRef = weakref.ref(controller)\r\n self._controllers.add(controllerRef)\r\n else:\r\n LOG_ERROR('Object is not extend IArenaController', controller)\r\n result = False\r\n return result\r\n\r\n def removeController(self, controller):\r\n result = False\r\n controllerRef = weakref.ref(controller)\r\n if controllerRef in self._controllers:\r\n self._controllers.remove(controllerRef)\r\n result = True\r\n return result\r\n\r\n def clear(self):\r\n while len(self._controllers):\r\n self._controllers.pop()\r\n\r\n def start(self, **kwargs):\r\n raise NotImplementedError\r\n\r\n def stop(self):\r\n raise NotImplementedError\r\n\r\n def _invokeListenersMethod(self, method, *args):\r\n for ref in set(self._controllers):\r\n controller = ref()\r\n if controller:\r\n getattr(controller, method)(*args)\r\n\r\n\r\nclass ArenaListener(_Listener):\r\n\r\n def __init__(self):\r\n super(ArenaListener, self).__init__()\r\n self._dataProvider = None\r\n self._controller = lambda : None\r\n self._arena = lambda : None\r\n self.__callbackID = None\r\n return\r\n\r\n def start(self, arenaDP = None):\r\n if arenaDP is None:\r\n LOG_ERROR('Arena data provider is None')\r\n return\r\n else:\r\n self._dataProvider = arenaDP\r\n arena = getClientArena()\r\n if arena is None:\r\n LOG_NOTE('Arena not found')\r\n return\r\n self._arena = weakref.ref(arena)\r\n self._dataProvider.buildVehiclesData(self._arena().vehicles, self._arena().guiType)\r\n self._dataProvider.buildStatsData(self._arena().statistics)\r\n arena.onNewVehicleListReceived += self.__arena_onNewVehicleListReceived\r\n arena.onVehicleAdded += self.__arena_onVehicleAdded\r\n arena.onVehicleUpdated += self.__arena_onVehicleUpdated\r\n arena.onVehicleKilled += self.__arena_onVehicleKilled\r\n arena.onAvatarReady += self.__arena_onAvatarReady\r\n arena.onNewStatisticsReceived += self.__arena_onNewStatisticsReceived\r\n arena.onVehicleStatisticsUpdate += self.__arena_onVehicleStatisticsUpdate\r\n arena.onTeamKiller += self.__arena_onTeamKiller\r\n arena.onRespawnAvailableVehicles += self.__arena_onRespawnAvailableVehicles\r\n arena.onRespawnCooldowns += self.__arena_onRespawnCooldowns\r\n arena.onRespawnRandomVehicle += self.__arena_onRespawnRandomVehicle\r\n arena.onRespawnResurrected += self.__arena_onRespawnResurrected\r\n arena.onInteractiveStats += self.__arena_onInteractiveStats\r\n return\r\n\r\n def stop(self):\r\n self.clear()\r\n if self.__callbackID is not None:\r\n BigWorld.cancelCallback(self.__callbackID)\r\n self.__callbackID = None\r\n if self._dataProvider is not None:\r\n self._dataProvider.clear()\r\n self._dataProvider = None\r\n arena = self._arena()\r\n self._arena = lambda : None\r\n if arena is None:\r\n return\r\n else:\r\n arena.onNewVehicleListReceived -= self.__arena_onNewVehicleListReceived\r\n arena.onVehicleAdded -= self.__arena_onVehicleAdded\r\n arena.onVehicleUpdated -= self.__arena_onVehicleUpdated\r\n arena.onVehicleKilled -= self.__arena_onVehicleKilled\r\n arena.onAvatarReady -= self.__arena_onAvatarReady\r\n arena.onNewStatisticsReceived -= self.__arena_onNewStatisticsReceived\r\n arena.onVehicleStatisticsUpdate -= self.__arena_onVehicleStatisticsUpdate\r\n arena.onTeamKiller -= self.__arena_onTeamKiller\r\n arena.onRespawnAvailableVehicles -= self.__arena_onRespawnAvailableVehicles\r\n arena.onRespawnCooldowns -= self.__arena_onRespawnCooldowns\r\n arena.onRespawnRandomVehicle -= self.__arena_onRespawnRandomVehicle\r\n arena.onRespawnResurrected -= self.__arena_onRespawnResurrected\r\n arena.onInteractiveStats -= self.__arena_onInteractiveStats\r\n return\r\n\r\n def addController(self, battleCtx, controller):\r\n result = super(ArenaListener, self).addController(battleCtx, controller)\r\n if result:\r\n controller.setBattleCtx(battleCtx)\r\n if self.__callbackID is None:\r\n self.__isRequiredDataExists()\r\n return result\r\n\r\n def removeController(self, controller):\r\n result = super(ArenaListener, self).removeController(controller)\r\n if result:\r\n controller.setBattleCtx(None)\r\n return result\r\n\r\n def clear(self):\r\n while len(self._controllers):\r\n controller = self._controllers.pop()()\r\n if controller:\r\n controller.setBattleCtx(None)\r\n\r\n return\r\n\r\n def __arena_onNewVehicleListReceived(self):\r\n arena = self._arena()\r\n self._dataProvider.buildVehiclesData(arena.vehicles, arena.guiType)\r\n self._invokeListenersMethod('invalidateVehiclesInfo', self._dataProvider)\r\n\r\n def __arena_onVehicleAdded(self, vID):\r\n arena = self._arena()\r\n vo = self._dataProvider.addVehicleInfo(vID, arena.vehicles[vID], arena.guiType)\r\n self._invokeListenersMethod('addVehicleInfo', vo, self._dataProvider)\r\n\r\n def __arena_onVehicleUpdated(self, vID):\r\n flags, vo = self._dataProvider.updateVehicleInfo(vID, self._arena().vehicles[vID], self._arena().guiType)\r\n self._invokeListenersMethod('invalidateVehicleInfo', flags, vo, self._dataProvider)\r\n\r\n def __arena_onVehicleKilled(self, victimID, killerID, reason):\r\n flags, vo = self._dataProvider.updateVehicleStatus(victimID, self._arena().vehicles[victimID])\r\n self._invokeListenersMethod('invalidateVehicleStatus', flags, vo, self._dataProvider)\r\n\r\n def __arena_onAvatarReady(self, vID):\r\n flags, vo = self._dataProvider.updateVehicleStatus(vID, self._arena().vehicles[vID])\r\n self._invokeListenersMethod('invalidateVehicleStatus', flags, vo, self._dataProvider)\r\n\r\n def __arena_onNewStatisticsReceived(self):\r\n self._dataProvider.buildStatsData(self._arena().statistics)\r\n self._invokeListenersMethod('invalidateStats', self._dataProvider)\r\n\r\n def __arena_onVehicleStatisticsUpdate(self, vID):\r\n flags, vo = self._dataProvider.updateVehicleStats(vID, self._arena().statistics[vID])\r\n self._invokeListenersMethod('invalidateVehicleStats', flags, vo, self._dataProvider)\r\n\r\n def __arena_onTeamKiller(self, vID):\r\n flags, vo = self._dataProvider.updatePlayerStatus(vID, self._arena().vehicles[vID])\r\n self._invokeListenersMethod('invalidatePlayerStatus', flags, vo, self._dataProvider)\r\n\r\n def __arena_onRespawnAvailableVehicles(self, vehsList):\r\n self._invokeListenersMethod('updateRespawnVehicles', vehsList)\r\n\r\n def __arena_onRespawnCooldowns(self, cooldowns):\r\n self._invokeListenersMethod('updateRespawnCooldowns', cooldowns)\r\n\r\n def __arena_onRespawnRandomVehicle(self, respawnInfo):\r\n self._invokeListenersMethod('updateRespawnInfo', respawnInfo)\r\n\r\n def __arena_onRespawnResurrected(self, respawnInfo):\r\n self._invokeListenersMethod('updateRespawnRessurectedInfo', respawnInfo)\r\n\r\n def __arena_onInteractiveStats(self, stats):\r\n self._dataProvider.updateVehicleInteractiveStats(stats)\r\n self._invokeListenersMethod('invalidateVehicleInteractiveStats')\r\n\r\n def __isRequiredDataExists(self):\r\n self.__callbackID = None\r\n if self._dataProvider is not None and self._dataProvider.isRequiredDataExists():\r\n self._invokeListenersMethod('invalidateArenaInfo')\r\n else:\r\n self.__callbackID = BigWorld.callback(0.1, self.__isRequiredDataExists)\r\n return\r\n\r\n\r\n_TAGS_TO_UPDATE = {USER_TAG.FRIEND, USER_TAG.IGNORED, USER_TAG.MUTED}\r\n\r\nclass UsersListListener(_Listener):\r\n\r\n def start(self, **kwargs):\r\n g_messengerEvents.users.onUsersListReceived += self.__me_onUsersListReceived\r\n g_messengerEvents.users.onUserActionReceived += self.__me_onUserActionReceived\r\n\r\n def stop(self):\r\n g_messengerEvents.users.onUsersListReceived -= self.__me_onUsersListReceived\r\n g_messengerEvents.users.onUserActionReceived -= self.__me_onUserActionReceived\r\n self.clear()\r\n\r\n def __me_onUsersListReceived(self, tags):\r\n if _TAGS_TO_UPDATE & tags:\r\n self._invokeListenersMethod('invalidateUsersTags')\r\n\r\n def __me_onUserActionReceived(self, actionID, user):\r\n if actionID in (USER_ACTION_ID.FRIEND_ADDED,\r\n USER_ACTION_ID.FRIEND_REMOVED,\r\n USER_ACTION_ID.IGNORED_ADDED,\r\n USER_ACTION_ID.IGNORED_REMOVED,\r\n USER_ACTION_ID.MUTE_SET,\r\n USER_ACTION_ID.MUTE_UNSET):\r\n self._invokeListenersMethod('invalidateUserTags', user)\r\n\r\n\r\nclass ArenaSpaceLoadListener(_Listener):\r\n MAX_PROGRESS_VALUE = 1.0\r\n SPACE_INVALIDATION_PERIOD = 0.5\r\n INFLUX_INVALIDATION_PERIOD = 0.5\r\n\r\n def __init__(self):\r\n super(ArenaSpaceLoadListener, self).__init__()\r\n self.__progress = 0.0\r\n self.__spaceLoadCB = None\r\n self.__influxDrawCB = None\r\n return\r\n\r\n def start(self, **kwargs):\r\n self.__onSpaceLoadStarted()\r\n self.__loadSpaceCallback()\r\n\r\n def stop(self):\r\n self.__clearSpaceCallback()\r\n self.__clearInfluxCallback()\r\n self.clear()\r\n\r\n def __loadSpaceCallback(self):\r\n self.__clearSpaceCallback()\r\n progress = 1.0\r\n import BattleReplay\r\n if not BattleReplay.g_replayCtrl.isTimeWarpInProgress:\r\n progress = BigWorld.spaceLoadStatus()\r\n if progress > self.__progress:\r\n self.__progress = progress\r\n self.__onSpaceLoadUpdated(progress)\r\n if progress < self.MAX_PROGRESS_VALUE:\r\n self.__spaceLoadCB = BigWorld.callback(self.SPACE_INVALIDATION_PERIOD, self.__loadSpaceCallback)\r\n BigWorld.SetDrawInflux(False)\r\n else:\r\n self.__onSpaceLoadCompleted()\r\n BigWorld.SetDrawInflux(True)\r\n self.__loadInfluxCallback()\r\n\r\n def __loadInfluxCallback(self):\r\n self.__clearInfluxCallback()\r\n if BigWorld.worldDrawEnabled():\r\n self.__onArenaLoadCompleted()\r\n else:\r\n self.__influxDrawCB = BigWorld.callback(self.SPACE_INVALIDATION_PERIOD, self.__loadInfluxCallback)\r\n\r\n def __clearSpaceCallback(self):\r\n if self.__spaceLoadCB is not None:\r\n BigWorld.cancelCallback(self.__spaceLoadCB)\r\n self.__spaceLoadCB = None\r\n return\r\n\r\n def __clearInfluxCallback(self):\r\n if self.__influxDrawCB is not None:\r\n BigWorld.cancelCallback(self.__influxDrawCB)\r\n self.__influxDrawCB = None\r\n return\r\n\r\n def __onSpaceLoadUpdated(self, progress):\r\n self._invokeListenersMethod('updateSpaceLoadProgress', progress)\r\n\r\n def __onSpaceLoadStarted(self):\r\n self._invokeListenersMethod('spaceLoadStarted')\r\n\r\n def __onSpaceLoadCompleted(self):\r\n self._invokeListenersMethod('spaceLoadCompleted')\r\n\r\n def __onArenaLoadCompleted(self):\r\n self._invokeListenersMethod('arenaLoadCompleted')\r\n\r\n\r\nclass ListenersCollection(_Listener):\r\n __slots__ = ('__arenaListener', '__usersListListener', '__arenaLoadListener')\r\n\r\n def __init__(self):\r\n super(ListenersCollection, self).__init__()\r\n self.__arenaListener = ArenaListener()\r\n self.__usersListListener = UsersListListener()\r\n self.__arenaLoadListener = ArenaSpaceLoadListener()\r\n\r\n def addController(self, battleCtx, controller):\r\n return self.__arenaListener.addController(battleCtx, controller) and self.__usersListListener.addController(battleCtx, controller) and self.__arenaLoadListener.addController(battleCtx, controller)\r\n\r\n def removeController(self, controller):\r\n result = self.__arenaListener.removeController(controller)\r\n result |= self.__usersListListener.removeController(controller)\r\n result |= self.__arenaLoadListener.removeController(controller)\r\n return result\r\n\r\n def start(self, **kwargs):\r\n self.__arenaListener.start(**kwargs)\r\n self.__usersListListener.start(**kwargs)\r\n self.__arenaLoadListener.start(**kwargs)\r\n\r\n def stop(self):\r\n self.__arenaListener.stop()\r\n self.__usersListListener.stop()\r\n self.__arenaLoadListener.stop()\r\n\r\n def clear(self):\r\n self.__arenaListener.clear()\r\n self.__usersListListener.clear()\r\n self.__arenaLoadListener.clear()","sub_path":"scripts/client/gui/battle_control/arena_info/listeners.py","file_name":"listeners.py","file_ext":"py","file_size_in_byte":13507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"3398935","text":"def arrays_1(list=[]):\n list = sorted(list)\n list_all = []\n list_single = []\n n = len(list)\n i = 0\n while i\\d+ \\w+ \\d+) - (?P\\d+ \\w+ \\d+)?'\n DETAIL_RE = r'^(?P\\w+) \\((?P.+)\\)$$'\n DATE_FORMAT = '%d %B %Y'\n\n def __init__(self, membership_obj, lang='E'):\n self._raw = membership_obj\n self.start_date, self.end_date = self.parse_dates(membership_obj[0])\n method, position = self.parse_position_method(membership_obj[1])\n # Appointed or Elected\n self.method_obtained = method\n # Ex Officio - Chief Secretary, Geographical Constituency - Kowloon East\n self.position = position\n # Retired, replaced, resigned, etc.\n if len(membership_obj) > 2:\n self.note = self.parse_note(membership_obj[2])\n else:\n self.note = None\n\n def parse_date(self, date_str):\n if date_str is None:\n return None\n try:\n return datetime.strptime(date_str, self.DATE_FORMAT).date()\n except ValueError:\n return None\n\n def parse_dates(self, date_string):\n # First element of the json object is the string\n matched_dates = re.match(self.DATE_RE, date_string)\n if matched_dates is None:\n return None, None\n\n matches = matched_dates.groups()\n return self.parse_date(matches[0]), self.parse_date(matches[1])\n\n def parse_position_method(self, position_string):\n matched = re.match(self.DETAIL_RE, position_string)\n if matched is None:\n return None, None\n\n groups = matched.groups()\n return groups[0], groups[1]\n\n def parse_note(self, note_string):\n res = note_string.replace('(', '').replace(')', '')\n return res\n\n\nclass ParsedCommittee(TimestampMixin, BaseParsedModel):\n code = models.CharField(max_length=100, blank=True)\n name_e = models.TextField()\n name_c = models.TextField()\n url_e = models.TextField(blank=True, default='')\n url_c = models.TextField(blank=True, default='')\n members = models.ManyToManyField(ParsedPerson, through='ParsedCommitteeMembership')\n\n RAW_MODEL = RawCommittee\n\n class Meta:\n ordering = ['name_e']\n app_label = 'raw'\n\n def __unicode__(self):\n return u'{}: {} {}'.format(self.code, self.name_e, self.name_c)\n\n\nclass CommitteeMembershipManager(BaseParsedManager):\n excluded = ['person', 'committee']\n\n def get_active_on_date(self, query_date):\n return self.filter(start_date__lt=query_date, end_date__gt=query_date)\n\n def get_current(self):\n # Finds memberships where end date is None\n today = date.today()\n return self.filter(Q(start_date__lt=today), Q(end_date__gt=today) | Q(end_date=None))\n\n def create_from_raw(self, raw_obj):\n obj = super(CommitteeMembershipManager, self).create_from_raw(raw_obj)\n # String up the person and the committee\n raw_committee = raw_obj.committee\n if raw_committee is not None:\n committee = ParsedCommittee.objects.get(uid=raw_committee.uid)\n obj.committee = committee\n\n if raw_obj.member is not None:\n raw_member = raw_obj.member.get_raw_member()\n if raw_member is not None:\n person = ParsedPerson.objects.get(uid=raw_member.uid)\n obj.person = person\n return obj\n\n\nclass ParsedCommitteeMembership(TimestampMixin, BaseParsedModel):\n \"\"\"\n Many to many table linking ParsedPerson and ParsedCommittee.\n \"\"\"\n committee = models.ForeignKey(ParsedCommittee, related_name='memberships')\n person = models.ForeignKey(ParsedPerson, related_name='committee_memberships')\n post_e = models.CharField(max_length=100, blank=True, default='')\n post_c = models.CharField(max_length=100, blank=True, default='')\n start_date = models.DateTimeField(null=False)\n end_date = models.DateTimeField(null=True)\n\n objects = CommitteeMembershipManager()\n RAW_MODEL = RawCommitteeMembership\n\n class Meta:\n app_label = 'raw'\n\n def __unicode__(self):\n return u'{} - {} - {}'.format(self.post_e, self.start_date, self.end_date)\n\n\nclass CouncilMeetingManager(BaseParsedManager):\n excluded = ['start_date', 'end_date']\n\n def create_from_raw(self, raw_obj):\n # Need to snip off the language on the agenda UID\n new_uid = u'cmeeting-{:%Y%m%d}'.format(raw_obj.start_date)\n try:\n obj = self.get(uid=new_uid)\n except self.model.DoesNotExist as e:\n obj = self.model()\n\n obj.uid = new_uid\n start_date = raw_obj.start_date\n obj.start_date = datetime.combine(start_date, time(11, 0))\n obj.deactivate = False\n return obj\n\n def get_from_raw(self, raw_obj):\n # Get a ParsedCouncilMeeting from a RawCouncilAgenda\n new_uid = u'cmeeting-{:%Y%m%d}'.format(raw_obj.start_date)\n try:\n return self.get(uid=new_uid)\n except self.model.DoesNotExist as e:\n return None\n\n\nclass ParsedCouncilMeeting(TimestampMixin, BaseParsedModel):\n \"\"\"\n Meetings can span multiple days, but have only one agenda for all of the business that will occur on that day\n \"\"\"\n # Usual time of start is 11am\n start_date = models.DateTimeField(null=False)\n end_date = models.DateTimeField(null=True)\n\n objects = CouncilMeetingManager()\n RAW_MODEL = RawCouncilAgenda\n\n class Meta:\n app_label = 'raw'\n\n def __unicode__(self):\n if self.end_date is None:\n return u'Meeting on {}'.format(self.start_date.date())\n else:\n return u'Meeting on {} to {}'.format(self.start_date.date(), self.end_date.date())\n\n\nclass QuestionManager(BaseParsedManager):\n def create_from_raw(self, raw_obj):\n pass\n\n def populate(self, dry_run=False):\n \"\"\"\n Create ParsedQuestions. Strategy is to start with all RawCouncilQuestions, get the basic information from there,\n then cross reference against the CouncilAgenda for that date.\n\n Since CouncilAgenda parsing is not perfect, will probably result in a lot of missing cross references. In these\n cases, we just don't populate the question's body.\n \"\"\"\n self._deactivate_db_debug()\n # Deactivate the agenda logging\n agenda_logger.deactivate = True\n parser_cache = OrderedDict()\n all_questions = RawCouncilQuestion.objects.order_by('raw_date').all()\n name_matcher_e = ParsedPerson.get_matcher()\n name_matcher_c = ParsedPerson.get_matcher(False)\n count = 0\n skipped = 0\n incomplete = 0\n for raw_question in all_questions:\n # Get the agenda\n agenda = raw_question.get_agenda()\n if agenda is None:\n logger.warn(u'Could not find agenda ({}).'.format(agenda))\n skipped += 1\n continue\n\n meeting = ParsedCouncilMeeting.objects.get_from_raw(agenda)\n if meeting is None:\n logger.warn(u'Could not find meeting ({}).'.format(meeting, agenda))\n skipped += 1\n continue\n\n # Get the parser and cache it\n if agenda.uid in parser_cache:\n parser = parser_cache[agenda.uid]\n else:\n parser = agenda.get_parser()\n parser_cache[agenda.uid] = parser\n\n # Now try to find the question in the parser\n # CouncilAgenda's can't yet tell if a question is urgent or not, so we check against the asker\n if parser is not None:\n agenda_question = raw_question.get_matching_question_from_parser(parser)\n else:\n agenda_question = None\n\n # if we couldn't find it, then log it\n if agenda_question is None:\n logger.warn(u'Could not find corresponding Agenda question for {}'.format(raw_question))\n incomplete += 1\n\n # Check that the names on the askers match, then get the ParsedPerson object that we'll attach to the question\n is_english = raw_question.language == LANG_EN\n agenda_name = None\n raw_name = None\n if raw_question.asker is not None:\n raw_name = raw_question.asker.get_name_object(is_english)\n if agenda_question is not None and agenda_question.asker is not None:\n agenda_name = MemberName(agenda_question.asker)\n\n asker = None\n if raw_name is not None:\n if agenda_name is not None:\n if agenda_name != raw_name:\n logger.warn(u\"Askers don't match on question {}. Agenda: {} Raw: {}\".format(\n force_unicode(raw_question), force_unicode(agenda_name), force_unicode(raw_name)))\n # Either way, we use the raw_question's asker\n asker = ParsedPerson.objects.get(uid=raw_question.asker.uid)\n else:\n if agenda_name is not None:\n # Try to find a name match based on the agenda name\n matcher = name_matcher_e if is_english else name_matcher_c\n match = matcher.match(agenda_name)\n if match is not None:\n asker = match[1]\n else:\n asker = None\n\n # Can't find an asker, abort the creation\n if asker is None:\n logger.warn(u'Could not find an asker for the question {}'.format(raw_question))\n skipped += 1\n continue\n\n # Check some other fields to see if they match, for diagnostic purposes\n if agenda_question is not None:\n raw_question.validate_question(agenda_question)\n\n # Create the ParsedQuestion object and populate the fields\n q_uid = ParsedQuestion.generate_uid(meeting, raw_question.number, raw_question.is_urgent)\n try:\n obj = self.get(uid=q_uid)\n except self.model.DoesNotExist as e:\n obj = self.model(uid=q_uid)\n\n obj.meeting = meeting\n obj.number = raw_question.number\n obj.urgent = raw_question.is_urgent\n obj.question_type = ParsedQuestion.ORAL if raw_question.is_oral else ParsedQuestion.WRITTEN\n obj.asker = asker\n if is_english:\n if agenda_question is not None:\n # Only keep the English replier\n obj.replier = agenda_question.replier or u''\n obj.body_e = agenda_question.body\n obj.subject_e = raw_question.subject\n else:\n if agenda_question is not None:\n obj.body_c = agenda_question.body\n obj.subject_c = raw_question.subject\n count += 1\n if not dry_run:\n obj.save()\n\n # Prune the parser cache so we don't keep all of the CouncilAgendas in memory\n if len(parser_cache) > 10:\n parser_cache.popitem(last=False)\n\n logger.info(u'{} questions created, {} skipped, {} without body text'.format(count, skipped, incomplete))\n agenda_logger.deactivate = False\n self._reactivate_db_debug()\n\n\nclass ParsedQuestion(TimestampMixin, BaseParsedModel):\n \"\"\"\n Questions asked during LegCo meetings\n \"\"\"\n ORAL = 1\n WRITTEN = 2\n QTYPES = (\n (ORAL, 'Oral'),\n (WRITTEN, 'Written')\n )\n meeting = models.ForeignKey(ParsedCouncilMeeting, related_name='questions')\n number = models.IntegerField()\n urgent = models.BooleanField(default=False)\n question_type = models.IntegerField(choices=QTYPES)\n asker = models.ForeignKey(ParsedPerson, related_name='questions')\n # A secretary of the government. Only keep the English\n replier = models.TextField(default='')\n # Actual content of the question\n subject_e = models.TextField(default='')\n subject_c = models.TextField(default='')\n body_e = models.TextField(default='')\n body_c = models.TextField(default='')\n reply_e = models.TextField(default='')\n reply_c = models.TextField(default='')\n\n objects = QuestionManager()\n\n class Meta:\n app_label = 'raw'\n ordering = ['number']\n\n def __unicode__(self):\n return u'Q{} - {}'.format(self.number, self.subject_e)\n\n @classmethod\n def generate_uid(cls, meeting, number, is_urgent):\n return u'{}-{}q{}'.format(meeting.uid, u'u' if is_urgent else u'', number)\n","sub_path":"app/raw/models/parsed.py","file_name":"parsed.py","file_ext":"py","file_size_in_byte":24715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99415645","text":"# Temperature conversion program Fahrenheit->Celsius\n\n# program greeting:\nprint('This program will convert degrees Celsius to degrees Fahrenheit')\n\n# get temperature in Fahrenheit:\ncelsius = float(input('Enter degrees Celsius: '))\n\n# convert Fahrenheit to Celsius:\nfahren = celsius * 9/5 + 32\n\n# print result:\nprint(celsius, 'degrees Celsius equals',\n format(fahren, '.1f'), 'degrees Fahrenheit')\n","sub_path":"Lab solutions/Lab02/lab2_p5.py","file_name":"lab2_p5.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403102302","text":"import bpy\nscene = bpy.context.scene\n\nscene.world.use_sky_blend = True\n#below multiplied by two for a better proportion Clear vs Overcast sky \n#since Clear sky is 20000 lux vs 2000 for overcast\nscene.world.horizon_color = (0.0, 0.0, 0.0)\nscene.world.zenith_color = (0.250980406999588, 0.6117647290229797, 1.0)\nscene.world.ambient_color = (0.0, 0.0, 0.0)\nscene.world.mist_settings.use_mist = False\nscene.world.mist_settings.intensity = 0.0\nscene.world.mist_settings.depth = 25.0\nscene.world.mist_settings.start = 5.0\nscene.pov.media_enable = True\nscene.pov.media_scattering_type = '5'\nscene.pov.media_samples = 35\nscene.pov.media_diffusion_color = (0.000034, 0.000034, 0.000017)\nscene.pov.media_absorption_color = (0.00000455, 0.00000165, 0.00000031)\nscene.pov.media_eccentricity = 0.7","sub_path":"engine/2.80/scripts/addons/presets/pov/world/5_Under_Water.py","file_name":"5_Under_Water.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616876476","text":"\"\"\"\nUDP 客户端\n\"\"\"\n\nfrom socket import *\n\nsockfd = socket(AF_INET,SOCK_DGRAM)\n\n#服务端 地址\naddr = ((\"172.40.74.177\", 22222))\n\n#循环发送消息\nwhile True:\n data = input(\"please send the message:\")\n\n sockfd.sendto(data.encode(),addr)\n\n msg, addr = sockfd.recvfrom(1024)\n print(\"i am received\")\n\n","sub_path":"xiaojian/xiaojian/second_phase/day06/udp_client.py","file_name":"udp_client.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513473717","text":"import time\n\nfrom PLC.Faults import *\nfrom PLC.Method import Method\nfrom PLC.Parameter import Parameter, Mixed\nfrom PLC.Filter import Filter\nfrom PLC.Auth import Auth\nfrom PLC.Nodes import Node, Nodes\nfrom PLC.Interfaces import Interface, Interfaces\nfrom PLC.NodeGroups import NodeGroup, NodeGroups\nfrom PLC.ConfFiles import ConfFile, ConfFiles\nfrom PLC.Slices import Slice, Slices\nfrom PLC.Persons import Person, Persons\nfrom PLC.Sites import Sites\nfrom PLC.Roles import Roles\nfrom PLC.Keys import Key, Keys\nfrom PLC.SliceTags import SliceTag, SliceTags\nfrom PLC.InitScripts import InitScript, InitScripts\nfrom PLC.Leases import Lease, Leases\nfrom PLC.Timestamp import Duration\nfrom PLC.Methods.GetSliceFamily import GetSliceFamily\nfrom PLC.PersonTags import PersonTag,PersonTags\n\nfrom PLC.Accessors.Accessors_standard import *\nfrom functools import reduce\n\n# XXX used to check if slice expiration time is sane\nMAXINT = 2**31-1\n\n# slice_filter essentially contains the slice_ids for the relevant slices (on the node + system & delegated slices)\ndef get_slivers(api, caller, auth, slice_filter, node = None):\n # Get slice information\n slices = Slices(api, slice_filter, ['slice_id', 'name', 'instantiation', 'expires', 'person_ids', 'slice_tag_ids'])\n\n # Build up list of users and slice attributes\n person_ids = set()\n slice_tag_ids = set()\n for slice in slices:\n person_ids.update(slice['person_ids'])\n slice_tag_ids.update(slice['slice_tag_ids'])\n\n # Get user information\n all_persons = Persons(api, {'person_id':person_ids,'enabled':True}, ['person_id', 'enabled', 'key_ids']).dict()\n\n # Build up list of keys\n key_ids = set()\n for person in list(all_persons.values()):\n key_ids.update(person['key_ids'])\n\n # Get user account keys\n all_keys = Keys(api, key_ids, ['key_id', 'key', 'key_type']).dict()\n\n # Get slice attributes\n all_slice_tags = SliceTags(api, slice_tag_ids).dict()\n\n slivers = []\n for slice in slices:\n keys = []\n for person_id in slice['person_ids']:\n if person_id in all_persons:\n person = all_persons[person_id]\n if not person['enabled']:\n continue\n for key_id in person['key_ids']:\n if key_id in all_keys:\n key = all_keys[key_id]\n keys += [{'key_type': key['key_type'],\n 'key': key['key']}]\n\n attributes = []\n\n # All (per-node and global) attributes for this slice\n slice_tags = []\n for slice_tag_id in slice['slice_tag_ids']:\n if slice_tag_id in all_slice_tags:\n slice_tags.append(all_slice_tags[slice_tag_id])\n\n # Per-node sliver attributes take precedence over global\n # slice attributes, so set them first.\n # Then comes nodegroup slice attributes\n # Followed by global slice attributes\n sliver_attributes = []\n\n if node is not None:\n for sliver_attribute in [ a for a in slice_tags if a['node_id'] == node['node_id'] ]:\n sliver_attributes.append(sliver_attribute['tagname'])\n attributes.append({'tagname': sliver_attribute['tagname'],\n 'value': sliver_attribute['value']})\n\n # set nodegroup slice attributes\n for slice_tag in [ a for a in slice_tags if a['nodegroup_id'] in node['nodegroup_ids'] ]:\n # Do not set any nodegroup slice attributes for\n # which there is at least one sliver attribute\n # already set.\n if slice_tag['tagname'] not in sliver_attributes:\n sliver_attributes.append(slice_tag['tagname'])\n attributes.append({'tagname': slice_tag['tagname'],\n 'value': slice_tag['value']})\n\n for slice_tag in [ a for a in slice_tags if a['node_id'] is None and a['nodegroup_id'] is None ]:\n # Do not set any global slice attributes for\n # which there is at least one sliver attribute\n # already set.\n if slice_tag['tagname'] not in sliver_attributes:\n attributes.append({'tagname': slice_tag['tagname'],\n 'value': slice_tag['value']})\n\n # XXX Sanity check; though technically this should be a system invariant\n # checked with an assertion\n if slice['expires'] > MAXINT: slice['expires']= MAXINT\n\n # expose the slice vref as computed by GetSliceFamily\n family = GetSliceFamily (api,caller).call(auth, slice['slice_id'])\n\n slivers.append({\n 'name': slice['name'],\n 'slice_id': slice['slice_id'],\n 'instantiation': slice['instantiation'],\n 'expires': slice['expires'],\n 'keys': keys,\n 'attributes': attributes,\n 'GetSliceFamily': family,\n })\n\n return slivers\n\n### The pickle module, used in conjunction with caching has a restriction that it does not\n### work on \"connection objects.\" It doesn't matter if the connection object has\n### an 'str' or 'repr' method, there is a taint check that throws an exception if\n### the pickled class is found to derive from a connection.\n### (To be moved to Method.py)\n\ndef sanitize_for_pickle (obj):\n if (isinstance(obj, dict)):\n parent = dict(obj)\n for k in list(parent.keys()): parent[k] = sanitize_for_pickle (parent[k])\n return parent\n elif (isinstance(obj, list)):\n parent = list(obj)\n parent = list(map(sanitize_for_pickle, parent))\n return parent\n else:\n return obj\n\nclass GetSlivers(Method):\n \"\"\"\n Returns a struct containing information about the specified node\n (or calling node, if called by a node and node_id_or_hostname is\n not specified), including the current set of slivers bound to the\n node.\n\n All of the information returned by this call can be gathered from\n other calls, e.g. GetNodes, GetInterfaces, GetSlices, etc. This\n function exists almost solely for the benefit of Node Manager.\n \"\"\"\n\n roles = ['admin', 'node']\n\n accepts = [\n Auth(),\n Mixed(Node.fields['node_id'],\n Node.fields['hostname']),\n ]\n\n returns = {\n 'timestamp': Parameter(int, \"Timestamp of this call, in seconds since UNIX epoch\"),\n 'node_id': Node.fields['node_id'],\n 'hostname': Node.fields['hostname'],\n 'interfaces': [Interface.fields],\n 'groups': [NodeGroup.fields['groupname']],\n 'conf_files': [ConfFile.fields],\n 'initscripts': [InitScript.fields],\n 'accounts': [{\n 'name': Parameter(str, \"unix style account name\", max = 254),\n 'keys': [{\n 'key_type': Key.fields['key_type'],\n 'key': Key.fields['key']\n }],\n }],\n 'slivers': [{\n 'name': Slice.fields['name'],\n 'slice_id': Slice.fields['slice_id'],\n 'instantiation': Slice.fields['instantiation'],\n 'expires': Slice.fields['expires'],\n 'keys': [{\n 'key_type': Key.fields['key_type'],\n 'key': Key.fields['key']\n }],\n 'attributes': [{\n 'tagname': SliceTag.fields['tagname'],\n 'value': SliceTag.fields['value']\n }]\n }],\n # how to reach the xmpp server\n 'xmpp': {'server':Parameter(str,\"hostname for the XMPP server\"),\n 'user':Parameter(str,\"username for the XMPP server\"),\n 'password':Parameter(str,\"username for the XMPP server\"),\n },\n # we consider three policies (reservation-policy)\n # none : the traditional way to use a node\n # lease_or_idle : 0 or 1 slice runs at a given time\n # lease_or_shared : 1 slice is running during a lease, otherwise all the slices come back\n 'reservation_policy': Parameter(str,\"one among none, lease_or_idle, lease_or_shared\"),\n 'leases': [ { 'slice_id' : Lease.fields['slice_id'],\n 't_from' : Lease.fields['t_from'],\n 't_until' : Lease.fields['t_until'],\n }],\n }\n\n def call(self, auth, node_id_or_hostname = None):\n return self.raw_call(auth, node_id_or_hostname)\n\n\n def raw_call(self, auth, node_id_or_hostname):\n timestamp = int(time.time())\n\n # Get node\n if node_id_or_hostname is None:\n if isinstance(self.caller, Node):\n node = self.caller\n else:\n raise PLCInvalidArgument(\"'node_id_or_hostname' not specified\")\n else:\n nodes = Nodes(self.api, [node_id_or_hostname])\n if not nodes:\n raise PLCInvalidArgument(\"No such node\")\n node = nodes[0]\n\n if node['peer_id'] is not None:\n raise PLCInvalidArgument(\"Not a local node\")\n\n # Get interface information\n interfaces = Interfaces(self.api, node['interface_ids'])\n\n # Get node group information\n nodegroups = NodeGroups(self.api, node['nodegroup_ids']).dict('groupname')\n groups = list(nodegroups.keys())\n\n # Get all (enabled) configuration files\n all_conf_files = ConfFiles(self.api, {'enabled': True}).dict()\n conf_files = {}\n\n # Global configuration files are the default. If multiple\n # entries for the same global configuration file exist, it is\n # undefined which one takes precedence.\n for conf_file in list(all_conf_files.values()):\n if not conf_file['node_ids'] and not conf_file['nodegroup_ids']:\n conf_files[conf_file['dest']] = conf_file\n\n # Node group configuration files take precedence over global\n # ones. If a node belongs to multiple node groups for which\n # the same configuration file is defined, it is undefined\n # which one takes precedence.\n for nodegroup in list(nodegroups.values()):\n for conf_file_id in nodegroup['conf_file_ids']:\n if conf_file_id in all_conf_files:\n conf_file = all_conf_files[conf_file_id]\n conf_files[conf_file['dest']] = conf_file\n\n # Node configuration files take precedence over node group\n # configuration files.\n for conf_file_id in node['conf_file_ids']:\n if conf_file_id in all_conf_files:\n conf_file = all_conf_files[conf_file_id]\n conf_files[conf_file['dest']] = conf_file\n\n # Get all (enabled) initscripts\n initscripts = InitScripts(self.api, {'enabled': True})\n\n # Get system slices\n system_slice_tags = SliceTags(self.api, {'tagname': 'system', 'value': '1'}).dict('slice_id')\n system_slice_ids = list(system_slice_tags.keys())\n\n # Get nm-controller slices\n # xxx Thierry: should these really be exposed regardless of their mapping to nodes ?\n controller_and_delegated_slices = Slices(self.api, {'instantiation': ['nm-controller', 'delegated']}, ['slice_id']).dict('slice_id')\n controller_and_delegated_slice_ids = list(controller_and_delegated_slices.keys())\n slice_ids = system_slice_ids + controller_and_delegated_slice_ids + node['slice_ids']\n\n slivers = get_slivers(self.api, self.caller, auth, slice_ids, node)\n\n # get the special accounts and keys needed for the node\n # root\n # site_admin\n accounts = []\n if False and 'site_id' not in node:\n nodes = Nodes(self.api, node['node_id'])\n node = nodes[0]\n\n # used in conjunction with reduce to flatten lists, like in\n # reduce ( reduce_flatten_list, [ [1] , [2,3] ], []) => [ 1,2,3 ]\n def reduce_flatten_list (x,y): return x+y\n\n # root users are users marked with the tag 'isrootonsite'. Hack for Mlab and other sites in which admins participate in diagnosing problems.\n def get_site_root_user_keys(api,site_id_or_name):\n site = Sites (api,site_id_or_name,['person_ids'])[0]\n all_site_persons = site['person_ids']\n all_site_person_tags = PersonTags(self.api,{'person_id':all_site_persons,'tagname':'isrootonsite'},['value','person_id'])\n site_root_person_tags = [r for r in all_site_person_tags if r['value']=='true']\n site_root_person_ids = [r['person_id'] for r in site_root_person_tags]\n key_ids = reduce (reduce_flatten_list,\n [ p['key_ids'] for p in \\\n Persons(api,{ 'person_id':site_root_person_ids,\n 'enabled':True, '|role_ids' : [20, 40] },\n ['key_ids']) ],\n [])\n return [ key['key'] for key in Keys (api, key_ids) if key['key_type']=='ssh']\n\n # power users are pis and techs\n def get_site_power_user_keys(api,site_id_or_name):\n site = Sites (api,site_id_or_name,['person_ids'])[0]\n key_ids = reduce (reduce_flatten_list,\n [ p['key_ids'] for p in \\\n Persons(api,{ 'person_id':site['person_ids'],\n 'enabled':True, '|role_ids' : [20, 40] },\n ['key_ids']) ],\n [])\n return [ key['key'] for key in Keys (api, key_ids) if key['key_type']=='ssh']\n\n # all admins regardless of their site\n def get_all_admin_keys(api):\n key_ids = reduce (reduce_flatten_list,\n [ p['key_ids'] for p in \\\n Persons(api, {'peer_id':None, 'enabled':True, '|role_ids':[10] },\n ['key_ids']) ],\n [])\n return [ key['key'] for key in Keys (api, key_ids) if key['key_type']=='ssh']\n\n # 'site_admin' account setup\n personsitekeys=get_site_power_user_keys(self.api,node['site_id'])\n accounts.append({'name':'site_admin','keys':personsitekeys})\n\n # 'root' account setup on nodes from all 'admin' users and ones marked with 'isrootonsite' for this site\n siterootkeys=get_site_root_user_keys(self.api,node['site_id'])\n personsitekeys=get_all_admin_keys(self.api)\n personsitekeys.extend(siterootkeys)\n\n accounts.append({'name':'root','keys':personsitekeys})\n\n hrn = GetNodeHrn(self.api,self.caller).call(auth,node['node_id'])\n\n # XMPP config for omf federation\n try:\n if not self.api.config.PLC_OMF_ENABLED:\n raise Exception(\"OMF not enabled\")\n xmpp={'server':self.api.config.PLC_OMF_XMPP_SERVER}\n except:\n xmpp={'server':None}\n\n node.update_last_contact()\n\n # expose leases & reservation policy\n # in a first implementation we only support none and lease_or_idle\n lease_exposed_fields = [ 'slice_id', 't_from', 't_until', 'name', ]\n leases=None\n if node['node_type'] != 'reservable':\n reservation_policy='none'\n else:\n reservation_policy='lease_or_idle'\n # expose the leases for the next 24 hours\n leases = [ dict ( [ (k,l[k]) for k in lease_exposed_fields ] )\n for l in Leases (self.api, {'node_id':node['node_id'],\n 'clip': (timestamp, timestamp+24*Duration.HOUR),\n '-SORT': 't_from',\n }) ]\n granularity=self.api.config.PLC_RESERVATION_GRANULARITY\n\n raw_data = {\n 'timestamp': timestamp,\n 'node_id': node['node_id'],\n 'hostname': node['hostname'],\n 'interfaces': interfaces,\n 'groups': groups,\n 'conf_files': list(conf_files.values()),\n 'initscripts': initscripts,\n 'slivers': slivers,\n 'accounts': accounts,\n 'xmpp':xmpp,\n 'hrn':hrn,\n 'reservation_policy': reservation_policy,\n 'leases':leases,\n 'lease_granularity': granularity,\n }\n\n sanitized_data = sanitize_for_pickle (raw_data)\n return sanitized_data\n\n","sub_path":"PLC/Methods/GetSlivers.py","file_name":"GetSlivers.py","file_ext":"py","file_size_in_byte":16550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270602276","text":"from datetime import datetime\nfrom flask import render_template, request, g, abort\nfrom flask_login import login_required\n\nfrom controller import c3bottles, db\nfrom model.drop_point import DropPoint\nfrom model.location import Location\n\n\n@c3bottles.route(\"/edit/\", methods=(\"GET\", \"POST\"))\n@c3bottles.route(\"/edit\")\n@login_required\ndef edit_dp(\n number=None, description=None, lat=None,\n lng=None, level=None, errors=None,\n success=None, center_lat=None, center_lng=None\n):\n\n if not g.user.can_edit:\n abort(401)\n\n if number:\n dp = DropPoint.get(number)\n else:\n dp = DropPoint.get(request.values.get(\"number\"))\n\n if not dp:\n return render_template(\n \"error.html\",\n heading=\"Error!\",\n text=\"Drop point not found.\"\n )\n\n description_old = str(dp.get_current_location().description)\n lat_old = str(dp.get_current_location().lat)\n lng_old = str(dp.get_current_location().lng)\n level_old = str(dp.get_current_location().level)\n\n if request.method == \"POST\":\n\n description = request.form.get(\"description\")\n lat = request.form.get(\"lat\")\n lng = request.form.get(\"lng\")\n level = request.form.get(\"level\")\n remove = request.form.get(\"remove\")\n\n try:\n\n if description != description_old \\\n or lat != lat_old or lng != lng_old:\n Location(\n dp,\n description=description,\n lat=lat,\n lng=lng,\n level=level\n )\n\n if remove == \"yes\":\n dp.removed = datetime.now()\n\n except ValueError as e:\n errors = e.args\n else:\n db.session.commit()\n return render_template(\n \"success.html\",\n text=\"Your changes have been saved.\"\n )\n\n else:\n description = description_old\n lat = lat_old\n lng = lng_old\n level = level_old\n\n try:\n lat_f = float(lat)\n lng_f = float(lng)\n except (ValueError, TypeError):\n lat_f = None\n lng_f = None\n\n if errors is not None:\n error_list = [v for d in errors for v in d.values()]\n error_fields = [k for d in errors for k in d.keys()]\n else:\n error_list = []\n error_fields = []\n\n return render_template(\n \"edit_dp.html\",\n all_dps_json=DropPoint.get_dps_json(),\n number=number,\n description=description,\n lat=lat_f,\n lng=lng_f,\n level=level,\n error_list=error_list,\n error_fields=error_fields\n )\n\n# vim: set expandtab ts=4 sw=4:\n","sub_path":"view/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150372352","text":"import socket\r\nimport threading\r\nimport os\r\nimport time\r\n\r\nhost = \"127.0.0.1\"\r\nport = 1337\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\ns.bind((host,port))\r\nprint('Server ready')\r\n\r\n\r\nfilename, addr = s.recvfrom(1024)\r\nfilename = filename.decode('ascii')\r\nprint(filename)\r\n\r\n##while True:\r\n \r\nif os.path.isfile(filename):\r\n\r\n x = \"EXIST\"\r\n length = str(os.path.getsize(filename))\r\n \r\n s.sendto(x.encode('ascii'),(host,1338))\r\n## time.sleep(3)\r\n s.sendto(length.encode('ascii'),(host,1339))\r\n## time.sleep(3)\r\n print('sent')\r\n userResponse,addr = s.recvfrom(2048)\r\n userResponse = userResponse.decode('ascii')\r\n## time.sleep(3)\r\n print('3')\r\n\r\n if userResponse == \"ok\":\r\n with open(filename, 'rb') as f:\r\n ## rb == read binary\r\n bytesToSend = f.read(100)\r\n s.sendto(bytesToSend,(host,port))\r\n while bytesToSend != \"\":\r\n bytesToSend = f.read(100)\r\n s.sendto(bytesToSend,(host,port))\r\n\r\n else:\r\n print('Failed')\r\n\r\nelse:\r\n y = \"ERR\".encode(\"ascii\")\r\n s.sendto(y,(host,port))\r\n\r\ns.close()\r\n","sub_path":"UDP/serverfile.py","file_name":"serverfile.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375272542","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nimport json\nimport re\n\n\ndef format_name(name):\n \"\"\" Function que formatea un nombre para el nombre del json\"\"\"\n formated_name = re.sub('▒~V~R~V~R~A', 'a', name)\n formated_name = re.sub('▒~V~R~I', 'e', formated_name)\n formated_name = re.sub('▒~V~R~M', 'i', formated_name)\n formated_name = re.sub('▒~V~R~S', 'o', formated_name)\n formated_name = re.sub('▒~V~R~Z', 'u', formated_name)\n formated_name = re.sub('▒~V~R~Q', 'n', formated_name)\n formated_name = re.sub('[^\\sa-zA-Z\\d]+', ' ', formated_name)\n formated_name = re.sub('\\s+', '_', formated_name)\n formated_name = re.sub('^_+', '', formated_name)\n formated_name = re.sub('_+$', '', formated_name)\n return formated_name.lower()\n\n\n# Load csv into dataframe\ndf = pd.read_csv('./data/nombres1922a2015conpp.csv',\n header=None,\n dtype={'0': str,\n '1': np.int32,\n '2': np.int32,\n '3': str,\n '4': np.float64})\n\nprint('-------------- termino loading csv --------------')\n\ndf.columns = ['name', 'quantity', 'year', 'gender', 'percentage']\n\n# Reemplazar por nombre en cuestión\ndf = df[df['name'] == 'MICKEY']\ndf = df.groupby(('name', 'year', 'gender')).agg(\n {'quantity': sum, 'percentage': sum}).reset_index()\n\nprint(df.head())\n\nprint('-------------- termino de agrupar por año --------------')\n# --- Start procesamiento de nombres\n\n# Sacar distinct de nombres para hacer el cruce cartesiano luego\nall_unique_names = df.groupby(('name', 'gender')).count().reset_index()\nall_unique_names = all_unique_names[['name', 'gender']]\n\n# Crear dataframe de anios para hacer el cruce cartesiano luego\nyears = pd.DataFrame({'year': list(range(1922, 2016))})\nyears['year'] = years['year'].astype(np.int32)\n\n# Crear key en comun para hacer cartesian product\nall_unique_names['tmp_key'] = 1\nyears['tmp_key'] = 1\n\n# # Especificar dtype para hacer mas eficiente el cruce\nall_unique_names['tmp_key'] = all_unique_names['tmp_key'].astype(np.int32)\nyears['tmp_key'] = years['tmp_key'].astype(np.int32)\n\nprint('-------------- arranco cruce cartesiano --------------')\n\n# Realizar cruce cartesiano\ncross_names_years = pd.merge(\n all_unique_names, years, on='tmp_key', how='outer')\ncross_names_years = cross_names_years[['name', 'gender', 'year']]\ntodos_con_todos = pd.merge(cross_names_years, df, on=[\n 'name', 'gender', 'year'], how='left')\ntodos_con_todos = todos_con_todos.fillna(0)\ntodos_con_todos['quantity'] = todos_con_todos['quantity'].astype(int)\ntodos_con_todos['gender'] = todos_con_todos['gender'].str.lower()\n\nnames_group = todos_con_todos.groupby('name')\n\nprint(todos_con_todos.head())\n\n# Escribir jsons de nombres\nfor name, group in names_group:\n file_url = 'public/names/' + format_name(str(name)) + '.json'\n print(file_url)\n list_name = group.reset_index(\n )[['gender', 'year', 'percentage', 'quantity']].to_dict('records')\n\n with open(file_url, 'w') as fp:\n json.dump(list_name, fp)\n","sub_path":"scripts/process_one_name.py","file_name":"process_one_name.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194032168","text":"# Functions controlling the AJAX requests\n# (c) 2013 Radical Graphics Studios\nfrom radicalwebapp.models import Portfolio, HowWeWork\nfrom dajax.core import Dajax\nfrom dajaxice.core import dajaxice_functions\nfrom dajaxice.decorators import dajaxice_register\n\n\nfrom django.core.mail import send_mail\n\nfrom django.shortcuts import get_object_or_404\n\n\nfrom radicalwebapp import views\nfrom django.conf import settings\n\n@dajaxice_register\ndef get_portfolio(request, page, tag):\n\n\tdajax = Dajax()\n\n\tids_to_get_to = int(page) * 8 \n\tids_to_get_from = ((int(page) - 1) * 8)\n\n\tif (tag == \"all\"):\n\t\tpictures = Portfolio.objects.all().order_by('-featured')\n\t\tportfolio_length = Portfolio.objects.all().count()\n\telse:\n\t\tpictures = Portfolio.objects.filter(tag=tag).all().order_by('-featured')\n\t\tportfolio_length = Portfolio.objects.filter(tag=tag).count()\n\t\n\thtml = \"\"\n\tfor pic in pictures[ids_to_get_from:ids_to_get_to]:\n\t\t\n\t\tstr_len = len(pic.name)\n\t\tif str_len > 15:\n\t\t\tpic_name = pic.name[0:15] + \"...\"\n\t\telse:\n\t\t\tpic_name = pic.name\n\n\t\thtml += \"
\"\n\t\thtml += \"\t
\"\n\t\thtml += \"\t\t
\" + pic_name + \"
\"\n\t\thtml += \"\t\t

\" + pic.platform + \"

\"\n\t\thtml += \"\t\t\"\n\t\thtml += \"\t
\"\n\t\thtml += \"
\"\n\n\tif (portfolio_length\"\n\thtml += \"\"\n\thtml += \"\"\n\thtml += \"\"\n\n\t# html += \"\"\n\t\n\n\tdajax.assign('#portfolio_pics', 'innerHTML', html)\n\n\treturn dajax.json()\n\n\n\n\n@dajaxice_register(method='POST')\ndef send_message(request, subject, mailbody, from_mail):\n\n\tdajax = Dajax()\n\t# print \"CORREO: \"\n\t# print 'subject: ' + subject\n\t# print 'from: ' + from_mail\n\t# print 'body: ' + mailbody\n\n\t\n\n\tsend_mail(subject,mailbody,from_mail,['info@radicalgraphics.com'],fail_silently=False)\n\n\t\n\n\thtml = '

Thanks for your message!.
We will contact you back as soon as possible :D

'\n\n\tdajax.assign('#contactform','innerHTML',html)\n\t\n\n\treturn dajax.json()\n\n@dajaxice_register\ndef increase_rocks(request):\n\n\tdajax = Dajax()\n\n\thow_we_work = get_object_or_404(HowWeWork)\n\thow_we_work.we_rock += 1\n\thow_we_work.save()\n\n\tdajax.assign('#increase_rock_value', 'data-total', how_we_work.we_rock)\n\tdajax.assign('#increase_rock_value', 'innerHTML', how_we_work.we_rock)\n\tdajax.assign('#yeah_button', 'innerHTML', \"Rock On!\")\n\tdajax.remove_css_class('#rocking_icon','not_rockingIcon')\n\tdajax.add_css_class('#rocking_icon','rockingIcon')\n\t\n\treturn dajax.json()\n\n","sub_path":"radicalsite/radicalwebapp/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568441188","text":"# -*- coding: utf-8 -*-\nfrom decorated.base.dict import Dict\nfrom decorated.base.proxy import Proxy\nfrom decorated.base.thread_local import ThreadLocal\nimport doctest\nimport logging\n\nlog = logging.getLogger(__name__)\n\nclass Context(Dict):\n _current = ThreadLocal()\n\n def __init__(self, **kw):\n super(Context, self).__init__(**kw)\n self._parent = Context._current.get()\n\n def __contains__(self, name):\n raise NotImplementedError()\n\n def __enter__(self):\n Context._current.set(self)\n self._defers = []\n return self\n\n def __exit__(self, error_type, error_value, traceback):\n for defer in self._defers:\n try:\n defer()\n except:\n log.warn('Failed to execute defer \"%s\".' % defer)\n pass\n Context._current.set(self._parent)\n\n def __getattr__(self, name):\n try:\n return super(Context, self).__getattr__(name)\n except AttributeError as e:\n if self._parent:\n try:\n return getattr(self._parent, name)\n except AttributeError:\n raise e\n else:\n raise e\n\n def __getitem__(self, name):\n raise NotImplementedError()\n\n def defer(self, action):\n self._defers.append(action)\n\n def dict(self):\n data = self._parent.dict() if self._parent else Dict()\n data.update(dict([(k, v) for k, v in self.items() if not k.startswith('_')]))\n return data\n\n def get(self, name, default=None):\n raise NotImplementedError()\n\nclass ContextProxy(Proxy):\n def __init__(self):\n super(ContextProxy, self).__init__()\n self._inited = True\n\n def __setattr__(self, name, value):\n if self.__dict__.get('_inited'):\n target = self._target()\n return setattr(target, name, value)\n else:\n self.__dict__[name] = value\n\n def get(self):\n return self._target()\n\n def _target(self):\n ctx = Context._current.get()\n if ctx:\n return ctx\n else:\n raise ContextError('Context should be set first.')\n\nclass ContextError(Exception):\n pass\n\nctx = ContextProxy()\n\nif __name__ == '__main__':\n doctest.testmod()\n","sub_path":"src/decorated/base/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611968778","text":"\nprint(\"PP Module Loaded\")\n\ndef dist(Avec, Bvec): #2d or 3d distance\n\tret=0\n\tfor x,y in zip(Avec, Bvec):\n\t\tret += (float(x)-float(y))**2\n\treturn ret**0.5\n\ndef genFiles(lineNumbers, filesOrigin, folderDest, reflectZ=1, ext='txt', idx=0):\n\t\"\"\"Takes list of line numbers and creates txt/3d files for Visit\"\"\"\n\tlineNumbers = list(set(lineNumbers)); #Remove duplicates\n\tlineNumbers.sort()\n\tprint(\"Plot # {}\".format(idx))\n\tprint(\"We got {} particles\".format(len(lineNumbers)))\n\tprint(\"lineNumbers:\",lineNumbers)\n\n\tif (folderDest[-1] != '/'): folderDest += '/'\n\n\tfil = open(filesOrigin, 'r')\n\tfor datFile in fil:\n\t\tdatFile = datFile.strip() #remove whitespace\n\t\tfName = datFile.split('/')[-1][:-4] #just filename not path, remove extension\n\t\tfName = \"{:010.3f}\".format(float(fName))\n\t\tmyString = folderDest + fName + \"_{}.\".format(idx) + ext\n\n\t\twith open(datFile, 'r') as dat, open(myString, 'w') as saveFile:\n\t\t\tif (ext == '3d'): saveFile.write(\"x\\ty\\tz\\trho\\n\")\n\t\t\tparticleCount = 0\n\n\t\t\tfor lineNumber, line in enumerate(dat):\n\t\t\t\tif (particleCount >= len(lineNumbers)): break #found all particles\n\t\t\t\tif (lineNumbers[particleCount] == lineNumber): \n\t\t\t\t\tparticleCount += 1\n\t\t\t\t\tdata = line.split()\n\t\t\t\t\tsaveString = \"{}\\t{}\\t{}\".format(data[1], data[2], data[3])\n\n\t\t\t\t\tif (ext == '3d'):\n\t\t\t\t\t\trho = '1.0'\n\t\t\t\t\t\tif (len(data)>4): rho = data[4]\n\t\t\t\t\t\tendString =\"\\t{}\\n\".format(rho)\n\n\t\t\t\t\telse: endString = \"\\n\"\n\n\t\t\t\t\tsaveString += endString\n\t\t\t\t\tsaveFile.write(saveString)\n\n\t\t\t\t\tif (reflectZ):\n\t\t\t\t\t\tsaveString = \"{}\\t{}\\t{}\".format(data[1], data[2], '-'+data[3])\n\t\t\t\t\t\tsaveString += endString\n\t\t\t\t\t\tsaveString.replace('--','')\n\t\t\t\t\t\tsaveFile.write(saveString)\n\tprint(\"Done generating {} files!\".format(ext))\t\n\ndef genFilesOrigin(bigTimeStep, filesDir, startTime=0.0, endTime=-1):\n\t\"\"\"Creates list of all dat files used, writes to filesOrigin.txt\"\"\"\n\tfrom os import listdir\n\tprint(\"Generating filesOrigin...\")\n\n\tif (filesDir[-1] != '/'): filesDir += '/'\n\tmyFiles = listdir(filesDir)\n\t\n\tkeyMap = {}#key=time, value=file\n\tmyFloats = []#times\n\tfor file in myFiles:\n\t\tkey = float(file[:-4])\n\t\tmyFloats.append(key)\n\t\tkeyMap[key] = file\n\tmyFloats.sort()\n\n\tif (endTime == -1): largestNumber = myFloats[-1]\n\telse: largestNumber = endTime\n\t\n\tshortList = []\n\ttimeList = []\n\tcur = startTime\n\twhile (cur < largestNumber):\n\t\ttimeList.append(cur)\n\t\tcur += bigTimeStep\n\n\tfor time in timeList:#find closest times for particles\n\t\tclosestTime = min(myFloats, key=lambda x:abs(x-time))\n\t\tshortList.append(keyMap[closestTime])\n\tprint(len(shortList),\" files found\")\n\n\tfilesOrigin = open(filesDir[:-4]+\"filesOrigin.txt\", 'w')\n\tfor time in shortList:\n\t\tmyString = filesDir + time +\"\\n\"\n\t\tfilesOrigin.write(myString)\n\tprint(\"Done generating Files Origin!\")\n\tfilesOrigin.close()\n\n\treturn\n\ndef findInVolume(sourceFile, maxParticles, volumeFunction, Seed=-1):\n\t\"\"\"Finds all particles in specified volume and returns line numbers\"\"\"\n\t\n\tprint(\"Finding in volume...\")\n\timport random\n\tlineNumbers = []\n\twith open(sourceFile, 'r') as datFile:\n\t\tfor lineNumber, line in enumerate(datFile):\n\t\t\tdata = line.split()\n\t\t\tx, y, z = data[1:4]\n\t\t\tif (volumeFunction(x,y,z)): lineNumbers.append(lineNumber)\n\n\tif (Seed != -1): random.seed(Seed)\n\telse: random.seed()\n\n\trandom.shuffle(lineNumbers)\n\treturn lineNumbers[:maxParticles]\n\ndef findInVolumeAllTimes(filesOrigin, maxParticles, volumeFunction, startIdx=-1, endIdx=-1):\n\t\n\tlineNumbers = []\n\t\n\tfor fOrigin in filesOrigin:\n\t\twith open(fOrigin, 'r') as datFile:\n\t\t\tfor lineNumber, line in enumerate(datFile):\n\n\t\t\t\tdata = line.split()\n\t\t\t\tx, y, z = data[1:4]\n\t\t\t\tif(volumeFunction(x,y,z)): lineNumbers.append(lineNumber)\n\n\tlineNumbers = list(set(lineNumbers))\n\trandom.shuffle(lineNumbers)\n\treturn lineNumbers[:maxParticles]\n\ndef nearestNeighbor(sourceFile, listOfPoints):\n\t\"\"\"Takes in list of points and returns list of closest line numbers\"\"\"\n\tprint(\"Finding Nearest Neighbor...\")\n\tlineNumbers = []\n\n\tfor seed in listOfPoints:\n\t\tdatFile = open(sourceFile, 'r')\n\t\tminDist = 10000; minIdx = -1\n\t\tfor lineNumber, line in enumerate(datFile):\n\t\t\tdata = line.split()\n\t\t\tparticle = [float(x) for x in data[1:4] ]\n\t\t\tnewDist = dist(seed, particle)\n\t\t\tif newDist < minDist: minDist = newDist; minIdx = lineNumber\n\t\tlineNumbers.append(minIdx)\n\tlineNumbers = list(set(lineNumbers))\n\tprint(\"Nearest Neighbor finds {} points\".format(len(lineNumbers)))\n\tprint(\"Done finding nearest neighbor\")\n\treturn lineNumbers\n\ndef loadLOP(filename):\n\timport numpy\n\tlistOfPoints = numpy.loadtxt(filename)\n\tLOP = []\n\tfor i in listOfPoints:\n\t\tLOP.append(i)\n\treturn LOP\n\n","sub_path":"abid_bot_v2.8/bin/particle_code/particlePickerModule.py","file_name":"particlePickerModule.py","file_ext":"py","file_size_in_byte":4544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67636946","text":"import socket\r\nimport sys\r\nimport _thread\r\nfrom Crypto.PublicKey import RSA\r\n\r\nfrom custom_packages.endpoint import EndPoint, Colors\r\n\r\n\r\nclass Server(EndPoint):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.renderStartingScreen(display_text=\"s e r v e r\")\r\n self.startServer()\r\n\r\n def startServer(self):\r\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\r\n self.server_socket.bind((self.HOST, self.PORT))\r\n self.server_socket.listen(5)\r\n print(f\"[*] Waiting For Incoming Connections\")\r\n\r\n def acceptConnection(self):\r\n client_socket, address = self.server_socket.accept()\r\n client_socket.settimeout(10) # Set a timeout for the connection\r\n return client_socket, address\r\n\r\n def getCommandToBeSent(self, client_socket, address):\r\n client_ip_address, client_port = address[0], address[1]\r\n client_full_address = f\"{client_ip_address}:{client_port}\"\r\n client_user_name = self.user.username.lower() or 'client'\r\n\r\n while True:\r\n str_msg = input(f\"{client_user_name}@{client_full_address} >> \")\r\n\r\n if str_msg:\r\n break\r\n\r\n msg = dict({\r\n 'msg': str_msg\r\n }) \r\n\r\n return msg\r\n\r\n @staticmethod\r\n def displayReceivedMsg(received_msg: dict):\r\n return_code, stdout, stderr = received_msg['return_code'], received_msg['stdout'].decode(), received_msg['stderr'].decode()\r\n\r\n if return_code == 0:\r\n print(f\"{Colors.SUCCESS.value} {stdout} {Colors.RESET.value}\")\r\n else:\r\n print(f\"{Colors.FAIL.value} {stderr} {Colors.RESET.value}\")\r\n\r\n def keyExchange(self, _socket):\r\n self.sendMsg(_socket, {\r\n \"public_key\": self.public_key.export_key().decode(\"UTF-8\")\r\n })\r\n key_obj: dict = self.receiveMsg(_socket)\r\n received_key = key_obj['public_key']\r\n return received_key\r\n\r\n def onNewClient(self, client_socket, address):\r\n print(f\"[+] Connection established with ip - {address[0]}:{address[1]}\")\r\n\r\n received_key = self.keyExchange(client_socket)\r\n client_public_key = RSA.import_key(received_key)\r\n\r\n while True:\r\n msg: dict = self.getCommandToBeSent(client_socket, address)\r\n self.sendEncryptedMsg(client_socket, msg, client_public_key)\r\n\r\n if msg['msg'] == \"exit\":\r\n self.closeConnection(socket=client_socket, HOST=address[0], PORT=address[1])\r\n self.server_socket.close()\r\n sys.exit()\r\n\r\n received_msg = self.receiveEncryptedMsg(client_socket, self.private_key)\r\n self.displayReceivedMsg(received_msg)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n server = Server()\r\n \r\n while True:\r\n client_socket, address = server.acceptConnection()\r\n _thread.start_new_thread(server.onNewClient, (client_socket, address))\r\n\r\n except (socket.error, Exception) as error:\r\n print(f\"[-] Error : {error}\")\r\n sys.exit()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71935075","text":"from tkinter import *\nimport os\nfrom gtts import gTTS\nimport pygame\n\ndef play():\n text = input_field.get(\"1.0\", END)\n output = gTTS(text=text, lang='en', slow=False)\n output.save('output.mp3')\n pygame.mixer.music.load('output.mp3')\n pygame.mixer.music.play(loops=0)\n\n\nroot = Tk()\n\nroot.title('TTS')\nroot.geometry('300x350')\nroot.configure(background='black')\nroot.resizable(0, 0)\n\nLabel(root, text='Text-to-Speech Application', bg='#000', fg='#fff', font=('helvetica', 12, 'bold'), justify=CENTER).pack(fill=X, pady=5)\n\ninput_field = Text(root, height=15)\ninput_field.pack(fill=X, pady=5)\n\nButton(root, text=\"LISTEN\", command=play, bg=\"#2d3436\", fg=\"#ffffff\", bd=0, font=(\"helvetica\", 10, 'bold')).pack(pady=10)\n\nroot.mainloop()\n","sub_path":"Text to Speech GUI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222155794","text":"# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nimport time\nimport zipfile\nfrom custom_logging import CustomLogger\nfrom client_session_helper import boto3_client, boto3_session\n\nlogger = CustomLogger().logger\n\n\ndef download_file_from_pipeline_s3(job_data, artifact, file_in_zip, download_dir):\n \"\"\"Pulls artifact credentials from job_data then downloads specific file from the artifact to /tmp\n\n Args:\n job_data (dict): Job_data section of pipeline event\n artifact (dict): Artifact object from pipeline to pull file from\n file_in_zip (str): File within the artifact dict to download\n download_dir (str): Temporary directory to download file to\n\n Returns:\n str: Full path to the downloaded file\n \"\"\"\n logger.debug(f'Getting file ({file_in_zip}) from S3...')\n\n credentials = {\n 'AccessKeyId': job_data['artifactCredentials']['accessKeyId'],\n 'SecretAccessKey': job_data['artifactCredentials']['secretAccessKey'],\n 'SessionToken': job_data['artifactCredentials']['sessionToken']\n }\n session = boto3_session(credentials=credentials)\n\n bucket = artifact['location']['s3Location']['bucketName']\n artifact_path = artifact['location']['s3Location']['objectKey']\n zip_file = artifact_path.split('/')[2]\n\n try:\n logger.debug(f'Downloading {artifact_path} from S3 Bucket ({bucket})...')\n _response = s3_download_file(\n bucket_name=bucket,\n input_file_name=artifact_path,\n output_file_name=f\"{download_dir}/{zip_file}\",\n session=session\n )\n with zipfile.ZipFile(f\"{download_dir}/{zip_file}\", \"r\") as z:\n z.extract(file_in_zip, download_dir)\n\n return str(f\"{download_dir}/{file_in_zip}\")\n\n except (KeyError, AttributeError, OSError) as e:\n logger.error(f'Something went wrong trying to download file. {e}')\n raise Exception(str(e)) from e\n\n\ndef s3_download_file(bucket_name, input_file_name, output_file_name, session=None):\n \"\"\"Download a file from S3 to disk\n\n Args:\n bucket_name (str): Name of the bucket\n input_file_name (str): Name of the file to download from S3 (including path if necessary)\n output_file_name (str): Path to where the file should be downloaded to including its name\n session (object, optional): boto3 session object\n\n Returns:\n dict: Standard AWS response dict\n \"\"\"\n logger.debug(f\"bucket_name:{bucket_name}\")\n logger.debug(f\"input_file_name:{input_file_name}\")\n logger.debug(f\"output_file_name:{output_file_name}\")\n logger.debug(f\"session:{session}\")\n\n tries = 3\n count = 1\n client = boto3_client(service='s3', session=session)\n while True:\n try:\n logger.info(f\"Attempt {count} of {tries} to download file {input_file_name} from {bucket_name}\")\n response = client.download_file(bucket_name, input_file_name, output_file_name)\n return response\n\n except Exception as e:\n count += 1\n time.sleep(10)\n if count > tries:\n raise Exception(\n f\"Failed to download key {input_file_name} in bucket {bucket_name}: {str(e)}\"\n ) from e\n","sub_path":"src/s3_helper.py","file_name":"s3_helper.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"505231742","text":"from docusign_rooms import (\n FormGroupsApi,\n FormGroupSummaryList,\n OfficesApi,\n OfficeSummaryList,\n)\nfrom flask import session, request\n\nfrom app.rooms import create_rooms_api_client\n\n\nclass Eg008Controller:\n @staticmethod\n def get_args():\n \"\"\"Get required session and request arguments\"\"\"\n return {\n \"account_id\": session[\"ds_account_id\"], # Represents your {ACCOUNT_ID}\n \"access_token\": session[\"ds_access_token\"], # Represents your {ACCESS_TOKEN}\n \"form_group_id\": request.form.get(\"form_group_id\"),\n \"office_id\": request.form.get(\"office_id\")\n }\n\n @staticmethod\n def get_form_groups(args):\n \"\"\"\n 1. Create an API Client with headers\n 2. GET Form Groups via FormGroupsAPI\n \"\"\"\n\n api_client = create_rooms_api_client(access_token=args[\"access_token\"])\n\n # Step 4 start\n\n # GET Form Groups via FormGroupsAPI\n form_groups_api = FormGroupsApi(api_client)\n response = form_groups_api.get_form_groups(account_id=args[\"account_id\"]) # type: FormGroupSummaryList\n\n # Step 4 end\n\n return response.form_groups\n\n @staticmethod\n def get_offices(args):\n \"\"\"\n 1. Create an API Client with headers\n 2. Get Offices via OfficesAPI\n \"\"\"\n\n # Create an API with headers with headers\n api_client = create_rooms_api_client(args[\"access_token\"])\n\n # Step 3 start\n\n # GET offices via OfficesAPI\n offices_api = OfficesApi(api_client=api_client)\n response = offices_api.get_offices(account_id=args[\"account_id\"]) # type: OfficeSummaryList\n\n # Step 3 end\n\n return response.office_summaries\n\n @staticmethod\n def worker(args):\n \"\"\"\n 1. Create an API client with headers\n 2. Grant office access to a form group via FormGroups API\n \"\"\"\n\n # Step 2 start\n\n # Create an API client with headers\n api_client = create_rooms_api_client(access_token=args[\"access_token\"])\n\n # Step 2 end\n\n # Step 5 start\n\n # Grant office access to a form group via FormGroups API\n form_groups_api = FormGroupsApi(api_client)\n\n form_groups_api.grant_office_access_to_form_group(\n form_group_id=args[\"form_group_id\"], office_id=args[\"office_id\"],\n account_id=args[\"account_id\"]\n )\n\n # Step 5 end\n","sub_path":"app/rooms/examples/eg008_grant_office_access_to_form_group/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575185007","text":"from rest_framework import status\n\nfrom rest_framework.test import APIClient\n\nimport pytest\n\nfrom ..models import Post, Profile\nfrom .test_utils import author, non_author\n\n\n@pytest.mark.django_db\ndef test_author_permissions(client, author, non_author):\n \"\"\"should only allow authors to read posts\"\"\"\n client.force_login(non_author)\n blocked_response = client.get(\"/posts/\")\n\n client.force_login(author)\n permitted_response = client.get(\"/posts/\")\n\n assert blocked_response.status_code == status.HTTP_403_FORBIDDEN\n assert (\n blocked_response.json()[\"detail\"]\n == \"You do not have permission to perform this action.\"\n )\n\n assert permitted_response.status_code == status.HTTP_200_OK\n assert len(permitted_response.json()) == 1\n","sub_path":"2. Advance Your Skills in Python/5. Secure Coding in Python/Avoiding Python Pitfalls/Dynamic Typing/Django Files/post/test/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382543100","text":"import os,sys\nimport urllib.request\nfrom html.parser import HTMLParser\nimport time\nimport requests\nimport math\n\n\n\n#[url, line keyword, ip col, portcol, proxytype col] <<<<< later use array to check multiple sites with dif table setups too lazy right now\n#['http://www.socks-proxy.net/','Anonymous', 0,1,4]\n# target = 'https://www.xroxy.com/free-proxy-lists/' #0,1,2\n# target = 'https://www.xroxy.com/free-proxy-lists/?port=&type=Socks4&ssl=&country=&latency=1000&reliability=7500'\nsites = [['http://www.socks-proxy.net/','Anonymous', 0,1,4]]#,['http://www.socks-proxy.net/','Anonymous', 0,1,4]]\n\nglobal MAX_LAT; MAX_LAT = 3 #max latency\n\nbase_config = \"\"\"\\n# proxychains.conf VER 3.1\n#\n# HTTP, SOCKS4, SOCKS5 tunneling proxifier with DNS.\n#\t\n\n# The option below identifies how the ProxyList is treated.\n# only one option should be uncommented at time,\n# otherwise the last appearing option will be accepted\n#\n#dynamic_chain\n#\n# Dynamic - Each connection will be done via chained proxies\n# all proxies chained in the order as they appear in the list\n# at least one proxy must be online to play in chain\n# (dead proxies are skipped)\n# otherwise EINTR is returned to the app\n#\n#strict_chain\n#\n# Strict - Each connection will be done via chained proxies\n# all proxies chained in the order as they appear in the list\n# all proxies must be online to play in chain\n# otherwise EINTR is returned to the app\n#\nrandom_chain\n#\n# Random - Each connection will be done via random proxy\n# (or proxy chain, see chain_len) from the list.\n# this option is good to test your IDS :)\n\n# Make sense only if random_chain\nchain_len = 1\n\n# Quiet mode (no output from library)\n#quiet_mode\n\n# Proxy DNS requests - no leak for DNS data\nproxy_dns \n\n# Some timeouts in milliseconds\ntcp_read_time_out 5000\ntcp_connect_time_out 5000\n[ProxyList]\\n\"\"\"\n\n\nclass HTMLTableParser(HTMLParser):\n \"\"\" This class serves as a html table parser. It is able to parse multiple\n tables which you feed in. You can access the result per .tables field.\n \"\"\"\n def __init__(\n self,\n decode_html_entities=False,\n data_separator=' ',\n ):\n\n HTMLParser.__init__(self)\n\n self._parse_html_entities = decode_html_entities\n self._data_separator = data_separator\n\n self._in_td = False\n self._in_th = False\n self._current_table = []\n self._current_row = []\n self._current_cell = []\n self.tables = []\n\n def handle_starttag(self, tag, attrs):\n \"\"\" We need to remember the opening point for the content of interest.\n The other tags (, ) are only handled at the closing point.\n \"\"\"\n if tag == 'td':\n self._in_td = True\n if tag == 'th':\n self._in_th = True\n\n def handle_data(self, data):\n \"\"\" This is where we save content to a cell \"\"\"\n if self._in_td or self._in_th:\n self._current_cell.append(data.strip())\n\n def handle_charref(self, name):\n \"\"\" Handle HTML encoded characters \"\"\"\n\n if self._parse_html_entities:\n self.handle_data(self.unescape('&#{};'.format(name)))\n\n def handle_endtag(self, tag):\n \"\"\" Here we exit the tags. If the closing tag is , we know that we\n can save our currently parsed cells to the current table as a row and\n prepare for a new row. If the closing tag is
, we save the\n current table and prepare for a new one.\n \"\"\"\n if tag == 'td':\n self._in_td = False\n elif tag == 'th':\n self._in_th = False\n\n if tag in ['td', 'th']:\n final_cell = self._data_separator.join(self._current_cell).strip()\n self._current_row.append(final_cell)\n self._current_cell = []\n elif tag == 'tr':\n self._current_table.append(self._current_row)\n self._current_row = []\n elif tag == 'table':\n self.tables.append(self._current_table)\n self._current_table = []\n\ndef ProxyTest(proxtyp, proxip,proxport):\n\tstart_time = time.time()\n# 119.15.155.77:49343\n# 119.15.155.77:49343\n# 6.66.45.22:4145\n\tglobal MAX_LAT\n\t\n\ttry:\n\t\tproxies = {'http':'%s://%s:%s'%(proxtyp,proxip,proxport)}\n\t\tr = requests.get('http://www.google.com', proxies = proxies, timeout=MAX_LAT)\n\t\t# print(r.status_code)\n\t\tstatusCode = str(r.status_code)\n\t\tif statusCode==\"200\":\n\t\t\tend_time = time.time() - start_time\n\t\t\tif end_time < MAX_LAT:\n\t\t\t\tprint(\"Passed (%s ms)\"%math.trunc(end_time * 1000))\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\texcept:\n\t\t\n\t\treturn False\n\n\n\n\nprint(\"ProxyFresh a tool to update proxychains proxy list. \\nDrift was here!\")\n\t\nfor site in sites:\n\ttarget = site[0]\n\tprint(\"ProxyFresh- Loading list from %s\" %target)\n\n\t# get website content\n\treq = urllib.request.Request(url=target, headers={'User-Agent': 'Mozilla/5.0'})\n\tf = urllib.request.urlopen(req)\n\txhtml = f.read().decode('utf-8')\n\t# instantiate the parser and feed it\n\tp = HTMLTableParser()\n\tp.feed(xhtml)\n\n\t#make sure orig is backed up\n\tif not os.path.isfile('/etc/proxychains.conf.bak'): \n\t\tos.system(\"mv -f /etc/proxychains.conf /etc/proxychains.conf.bak\")\n\n\tf = open('/etc/proxychains.conf','w')\n\tf.write(base_config)\n\tcnt = 0\n\t#print(p.tables)\n\tfor a in p.tables:\n\t\tfor b in a:\n\t\t\t# print(\"%s\\n\\n\"%b)\n\n\t\t\tif 'Anonymous' or 'Distorting' in b:\n\t\t\t\t# print(b)\n\t\t\t\tif len(b) < 5:\n\t\t\t\t\tcontinue\n\t\t\t\tip = b[site[2]]\n\t\t\t\tport = b[site[3]]\n\t\t\t\tproxtype = b[site[4]]\n\n\t\t\t\t# print(proxtype)\n\t\t\t\tif proxtype.lower() != 'socks4' or 'socks5':\n\t\t\t\t\tproxtype = 'socks4'\n\n\t\t\t\tprint(\"Testing %s://%s:%s--->\" %(proxtype.lower(),ip,port),end=\"\",file=sys.stdout, flush=True),\n\t\t\t\tif ProxyTest(proxtype.lower(),ip,port):\n\t\t\t\t\tprint(\"+++%s://%s:%s\" %(proxtype.lower(),ip,port))\n\t\t\t\t\tf.write(\"%s %s %s\\n\" %(proxtype.lower(),ip,port))\n\t\t\t\t\tcnt += 1\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Failed\"),\nprint(\"ProxyFresh- Added %s proxies to /etc/proxychains.conf\" %cnt)\nf.close()","sub_path":"proxyfresh.py","file_name":"proxyfresh.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515909093","text":"import collections\n\ndef migratoryBirds(arr):\n list_of_birds = collections.Counter(arr)\n migrating_birds_id = []\n max_birds = max(list_of_birds.values())\n for key, value in list_of_birds.items():\n if value == max_birds:\n migrating_birds_id.append(key)\n\n return min(migrating_birds_id)\n\n\nprint(migratoryBirds([1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4]))\n","sub_path":"src/Week9/migrating_birds.py","file_name":"migrating_birds.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"351799156","text":"import os\nfrom unittest import mock, skip, skipIf\n\nimport requests_mock\n\nfrom ussd.tests import UssdTestCase\n\n\n@skipIf(os.getenv('CI', None), \"Hangs in CI. Needs to be fixed\")\nclass TestHttpScreen(UssdTestCase.BaseUssdTestCase):\n validation_error_message = dict(\n screen_name=\"Screen not available\",\n http_invalid_screen=dict(\n next_screen=['This field is required.'],\n session_key=['This field is required.'],\n http_request=['This field is required.']\n ),\n http_screen_invalid_method=dict(\n http_request=dict(\n method=['Must be one of: post, get, put, delete.'],\n )\n ),\n http_screen_invalid_synchronous=dict(\n synchronous=['Not a valid boolean.']\n )\n )\n\n def test(self):\n with requests_mock.Mocker() as m:\n m.get(requests_mock.ANY, json={\"balance\": 250})\n m.post(requests_mock.ANY, json={\"balance\": 250})\n ussd_client = self.ussd_client()\n\n self.assertEqual(\n \"Testing response is being saved in \"\n \"session status code is 200 and \"\n \"balance is 250 and full content {'balance': 250}.\\n\",\n ussd_client.send('')\n )\n history = m.request_history\n assert history[0].method == 'GET'\n assert history[0].qs == {'phone_number': ['200'], 'session_id': [ussd_client.session_id]}\n assert not history[0].verify\n\n assert history[1].method == 'GET'\n\n assert history[2].method == 'POST'\n assert history[2].qs == {'phone_numbers': ['200', '201', '202'], 'session_id': [ussd_client.session_id]}\n assert history[2].verify\n\n @mock.patch(\"ussd.screens.http_screen.http_task.delay\")\n def test_async_workflow(self, mock_http_task):\n with requests_mock.Mocker() as m:\n m.get(requests_mock.ANY, json={\"balance\": 250})\n m.post(requests_mock.ANY, json={\"balance\": 250})\n\n ussd_client = self.ussd_client()\n ussd_client.send('')\n\n # check http_task is called\n mock_http_task.assert_called_once_with(\n request_conf=dict(\n method='get',\n url=\"https://localhost:8000/mock/submission\",\n params={'phone_number': '200',\n 'session_id': ussd_client.session_id}\n )\n )\n\n def test_json_decoding(self):\n with requests_mock.Mocker() as m:\n m.get(requests_mock.ANY, text='Balance is 257')\n m.post(requests_mock.ANY, text='Balance is 257')\n\n ussd_client = self.ussd_client()\n ussd_client.send('')\n\n self.assertEqual(\n \"Testing response is being saved in \"\n \"session status code is 200 and \"\n \"balance is and full content Balance is 257.\\n\",\n ussd_client.send('')\n )\n","sub_path":"ussd/tests/test_http_screen.py","file_name":"test_http_screen.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361262869","text":"#!/usr/bin/env python\n\"\"\"\nCollection specifically for dealing with a specific users private flags\n\nhttp://xkcd.com/353/\n\nJosh Ashby\n2013\nhttp://joshashby.com\njoshuaashby@joshashby.com\n\"\"\"\nimport models.redis.baseRedisModel as brm\nimport models.couch.baseCouchCollection as bcc\nimport models.couch.flag.flagModel as fm\nimport config.config as c\n\n\nclass userFlagsCollection(bcc.baseCouchCollection):\n \"\"\"\n Attempts to provide a collection for `Documents` providing\n a way to customize the creation of each object, and a way to sort\n the objects by various fields. Inheriting classes should only need\n to override `preInitAppend` and `postInitAppend` currently.\n \"\"\"\n def __init__(self, userID, couch=c.database.couchServer):\n \"\"\"\n Initializes the object, getting the list of ID's which will result in\n the collection being built when `fetch()` is called.\n\n :param model: A model which inherits from both `couchdb.Document`\n and `baseCouchModel`\n :param couch: The couchdb instance which this collection should use\n \"\"\"\n self._view = \"typeViews/flagByUserID\"\n self._collection = []\n self.couch = couch\n self.model = fm.flagORM\n self.userID = userID\n self.pattern = \"couch:\" + self.model._name + \":user:\" + self.userID\n self.pail = brm.redisList(self.pattern)\n if not self.pail:\n self.update()\n\n def update(self):\n \"\"\"\n Updates the internal list of objects, stored in a couch list, deleting\n keys that no longer exist, and adding new keys that are not currently\n part of the collection.\n \"\"\"\n keys = [ item.id for item in self.model.getAll(self._view, self.userID) ]\n self.pail = brm.redisList(self.pattern, keys, reset=True)\n","sub_path":"flagr_core/models/couch/flag/collections/userFlagsCollection.py","file_name":"userFlagsCollection.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170184216","text":"from . import NotifyOutput\nfrom twilio.rest import TwilioRestClient as TwilioClient\n\n\nclass SmsOutput(NotifyOutput):\n def __init__(self, config_file, perform=True):\n super(SmsOutput, self).__init__('SmsOutput', config_file=config_file, perform=perform)\n self._twilio_client = TwilioClient(\n self._config['notify']['sms']['twilio_account_sid'],\n self._config['notify']['sms']['twilio_auth_token']\n )\n\n def send_message(self, body):\n message = self._twilio_client.messages.create(\n from_=self._from,\n to=self._to,\n body=body\n )\n print('Message', message.sid, 'sent')\n","sub_path":"sentry/output/notify/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167846224","text":"import sys\nsys.path.append('../libraries/python/')\nfrom super7 import Super7, BaudRates\nimport serial.tools.list_ports\nimport time\n\nTOTAL_CHARS = 24\n\ns7 = Super7(serial.tools.list_ports.comports()[0].device,\n baudrate=BaudRates.BAUD_38400)\n\nmsg = ([' '] * TOTAL_CHARS) + [chr(i) for i in range(32, 123)]\nmsg = ''.join(msg)\nfor i in range(len(msg) + 1):\n extra = msg[i:i + TOTAL_CHARS].count('.')\n s7.write(msg[i:i + TOTAL_CHARS + extra])\n time.sleep(0.05)\n\ns7.clear()\n\nfor i in range(0, 64 - TOTAL_CHARS):\n s7.send_raw([i + a for a in range(TOTAL_CHARS)])\n time.sleep(0.05)\n\nfor i in range(1, 11):\n s7.set_brightness(i)\n time.sleep(0.5)\n\ns7.clear()\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"267243604","text":"import plotly.figure_factory as ff\nimport numpy as np\nimport plotly\n\ndisease = ['Amebiasis', 'Dengue Virus Infection', 'Salmonellosis', 'Campylobacteriosis']\ncounty = ['Alameda', 'Los Angeles', 'San Diego', 'San Francisco']\ncases = np.array([[12, 75, 62, 52],\n [5, 36, 8, 7],\n [272, 1228, 534, 174],\n [391, 1573, 841, 389]])\n\nfig = ff.create_annotated_heatmap(z=cases, x=disease, y=county, annotation_text=cases, colorscale='Viridis')\n\nfig.update_layout(title='Disease by California County')\nplotly.offline.plot(fig, filename='heatmap_plotlygo_ca_disaese.html')\nfig.show()\n","sub_path":"plotly/heatmap/heatmap_plotlygo.py","file_name":"heatmap_plotlygo.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115775578","text":"def build_heap(nums, index, size):\n \"\"\"\n 堆:是一种完全二叉树,按不同的性质分成两种:大顶堆和小顶堆\n 1.大顶堆:每个节点的值大于或等于其左右子节点的值\n 2.小顶堆:每个节点的值小于或等于其左右子节点的值\n 一般升序排序则构建大顶堆,降序排序则构建小顶堆\n \"\"\"\n # 当前节点索引\n large_index = index\n # 左节点索引\n left_index = 2*index + 1\n # 右节点索引\n right_index = 2*index + 2\n # 判断当前节点的值与其左右节点的值的大小\n if left_index < size and nums[left_index] > nums[large_index]:\n large_index = left_index\n if right_index < size and nums[right_index] > nums[large_index]:\n large_index = right_index\n # 如果large_index!=index 代表需要调整当前节点\n if large_index != index:\n nums[index], nums[large_index] = nums[large_index], nums[index]\n # 同时对该节点继续延伸调整\n build_heap(nums, large_index, size)\n\n\ndef heap_sort(nums):\n \"\"\"\n 堆排序\n 任何情况下的时间复杂度都为 O(n*logn)\n :param nums: unsorted list\n :return: list\n \"\"\"\n size = len(nums)\n for i in range(size//2 - 1, -1, -1):\n build_heap(nums, i, size)\n for i in range(size-1, 0, -1):\n # 0索引位置的值就是堆顶的值,也就是最大值,移到数组的最右边\n nums[0], nums[i] = nums[i], nums[0]\n # 每次都从0索引位置开始构建, 同时把最大的值移除,不加入堆的构建\n build_heap(nums, 0, i)\n print(f\"堆排序的结果: {nums}\")\n return nums\n\n\nif __name__ == '__main__':\n s = input(\"请输入要排序的数字,以','隔开:\")\n unsorted_list = [int(i) for i in s.strip().split(',')]\n heap_sort(unsorted_list)\n","sub_path":"sort/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550933862","text":"\n\n#calss header\nclass _INTERACTIVE():\n\tdef __init__(self,): \n\t\tself.name = \"INTERACTIVE\"\n\t\tself.definitions = [u'An interactive system or computer program is designed to involve the user in the exchange of information: ', u'involving communication between people: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_interactive.py","file_name":"_interactive.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"144908031","text":"import pymysql.cursors\nimport logging\nimport sys\nimport socket\nimport netifaces\nfrom subprocess import Popen, PIPE\nfrom picamera import PiCamera\nfrom datetime import datetime\nfrom pytz import timezone\n\n\ndef take_picture():\n\tcamera = PiCamera()\n\n\tcamera.start_preview()\n\ttdatetime = datetime.now(timezone('UTC'))\n\t#tstr = tdatetime.strftime('%Y%m%d_%H%M_%s')\n\tjdatetime = tdatetime.astimezone(timezone('Asia/Tokyo'))\n\tjstr = jdatetime.strftime('%Y%M%d_%H%M_%s')\n\tfilename = \"pictures/\" + jstr + \".jpeg\"\n\tcamera.capture(filename)\n\tcamera.stop_preview()\n\n\ndef speak():\n# -*- coding: utf-8 -*-\n\n# Convert te\n\n\n# Speak te\n\n Te = \"2 3 \"\n p1 = Popen([aquestalkpi/AquesTalkPi, Te, \"|\", \"aplay\"]) \n aquestalkpi\n\ndef insert_kifu(user1, user2, winner, kifu):\n connection = pymysql.connect(\n host = \"localhost\",\n user = \"pi\",\n password = \"takeru_ryuou\",\n db = \"kifu\",\n charset = \"utf8\",\n cursorclass = pymysql.cursors.DictCursor )\n\n with connection.cursor() as cursor:\n sql = \"INSERT INTO kifu(USER1, USER2, WINNER, KIFU) VALUES(%s, %s, %s, %s)\"\n r = cursor.execute(sql, (user1, user2, winner, kifu))\n connection.commit()\n\n\ndef start_menu():\n print(\"Input Users.\")\n print(\"User1 : \")\n user1 = raw_input()\n print(\"User2 : \")\n user2 = raw_input()\n return([user1, user2])\n","sub_path":"modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369812148","text":"def text_stat(input_text):\r\n\r\n input_text_str = '\\n'.join(input_text).lower()\r\n\r\n print('Был использован следующий текст:')\r\n print('<--- Текст ---')\r\n for i in input_text:\r\n print(i)\r\n print('--- Текст --->')\r\n\r\n def stat_count(text):\r\n key_ = {i for i in text }\r\n return {i: text.count(i) for i in key_}\r\n\r\n def digit_count(text):\r\n digits_ = [i for i in text if i.isdigit()]\r\n return len(digits_)\r\n\r\n digits = digit_count(input_text_str)\r\n chars_stat = stat_count(input_text_str)\r\n words_stat = stat_count(input_text_str.split())\r\n\r\n main_dict_def = {'digits': digits, 'lines':len(input_text), 'chars_stat':chars_stat, 'words_stat':words_stat}\r\n return main_dict_def\r\n\r\ndef print_dict(dict_: dict, word):\r\n print(' <--- Статистика {} --- '.format(word))\r\n for k, v in sorted(dict_.items()):\r\n print('{} = {}'.format(repr(k), v))\r\n print(' --- Статистика {} ---> '.format(word))\r\n print()\r\n\r\ndef main_input():\r\n list_in = []\r\n print('Введите текст >>> ')\r\n\r\n while True:\r\n text = input()\r\n if text==\"\":\r\n return list_in\r\n else:\r\n list_in.append(text)\r\n\r\nmain_dict = dict(text_stat(main_input()))\r\n\r\nprint ('Всего цифр в тексте = {}'.format(main_dict.get('digits')))\r\nprint ('Всего строк в тексте = {}'.format(main_dict.get('lines')))\r\nprint_dict(main_dict.get('chars_stat'), 'символов')\r\nprint_dict(main_dict.get('words_stat'), 'слов')","sub_path":"hw_4_2.py","file_name":"hw_4_2.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"360797296","text":"\"\"\" BAlto is a Language independent Test Orchestrator.\n\"\"\"\nfrom __future__ import print_function, unicode_literals\n\nimport argparse\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport time\nimport webbrowser\nfrom multiprocessing import Process\n\nfrom balto._logging import setup_logging\nfrom balto.server import server\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\n \"directory\", help=\"The directory LITR should start looking for its config file\"\n )\n parser.add_argument(\n \"--interface\",\n \"-i\",\n help=\"which interface to start\",\n action=\"store\",\n default=\"web\",\n )\n parser.add_argument(\n \"--runner\",\n \"-r\",\n help=\"which runner to use\",\n action=\"store\",\n default=\"subprocess\",\n )\n parser.add_argument(\n \"--verbose\",\n \"-v\",\n help=\"activate the verbose mode\",\n action=\"store_true\",\n default=False,\n )\n parser.add_argument(\n \"--debug\", help=\"activate the debug mode\", action=\"store_true\", default=False\n )\n args = parser.parse_args()\n\n setup_logging(args.verbose, args.debug)\n\n # Launch the server\n port = 8889\n\n try:\n _server = Process(target=server, args=(args.directory, args.runner))\n _server.start()\n # server = subprocess.Popen(server_args)\n\n # Let the server starts\n time.sleep(1)\n\n # Launch the interface\n if args.interface == \"curses\":\n balto_interface = shutil.which(\"balto-curses\")\n\n env = os.environ.copy()\n env[\"BALTO_PORT\"] = \"%d\" % port\n\n interface = subprocess.Popen([balto_interface], env=env)\n interface.join()\n elif args.interface == \"web\":\n webbrowser.open(\n \"http://localhost:%d/interface/balto_react/build/index.html\" % port\n )\n _server.join()\n finally:\n _server.terminate()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"balto/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466018918","text":"import functools\nclass Solution:\n #f(i,j)=min(f(i,j),f(i,k−1)+f(k,j)+max(arr[i:k])∗max(arr[k:j+1]))\n def mctFromLeafValues(self, arr: List[int]) -> int:\n #res = float('inf')\n #@functools.lru_cache\n mem = {}\n def dfs(i, j):\n if i >= j:\n return 0\n \n if (i, j) in mem:\n return mem[(i, j)]\n \n #res = float('inf')\n min_v = min([dfs(i, k - 1) + dfs(k, j) + max(arr[i:k]) * max(arr[k: j + 1]) for k in range(i + 1, j + 1)])\n #print(min_v)\n #res = min_v\n mem[(i, j)] = min_v\n return mem[(i, j)]\n \n return dfs(0, len(arr) - 1)\n\n def mctFromLeafValues2(self, arr: List[int]) -> int:\n stack = [float('inf')]\n ret = 0\n for c in arr:\n while stack[-1] <= c:\n tmp = stack.pop()\n ret += tmp * min(stack[-1], c)\n stack.append(c)\n while len(stack) > 2:\n ret += stack.pop() * stack[-1]\n \n return ret \n \n \n ","sub_path":"Python/1130_Minimum Cost Tree From Leaf Values.py","file_name":"1130_Minimum Cost Tree From Leaf Values.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610519506","text":"\"\"\"\nGeneric, configurable scatterplot\n\"\"\"\nimport collections\nimport warnings\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\n\nclass PlottingAttribute(object):\n\n __slots__ = 'groupby', 'title', 'palette', 'group_to_attribute'\n\n def __init__(self, groupby, title, palette, order):\n \"\"\"An attribute that you want to visualize with a specific visual cue\n\n Parameters\n ----------\n groupby : mappable\n A series or dict or list to groupby on the rows of the data\n title : str\n Title of this part of the legend\n palette : list-like\n What to plot for each group\n \"\"\"\n self.groupby = groupby\n self.title = title\n self.palette = palette\n if order is not None:\n # there's more than one attribute\n self.group_to_attribute = dict(zip(order, palette))\n else:\n # There's only one attribute\n self.group_to_attribute = {None: palette[0]}\n\n def __getitem__(self, item):\n return self.group_to_attribute[item]\n\n\nclass PlotterMixin(object):\n\n \"\"\"\n Must be mixed with something that creates the ``self.plot_data`` attribute\n\n\n Attributes\n ----------\n\n color :\n\n\n\n \"\"\"\n # Markers that can be filled, in a reasonable order so things that can be\n # confused with each other (e.g. triangles pointing to the left or right) are\n # not next to each other\n filled_markers = (u'o', u'v', u's', u'*', u'h', u'<', u'H', u'x', u'8',\n u'>', u'D', u'd', u'^')\n linewidth_min, linewidth_max = 0.1, 5\n\n alpha_min, alpha_max = 0.1, 1\n\n size_min, size_max = 3, 30\n\n legend_order = 'color', 'symbol', 'linewidth', 'edgecolor', 'alpha', 'size'\n\n def establish_colors(self, color, hue, hue_order, palette):\n \"\"\"Get a list of colors for the main component of the plots.\"\"\"\n n_colors = None\n\n current_palette = sns.utils.get_color_cycle()\n\n\n color_labels = None\n color_title = None\n\n\n if color is not None and palette is not None:\n error = 'Cannot interpret colors to plot when both \"color\" and ' \\\n '\"palette\" are specified'\n raise ValueError(error)\n\n\n # Force \"hue\" to be a mappable\n if hue is not None:\n try:\n # Check if \"hue\" is a column in the data\n color_title = str(hue)\n hue = self.data[hue]\n except (ValueError, KeyError):\n # Hue is already a mappable\n if isinstance(hue, pd.Series):\n color_title = hue.name\n else:\n color_title = None\n\n # This will give the proper number of categories even if there are\n # more categories in \"hue_order\" than represented in \"hue\"\n hue_order = sns.utils.categorical_order(hue, hue_order)\n color_labels = hue_order\n hue = pd.Categorical(hue, hue_order)\n n_colors = len(self.plot_data.groupby(hue))\n else:\n if hue_order is not None:\n\n # Check if \"hue_order\" specifies rows in the data\n samples_to_plot = self.plot_data.index.intersection(hue_order)\n n_colors = len(samples_to_plot)\n if n_colors > 0:\n # Different color for every sample (row name)\n hue = pd.Series(self.plot_data.index,\n index=self.plot_data.index)\n\n else:\n error = \"When 'hue=None' and 'hue_order' is specified, \" \\\n \"'hue_order' must overlap with the data row \" \\\n \"names (index)\"\n raise ValueError(error)\n else:\n # Same color for everything\n hue = pd.Series('hue', index=self.plot_data.index)\n n_colors = 1\n\n if palette is not None:\n colors = sns.color_palette(palette, n_colors=n_colors)\n elif color is not None:\n colors = sns.light_palette(color, n_colors=n_colors)\n else:\n colors = sns.light_palette(current_palette[0],\n n_colors=n_colors)\n self.color = PlottingAttribute(hue, color_title, colors, hue_order)\n\n def _maybe_make_grouper(self, attribute, palette_maker, order=None,\n func=None, default=None):\n \"\"\"Create a Series from a single attribute, else make categorical\n\n Checks if the attribute is in the data provided, or is an external\n mapper\n\n Parameters\n ----------\n attribute : object\n Either a single item to create into a series, or a series mapping\n each sample to an attribute (e.g. the plotting symbol 'o' or\n linewidth 1)\n palette_maker : function\n Function which takes an integer and creates the appropriate\n palette for the attribute, e.g. shades of grey for edgecolor or\n linearly spaced sizes\n order : list\n The order to create the attributes into\n func : function\n A function which returns true if the attribute is a single valid\n instance, e.g. \"black\" for color or 0.1 for linewidth. Otherwise,\n we assume that \"attribute\" is a mappable\n\n Returns\n -------\n grouper : pandas.Series\n A mapping of the high dimensional data samples to the attribute\n \"\"\"\n\n title = None\n\n if func is None or func(attribute):\n # Use this single attribute for everything\n return PlottingAttribute(pd.Series(None, index=self.samples),\n title, (attribute,), order)\n else:\n\n try:\n # Check if this is a column in the data\n attribute = self.data[attribute]\n except (ValueError, KeyError):\n pass\n\n if isinstance(attribute, pd.Series):\n title = attribute.name\n order = sns.utils.categorical_order(attribute, order)\n\n palette = palette_maker(len(order))\n attribute = pd.Categorical(attribute, categories=order,\n ordered=True)\n return PlottingAttribute(pd.Series(attribute, index=self.samples),\n title, palette, order)\n\n def establish_symbols(self, marker, marker_order, text, text_order):\n \"\"\"Figure out what symbol put on the axes for each data point\"\"\"\n\n symbol_title = None\n\n if isinstance(text, bool):\n # Option 1: Text is a boolean\n if text:\n # 1a: text=True, so use the sample names of data as the\n # plotting symbol\n symbol_title = 'Samples'\n symbols = [str(x) for x in self.samples]\n symbol = pd.Series(self.samples, index=self.samples)\n else:\n # 1b: text=False, so use the specified marker for each sample\n symbol = self._maybe_make_grouper(marker, marker_order, str)\n if marker is not None:\n try:\n symbol_title = marker\n symbol = self.data[marker]\n symbols = sns.categorical_order(symbol, marker_order)\n except (ValueError, KeyError):\n # Marker is a single marker, or already a groupable\n if marker in self.filled_markers:\n # Single marker so make a tuple so it's indexable\n symbols = (marker,)\n else:\n # already a groupable object\n if isinstance(marker, pd.Series):\n symbol_title = marker.name\n n_symbols = len(self.plot_data.groupby(symbol))\n if n_symbols > len(self.filled_markers):\n # If there's too many categories, then\n # auto-expand the existing list of filled\n # markers\n multiplier = np.ceil(\n n_symbols/float(len(self.filled_markers)))\n filled_markers = list(self.filled_markers) \\\n * multiplier\n symbols = filled_markers[:n_symbols]\n else:\n symbols = self.filled_markers[:n_symbols]\n\n symbol = PlottingAttribute(symbol, symbol_title, symbols,\n marker_order)\n else:\n # Assume \"text\" is a mapping from row names (sample ids) of the\n # data to text labels\n text_order = sns.utils.categorical_order(text, text_order)\n symbols = text_order\n symbol = pd.Series(pd.Categorical(text, categories=text_order,\n ordered=True),\n index=self.samples)\n symbol = PlottingAttribute(symbol, symbol_title, symbols,\n text_order)\n if marker is not None:\n warnings.warn('Overriding plotting symbol from \"marker\" with '\n 'values in \"text\"')\n\n # Turn text into a boolean\n text = True\n\n self.symbol = symbol\n\n self.text = text\n\n def establish_symbol_attributes(self,linewidth, linewidth_order, edgecolor,\n edgecolor_order, alpha, alpha_order, size,\n size_order):\n self.edgecolor = self._maybe_make_grouper(\n edgecolor, self._edgecolor_palette, edgecolor_order,\n mpl.colors.is_color_like)\n self.linewidth = self._maybe_make_grouper(\n linewidth, self._linewidth_palette, linewidth_order, np.isfinite)\n self.alpha = self._maybe_make_grouper(\n alpha, self._alpha_palette, alpha_order, np.isfinite)\n self.size = self._maybe_make_grouper(\n size, self._size_palette, size_order, np.isfinite)\n\n @staticmethod\n def _edgecolor_palette(self, n_groups):\n return sns.color_palette('Greys', n_colors=n_groups)\n\n def _linewidth_palette(self, n_groups):\n return np.linspace(self.linewidth_min, self.linewidth_max, n_groups)\n\n def _alpha_palette(self, n_groups):\n return np.linspace(self.alpha_min, self.alpha_max, n_groups)\n\n def _size_palette(self, n_groups):\n return np.linspace(self.size_min, self.size_max, n_groups)\n\n def symbolplotter(self, xs, ys, ax, symbol, linewidth, edgecolor, **kwargs):\n \"\"\"Plots either a matplotlib marker or a string at each data position\n\n Wraps plt.text and plt.plot\n\n Parameters\n ----------\n xs : array-like\n List of x positions for data\n ys : array-like\n List of y-positions for data\n symbol : str\n What to plot at each (x, y) data position\n text : bool\n If true, then \"symboL\" is assumed to be a string and iterates over\n each data point individually, using plt.text to position the text.\n Otherwise, \"symbol\" is a matplotlib marker and uses plt.plot for\n plotting\n kwargs\n Any other keyword arguments to plt.text or plt.plot\n \"\"\"\n # If both the x- and y- positions don't have data, don't do anything\n if xs.empty and ys.empty:\n return\n\n if self.text:\n # Add dummy plot to make the axes in the right window\n ax.plot(xs, ys, color=None)\n # Plot each (x, y) position as text\n for x, y in zip(xs, ys):\n ax.text(x, y, symbol, **kwargs)\n else:\n # use plt.plot instead of plt.scatter for speed, since plotting all\n # the same marker shape and color and linestyle\n ax.plot(xs, ys, 'o', marker=symbol, markeredgewidth=linewidth,\n markeredgecolor=edgecolor, **kwargs)\n\n def annotate_axes(self, ax):\n \"\"\"Add descriptive labels to an Axes object.\"\"\"\n if self.xlabel is not None:\n ax.set_xlabel(self.xlabel)\n if self.ylabel is not None:\n ax.set_ylabel(self.ylabel)\n\n def establish_legend_data(self):\n self.legend_data = pd.DataFrame(dict(color=self.color.groupby,\n symbol=self.symbol.groupby,\n size=self.size.groupby,\n linewidth=self.linewidth.groupby,\n edgecolor=self.edgecolor.groupby,\n alpha=self.alpha.groupby),\n index=self.samples)\n self.legend_data = self.legend_data.reindex(columns=self.legend_order)\n\n def draw_symbols(self, ax, plot_kws):\n \"\"\"Plot each sample in the data\"\"\"\n\n plot_kws = {} if plot_kws is None else plot_kws\n\n for labels, df in self.legend_data.groupby(self.legend_order):\n\n # Get the attributes in order, using the group label to get the\n # attribute\n for name, label in zip(self.legend_order, labels):\n plot_kws[name] = getattr(self, name)[label]\n\n self.symbolplotter(df.iloc[:, 0], df.iloc[:, 1], **plot_kws)\n\n # Iterate over all the possible modifications of the points\n # TODO: add alpha and size\n # for i, (color_label, df1) in enumerate(self.plot_data.groupby(self.color.groupby)):\n # color = self.color.palette[i]\n # for j, (marker_label, df2) in enumerate(df1.groupby(self.symbol.groupby)):\n # symbol = self.symbol.palette[j]\n # for k, (lw_label, df3) in enumerate(df2.groupby(self.linewidth.groupby)):\n # linewidth = self.linewidth.palette[k]\n # for l, (ec_label, df4) in df3.groupby(self.edgecolor):\n # edgecolor = self.edgecolor.palette[l]\n # # and finally ... actually plot the data!\n # for m\n # self.symbolplotter(df4.iloc[:, 0], df4.iloc[:, 1],\n # symbol=symbol, color=color,\n # ax=ax, linewidth=linewidth,\n # edgecolor=edgecolor, **plot_kws)\n #\n\n\nclass ScatterPlotter(PlotterMixin):\n\n def __init__(self, data, x, y, color, hue, hue_order, palette, marker,\n marker_order, text, text_order, linewidth, linewidth_order,\n edgecolor, edgecolor_order, alpha, alpha_order, size,\n size_order):\n self.establish_data(data, x, y)\n self.establish_symbols(marker, marker_order, text, text_order)\n self.establish_symbol_attributes(linewidth, linewidth_order, edgecolor,\n edgecolor_order, alpha, alpha_order, size, size_order)\n self.establish_colors(color, hue, hue_order, palette)\n self.establish_legend_data()\n # import pdb; pdb.set_trace()\n\n def establish_data(self, data, x, y):\n if isinstance(data, pd.DataFrame):\n xlabel = data.columns[x]\n ylabel = data.columns[y]\n else:\n data = pd.DataFrame(data)\n xlabel = None\n ylabel = None\n\n self.data = data\n self.plot_data = self.data.iloc[:, [x, y]]\n self.xlabel = xlabel\n self.ylabel = ylabel\n\n self.samples = self.plot_data.index\n self.features = self.plot_data.columns\n self.n_samples = len(self.samples)\n self.n_features = len(self.features)\n\n def plot(self, ax, kwargs):\n self.draw_symbols(ax, kwargs)\n self.annotate_axes(ax)\n\n\ndef scatterplot(data, x=0, y=1, color=None, hue=None, hue_order=None,\n palette=None, marker='o', marker_order=None, text=False,\n text_order=None, linewidth=1, linewidth_order=None,\n edgecolor='k', edgecolor_order=None, alpha=1, alpha_order=None,\n size=7, size_order=None, ax=None, **kwargs):\n\n plotter = ScatterPlotter(data, x, y, color, hue, hue_order, palette,\n marker, marker_order, text, text_order, linewidth,\n linewidth_order, edgecolor, edgecolor_order,\n alpha, alpha_order, size, size_order)\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n","sub_path":"cupcake/scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":16979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286246444","text":"\"\"\"\nalert.py - An Alert in the monitoring system.\n\"\"\"\n\n__author__ = \"Thomas J. Daley, J.D.\"\n__version__ = \"0.0.2\"\n__date__ = \"27 Aug 2017\"\n\n# pylint: disable=R0902\n# I've looked this over and decided to stick with this implementation for now /tjd/\nclass Alert:\n \"\"\"\n Defines an Alert, which will be normalized across camera implementations.\n \"\"\"\n\n FIRST = 0\n UNKNOWN = 0\n HEALTH_CHECK = 1\n MOTION_DETECT = 2\n SOUND_DETECT = 3\n TAMPER_DETECT = 4\n SD_MISSING = 5\n SD_CORRUPT = 6\n SD_FULL = 7\n MAIL_TEST = 8\n REPORT = 9\n LAST = 9\n\n ALERT_NAMES = {\n \"en\": [\n \"Unknown\",\n \"Status OK\",\n \"Motion Detected\",\n \"Sound Detected\",\n \"Device Tampering\",\n \"SD Missing\",\n \"SD Corrupted\",\n \"SD Full\",\n \"Mail Test\",\n \"Report\"]\n }\n\n def __init__(self): #, *args, **nargs):\n \"\"\"\n Constructor that sets some internal flags and default values.\n \"\"\"\n self.fields = {}\n self.multipart_boundary = ''\n self.mime_version = ''\n self._text = []\n self._attachments = []\n self._date = ''\n self.sender = ''\n self.recipient = ''\n self.subject = ''\n self.alert_details = {}\n self.from_ip_address = None\n self.from_device_name = None\n self.from_device_serial_number = None\n self.from_device_mac = None\n self.from_stream_name = None\n self.from_manufacturer = None\n self.camera_class = None\n self.camera_class_name = None\n self._type = Alert.UNKNOWN\n self.cv2_image = None\n self.cv2_gray_image = None\n self.preview_file_name = None\n self.full_file_name = None\n self.numpy_image = None\n self.sms_text = None\n self.mail_text = None\n\n def get_type_name(self, language=\"en\", alert_type=None):\n ''' Return a name for the alert type '''\n\n if language not in Alert.ALERT_NAMES:\n language = \"en\"\n\n if alert_type is None:\n alert_type = self._type\n\n if alert_type in Alert.ALERT_NAMES[language]:\n return Alert.ALERT_NAMES[language][alert_type]\n elif self.alert_details and \"event\" in self.alert_details:\n return self.alert_details[\"event\"]\n\n return \"Unknown event\"\n\n @property\n def type_value(self):\n ''' Gets the event type '''\n return self._type\n\n @type_value.setter\n def type_value(self, type_flag):\n ''' Sets the event type '''\n if type_flag in range(Alert.FIRST, Alert.LAST+1):\n self._type = type_flag\n else:\n raise Exception(\"Unknown event type value: {}\".format(type_flag))\n\n @property\n def has_date(self):\n ''' Returns True if date has been assigned, otherwise False. '''\n return self.date != ''\n\n @property\n def date(self):\n ''' Returns the date and time the alert was generated. '''\n return self._date\n\n @date.setter\n def date(self, date):\n ''' Need validation '''\n self._date = date\n\n @property\n def has_sender(self):\n ''' Returns True if sender has been assigned, otherwise False. '''\n return self.sender != ''\n\n @property\n def has_recipient(self):\n ''' Returns True if recipient has been assigned, otherwise False. '''\n return self.recipient != ''\n\n @property\n def has_subject(self):\n ''' Returns True if subject has been assigned, otherwise False. '''\n return self.subject != ''\n\n @property\n def has_mime_version(self):\n ''' Returns True if this alert has a MIME version, otherwise False '''\n return self.mime_version != ''\n\n @property\n def has_multipart_boundary(self):\n ''' Returns True if this alert has a multipart MIME boundary defined, otherwise False '''\n return self.multipart_boundary != ''\n\n @property\n def text(self):\n ''' Returns a list of lines of text from the data portion of this message '''\n return self._text\n\n @text.setter\n def text(self, zvalue):\n '''\n Appends a line of text to list of lines of text from the DATA portion\n of this message.\n '''\n self._text.append(zvalue)\n\n @property\n def attachment(self):\n '''\n Returns a list of non-text attachments arriving with this message.\n\n Each entry in the list is of the form {\"type\": \"\", \"content\": \"\"}\n '''\n return self._attachments\n\n @attachment.setter\n def attachment(self, zvalue, ztype):\n ''' Appends an attachment to the list of non-text attachments. '''\n self._attachments.append({\"type\": ztype, \"content\": zvalue})\n\n def sms_message(self, language=\"en\"):\n ''' Format a version of this alert suitable to SMS transmission. '''\n templates = {\n \"en\": \"{} reporting {}\",\n \"es\": \"{} reportando {}\"\n }\n\n if language not in templates:\n language = \"en\"\n\n template = templates[language]\n\n return template.format(\n self.from_stream_name,\n self.get_type_name(language=language))\n\n def mail_message(self, language=\"en\"):\n ''' Format a version of this alert suitable for Email transmission. '''\n templates = {\n \"en\": \"The {} camera reports: {}.\",\n \"es\": \"La camera {} informa: {}.\"\n }\n\n if language not in templates:\n language = \"en\"\n\n template = templates[language]\n\n return template.format(\n self.from_stream_name,\n self.get_type_name(language=language))\n\n def __str__(self):\n \"\"\"\n Overrides the default string representation.\n \"\"\"\n result = \"{} [From:{}] [To:{}] [Subject:{}]\".format(\n self.date, self.sender, self.recipient, self.subject\n )\n\n if self.mime_version != None:\n result += \" [{}]\".format(self.mime_version)\n\n if self.multipart_boundary != None:\n result += \" [{}]\\n\".format(self.multipart_boundary)\n\n if self.text:\n for text in self.text:\n result += text + \"\\n\\n\"\n\n attachment_count = len(self._attachments)\n result += \"Contains {} attachment(s)\".format(attachment_count)\n\n if attachment_count:\n for att in self._attachments:\n result += att[\"type\"] + \", \"\n\n return result\n","sub_path":"lib/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180123411","text":"# -*- coding: utf-8 -*-\n# ref https://medium.com/python-pandemonium/develop-your-first-web-crawler-in-python-scrapy-6b2ee4baf954\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom tutorial.items import OlxItem\nimport logging\n\n\nclass OlxSpider(CrawlSpider):\n name = 'olx'\n allowed_domains = ['www.olx.com.pk']\n start_urls = [\n 'https://www.olx.com.pk/computers-accessories/',\n #'https://www.olx.com.pk/tv-video-audio/',\n #'https://www.olx.com.pk/games-entertainment/'\n ]\n\n rules = (\n Rule(LinkExtractor(allow='', restrict_css=('.pageNextPrev',)),callback='parse_item', follow=False),\n )\n\n def parse_item(self, response):\n print('Processing..' +response.url)\n logging.warning(\"This is a warning\")\n item_links=response.css('.large > .detailsLink::attr(href)').extract()\n\n for a in item_links:\n yield scrapy.Request(a,callback=self.parse_detail_page)\n #i = {}\n #i['domain_id'] = response.xpath('//input[@id=\"sid\"]/@value').extract()\n #i['name'] = response.xpath('//div[@id=\"name\"]').extract()\n #i['description'] = response.xpath('//div[@id=\"description\"]').extract()\n #return i\n\n def parse_detail_page(self,response):\n title = response.css('h1::text').extract()[0].strip()\n price = response.css('.pricelabel > strong::text').extract()[0]\n\n item = OlxItem()\n item['title'] = title\n item['price'] = price\n item['url'] = response.url\n #iterator function \n yield item\n \n","sub_path":"tutorial/tutorial/spiders/olx_crawl.py","file_name":"olx_crawl.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"495835363","text":"import numpy as np\nfrom pprint import pprint\n\n\nclass Config:\n # data\n voc_data_dir = '/home/lz/Lab/pytorch/pytorch_az/datasets/tomato/'\n min_size = 400\n max_size = 800\n\n num_workers = 32\n n_class = 2\n\n\n sub_divide = np.array([[0, 0, 0.5, 0.5],\n [0, 0.5, 0.5, 1],\n [0.5, 0, 1, 0.5],\n [0.5, 0.5, 1, 1],\n [0.25, 0.25, 0.75, 0.75]])\n\n\n\n\n SEAR_MIN_SIDE = 10\n # zoom label\n max_area_ratio = 0.25\n min_overlaps = 0.5\n\n # Visualize\n env = 'ectractor_az'\n cls_env = 'classifier'\n plot_every = 10\n\n # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16\n DEDUP_BOXES = 1. / 16.\n\n\n\n # train\n az_lr = 0.001\n az_lr_decay = 0.2\n az_epoch = 1000\n\n az_train_num_proposals = 256\n az_pos_ratio = 0.4\n\n cls_lr = 0.001\n cls_lr_decay = 0.2\n cls_epoch = 1000\n\n BN = False\n\n # sigma for l1_smooth_loss\n az_sigma = 1.\n roi_sigma = 1.\n\n weight_decay = 0.0005\n # Overlap threshold for a ROI to be considered background (class = 0 if\n # overlap in [LO, HI))\n TRAIN_BG_THRESH_LO = 0.1\n TRAIN_BG_THRESH_HI = 0.5\n # Overlap required between a ROI and ground-truth box in order for that ROI to\n # be used as a bounding-box regression training example\n TRAIN_BBOX_THRESH=0.5\n\n # Fraction of minibatch that is labeled foreground (i.e. class > 0)\n TRAIN_FG_FRACTION = 0.1\n\n # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)\n TRAIN_FG_THRESH = 0.5\n\n TRAIN_REP = 8\n TRAIN_NUM_PROPOSALS = 2000\n TRAIN_ADDREGIONS = [[0, 0, 1, 1],\n [0, 0, 0.8, 0.8],\n [0, 0.2, 0.8, 1],\n [0.2, 0, 1, 0.8],\n [0.2, 0.2, 1, 1]]\n\n SEAR_ZOOM_ERR_PROB = 0.3\n SEAR_ADJ_THRESH = 0.1\n # batch size of region processing (to prevent excessive GPU memory consumption)\n SEAR_BATCH_SIZE = 5000\n SUBREGION = [[0, 0, 1, 1],\n [-0.5, 0, 0.5, 1], [0.5, 0, 1.5, 1],\n [0, -0.5, 1, 0.5], [0, 0.5, 1, 1.5],\n [0, 0, 0.5, 1], [0.5, 0, 1, 1],\n [0, 0, 1, 0.5], [0, 0.5, 1, 1],\n [0.25, 0, 0.75, 1], [0, 0.25, 1, 0.75]]\n NUM_SUBREG = len(SUBREGION)\n SEAR_SCALE_ADJ_CONF = False\n\n TEST_NUM_PROPOSALS = 300\n\n # threshold in confidence score\n SEAR_Tc = 0.05\n SEAR_FIXED_PROPOSAL_NUM = True\n SEAR_NUM_PROPOSALS = 2000\n\n\n\n EPS = 1e-14\n vis_threshold = 0.5\n\n\n USE_GPU_NMS = True\n GPU_ID = 0\n Use_classifier_extractor = False\n\n # threshold at zoom indicator\n def Tz(self, mode, thresh=0.0):\n if mode == 'Train':\n return thresh\n else:\n threshold = 0.01\n return threshold\n\n\n\n def _parse(self, kwargs):\n print(kwargs)\n state_dict = self._state_dict()\n for k, v in kwargs.items():\n if k not in state_dict:\n raise ValueError('UnKnown Option: \"--%s\"' % k)\n setattr(self, k, v) # setattr(x, 'y', v) is equivalent to ``x.y = v''\n\n print('************use config************')\n pprint(self._state_dict())\n\n def _state_dict(self):\n return {k: getattr(self, k) for k, _ in Config.__dict__.items() \\\n if not k.startswith('_')}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nopt = Config()","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205090924","text":"import grpc\nimport json\nimport libs.et_service_pb2 as et_service_pb2\nimport libs.et_service_pb2_grpc as et_service_pb2_grpc\nfrom main_service.feature_extraction import Features\n\n\nclass GrpcHandler:\n\n def __init__(self, server_ip_port, manager_id, manager_email, campaign_id):\n self.channel = grpc.insecure_channel(server_ip_port)\n self.stub = et_service_pb2_grpc.ETServiceStub(self.channel)\n self.manager_id = manager_id\n self.manager_email = manager_email\n self.campaign_id = campaign_id\n\n def grpc_close(self):\n self.channel.close()\n\n def grpc_load_user_emails(self):\n user_info = {}\n # retrieve participant emails\n request = et_service_pb2.RetrieveParticipants.Request( # Kevin\n userId=self.manager_id,\n email=self.manager_email,\n campaignId=self.campaign_id\n )\n response = self.stub.retrieveParticipants(request)\n if not response.success:\n return False\n for idx, email in enumerate(response.email):\n user_info[email] = {}\n user_info[email]['uid'] = response.userId[idx]\n # user_info.append((email, response.userId[idx]))\n\n for email, id in user_info.items():\n request = et_service_pb2.RetrieveParticipantStats.Request( # Kevin\n userId=self.manager_id,\n email=self.manager_email,\n targetEmail=email,\n targetCampaignId=self.campaign_id\n )\n response = self.stub.retrieveParticipantStats(request) # Kevin\n if not response.success:\n return False\n\n user_info[email]['joinedTime'] = response.campaignJoinTimestamp\n\n return user_info\n\n def grpc_get_campaign_info(self):\n # retrieve campaign details --> data source ids\n request = et_service_pb2.RetrieveCampaign.Request( # Kevin\n userId=self.manager_id,\n email=self.manager_email,\n campaignId=self.campaign_id\n )\n response = self.stub.retrieveCampaign(request)\n if not response.success:\n return None\n\n return response\n\n def grpc_load_user_data(self, from_ts, uid, data_sources, data_src_for_sleep_detection):\n # retrieve data of each participant\n data = {}\n for data_source_name in data_sources:\n # from_time for screen on and off must be more amount of data to detect sleep duration\n if data_source_name == data_src_for_sleep_detection:\n from_time = from_ts - 48 * 60 * 60 * 1000\n elif data_source_name == Features.LOCATIONS_MANUAL or data_source_name == Features.STRESS_LVL_THRESHOLDS: # take all data for LOCATIONS_MANUAL and STRESS_LVL_THRESHOLDS\n from_time = 0\n else:\n from_time = from_ts\n\n data[data_source_name] = []\n data_available = True\n while data_available:\n grpc_req = et_service_pb2.Retrieve100DataRecords.Request( # Kevin\n userId=self.manager_id,\n email=self.manager_email,\n targetEmail=uid,\n targetCampaignId=self.campaign_id,\n targetDataSourceId=data_sources[data_source_name],\n fromTimestamp=from_time\n )\n grpc_res = self.stub.retrieve100DataRecords(grpc_req)\n if grpc_res.success:\n for timestamp, value in zip(grpc_res.timestamp, grpc_res.value):\n from_time = timestamp\n data[data_source_name] += [(timestamp, value)]\n data_available = grpc_res.success and grpc_res.moreDataAvailable\n return data\n\n def grpc_send_user_data(self, user_id, user_email, data_src, timestamp, value):\n req = et_service_pb2.SubmitDataRecords.Request( # Kevin\n userId=user_id,\n email=user_email,\n campaignId=self.campaign_id\n )\n req.timestamp.extend([timestamp])\n req.dataSource.extend([data_src])\n req.accuracy.extend([1])\n req.values.extend([value])\n\n response = self.stub.submitDataRecords(req)\n print(response)\n","sub_path":"main_service/grpc_handler.py","file_name":"grpc_handler.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"442217678","text":"import unittest\nimport stop\n\n\nclass TestStopRoutes(unittest.TestCase):\n\n def setUp(self):\n stop.app.config['TESTING'] = True\n self.app = stop.app.test_client()\n\n\n def test_stops_get(self):\n response = self.app.get('/stops?lat=1.0&lon=2.0')\n self.assertEqual(response.status_code, 200)\n\n def test_stopsrequests_post(self):\n jsonString = '{\"trip_id\": \"1234\", \"stop_id\": \"HSL:1282106\", \"device_id\": \"123\", \"push_notification\": false}'\n response = self.app.post('/stoprequests', data=jsonString, content_type='application/json')\n self.assertEquals(response.status_code, 200)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"src/tests/test_stop.py","file_name":"test_stop.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37575316","text":"import os\nimport random\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, Sampler\nfrom PIL import Image\nimport torchvision\nimport torch.nn as nn\nfrom classifiers import EuclideanClassifier\nfrom networks import ConvNet4, ResNet12\nimport dataload\nfrom utils import compute_confidence_interval, loadLogger\nimport argparse\nimport torch.optim as optim\nfrom tqdm import tqdm\n\n\nclass Model:\n def __init__(self, args, image_channel, out_channel, image_size, logger):\n if args.backbone == 'ResNet12':\n self.net = ResNet12(image_channel, image_size)\n else:\n self.net = ConvNet4(image_channel, out_channel, image_size)\n self.classifier = EuclideanClassifier(args)\n if torch.cuda.is_available():\n print('GPU is used!')\n logger.info('GPU is used!')\n self.models_on_cuda()\n else:\n print('cuda is not running')\n logger.info('cuda is not running')\n self.optimizer = torch.optim.Adam(self.net.parameters(), lr=0.001)\n self.loss_fn = nn.CrossEntropyLoss()\n self.n_way = args.n_way\n self.k_shot = args.k_shot\n self.q_query = args.q_query\n self.dataset = args.dataset\n self.logger = logger\n\n def train(self, epoch, episodes, train_folders, print_each=20):\n self.net.train()\n self.classifier.train()\n loss_avg = 0\n for i in tqdm(range(episodes)):\n task = dataload.FewShotTask(train_folders, self.n_way, self.k_shot, self.q_query, self.dataset)\n spt_loader = dataload.get_Dataloader(task, self.k_shot, 'support')\n qry_loader = dataload.get_Dataloader(task, self.q_query, 'query', shuffle=True)\n spt, spt_y = iter(spt_loader).next()\n qry, qry_y = iter(qry_loader).next()\n if torch.cuda.is_available():\n spt, spt_y, qry, qry_y = self.datas_on_cuda(spt, spt_y, qry, qry_y)\n\n spt_feature = self.net(spt)\n qry_feature = self.net(qry)\n dist = self.classifier(spt_feature, qry_feature)\n loss = self.loss_fn(-dist, qry_y.long())\n loss_avg += loss.item()\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n if (i+1) % print_each == 0:\n print(\"epoch: {}\\tepisodes: {}\\tloss: {:.2f}\".format(epoch+1, i+1, loss_avg/1.0/print_each))\n self.logger.info(\"epoch: {}\\tepisodes: {}\\tloss: {:.2f}\".format(epoch+1, i+1, loss_avg/1.0/print_each))\n loss_avg = 0\n\n def val(self, episodes, val_folders):\n self.net.eval()\n self.classifier.eval()\n accs = []\n for i in range(episodes):\n task = dataload.FewShotTask(val_folders, self.n_way, self.k_shot, self.q_query, self.dataset)\n spt_loader = dataload.get_Dataloader(task, self.k_shot, 'support')\n qry_loader = dataload.get_Dataloader(task, self.q_query, 'query', shuffle=True)\n spt, spt_y = iter(spt_loader).next()\n qry, qry_y = iter(qry_loader).next()\n if torch.cuda.is_available():\n spt, spt_y, qry, qry_y = self.datas_on_cuda(spt, spt_y, qry, qry_y)\n\n spt_feature = self.net(spt)\n qry_feature = self.net(qry)\n dist = self.classifier(spt_feature, qry_feature)\n predict_label = torch.argmin(dist, dim=1)\n score = [1 if predict_label[j] == qry_y[j].long() else 0 for j in range(len(qry_y))]\n acc = np.sum(score) / 1.0 / len(score)\n accs.append(acc)\n acc, pacc = compute_confidence_interval(accs)\n print('acc is {:.4f} pacc is {:.4f}'.format(acc, pacc))\n self.logger.info('acc is {:.4f} pacc is {:.4f}'.format(acc, pacc))\n return acc, pacc\n\n def models_on_cuda(self):\n self.net.cuda()\n\n def datas_on_cuda(self, spt, spt_y, qry, qry_y):\n spt = spt.cuda()\n spt_y = spt_y.cuda()\n qry = qry.cuda()\n qry_y = qry_y.cuda()\n return spt, spt_y, qry, qry_y\n\n\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113359821","text":"from intervaltree import IntervalTree\nfrom .taskunit import TaskUnit\nfrom .taskunitpriorityqueue import TaskUnitPriorityQueue\nfrom .exceptions import DuplicateTaskException\nfrom .conflict import Conflict, ConflictSet\nfrom datetime import datetime\n\nclass TaskSet(object):\n \"\"\"\n Holds a set of tasks in a priority queue.\n \"\"\"\n def __init__(self):\n self._tasksQueue = TaskUnitPriorityQueue() # keep r1 < r2 < r3 order.\n self._intervalTree = IntervalTree()\n\n\n @property\n def tasks(self):\n return self._tasksQueue.items()\n\n\n def add(self, task):\n if not self._tasksQueue.contains(task.taskID):\n self._addTaskToTree(task)\n self._tasksQueue.push(task)\n else:\n raise DuplicateTaskException\n\n\n def _addTaskToTree(self, task):\n \"\"\"\n Adds task to interval tree.\n \"\"\"\n self._intervalTree.addi(\n begin=task.release,\n end=task.deadline,\n data=task.taskID\n )\n\n\n def remove(self, task):\n self._intervalTree.discardi(task.release, task.deadline, task.taskID)\n self._tasksQueue.remove(task.taskID)\n\n\n def _findLatestInterval(self, intervals):\n \"\"\"\n Find the latest interval.\n \"\"\"\n latest = intervals[0]\n for interval in intervals:\n if interval.begin > latest.begin:\n latest = interval\n return latest\n\n def _orIntervals(self, intervalListA, intervalListB):\n return list(set(intervalListA) | set(intervalListB))\n\n def _conflictPath(self, interval, intervalTree):\n \"\"\"\n @param interval The interval to find conflicts with.\n @param intervalTree The intervalTree that contains all intervals\n Finds the longest number of intervals that are all overlapping (conflicting).\n For example:\n if A and B conflict and B and C conflict and A is the\n interval we're looking for conflicts with, the returned\n intervals will be A, B, C.\n Another example:\n if D and E conflict and F and G conflict, and we're looking\n for all conflicts with D, only D and E will be returned as\n F and G are not overlapping with either D and E.\n \"\"\"\n intervals = list(intervalTree.search(interval))\n # if only one interval, check if its the one we're\n # trying to find conflicts with.\n if len(intervals) == 1 and intervals[0] == interval:\n return []\n # now find the latest of all the intervals and get all conflicts\n # with and keep going until there are no more conflicts.\n latestInterval = self._findLatestInterval(intervals)\n # remove all the conflicts, we dont need to check them again.\n intervalTree.remove_overlap(interval)\n # put the latest conflict back into the tree and find its conflicts\n intervalTree.add(latestInterval)\n # now go find all conflicts with the latest interval until there are none.\n return self._orIntervals(intervals, self._conflictPath(latestInterval, intervalTree))\n\n\n def _intervalConflictAlreadyDetected(self, interval, conflicts):\n \"\"\"\n Checks to see if interval was already detected to conflict.\n \"\"\"\n for conflict in conflicts:\n for ival in conflict:\n if ival == interval:\n return True\n return False\n\n\n def findConflicts(self):\n \"\"\"\n Finds all conflicts within the task set.\n \"\"\"\n begin = self._intervalTree.begin()\n end = self._intervalTree.end()\n conflicts = []\n conflictObjs = []\n nonConflictsObjs = []\n intervals = sorted(self._intervalTree[begin:end])\n for interval in intervals:\n # check if this interval was already detected to conflict\n if self._intervalConflictAlreadyDetected(interval, conflicts):\n continue\n conflictIntervals = self._conflictPath(interval, self._intervalTree.copy())\n if len(conflictIntervals) > 0: # there was a conflict\n conflicts.append(conflictIntervals)\n conflictObjs.append(Conflict(conflictIntervals))\n else:\n nonConflictsObjs.append(Conflict(interval))\n return ConflictSet(conflictObjs), ConflictSet(nonConflictsObjs)\n\n\n def __iter__(self):\n return self._tasksQueue\n","sub_path":"QuickProactive/proactive/priority/taskset.py","file_name":"taskset.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591769290","text":"from django.conf.urls import patterns, url\n\nfrom views import (\n CourseListView, CourseDetailView, CourseDetailRedirectView,\n CourseEnrollView, CourseDisenrollView, LectureDetailView,\n CreateCourseView, AddLectureView\n)\n\n\nurlpatterns = patterns('courses.views', # nopep8\n url(r'^$', CourseListView.as_view(), name='courses-list'),\n url(r'^create/$', CreateCourseView.as_view(), name='course-create'),\n url(r'^(?P\\d+)/(?P[-_\\w]+)$',\n CourseDetailView.as_view(), name='course-detail'),\n url(r'^(?P\\d+)/(?P[-_\\w]+)/add-lecture/$',\n AddLectureView.as_view(), name='add-lecture'),\n url(r'^(?P\\d+)$', CourseDetailRedirectView.as_view()),\n url(r'^(?P\\d+)/(?P[-_\\w]+)/(?P\\d+)$',\n LectureDetailView.as_view(), name='lecture-detail'),\n url(r'^enroll/(?P\\d+)$',\n CourseEnrollView.as_view(), name='course-enroll'),\n url(r'^disenroll/(?P\\d+)$',\n CourseDisenrollView.as_view(), name='course-disenroll'),\n)\n","sub_path":"courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34013240","text":"import os\nimport sys\nprint(\"main process (%s) start\" % os.getpid())\npid=os.fork()\nif pid==0:\n print(\"I'm child process (%s) and my parent process is %s\" % (os.getpid(),os.getppid()))\n sys.exit(0)\nelse:\n print('I (%s) just created a child process (%s).' % (os.getpid(), pid))\n sys.exit(0)\n","sub_path":"python标准库/os/创建进程/fork创建进程.py","file_name":"fork创建进程.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71362329","text":"import json\nimport os.path as osp\nimport os\n\nimport collections\n\nframe_privacy_dict = collections.defaultdict(dict)\nattr_mapping_dict = {'gender':'a4_gender', 'face':'a10_face_partial', 'nudity':'a12_semi_nudity',\n 'skin_color': 'a17_color', 'relationship':'a64_rel_personal'}\njson_files = os.listdir('raw_pa_hmdb51_annos')\nvid_lst = []\nfor jf in json_files:\n action = jf[:-5]\n with open(osp.join('raw_pa_hmdb51_annos', jf)) as handle:\n anno = json.load(handle)\n for vid in anno.keys():\n print(vid)\n vid_lst.append(vid)\n for attr in anno[vid].keys():\n if attr == \"review\" or attr == \"note\":\n continue\n for split in anno[vid][attr]:\n start, end, value = split[0], split[1], split[2]\n for i in range(start, end+1):\n frame_name = '{}_{}_{}'.format(action,vid[:-4],i)\n frame_privacy_dict[frame_name][attr_mapping_dict[attr]] = value\n #print(\"{}: {}, {}, {}\".format(frame_name, attr, i, value))\n\nimport json\nif not os.path.exists('pa_hmdb51_annos'):\n os.makedirs('pa_hmdb51_annos')\nfor frame in frame_privacy_dict.keys():\n print(frame)\n privacy_attrs = []\n for attr in frame_privacy_dict[frame].keys():\n if frame_privacy_dict[frame][attr] != 0:\n privacy_attrs.append(attr)\n with open(osp.join('pa_hmdb51_annos', '{}.json'.format(frame)), 'w') as fp:\n json.dump({\"image_path\":os.path.join('pa_hmdb51_frames', frame+'.png'), \"labels\":privacy_attrs}, fp, indent=4)","sub_path":"data-preparation/PA_HMDB51/vispr_anno_conversion.py","file_name":"vispr_anno_conversion.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"385341078","text":"import os\nimport aiohttp\nimport logging\nfrom datetime import datetime, timezone\nfrom dotenv import load_dotenv\nfrom discord import Member\nfrom typing import Optional, List\n\nload_dotenv()\nlogger = logging.getLogger(__name__)\n\n\nclass ResponseCodeError(ValueError):\n \"\"\"Raised when a non-OK HTTP response is received.\"\"\"\n\n def __init__(\n self,\n response: aiohttp.ClientResponse,\n response_json: Optional[dict] = None,\n response_text: str = \"\"\n ):\n self.status = response.status\n self.response_json = response_json or {}\n self.response_text = response_text\n self.response = response\n\n def __str__(self):\n response = self.response_json if self.response_json else self.response_text\n return f\"Status: {self.status} Response: {response}\"\n\n\nclass APIClient:\n def __init__(self, loop):\n self.auth_header = {\"Authorization\": f\"Token {os.getenv('API_ACCESS_TOKEN')}\"}\n self.session = aiohttp.ClientSession(loop=loop, headers=self.auth_header)\n\n @staticmethod\n def _url_for(endpoint: str) -> str:\n return f\"https://api.tortoisecommunity.ml/{endpoint}\"\n \n @classmethod\n async def raise_for_status(cls, response: aiohttp.ClientResponse) -> None:\n \"\"\"Raise ResponseCodeError for non-OK response if an exception should be raised.\"\"\"\n if response.status >= 400:\n try:\n response_json = await response.json()\n raise ResponseCodeError(response=response, response_json=response_json)\n except aiohttp.ContentTypeError:\n response_text = await response.text()\n raise ResponseCodeError(response=response, response_text=response_text)\n\n async def get(self, endpoint: str, **kwargs) -> dict:\n async with self.session.get(self._url_for(endpoint), **kwargs) as resp:\n await self.raise_for_status(resp)\n return await resp.json()\n\n async def patch(self, endpoint: str, **kwargs) -> dict:\n async with self.session.patch(self._url_for(endpoint), **kwargs) as resp:\n await self.raise_for_status(resp)\n return await resp.json()\n\n async def post(self, endpoint: str, **kwargs) -> dict:\n async with self.session.post(self._url_for(endpoint), **kwargs) as resp:\n await self.raise_for_status(resp)\n return await resp.json()\n\n async def put(self, endpoint: str, **kwargs) -> dict:\n async with self.session.put(self._url_for(endpoint), **kwargs) as resp:\n await self.raise_for_status(resp)\n return await resp.json()\n\n async def delete(self, endpoint: str, **kwargs) -> Optional[dict]:\n async with self.session.delete(self._url_for(endpoint), **kwargs) as resp:\n if resp.status == 204:\n return\n\n await self.raise_for_status(resp)\n return await resp.json()\n\n\nclass TortoiseAPI(APIClient):\n def __init__(self, loop):\n super().__init__(loop)\n\n async def does_member_exist(self, member_id: int) -> bool:\n try:\n await self.is_verified(member_id, re_raise=True)\n return True\n except ResponseCodeError:\n return False\n\n async def is_verified(self, member_id: int, *, re_raise=False) -> bool:\n \"\"\"\n \"verify-confirmation/{member_id}/\" endpoint return format {'verified': True} or 404 status\n :param member_id: int member id\n :param re_raise: bool whether to re-raise ResponseCodeError if member_id is not found.\n :return: bool\n \"\"\"\n # Endpoint return format {'verified': True} or 404 status\n try:\n data = await self.get(f\"verify-confirmation/{member_id}/\")\n except ResponseCodeError as e:\n if re_raise:\n raise e\n else:\n return False\n\n return data[\"verified\"]\n\n async def insert_new_member(self, member: Member):\n \"\"\"For inserting new members in the database.\"\"\"\n data = {\"user_id\": member.id,\n \"guild_id\": member.guild.id,\n \"join_date\": datetime.now(timezone.utc).isoformat(),\n \"name\": member.display_name,\n \"tag\": member.discriminator,\n \"member\": True}\n await self.post(\"members/\", json=data)\n\n async def member_rejoined(self, member: Member):\n data = {\"user_id\": member.id, \"guild_id\": member.guild.id, \"member\": True, \"leave_date\": None}\n await self.put(f\"members/edit/{member.id}/\", json=data)\n\n async def member_left(self, member: Member):\n data = {\"user_id\": member.id,\n \"guild_id\": member.guild.id,\n \"leave_date\": datetime.now(timezone.utc).isoformat(),\n \"member\": False}\n await self.put(f\"members/edit/{member.id}/\", json=data)\n\n async def get_member_roles(self, member_id: int) -> List[int]:\n # Endpoint return format {'roles': [int...]} or 404 status\n data = await self.get(f\"members/{member_id}/roles/\")\n return data[\"roles\"]\n\n async def edit_member_roles(self, member: Member, roles_ids: List[int]):\n await self.put(f\"members/edit/{member.id}/\", json={\"user_id\": member.id,\n \"guild_id\": member.guild.id,\n \"roles\": roles_ids})\n","sub_path":"api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":5413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"57204174","text":"\"\"\"\npython实现二叉树\n\"\"\"\nfrom binaryTreeExercise01 import Solution\n\nclass Node:\n \"\"\"节点类\"\"\"\n\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n\nclass BinaryTree:\n def __init__(self):\n \"\"\" 初始化一棵空树,树根为None的树为空树 \"\"\"\n self.root = None\n\n def add(self, item):\n \"\"\"二叉树中添加1个节点,使用队列思想\"\"\"\n node = Node(item)\n q = [self.root]\n while True:\n # 空树情况,插入为根\n if not self.root:\n self.root = node\n return\n cur = q.pop(0)\n # 判断左孩子\n if cur.left: # 如果是空树,会报错\n q.append(cur.left) # 添加进列表用于左右孩子的判断\n else:\n # 直接添加节点,添加完以后直接return结束\n cur.left = node\n return\n # 判断右孩子\n if cur.right:\n q.append(cur.right)\n else:\n cur.right = node\n return\n\n def breadth_travel(self):\n \"\"\"广度遍历:从上到下,从左到右\"\"\"\n # 空树的情况\n if not self.root:\n return\n # 非空树的情况\n q = [self.root]\n while q:\n cur = q.pop(0)\n print(cur.value, end=' ')\n if cur.left:\n q.append(cur.left)\n if cur.right:\n q.append(cur.right)\n\n def pre_travel(self, node):\n if node is None:\n return\n print(node.value, end=' ')\n self.pre_travel(node.left)\n self.pre_travel(node.right)\n\n def mid_travel(self, node):\n if node is None:\n return\n self.mid_travel(node.left)\n print(node.value, end=' ')\n self.mid_travel(node.right)\n\n def last_travel(self, node):\n if node is None:\n return\n self.last_travel(node.left)\n self.last_travel(node.right)\n print(node.value, end=' ')\n\n\n\nbinary_tree = BinaryTree()\ns = Solution()\n# binary_tree.add(1)\n# binary_tree.add(2)\n# binary_tree.add(3)\n# binary_tree.add(4)\n# binary_tree.add(5)\n# binary_tree.add(6)\n# binary_tree.add(7)\n# binary_tree.add(8)\n# binary_tree.add(9)\n# binary_tree.add(10)\nbinary_tree.add(5)\nbinary_tree.add(3)\nbinary_tree.add(7)\nbinary_tree.add(2)\nbinary_tree.add(4)\nbinary_tree.add(6)\n# binary_tree.breadth_travel()\n# print()\n# binary_tree.pre_travel(binary_tree.root)\n# print()\nbinary_tree.mid_travel(binary_tree.root)\nprint()\n# binary_tree.last_travel(binary_tree.root)\n# print()\ns.find_k_smallest(binary_tree.root,3)","sub_path":"month05/DataStructure/day03_course/day03_code/01_binaryTree.py","file_name":"01_binaryTree.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"453503914","text":"from mongoengine import document, fields\n\n\nclass BaseOrgVisitsCounterPerDay(document.EmbeddedDocument):\n id = fields.StringField(max_length=36, required=True)\n orgname = fields.StringField(max_length=60, required=True)\n counter = fields.IntField(default=0, required=True)\n\n\nclass BaseOrgVisitsCounterMultiTimeRange(document.EmbeddedDocument):\n today = fields.ListField(\n fields.EmbeddedDocumentField(BaseOrgVisitsCounterPerDay))\n last7Ds = fields.ListField(\n fields.EmbeddedDocumentField(BaseOrgVisitsCounterPerDay))\n last1M = fields.ListField(\n fields.EmbeddedDocumentField(BaseOrgVisitsCounterPerDay))\n\n\nclass BaseOrgVisitsCounter(document.Document):\n logdate = fields.StringField(max_length=10)\n info = fields.EmbeddedDocumentField(BaseOrgVisitsCounterMultiTimeRange)\n\n meta = {\n 'abstract': True,\n }\n\n\nclass QidaOrgVisitsCounter(BaseOrgVisitsCounter):\n meta = {\n 'ordering': ['-logdate'],\n }\n\n\nclass LecaiOrgVisitsCounter(BaseOrgVisitsCounter):\n meta = {\n 'ordering': ['-logdate'],\n }\n\n\nclass WangxiaoOrgVisitsCounter(BaseOrgVisitsCounter):\n meta = {\n 'ordering': ['-logdate'],\n }\n","sub_path":"OrgActivity/config/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259869994","text":"from time import time\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport json\nimport wget\nimport uuid\nimport os\n\ntmp = \"/tmp/\"\n\ndef handle(req):\n \"\"\"handle a request to the function\n Args:\n req (str): request body\n \"\"\"\n event = json.loads(req)\n \n input_path = event['input_path']\n key = event[\"object_key\"]\n\n download_path = tmp+'{}{}'.format(uuid.uuid4(), key)\n wget.download(input_path, download_path)\n\n result = []\n latency = 0\n\n with open(download_path) as f:\n body = f.read()\n start = time()\n word = body.replace(\"'\", '').split(',')\n result.extend(word)\n latency += time() - start\n\n print(len(result))\n\n tfidf_vect = TfidfVectorizer().fit(result)\n feature = str(tfidf_vect.get_feature_names())\n feature = feature.lstrip('[').rstrip(']').replace(' ' , '')\n\n feature_key = download_path.split('.')[0]+'-feature.txt'\n\n with open(feature_key, 'w') as f:\n f.write(feature)\n \n os.remove(download_path)\n os.remove(feature_key)\n\n return latency\n","sub_path":"benchmarks/FunctionBench/featurereduce/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435176044","text":"types_of_people = 10\nx = f\"There are {types_of_people} types of people.\"\n\nbinary = \"binary\"\ndo_not = \"don't\"\ny = f\"Those who know {binary} and those who {do_not}.\"\n\nprint(x)\nprint(y)\n\nprint(f\"I said: {x}\")\nprint(f\"I also said: '{y}'\")\n\n# Formatters work by putting in one or more replacement fields or placeholders\n# — defined by a pair of curly braces {} —\n# into a string and calling the str.format() method.\n# ex: print(\"Sammy has {} balloons.\".format(5))\n# output: Sammy has 5 balloons.\nhilarious = False\njoke_evaluation = \"Isnt' that joke so funny?! {}\"\n\nprint(joke_evaluation.format(hilarious))\n\nw = \"This is the left side of...\"\ne = \"a string with a right side.\"\n\nprint(w + e)\n","sub_path":"ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622817176","text":"import os\r\nimport numpy as np\r\nimport skimage.data\r\nfrom skimage.io import imsave, imread\r\nfrom skimage import transform\r\nfrom skimage.color import rgb2gray\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nimg_w = 128\r\nimg_h = 128\r\n\r\nPATH_NEW_IMGS_FOLDER = 'Resized_images'\r\n\r\n\r\ndef load_imgs():\r\n\tCONDITIONS = lambda img_name: False if '_mask' in img_name or '.json' in img_name or '.py' in img_name else True\r\n\r\n\timg_names = [img_name for img_name in os.listdir() if CONDITIONS(img_name) and os.path.isfile(img_name)]\r\n\timgs = [imread(img_name) for img_name in img_names]\r\n\r\n\treturn imgs, img_names\r\n\r\n\r\ndef resize(imgs):\r\n\tresized_imgs = [transform.resize(img, (img_w, img_h)) for img in imgs]\r\n\treturn resized_imgs\r\n\r\n\r\ndef save_imgs(imgs, img_names):\r\n\tfor img, img_name in zip(imgs, img_names):\r\n\t\timsave(os.path.join(PATH_NEW_IMGS_FOLDER, img_name), img)\r\n\r\n\r\nif __name__ == '__main__':\r\n\timgs, img_names = load_imgs()\r\n\timgs = resize(imgs)\r\n\tsave_imgs(imgs, img_names)\r\n","sub_path":"script_to_resize_imgs.py","file_name":"script_to_resize_imgs.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596138475","text":"##############################################\r\n# #\r\n# Author: Richard Ruzsa (develru) #\r\n# Email: develru [at] me . com #\r\n# #\r\n##############################################\r\n\r\nimport sys\r\n#from PySide import QtCore\r\nfrom PySide import QtGui\r\nimport memoryOO\r\n\r\n\r\nclass StartForm(QtGui.QDialog):\r\n\r\n def __init__(self, parent=None):\r\n \"\"\"Init the main window\"\"\"\r\n super(StartForm, self).__init__(parent)\r\n self.setWindowTitle('Memory Game')\r\n self.startButton = QtGui.QPushButton('Start Game')\r\n self.quitButton = QtGui.QPushButton('Quit')\r\n layout = QtGui.QVBoxLayout()\r\n layout.addWidget(self.startButton)\r\n layout.addWidget(self.quitButton)\r\n self.setLayout(layout)\r\n self.quitButton.clicked.connect(QtGui.qApp.quit)\r\n self.startButton.clicked.connect(self.startGame)\r\n\r\n def startGame(self):\r\n \"\"\"Start the memory game\"\"\"\r\n self.quitButton.setEnabled(False)\r\n game = memoryOO.Game()\r\n game.main()\r\n self.quitButton.setEnabled(True)\r\n\r\nif __name__ == '__main__':\r\n app = QtGui.QApplication(sys.argv)\r\n win = StartForm()\r\n win.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"PyGame/Memory/memoryStart.py","file_name":"memoryStart.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463243966","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/getml/container.py\n# Compiled at: 2019-12-09 07:12:30\n# Size of source mod 2**32: 2440 bytes\nimport json\nimport getml.communication as comm\n\nclass Container(object):\n __doc__ = '\\n Base object not meant to be called directly\\n '\n\n def __init__(self):\n self.colnames = None\n self.units = None\n self.thisptr = dict()\n\n def send(self, numpy_array, s):\n \"\"\"\n Sends the object to the engine, data taken from a numpy array.\n\n Args:\n numpy_array (:class:`numpy.ndarray`): Number of columns should match the number of columns of the object itself.\n s: Socket\n \"\"\"\n comm.send_string(s, json.dumps(self.thisptr))\n if self.thisptr['type_'] == 'CategoricalColumn':\n comm.send_categorical_matrix(s, numpy_array)\n else:\n if self.thisptr['type_'] == 'Column':\n comm.send_matrix(s, numpy_array)\n msg = comm.recv_string(s)\n if msg != 'Success!':\n raise Exception(msg)\n if len(numpy_array.shape) > 1:\n self.colnames = self.colnames or ['column_' + str(i + 1) for i in range(numpy_array.shape[1])]\n\n def set_unit(self, unit):\n \"\"\"\n Sets the unit of the column.\n\n Args:\n unit: The new unit.\n \"\"\"\n cmd = dict()\n cmd.update(self.thisptr)\n cmd['unit_'] = unit\n cmd['type_'] += '.set_unit'\n comm.send(cmd)\n self.thisptr['unit_'] = unit","sub_path":"pycfiles/getml-0.10.0-py3.7/container.cpython-37.py","file_name":"container.cpython-37.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228066544","text":"import requests\r\n#调用requests库\r\nimport json\r\n#调用json库\r\nurl='https://c.y.qq.com/soso/fcgi-bin/client_search_cp'\r\nheaders={\r\n 'referer':'https://y.qq.com/portal/search.html',\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'\r\n#标记了请求从什么设备什么浏览器发出\r\n}\r\n#伪装请求头\r\nsinger=input('你喜欢的歌手是?')\r\n#输��喜欢的歌手\r\nfor x in range(5):\r\n params={\r\n 'ct':'24',\r\n 'qqmusic_ver': '1298',\r\n 'new_json':'1',\r\n 'remoteplace':'sizer.yqq.lyric_next',\r\n 'searchid':'94267071827046963',\r\n 'aggr':'1',\r\n 'cr':'1',\r\n 'catZhida':'1',\r\n 'lossless':'0',\r\n 'sem':'1',\r\n 't':'7',\r\n 'p':str(x+1),\r\n 'n':'10',\r\n 'w':singer,\r\n 'g_tk':'1714057807',\r\n 'loginUin':'0',\r\n 'hostUin':'0',\r\n 'format':'json',\r\n 'inCharset':'utf8',\r\n 'outCharset':'utf-8',\r\n 'notice':'0',\r\n 'platform':'yqq.json',\r\n 'needNewCode':'0'\r\n }\r\n #将参数封装成字典\r\n res=requests.get(url,params=params)\r\n #获取数据,下载该字典\r\n json_music=res.json()\r\n #使用json方法,将response对象,转为字典/列表\r\n list_music=json_music['data']['lyric']['list']\r\n #一层一层取字典获取歌单列表\r\n for music in list_music:\r\n print('歌曲名'+music['name'])\r\n #打印歌曲名\r\n print('专辑'+music['album']['name'])\r\n #打印专辑名\r\n print('播放时长:'+str(music['interval'])+'秒')\r\n #打印播放时长\r\n print('播放链接:https://y.qq.com/n/yqq/song/'+music['mid'] +'.html\\n\\n')\r\n #打印播放链接","sub_path":"songchangeCode.py","file_name":"songchangeCode.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228887089","text":"from discord import Webhook, RequestsWebhookAdapter\nimport asyncio\nimport random\nimport discord\nfrom discord.ext import commands\nimport re, time, datetime, sys\nimport yaml\n\na = open(\"config.yaml\", 'r')\nx = yaml.load(a)\nJchannel = x['JOINS']\nLchannel = x['LEAVES']\n\nclass Owner(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_guild_remove(self, guild):\n created = str(guild.created_at.strftime(\"%#d %B %Y\"))\n discord_webhook = Lchannel\n webhook_id = int(re.search(r\"\\d+\", discord_webhook).group())\n webhook_token = re.search(r\"(?!.*\\/)+(.*)\", discord_webhook).group()\n embed = discord.Embed(title = 'Left guild', description = f'Guild name: {guild.name}\\nGuild id: {guild.id}\\nGuild owner: {guild.owner}\\nMembers: {guild.member_count}', color=0xff0000)\n embed.set_footer(text=f\"Guild created: {created}\")\n embed.set_image(url=str(guild.icon_url))\n webhook = Webhook.partial(webhook_id, webhook_token, adapter=RequestsWebhookAdapter())\n webhook.send(embed=embed)\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n created = str(guild.created_at.strftime(\"%#d %B %Y\"))\n discord_webhook = Jchannel\n webhook_id = int(re.search(r\"\\d+\", discord_webhook).group())\n webhook_token = re.search(r\"(?!.*\\/)+(.*)\", discord_webhook).group()\n embed = discord.Embed(title = 'New guild', description = f'Guild name: {guild.name}\\nGuild id: {guild.id}\\nGuild owner: {guild.owner}\\nMembers: {guild.member_count}', color=0x00ff00)\n embed.set_image(url=str(guild.icon_url))\n embed.set_footer(text=f\"Created at {created}\")\n webhook = Webhook.partial(webhook_id, webhook_token, adapter=RequestsWebhookAdapter())\n webhook.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(Owner(bot))\n","sub_path":"cogs/owner.py","file_name":"owner.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"620545782","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom accounts.models import User\nfrom app.main.models import Card, Fraction, Hero \nfrom random import shuffle\n\nclass Deck(models.Model):\n name = models.CharField(max_length=100)\n user = models.ForeignKey(User)\n fraction = models.ForeignKey(Fraction)\n cards = models.ManyToManyField(Card, related_name='decks', through='CardOnDeck')\n hero = models.ForeignKey(Hero, related_name='decks')\n \n def __unicode__(self):\n return self.name\n\nclass CardOnDeck(models.Model):\n deck = models.ForeignKey(Deck)\n card = models.ForeignKey(Card)\n count = models.PositiveSmallIntegerField()\n \n class Meta:\n unique_together = ['deck', 'card']\n\nZONE_HAND = 1\nZONE_STACK = 2\nZONE_GAME = 3\nZONE_TRASH = 4\nZONE_HOLLOW = 5\n\nPHASE_START = 1\nPHASE_GET_CARD = 2\nPHASE_BOMB = 3\nPHASE_ATACK = 4\nPHASE_MAIN = 5\nPHASE_END = 6\n\nS_WAIT = 1\nS_READY = 2\nS_FINISH = 3\nS_CANCEL = 4\n\nclass HeroInBattle(models.Model):\n hero = models.ForeignKey(Hero)\n turned = models.BooleanField(default=False)\n\n def store_record(self):\n obj = self.hero.store_record()\n obj['card_id'] = obj['id']\n obj['id'] = self.pk\n obj['turned'] = self.turned\n return obj\n \n def play(self):\n self.turned = True\n self.save()\n\n @property\n def hand(self):\n return self.hero.hand\n \nclass PlayerInfo(models.Model):\n user = models.ForeignKey(User, null=True)\n fraction = models.ForeignKey(Fraction, null=True)\n hero = models.ForeignKey(HeroInBattle, null=True)\n \nclass Battle(models.Model):\n PHASE_CHOICES = (\n (PHASE_START, u'Start'),\n (PHASE_GET_CARD, u'Get card'),\n (PHASE_BOMB, u'Bomb'),\n (PHASE_ATACK, u'Atack'),\n (PHASE_MAIN, u'Main'),\n (PHASE_END, u'End') \n )\n STATUS_CHOICES = (\n (S_WAIT, u''),\n (S_READY, u''),\n (S_FINISH, u''),\n (S_CANCEL, u'')\n )\n player_one_info = models.ForeignKey(PlayerInfo, related_name='player_one_battle')\n player_two_info = models.ForeignKey(PlayerInfo, related_name='player_two_battle')\n turn_num = models.IntegerField(default=0)\n turn_phase = models.IntegerField(choices=PHASE_CHOICES, default=PHASE_START)\n created = models.DateTimeField(auto_now_add=True)\n use_bomb = models.BooleanField(default=False)\n use_creep = models.BooleanField(default=False)\n use_support = models.BooleanField(default=False)\n status = models.IntegerField(choices=STATUS_CHOICES, default=S_WAIT)\n \n def __unicode__(self):\n if self.player_two:\n return '%s vs %s' % (self.player_one, self.player_two)\n else:\n return '%s vs `any`' % (self.player_one)\n \n def get_enemy(self, user):\n if self.player_one == user:\n return self.player_two\n elif self.player_two == user:\n return self.player_one\n \n @property\n def player_one(self):\n return self.player_one_info.user\n\n @property\n def player_two(self):\n return self.player_two_info.user\n\n @property\n def player_one_hero(self):\n return self.player_one_info.hero\n\n @property\n def player_two_hero(self):\n return self.player_two_info.hero\n \n def play_hero(self, user):\n hero = self.hero_card(user)\n return hero and hero.play()\n \n def play_card(self, card_in_battle):\n \"\"\"\n Play @card_in_battle if it is posible\n \"\"\"\n if self.can_play_card(card_in_battle):\n played = card_in_battle.play()\n if played:\n if card_in_battle.is_bomb():\n self.use_bomb = True\n elif card_in_battle.is_creep():\n self.use_creep = True\n elif card_in_battle.is_support():\n self.use_support = True\n self.save()\n self.add_action(Action.PLAY_CARD, Action.COMPLITED, card_in_battle)\n return played\n return False\n \n def add_action(self, type, status, card=None, user=None):\n obj = Action()\n obj.action_card = card\n obj.battle = self\n if user is None:\n if self.playing_user == self.player_one:\n obj.user = Action.U_ONE\n else:\n obj.user = Action.U_TWO\n else:\n obj.user = user\n obj.status = status\n obj.type = type\n obj.save()\n return obj\n \n def can_play_card(self, card_in_battle):\n \"\"\"\n Return if @card_in_battle can be played\n \"\"\"\n if not self.is_playing(card_in_battle.user):\n return False\n \n #it should be MAIN phase of game\n if not self.turn_phase == PHASE_MAIN:\n return False\n \n if not card_in_battle.zone == ZONE_HAND:\n return False\n \n card = card_in_battle.card\n if card.is_bomb():\n return not self.use_bomb\n if card.is_creep():\n return not self.use_creep\n if card.is_circ() or card.is_change():\n return not self.use_support\n return True\n \n def move(self):\n \"\"\"\n Change turn phase to the next\n \"\"\"\n if self.turn_phase == PHASE_START:\n self.turn_phase = PHASE_GET_CARD\n self.save()\n self.move_first_card(self.playing_user)\n if self.turn_phase == PHASE_GET_CARD:\n self.turn_phase = PHASE_BOMB\n self.save()\n if self.turn_phase == PHASE_BOMB:\n self.turn_phase = PHASE_ATACK\n self.save()\n if self.turn_phase == PHASE_ATACK:\n self.turn_phase = PHASE_MAIN\n self.save()\n \n def move_first_card(self, user, target_zone=ZONE_HAND, from_zone=ZONE_STACK):\n \"\"\"\n Move first card of @user from @from_zone to @target_zone\n \"\"\"\n from_cards = self.cards_on_zone(user, from_zone).order_by('order')\n if not from_cards:\n return False\n from_cards[0].zone = target_zone\n from_cards[0].save()\n return True\n \n def is_player(self, user):\n \"\"\"\n Return is @user is player of this battle\n \"\"\"\n return self.player_one == user or self.player_two == user\n \n def is_playing(self, user):\n \"\"\"\n Return if @user can play now\n \"\"\"\n if not self.turn_num % 2:\n return self.player_two == user\n else:\n return self.player_one == user \n \n @property\n def playing_user(self):\n \"\"\"\n Return current playing user\n \"\"\"\n if not self.turn_num % 2:\n return self.player_two\n else:\n return self.player_one\n \n def start_battle(self):\n \"\"\"\n Start battle: set status READY, and get cards to players\n \"\"\"\n if not self.status == S_WAIT or not self.player_one or not self.player_two:\n raise Exception('Battle can\\'n be started')\n self.turn_num = 1\n self.status = S_READY\n self.save()\n self.give_cards()\n \n @property\n def player_one_cards(self):\n \"\"\"\n Return cards of player one\n \"\"\"\n return self.cards.filter(user=self.player_one)\n\n @property\n def player_two_cards(self):\n \"\"\"\n Return cards of player two\n \"\"\" \n return self.cards.filter(user=self.player_two)\n \n def give_cards(self):\n \"\"\"\n Give users cards on start of battle\n \"\"\"\n one_player_cards = list(self.player_one_cards)\n shuffle(one_player_cards)\n two_player_cards = list(self.player_two_cards)\n shuffle(two_player_cards) \n [card.to_hand() for card in one_player_cards[:self.player_one_hero.hand]]\n [card.to_hand() for card in two_player_cards[:self.player_two_hero.hand]]\n \n for i, card in enumerate(one_player_cards[self.player_one_hero.hand:]):\n card.order = i\n card.save()\n \n for i, card in enumerate(two_player_cards[self.player_two_hero.hand:]):\n card.order = i\n card.save()\n \n def reset_cards(self):\n \"\"\"\n Reset all cards(move them to ZONE_STACK except Hero card)\n \"\"\"\n self.cards.update(zone=ZONE_STACK)\n \n def cards_on_zone(self, user, zone):\n \"\"\"\n Return cards of @user on @zone\n \"\"\"\n return self.cards.filter(user=user, zone=zone)\n \n def hero_card(self, user):\n \"\"\"\n Return Hero card of @user\n \"\"\"\n if self.player_one_info.user == user:\n return self.player_one_hero\n elif self.player_two_info.user == user:\n return self.player_two_hero\n return None\n \n def stack_count(self, user):\n \"\"\"\n Return count of cards in ZONE_STACK for @user\n \"\"\"\n return self.cards_on_zone(user, ZONE_STACK).count()\n \n def info(self, user):\n \"\"\"\n Return current battle info for @user\n \"\"\"\n return {\n 'turn': self.turn_num,\n 'phase': self.turn_phase,\n 'phase_name': self.get_turn_phase_display(),\n 'is_playing': self.is_playing(user),\n 'use_bomb': self.use_bomb,\n 'use_creep': self.use_creep,\n 'use_support': self.use_support,\n 'stack_count': self.stack_count(user)\n } \n \nclass CardInBattle(models.Model):\n ZONE_CHOICES = (\n (ZONE_HAND, u'Рука'),\n (ZONE_STACK, u''),\n (ZONE_GAME, u''),\n (ZONE_TRASH, u''),\n (ZONE_HOLLOW, u'') \n )\n card = models.ForeignKey(Card)\n battle = models.ForeignKey(Battle, related_name='cards')\n user = models.ForeignKey(User)\n zone = models.IntegerField(choices=ZONE_CHOICES, default=ZONE_STACK)\n turned = models.BooleanField(default=False)\n order = models.IntegerField(default=0, null=True, blank=True)\n \n def to_hand(self, save=True):\n \"\"\"\n Move card to ZONE_HAND\n \"\"\"\n self.turned = False\n self.zone = ZONE_HAND\n self.order = None\n save and self.save()\n \n def to_trash(self, save=True):\n self.turned = False\n self.zone = ZONE_TRASH\n self.order = None\n save and self.save()\n \n def to_game(self, save=True):\n self.zone = ZONE_GAME\n self.order = None\n save and self.save() \n \n def turn(self, save=True):\n self.turned = True\n save and self.save()\n \n def unturn(self, save=True):\n self.turned = False\n save and self.save()\n \n def store_record(self):\n obj = self.card.store_record()\n obj['card_id'] = obj['id']\n obj['id'] = self.pk\n obj['turned'] = self.turned\n return obj\n \n def is_creep(self):\n return self.card.is_creep()\n \n def is_bomb(self):\n return self.card.is_bomb()\n \n def is_deal(self):\n return self.card.is_deal()\n \n def is_support(self):\n return self.card.is_circ() or self.card.is_change()\n \n def play(self):\n if self.is_bomb():\n self.turn(False)\n \n if self.is_deal():\n self.to_trash()\n else: \n self.to_game()\n return True\n \nclass Action(models.Model):\n U_ONE = 1\n U_TWO = 2\n USER_CHOICES = (\n (U_ONE, ''),\n (U_TWO, '') \n )\n \n COMPLITED = 1\n UNCOMPLITED = 2\n BLOCKED = 3\n STATUS_CHOICES = (\n (COMPLITED, ''),\n (UNCOMPLITED, ''),\n (BLOCKED, '')\n )\n \n PLAY_CARD = 1\n PAY_PRICE = 2\n TYPE_CHOICES = (\n (PLAY_CARD, ''),\n (PAY_PRICE, '')\n )\n battle = models.ForeignKey(Battle)\n user = models.IntegerField(choices=USER_CHOICES)\n action_card = models.ForeignKey(CardInBattle, null=True, blank=True, related_name='actions')\n cards = models.ManyToManyField(CardInBattle, blank=True)\n type = models.IntegerField(choices=TYPE_CHOICES)\n status = models.IntegerField(choices=STATUS_CHOICES)\n order = models.IntegerField(default=1)\n time = models.DateTimeField(auto_now_add=True)\n \n class Meta:\n ordering = ['-order']\n \n def save(self, *args, **kwargs):\n if not self.pk:\n try:\n last_action = Action.objects.filter(battle=self.battle)[:1].get()\n self.order = last_action.order + 1\n except models.ObjectDoesNotExist:\n self.order = 1\n super(Action, self).save(*args, **kwargs) ","sub_path":"src/app/game/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"208119351","text":"# 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现两次 ,返回删除后数组的新长度。\n#\n# 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。\n#\n#\n#\n# 说明:\n#\n# 为什么返回数值是整数,但输出的答案是数组呢?\n#\n# 请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。\n#\n# 你可以想象内部操作如下:\n#\n#\n# // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝\n# int len = removeDuplicates(nums);\n#\n# // 在函数里修改输入数组对于调用者是可见的。\n# // 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。\n# for (int i = 0; i < len; i++) {\n#     print(nums[i]);\n# }\n#\n#\n#\n#\n# 示例 1:\n#\n#\n# 输入:nums = [1,1,1,2,2,3]\n# 输出:5, nums = [1,1,2,2,3]\n# 解释:函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。 不需要考虑数组中超出新长度后面的元素。\n#\n#\n# 示例 2:\n#\n#\n# 输入:nums = [0,0,1,1,1,1,2,3,3]\n# 输出:7, nums = [0,0,1,1,2,3,3]\n# 解释:函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。 不需要考虑数组中超出新长度后面的\n# 元素。\n#\n#\n#\n#\n# 提示:\n#\n#\n# 1 <= nums.length <= 3 * 104\n# -104 <= nums[i] <= 104\n# nums 已按升序排列\n#\n# Related Topics 数组 双指针\n# 👍 614 👎 0\n\n\nfrom typing import List\n\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n slow = 0\n for fast in range(len(nums)):\n if slow < 2 or nums[fast] != nums[slow - 2]:\n nums[slow] = nums[fast]\n slow += 1\n return slow\n\n # 更一般的解法, 保留k位\n def removeDuplicates_k(self, nums: List[int], k) -> int:\n slow = 0\n for fast in range(len(nums)):\n if slow < k or nums[fast] != nums[slow - k]:\n nums[slow] = nums[fast]\n slow += 1\n return slow\n\n\nif __name__ == '__main__':\n print(Solution().removeDuplicates([1, 1, 1, 2, 2, 3]))\n","sub_path":"array/80_删除有序数组中的重复项II.py","file_name":"80_删除有序数组中的重复项II.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405504832","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\nimport association.models as association_models\nimport mediamines.models as mediamines_models\n\n\n# @login_required\ndef accueil(request):\n if request.user.is_authenticated():\n\n # Get the latest news (two weeks)\n associations = association_models.Association.objects.all().order_by(\"ordre\")\n date_min = datetime.date.today() - datetime.timedelta(days=7)\n if request.user.profile.en_premiere_annee():\n news_liste = association_models.News.objects.filter(hiddenFrom1A=False, association__is_hidden_1A=False,\n datePubli__gte=date_min).order_by(\"-datePubli\")\n else:\n news_liste = association_models.News.objects.filter(datePubli__gte=date_min).order_by(\"-datePubli\")\n\n # Get the latest mediamines video\n if association_models.Video.objects.count() > 0:\n latest_video = association_models.Video.objects.filter(association__pseudo=\"mediamines\").latest(\n field_name=\"date\")\n else:\n latest_video = None\n\n # Get the latest mediamines galerie\n if mediamines_models.Gallerie.objects.count() > 0:\n if request.user.profile.en_premiere_annee():\n gallerie = mediamines_models.Gallerie.objects.exclude(isHiddenFrom1A=True).order_by(\"-dateCreation\")[0]\n else:\n gallerie = mediamines_models.Gallerie.objects.all().order_by(\"-dateCreation\")[0]\n else:\n gallerie = None\n\n\n return render(\n request,\n \"base_index.html\",\n {\n 'news': news_liste,\n 'latest_video': latest_video,\n 'gallerie_affichee': gallerie,\n 'mineur': request.user,\n }\n )\n\n else:\n return HttpResponseRedirect(reverse_lazy(\"login\"))\n","sub_path":"portail/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35534684","text":"\"\"\"\nGiven a matrix M[][], the task is to check if the sum of i-th row is equal to the sum of i-th column or not.\n\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains two integers R and C and the second line contains R*C space separated matrix elements.\n\nOutput:\nFor each test case, if sums are equal for one or more rows and column, print \"Yes\" else print \"No\".\n\nConstraints:\n1<=T<=100\n1<=R,C<=500\n0<=M[][]<=103\n\nExample:\nInput:\n2\n4 4\n1 2 3 4 9 5 3 1 0 3 5 6 0 4 5 6\n3 3\n1 2 3 1 2 3 1 1 3\n\nOutput:\nYes\nNo\n\"\"\"\n\n\ndef sum_of_row_col(arr, r, c):\n l1 = []\n for i in range(0, r * c, c):\n l1.append(arr[i:i + c])\n a = 0\n for i in range(0, r):\n row_sum = sum(l1[i])\n col_sum = 0\n for j in range(0, r):\n if i < c:\n col_sum += l1[j][i]\n if row_sum == col_sum:\n a = 1\n break\n return \"Yes\" if a == 1 else \"No\"\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n r, c = [int(i) for i in input().split()][0:2]\n arr = [int(i) for i in input().split()][0:r * c]\n print(sum_of_row_col(arr, r, c))\n","sub_path":"practice/Basic/sums_of_i-th_row_and_i-th_column.py","file_name":"sums_of_i-th_row_and_i-th_column.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207707687","text":"import numpy as np \nimport random\nimport torch\nimport os\nfrom functools import reduce\nfrom torch.optim import Adam\nimport torch.nn.functional as F\nfrom utils import soft_update, hard_update\nfrom MADDPG.model import GaussianPolicy, QNetwork\nfrom MADDPG.buffer import ReplayMemory\n\n# This Trainer only contains one critic and one actor, the critic is trained by designated index\n# Assume all agent's obeservation and action spaces are identical\nclass AgentTrainer(object):\n def __init__(self, num_agents, obs_shape_list, action_shape_list, args):\n self.na = num_agents\n self.args = args\n\n self.target_update_interval = args.target_update_interval\n self.tau = args.tau\n self.alpha = 0.\n self.gamma = args.gamma\n self.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n num_inputs = sum(obs_shape_list) + num_agents # plus one-hot vector representation of agent index\n num_actions = sum(action_shape_list)\n\n self.critic = QNetwork(num_inputs, num_actions, args.hidden_dim).to(device=self.device)\n self.critic_target = QNetwork(num_inputs, num_actions, args.hidden_dim).to(device=self.device)\n self.critic_optim = Adam(self.critic.parameters(), lr=args.critic_lr)\n hard_update(self.critic_target, self.critic)\n\n self.policy = GaussianPolicy(obs_shape_list[0], action_shape_list[0], args.hidden_dim).to(device=self.device)\n self.policy_target = GaussianPolicy(obs_shape_list[0], action_shape_list[0], args.hidden_dim).to(device=self.device)\n self.policy_optim = Adam(self.policy.parameters(), lr=args.policy_lr)\n hard_update(self.policy_target, self.policy)\n\n def act(self, obs, eval=False):\n obs = torch.FloatTensor(obs).to(self.device)\n if eval:\n _, _, action = self.policy_target.sample(obs)\n else:\n action, _, _ = self.policy_target.sample(obs)\n \n return action.squeeze().detach().cpu().numpy()\n\n def update_parameters(self, samples, batch_size, index, updates):\n # Sample a batch\n obs_batch, action_batch, reward_batch, next_obs_batch, next_action_batch = samples\n # Leave the correspondent data\n obs_batch_i = obs_batch[:,index]\n action_batch_i = action_batch[:,index]\n reward_batch_i = reward_batch[:,index]\n next_obs_batch_i = next_obs_batch[:,index]\n # Reshape\n obs_batch = np.reshape(obs_batch, (batch_size, -1))\n action_batch = np.reshape(action_batch, (batch_size, -1))\n next_obs_batch = np.reshape(next_obs_batch, (batch_size, -1))\n # Add one-hot vector of agent's index\n ind = np.zeros((batch_size, self.na))\n ind[:,index] = 1.\n obs_batch = np.concatenate((obs_batch, ind), axis=1)\n next_obs_batch = np.concatenate((next_obs_batch, ind), axis=1)\n # Move to the device designated\n obs_batch = torch.FloatTensor(obs_batch).to(self.device)\n action_batch = torch.FloatTensor(action_batch).to(self.device)\n next_obs_batch = torch.FloatTensor(next_obs_batch).to(self.device)\n next_actions = torch.FloatTensor(next_action_batch).to(self.device)\n all_a = torch.FloatTensor(next_action_batch).to(self.device)\n obs_batch_i = torch.FloatTensor(obs_batch_i).to(self.device)\n action_batch_i = torch.FloatTensor(action_batch_i).to(self.device)\n reward_batch_i = torch.FloatTensor(reward_batch_i).to(self.device)\n reward_batch_i = reward_batch_i.unsqueeze(-1)\n next_obs_batch_i = torch.FloatTensor(next_obs_batch_i).to(self.device)\n\n with torch.no_grad():\n next_action, next_log_p, _ = self.policy_target.sample(next_obs_batch_i)\n next_actions[:,index] = next_action\n next_actions = torch.reshape(next_actions, (batch_size, -1))\n next_q = self.critic_target(next_obs_batch, next_actions) - self.alpha * next_log_p\n td_q = reward_batch_i + self.gamma * next_q\n\n q = self.critic(obs_batch, action_batch)\n q_loss = F.mse_loss(q, td_q)\n\n a, log_p, _ = self.policy.sample(obs_batch_i)\n all_a[:,index] = a\n all_a = torch.reshape(all_a, (batch_size, -1))\n q_p = self.critic(obs_batch, all_a)\n policy_loss = (self.alpha * log_p - q_p).mean()\n\n self.critic_optim.zero_grad()\n q_loss.backward()\n self.critic_optim.step()\n\n self.policy_optim.zero_grad()\n policy_loss.backward()\n self.policy_optim.step()\n\n if updates % self.target_update_interval == 0:\n soft_update(self.critic_target, self.critic, self.tau)\n soft_update(self.policy_target, self.policy, self.tau)\n\n return q_loss, policy_loss\n\n # Save model parameters\n def save_model(self, index, env_name, suffix=\"\", actor_path=None, critic_path=None):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n\n if actor_path is None:\n actor_path = \"models/maddpg_actor_{}_{}_{}\".format(env_name, suffix, index)\n if critic_path is None:\n critic_path = \"models/maddpg_critic_{}_{}_{}\".format(env_name, suffix, index)\n\n print('Saving models to {} and {}'.format(actor_path, critic_path))\n torch.save(self.policy.state_dict(), actor_path)\n torch.save(self.critic.state_dict(), critic_path) \n \n # Load model parameters\n def load_model(self, index, actor_path=None, critic_path=None, env_name=None, suffix=\"\"):\n print('Loading models from {} and {}'.format(actor_path, critic_path))\n if actor_path is not None:\n self.policy.load_state_dict(torch.load(actor_path))\n elif env_name is not None:\n actor_path = \"models/maddpg_actor_{}_{}_{}\".format(env_name, suffix, index)\n self.policy.load_state_dict(torch.load(actor_path))\n if critic_path is not None:\n self.critic.load_state_dict(torch.load(critic_path))\n elif env_name is not None:\n critic_path = \"models/maddpg_critic_{}_{}_{}\".format(env_name, suffix, index)\n self.critic.load_state_dict(torch.load(critic_path))\n\n hard_update(self.critic_target, self.critic)\n hard_update(self.policy_target, self.policy)","sub_path":"MADDPG/train2.py","file_name":"train2.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543297094","text":"\"\"\"Handle orders and pendingOrders endpoints.\"\"\"\nfrom .apirequest import APIRequest, dyndoc_insert, get_endpoint_config\n\n# responses serve both testing purpose aswell as dynamic docstring replacement\nresponses = {}\n\n# op flags\nORDER_CREATE = 1\nORDER_LIST = 2\nORDER_DETAILS = 4\nORDER_REPLACE = 8\nORDER_CANCEL = 16\nORDER_CLIENT_EXTENSIONS = 32\n\nendp_conf = {\n ORDER_CREATE: {\"path_comp\": None, \"method\": \"POST\"},\n ORDER_LIST: {\"path_comp\": None, \"method\": \"GET\"},\n ORDER_DETAILS: {\"path_comp\": None, \"method\": \"GET\"},\n ORDER_REPLACE: {\"path_comp\": None, \"method\": \"PUT\"},\n ORDER_CANCEL: {\"path_comp\": \"cancel\", \"method\": \"PUT\"},\n ORDER_CLIENT_EXTENSIONS: {\"path_comp\": \"clientExtensions\", \"method\": \"PUT\"}\n}\n\n\nclass PendingOrders(APIRequest):\n \"\"\"PendingOrders - class to handle the pendingOrders endpoint.\"\"\"\n\n ENDPOINT = \"v3/accounts/{}/pendingOrders\"\n\n def __init__(self, accountID):\n \"\"\"Instantiate a PendingOrders request.\n\n Parameters\n ----------\n accountID : string\n id of the account to perform the request on\n \"\"\"\n endpoint = self.ENDPOINT.format(accountID)\n super(PendingOrders, self).__init__(endpoint)\n\n\nclass Orders(APIRequest):\n \"\"\"Orders - class to handle the orders endpoints.\"\"\"\n\n ENDPOINT = \"v3/accounts/{accountID}/orders\"\n\n @dyndoc_insert(responses)\n def __init__(self, accountID, orderID=None, data=None, op=None):\n \"\"\"Instantiate an Orders request.\n\n Parameters\n ----------\n accountID : string (required)\n id of the account to perform the request on.\n\n op : operation flag (required)\n this flag acts as task identifier. It is used to construct the API\n endpoint and determine the HTTP method for the request.\n\n Possible flags::\n\n ORDER_CREATE (data)\n ORDER_LIST\n ORDER_DETAILS\n ORDER_REPLACE (data)\n ORDER_CANCEL\n ORDER_CLIENT_EXTENSIONS (data)\n\n requests involving the 'data'-parameter require headers to\n be set: Content-Type: application/json)\n\n orderID : string\n id of the order to perform the request for.\n\n data : dict (optional)\n configuration details for the order in case of a request\n to create or modify an order.\n \"\"\"\n endpoint = self.ENDPOINT\n method, path_comp = get_endpoint_config(endp_conf, op)\n\n if op in [ORDER_DETAILS, ORDER_REPLACE, ORDER_CANCEL,\n ORDER_CLIENT_EXTENSIONS]:\n endpoint = '{}/{{orderID}}'.format(endpoint)\n\n if path_comp:\n endpoint = '{}/{}'.format(endpoint, path_comp)\n\n endpoint = endpoint.format(accountID=accountID, orderID=orderID)\n super(Orders, self).__init__(endpoint, method=method, body=data)\n","sub_path":"oandapyV20/endpoints/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"214277099","text":"\r\nimport nltk\r\nimport numpy as np\r\nimport random\r\nimport string # to process standard python strings\r\nfrom nltk.chat.util import Chat, reflections\r\n\r\n\r\nfrom io import StringIO\r\nimport sys\r\nimport json\r\n\r\n\r\n\r\n\r\nimport requests\r\nfrom requests import get\r\nfrom bs4 import BeautifulSoup\r\nfrom lxml import html\r\n\r\n\r\n\r\nusr_agent = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\r\n 'Chrome/87.0.4280.141 Safari/537.36'}\r\ndef fetch_results(search_term, number_results, language_code):\r\n #First we have to replace spaces in the search query with plus symbols.\r\n escaped_search_term = search_term.replace(' ', '+')\r\n #Plug in the search term along with the number of results and the language code.\r\n google_url = 'https://www.google.com/search?q={}&num={}&hl={}'.format(escaped_search_term, number_results+1,\r\n language_code)\r\n #Get the response using requests.get\r\n response = get(google_url, headers=usr_agent)\r\n # raise_for_status() returns an HTTPError object if an error has occurred during the process. \r\n response.raise_for_status()\r\n #return the response as text\r\n return response.text\r\ndef parse_results(raw_html):\r\n #Beautiful Soup is a Python library for pulling data out of HTML and XML files. \r\n soup = BeautifulSoup(raw_html, 'html.parser')\r\n #This will help us find the relevant html attribute\r\n result_block = soup.find_all('div', attrs={'class': 'g'})\r\n for result in result_block:\r\n link = result.find('a', href=True)\r\n title = result.find('h3')\r\n if link and title:\r\n yield link['href']\r\n \r\ndef search(term, num_results=10, lang=\"en\"):\r\n #This will first call fetch_results above and then use that to return the list of results as a list of URLs\r\n html = fetch_results(term, num_results, lang)\r\n return list(parse_results(html))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef chatbot_query(query, index=0):\r\n #Fallback is just in case of error\r\n fallback = 'Sorry, I cannot find information regarding that.'\r\n result = ''\r\n\r\n #This is where Search is called, passing the search query.\r\n search_result_list = list(search(query, 10))\r\n #We'll use several try/except blocks to try extracting information from the response\r\n try:\r\n #Grab the page\r\n page = get(search_result_list[index], headers=usr_agent)\r\n\r\n #Prepare for soup\r\n tree = html.fromstring(page.content)\r\n #Declare an instance of BeautifulSoup\r\n soup = BeautifulSoup(page.content, features=\"lxml\")\r\n\r\n article_text = ''\r\n #Use our soup object to search for HTML

element, which indicates a paragraph of text.\r\n article = soup.findAll('p')\r\n #For each block of text found, join them in list form\r\n for element in article:\r\n article_text += '\\n' + ''.join(element.findAll(text = True))\r\n #Fix the newline characters left over\r\n article_text = article_text.replace('\\n', '')\r\n #Establish \"first_sentence\" as a first-guess of an answer\r\n first_sentence = article_text.split('.')[0]\r\n \r\n max_matches = 0\r\n answers = []\r\n #Here we are splitting the query into words and checking for the sentence in the response that contains words from the query (to avoid irrelevant text).\r\n #For each sentence in the article, split by periods, will undergo the following process.\r\n for sentence in article_text.split('.'):\r\n num_matches = 0\r\n #Iterate through each word in the query and compare to the sentence. This is a VERY simple solution.\r\n for word in query.split(' '):\r\n if word.lower() in sentence.lower():\r\n #Only compare words more than 3 letters long\r\n if len(word)>3:\r\n num_matches+=1\r\n #If the number of word matches is zero, we store the sentence for later, putting it in the top position if it has more matches than the previous zero slot,\r\n #or appending to the bottom of the list otherwise.\r\n if(num_matches > 0):\r\n ans = sentence\r\n if num_matches > max_matches:\r\n max_matches = num_matches\r\n answers.insert(0,ans)\r\n else:\r\n answers.append(ans)\r\n #Be sure to check for null values!\r\n #If the above process led to even a single result with a match, we will take that as our answer in \"first_sentence\". Otherwise, we stick to the original, first sentence.\r\n if(answers !=None and answers[0]!=''):\r\n \r\n first_sentence = str(answers[0])\r\n else:\r\n if(article_text!=None and article_text!= ''):\r\n first_sentence = article_text.split('.')\r\n else:\r\n first_sentence = fallback\r\n\r\n #If there is an error in the above process, the following will try some workarounds for a couple small, known issues with parsing data from Google.\r\n #It only varies slightly from the above, as a backup in case of error.\r\n except:\r\n #Call Google again for the search results\r\n escaped_search_term = query.replace(' ', '+')\r\n google_url = 'https://www.google.com/search?q=+define+{}'.format(escaped_search_term)\r\n reply = get(google_url, headers=usr_agent)\r\n reply.raise_for_status()\r\n\r\n \r\n search_result_list = list(parse_results(reply.text))\r\n try:\r\n page = get(search_result_list[index], headers=usr_agent)\r\n except:\r\n page = get('https://www.google.com'+search_result_list[index], headers=usr_agent)\r\n \r\n \r\n tree = html.fromstring(page.content)\r\n\r\n \r\n try:\r\n soup = BeautifulSoup(page.text, \"lxml\")\r\n article = soup.find('div', class_='Z0LcW')\r\n print('article',article.text)\r\n except:\r\n soup = BeautifulSoup(page.content, \"lxml\")\r\n article = soup.findAll('p')\r\n \r\n\r\n \r\n article_text = ''\r\n \r\n for element in article:\r\n article_text += '\\n' + ''.join(element.findAll(text = True))\r\n article_text = article_text.replace('\\n', '')\r\n max_matches = 0\r\n answers = []\r\n \r\n first_sentence = article_text.split('.')\r\n for sentence in article_text.split('.'):\r\n## print(sentence)\r\n num_matches = 0\r\n for word in query.split(' '):\r\n if word.lower() in sentence.lower():\r\n if(len(word)>=3):\r\n num_matches+=1\r\n## print(word+sentence)\r\n if num_matches > 0:\r\n ans = sentence\r\n if(num_matches > max_matches and ans != ''):\r\n max_matches = num_matches\r\n## print(\"win\",ans+' '+str(num_matches))\r\n answers.insert(0,ans)\r\n else:\r\n answers.append(ans)\r\n \r\n if(answers != None and answers[0] != ''):\r\n first_sentence = str(answers[0])\r\n## print(first_sentence)\r\n else:\r\n if(article_text!=None and article_text!= ''):\r\n first_sentence = article_text.split('.')\r\n else: first_sentence = fallback\r\n \r\n chars_without_whitespace = first_sentence.translate(\r\n { ord(c): None for c in string.whitespace }\r\n )\r\n\r\n if len(chars_without_whitespace) > 0:\r\n result = first_sentence\r\n else:\r\n result = fallback\r\n\r\n return result\r\n","sub_path":"web_query.py","file_name":"web_query.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"360966016","text":"# I am putting all packages and reading in the data here so each problem\r\n# can be specifically only the script for that given task\r\nimport pandas as pd\r\nimport numpy as np\r\nimport scipy\r\nimport scipy.integrate as spint\r\nfrom scipy import stats\r\nfrom scipy.stats import norm\r\nfrom scipy.optimize import minimize\r\nfrom plotnine import *\r\n\r\ndata = pd.read_csv('data.txt',header=0,sep=',')\r\n\r\n# Problem 1\r\nggplot(data, aes(x='x',y='y'))+geom_point()+theme_classic()\r\n\r\ndef ishump(p,obs):\r\n B0 = p[0]\r\n B1 = p[1]\r\n B2 = p[2]\r\n sigma = p[3]\r\n pred = B0+B1*data.x+B2*data.x**2\r\n nll = -1*norm(pred,sigma).logpdf(data.y).sum()\r\n return nll\r\ndef islinear(p,obs):\r\n B0 = p[0]\r\n B1 = p[1]\r\n sigma = p[2]\r\n pred = B0+B1*data.x\r\n nll = -1*norm(pred,sigma).logpdf(data.y).sum()\r\n return nll\r\n\r\nHumpGuess = np.array([1,1,1,1])\r\nLinearGuess = np.array([1,1,1])\r\nFitHump = minimize(ishump,HumpGuess,method='Nelder-Mead',args='data')\r\nFitLinear = minimize(islinear,LinearGuess,method='Nelder-Mead', args='data')\r\nteststat = 2*(FitLinear.fun-FitHump.fun)\r\ndf = len(FitHump.x)-len(FitLinear.x)\r\np_value = 1-stats.chi2.cdf(teststat,df)\r\n\r\nif p_value <= 0.05:\r\n print(\"Quadratic approximation is more accurate for this particular data\")\r\nelse:\r\n print('Linear approximation is more accurate for this particular data')\r\n\r\n# Problem 2\r\n\r\ndef LotVoltSim(y,t0,R1,R2,a11,a12,a21,a22):\r\n N1 = y[0]\r\n N2 = y[1]\r\n dN1dt = R1*(1-N1*a11-N2*a12)*N1\r\n dN2dt = R2*(1-N2*a22-N1*a21)*N2\r\n return [dN1dt,dN2dt]\r\n\r\n# The criteria for the coexistence of two species in a Lotka-Volterra Model are:\r\n# 1. a12 < a11\r\n# 2. a21 < a22 \r\n\r\n# First Model - (neither of the two coexistence criteria are satisfied)\r\n\r\ntimes = range(0,100)\r\ny0 = [1,5]\r\nparams = (0.6,0.6,0.1,0.5,0.5,0.1)\r\nsim = spint.odeint(func=LotVoltSim,y0=y0,t=times,args=params)\r\nsimDF = pd.DataFrame({\"t\":times,\"Species 1\":sim[:,0],\"Species 2\":sim[:,1]})\r\nggplot(simDF,aes(x=\"t\",y=\"Species 1\"))+geom_line()+geom_line(simDF,aes(x=\"t\",y=\"Species 2\"),color='red')+theme_classic()\r\n\r\n# Second Model - (first criterion is not satisfied, but second is)\r\ntimes = range(0,100)\r\ny0 = [1,5]\r\nparams = (0.6,0.6,0.1,0.5,0.1,0.5)\r\nsim = spint.odeint(func=LotVoltSim,y0=y0,t=times,args=params)\r\nsimDF = pd.DataFrame({\"t\":times,\"Species 1\":sim[:,0],\"Species 2\":sim[:,1]})\r\nggplot(simDF,aes(x=\"t\",y=\"Species 1\"))+geom_line()+geom_line(simDF,aes(x=\"t\",y=\"Species 2\"),color='red')+theme_classic()\r\n\r\n# Third Model - (second criterion is not satisfied, but first is)\r\ntimes = range(0,100)\r\ny0 = [1,5]\r\nparams = (0.6,0.6,0.5,0.1,0.5,0.1)\r\nsim = spint.odeint(func=LotVoltSim,y0=y0,t=times,args=params)\r\nsimDF = pd.DataFrame({\"t\":times,\"Species 1\":sim[:,0],\"Species 2\":sim[:,1]})\r\nggplot(simDF,aes(x=\"t\",y=\"Species 1\"))+geom_line()+geom_line(simDF,aes(x=\"t\",y=\"Species 2\"),color='red')+theme_classic()\r\n\r\n# Fourth Model - (both coexistence criteria are satisfied)\r\ntimes = range(0,100)\r\ny0 = [1,5]\r\nparams = (0.6,0.6,0.5,0.1,0.1,0.5)\r\nsim = spint.odeint(func=LotVoltSim,y0=y0,t=times,args=params)\r\nsimDF = pd.DataFrame({\"t\":times,\"Species 1\":sim[:,0],\"Species 2\":sim[:,1]})\r\nggplot(simDF,aes(x=\"t\",y=\"Species 1\"))+geom_line()+geom_line(simDF,aes(x=\"t\",y=\"Species 2\"),color='red')+theme_classic()","sub_path":"Exercise_10_Assignment.py","file_name":"Exercise_10_Assignment.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"624279457","text":"import numpy as np\nimport os\nfrom Neuro_Shit.Base_Loader import Base_Task_Loader\n\n\nclass Reliability():\n\n def __init__(self, task_to_covar_dict, rely_dr, cortical_dr,\n subcortical_dr, run_name=''):\n\n self.task_to_covar_dict = task_to_covar_dict\n self.run_name = run_name\n self.rely_dr = rely_dr\n \n self.prep_data(cortical_dr, subcortical_dr)\n\n def prep_data(self, cortical_dr, subcortical_dr):\n\n for task in list(self.task_to_covar_dict.keys()):\n covars_loc = self.task_to_covar_dict[task]\n \n Prep_Task_Rely(self.rely_dr, cortical_dr, subcortical_dr,\n covars_loc, task, end='.npy',\n run_name=self.run_name)\n\n\nclass Prep_Task_Rely(Base_Task_Loader):\n\n def __init__(self, rely_dr, cortical_dr, subcortical_dr, covars_loc, task,\n end='.npy', run_name=''):\n\n super().__init__(cortical_dr, subcortical_dr, covars_loc, task, end)\n\n self.rely_dr = rely_dr\n self.run_name = run_name\n\n self.load_covars()\n self.prep_dr()\n self.get_num_inds()\n self.make_data_files()\n\n def prep_dr(self):\n\n self.data_dr = os.path.join(self.rely_dr, 'data' + self.run_name)\n os.makedirs(self.data_dr, exist_ok=True)\n\n loc = os.path.join(self.data_dr, self.task + '_final_subjects.txt')\n with open(loc, 'w') as f:\n for subject in self.subject_order:\n f.write(subject)\n f.write('\\n')\n\n def load_cortical_hemi(self, hemi, ind):\n\n all_data, affine = super().load_cortical_hemi(hemi, ind)\n all_data = np.transpose(np.squeeze(all_data), (1, 0))\n\n loc = self.save_data(all_data, 'cortical_' + hemi + '_' + str(ind),\n self.data_dr, affine)\n\n def load_subcortical(self, ind):\n\n all_data, affine = super().load_subcortical(ind)\n all_data = np.transpose(np.squeeze(all_data), (1, 0))\n\n loc = self.save_data(all_data, 'subcortical_' + str(ind), self.data_dr,\n affine)\n","sub_path":"Neuro_Shit/Reliability.py","file_name":"Reliability.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569467814","text":"from typing import Optional\n\nfrom modules.core import *\n\nfrom ..base import API_VERSION\nfrom .models import BotListStats, BotQueueGet\n\nrouter = APIRouter(\n prefix = f\"/api/v{API_VERSION}\",\n include_in_schema = True,\n tags = [f\"API v{API_VERSION} - System\"]\n)\n\n@router.get(\n \"/blstats\", \n response_model = BotListStats,\n operation_id=\"blstats\"\n)\nasync def get_botlist_stats(\n request: Request,\n worker_session = Depends(worker_session)\n):\n \"\"\"\n Returns uptime and stats about the list.\n uptime - The current uptime for the given worker\n pid - The pid of the worker you are connected to\n up - Whether the databases are up on this worker\n dup - Always true now, but used to be: Whether we have connected to discord on this worker\n bot_count_total - The bot count of the list\n bot_count - The approved and certified bots on the list\n workers - The worker pids\n \"\"\"\n up = worker_session.up\n db = worker_session.postgres\n if up:\n bot_count_total = await db.fetchval(\"SELECT COUNT(1) FROM bots\")\n bot_count = await db.fetchval(\"SELECT COUNT(1) FROM bots WHERE state = 0 OR state = 6\")\n else:\n bot_count = 0\n bot_count_total = 0\n return {\n \"uptime\": time.time() - worker_session.start_time, \n \"pid\": os.getpid(), \n \"up\": up, \n \"dup\": True,\n \"bot_count\": bot_count, \n \"bot_count_total\": bot_count_total,\n \"workers\": worker_session.workers\n }\n\n@router.get(\"/features\")\ndef get_features(request: Request):\n \"\"\"Returns all of the features the list supports and information about them. Keys indicate the feature id and value is feature information. The value should but may not always have a name, type and a description keys in the json\"\"\"\n return features\n\n@router.get(\"/tags\")\ndef get_tags(request: Request):\n \"\"\"These are the tags the list supports. The key is the tag name and the value is the iconify class we use\"\"\"\n return TAGS\n\n@router.get(\n \"/is_staff\",\n operation_id=\"check_staff_member\"\n)\nasync def check_staff_member(request: Request, user_id: int, min_perm: int):\n \"\"\"Admin route to check if a user is staff or not\"\"\"\n staff = await is_staff(staff_roles, user_id, min_perm, json = True)\n return {\"staff\": staff[0], \"perm\": staff[1], \"sm\": staff[2]}\n\n@router.get(\n \"/queue/bots\", \n response_model=BotQueueGet,\n operation_id=\"get_bot_queue\"\n)\nasync def get_bot_queue(\n request: Request, \n state: enums.BotState = enums.BotState.pending, \n verifier: int = None, \n worker_session = Depends(worker_session)\n):\n \"\"\"Admin API to get the bot queue\"\"\"\n db = worker_session.postgres\n if verifier:\n bots = await db.fetch(\"SELECT bot_id, prefix, description FROM bots WHERE state = $1 AND verifier = $2 ORDER BY created_at ASC\", state, verifier)\n bots = await db.fetch(\"SELECT bot_id, prefix, description FROM bots WHERE state = $1 ORDER BY created_at ASC\", state)\n return {\"bots\": [{\"user\": await get_bot(bot[\"bot_id\"]), \"prefix\": bot[\"prefix\"], \"invite\": await invite_bot(bot[\"bot_id\"], api = True), \"description\": bot[\"description\"]} for bot in bots]}\n\n@router.get(\n \"/staff_roles\",\n operation_id=\"get_staff_roles\"\n)\ndef get_staff_roles(request: Request):\n \"\"\"Return all the staff roles so they can be used by our manager bot\"\"\"\n return staff_roles\n","sub_path":"modules/discord/api/v2/system/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102078016","text":"totamasc = tot18 = tot20 = 0\nwhile True:\n idade = int(input('Digite a idade:'))\n sexo = ' '\n while sexo not in 'MF':\n sexo = str(input('Digita o sexo [M/F]')).strip().upper()[0]\n if idade >= 18:\n tot18 += 1\n if sexo == 'M':\n totamasc += 1\n if sexo == 'F' and idade <20:\n tot20 += 1\n resp = ' '\n while resp not in 'SN':\n resp = str(input('Deseja continuar [S/N]')).strip().upper()[0]\n if resp == 'N':\n break\nprint(f'Total de pessoas com mais de 18 anos: {tot18}')\nprint(f'Temos {totamasc} homens cadastrados.')\nprint(f'Temos {tot20} mulheres com menos de 20 anos')\n\n","sub_path":"Desafios/Desafio 069.py","file_name":"Desafio 069.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277769910","text":"import csv\nimport re\n\nwith open('apprt_casa.csv', newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\";\", quotechar='\"')\n header = True\n prix_metre_total = 0\n prix_metre_secteur = {}\n nb = 0\n for row in csvreader:\n if header:\n header = False\n continue\n else:\n nb+=1\n annee = row[0]\n mois = row[1]\n prix = int(row[3])\n surface = row[5]\n secteur = row[6]\n surface_nb = int(surface[0:-2])\n prix_metre = prix/surface_nb;\n prix_metre_total += prix_metre\n if secteur in prix_metre_secteur:\n prix_metre_secteur[secteur].append(prix_metre)\n else:\n prix_metre_secteur[secteur] = [prix_metre]\n #end else\n #end for\nprint(\"moyenne total\", prix_metre_total/nb)\nwith open('prix_par_metre_casa.csv', 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=';')\n for secteur, val in prix_metre_secteur.items():\n nb_ann = len(val)\n prix_total_secteur = 0\n for prix in val:\n prix_total_secteur += prix\n moyenne = prix_total_secteur / nb_ann\n if nb_ann > 10:\n print(secteur, moyenne, nb_ann)\n csvwriter.writerow([secteur, moyenne, nb_ann])\n","sub_path":"prix_par_metre.py","file_name":"prix_par_metre.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67890305","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/romainegele/Documents/Argonne/deephyper/build/lib/deephyper/core/cli/nas_init.py\n# Compiled at: 2019-07-11 14:24:06\n# Size of source mod 2**32: 2992 bytes\nimport argparse, os, sys\n\ndef add_subparser(subparsers):\n subparser_name = 'nas-init'\n function_to_call = main\n subparser = subparsers.add_parser(subparser_name,\n help='Tool to init a neural architecture search package or a neural architecture search problem folder.')\n subparser.add_argument('--new-pckg', type=str, help='Name of the new neural architecture package to create.')\n subparser.add_argument('--new-pb', type=str, help='Name of the new neural architecture search folder to create.')\n subparser.set_defaults(func=function_to_call)\n\n\ndef main(new_pckg, new_pb, *args, **kwargs):\n pb_files = [\n '__init__.py',\n 'problem.py',\n 'load_data.py',\n 'preprocessing.py',\n 'structure.py']\n if new_pckg is not None:\n path = new_pckg\n try:\n os.mkdir(path)\n except OSError:\n print('Creation of the directory %s failed' % path)\n else:\n print('Successfully created the directory %s ' % path)\n with open(os.path.join(path, 'setup.py'), 'w') as (fp):\n fp.write(f\"from setuptools import setup\\n\\nsetup(\\n name='{new_pckg}',\\n packages=['{new_pckg}'],\\n install_requires=[]\\n)\")\n path = os.path.join(path, new_pckg)\n try:\n os.mkdir(path)\n except OSError:\n print('Creation of the directory %s failed' % path)\n else:\n print('Successfully created the directory %s ' % path)\n with open(os.path.join(path, '__init__.py'), 'w') as (fp):\n pass\n path = '/'.join(path.split('/')[:-1])\n os.chdir(path)\n cmd = f\"{sys.executable} {'setup.py'} install\"\n os.system(cmd)\n if new_pb is not None:\n os.chdir(new_pckg)\n path = os.path.join(os.getcwd(), new_pb)\n try:\n os.mkdir(path)\n except OSError:\n print('Creation of the directory %s failed' % path)\n else:\n print('Successfully created the directory %s ' % path)\n for fname in pb_files:\n file_path = os.path.join(path, fname)\n with open(file_path, 'w') as (fp):\n print(f\"create file: {file_path}\")\n if fname == 'problem.py':\n fp.write('from deephyper.benchmark import NaProblem\\n')\n\n elif new_pb is not None:\n path = os.path.join(os.getcwd(), new_pb)\n try:\n os.mkdir(path)\n except OSError:\n print('Creation of the directory %s failed' % path)\n else:\n print('Successfully created the directory %s ' % path)\n for fname in pb_files:\n file_path = os.path.join(path, fname)\n with open(file_path, 'w') as (fp):\n print(f\"create file: {file_path}\")","sub_path":"pycfiles/deephyper-0.1.6-py2.py3-none-any/nas_init.cpython-36.py","file_name":"nas_init.cpython-36.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"171343859","text":"'''\nCreated on 2015. 11. 20.\n\n@author: Haeun Kim\n@Student number: 01413456\n\n'''\ndef outputFasta(des,seq,width=80,file=None):\n if file == None: #if the file is none\n print('>'+des) #print >description first\n count = 0\n range1 = width\n for x in range(len(seq)//width): #divide the length of sequence by width \n print( seq[count:range1]) #print sequence from count to range1\n count += width\n range1 += width\n if seq[range1-width:] != '': # if written sequence from range1 minus with is nor empty string\n print(seq[range1-width:])# print sequence from range1 minus width to end\n else: # if file is output\n file.write('>' + des + '\\n') \n count = 0\n range1 = width\n for x in range(len(seq)//width):\n file.write(seq[count:range1] + '\\n') \n count += width\n range1 += width\n if seq[range1-width:] != '':\n file.writelines(seq[range1-width:] + '\\n') #\\n helps to divide the lines\n \ndef demultiplexFasta(readfile, width = 80): \n \n reader = open(readfile, 'r').read() #open the text file and read\n list1 = []\n num = ''\n for line in reader.split('>read'): \n \n if line == None:\n pass\n \n else: # if line is not none\n line = line.replace('\\n','').strip() \n # Make the sequence into one line and remove the spaces at the edges\n for char in line:\n if char.isdigit(): #only digits\n num += str(char)\n \n file_name = line[len(num):len(num) + 8] + '.fasta' #the format of file name \n \n if file_name not in list1: \n file = open(file_name,'w') #open file and write\n \n outputFasta('read' + num, line[len(num)+8:], width, file)\n #Write the sequence with the given format\n #into the indicated fasta file with the use of OutFasta function \n file.close() #close file\n else: #if file is in list1\n file = open(file_name, 'a') #open file and overwrite\n outputFasta('read' + num, line[len(num) + 8:], width, file)\n \n list1.append(file_name)\n \n num = ''","sub_path":"informatics/previous informatics/Informatics-2/Advance_problem/Demultiplexing_reads.py","file_name":"Demultiplexing_reads.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"601996757","text":"import sys\nimport numpy as np\nfrom pandas import DataFrame, Series\n\nfrom .base import BaseStateEstimate\nfrom .stateseries import StatePandasBase, StateSeries\n\nDEFAULT_STATE_COLUMN_NAME = 'states'\nPY3 = sys.version_info[0] == 3\n\n\nclass StateDataFrame(StatePandasBase, DataFrame):\n _metadata = ['_states_column_name']\n _states_column_name = DEFAULT_STATE_COLUMN_NAME\n\n def __init__(self, *args, **kwargs):\n states = kwargs.pop('states', None)\n super(StateDataFrame, self).__init__(*args, **kwargs)\n if states is not None:\n self.set_states(states, inplace=True)\n\n def __setattr__(self, attr, val):\n # have to special case states b/c pandas tries to use as column...\n if attr == 'states':\n object.__setattr__(self, attr, val)\n else:\n super(StateDataFrame, self).__setattr__(attr, val)\n\n def _get_states(self):\n if self._states_column_name not in self:\n raise AttributeError(\"No states data set yet (expected in\"\n \" column '%s'.\" % self._states_column_name)\n return self[self._states_column_name]\n\n def _set_states(self, col):\n # TODO: Use pandas' core.common.is_list_like() here.\n if not isinstance(col, (list, np.ndarray, Series)):\n raise ValueError(\"Must use a list-like to set the states\"\n \" property\")\n\n self.set_states(col, inplace=True)\n\n states = property(fget=_get_states, fset=_set_states, doc=\"states data for StateDataFrame\")\n\n def set_states(self, col, drop=False, inplace=False):\n # Most of the code here is taken from DataFrame.set_index()\n if inplace:\n frame = self\n else:\n frame = self.copy()\n\n to_remove = None\n state_column_name = DEFAULT_STATE_COLUMN_NAME\n if isinstance(col, Series):\n level = col.values\n elif isinstance(col, (list, np.ndarray)):\n level = col\n elif hasattr(col, 'ndim') and col.ndim != 1:\n raise ValueError(\"Must pass array with one dimension only.\")\n else:\n try:\n level = frame[col].values\n except KeyError:\n raise ValueError(\"Unknown column %s\" % col)\n except:\n raise\n if drop:\n to_remove = col\n state_column_name = DEFAULT_STATE_COLUMN_NAME\n else:\n state_column_name = col\n\n if to_remove:\n del frame[to_remove]\n\n if isinstance(level, StateSeries):\n level = level.copy()\n\n # Check that we are using a listlike of states\n if not all(isinstance(item, BaseStateEstimate) for item in level):\n raise TypeError(\"Input states column must contain valid states objects.\")\n frame[state_column_name] = level\n frame._states_column_name = state_column_name\n\n if not inplace:\n return frame\n\n #\n # Implement pandas methods\n #\n @property\n def _constructor(self):\n return StateDataFrame\n\n def __finalize__(self, other, method=None, **kwargs):\n \"\"\" propagate metadata from other to self \"\"\"\n # NOTE: backported from pandas master (upcoming v0.13)\n for name in self._metadata:\n object.__setattr__(self, name, getattr(other, name, None))\n return self\n\n # def copy(self, deep=True):\n # \"\"\"\n # Make a copy of this StateDataFrame object\n\n # Parameters\n # ----------\n # deep : boolean, default True\n # Make a deep copy, i.e. also copy data\n\n # Returns\n # -------\n # copy : StateDataFrame\n # \"\"\"\n # # FIXME: this will likely be unnecessary in pandas >= 0.13\n # data = self._data\n # if deep:\n # data = data.copy()\n # return StateDataFrame(data).__finalize__(self)\n\n\ndef _dataframe_set_states(self, col, drop=False, inplace=False, crs=None):\n if inplace:\n raise ValueError(\"Can't do inplace setting when converting from\"\n \" DataFrame to StateDataFrame\")\n gf = StateDataFrame(self)\n # this will copy so that BlockManager gets copied\n return gf.set_states(col, drop=drop, inplace=False, crs=crs)\n\nif PY3:\n DataFrame.set_states = _dataframe_set_states\nelse:\n import types\n DataFrame.set_states = types.MethodType(_dataframe_set_states, None,\n DataFrame)\n","sub_path":"peds/state/stateframe.py","file_name":"stateframe.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580125919","text":"import sys\nimport os\nimport time\nimport random\nimport math\nimport pygame as pg\nimport numpy as np\nfrom pygame.locals import *\nfrom Neuralnet import Neuralnet\n\nrandom.seed(time.time())\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nclass Board:\n def __init__(self, bwidth, bheight, amount_tile_w, amount_tile_h):\n self.WIDTH = bwidth\n self.HEIGHT = bheight\n self.AMOUNT_TILES_W = amount_tile_w\n self.AMOUNT_TILES_H = amount_tile_h\n\n self.Tile_width = self.WIDTH / self.AMOUNT_TILES_W\n self.Tile_height = self.HEIGHT / self.AMOUNT_TILES_H\n\n self.Board_Coords = [[(x * self.Tile_width, y * self.Tile_height) for x in range(self.AMOUNT_TILES_W)] for y in range(self.AMOUNT_TILES_H)]\n self.Board_Data = [[0 for _ in range(self.AMOUNT_TILES_W)] for y in range(self.AMOUNT_TILES_H)]\n \n def convert_board_data(self):\n lst = []\n for i in self.Board_Data:\n for j in i:\n lst.append(j)\n return lst\n\n def draw_grid(self,surface):\n for i in range(len(self.Board_Coords)):\n for j in self.Board_Coords[i]:\n rect = (j[0], j[1], self.Tile_width, self.Tile_height)\n pg.draw.rect(surface, WHITE, rect, 1)\n\n def draw(self, surface):\n for i in range(len(self.Board_Data)):\n for j in range(len(self.Board_Data[i])):\n tile_type = self.Board_Data[i][j]\n tile_coords = (self.Board_Coords[i][j][0], self.Board_Coords[i][j][1], self.Tile_width, self.Tile_height)\n \n if tile_type is 0:\n pg.draw.rect(surface, BLACK, tile_coords, 0)\n elif tile_type is 1:\n pg.draw.rect(surface, GREEN, tile_coords, 0)\n elif tile_type is 2:\n pg.draw.rect(surface, RED, tile_coords, 0)\n\n self.draw_grid(surface)\n\n def update(self, Snake):\n for piece in Snake.Segments:\n self.Board_Data[piece[0]][piece[1]] = 3\n\n for i in range(len(self.Board_Data)):\n for j in range(len(self.Board_Data[i])):\n if self.Board_Data[i][j] is 1:\n self.Board_Data[i][j] = 0\n elif self.Board_Data[i][j] is 3:\n self.Board_Data[i][j] = 1\n\n self.Board_Data[Snake.Apple[0]][Snake.Apple[1]] = 2\n\nclass Snake:\n def __init__(self, bw, bh):\n self.Length = 3\n self.Segments = [[0,x] for x in range(3)]\n self.PrevSegs = []\n self.Apple = [random.randint(0, bh-1), random.randint(0, bw-1)]\n\n self.BW = bw\n self.BH = bh\n\n self.check_apple_position()\n\n self.Direction = 1\n self.Score = 0\n self.DScore = 0\n\n def get_data(self):\n apple_y = self.Apple[0]\n apple_x = self.Apple[1]\n head_y = self.Segments[0][0]\n head_x = self.Segments[0][1]\n dy = abs(apple_y - head_y)\n dx = abs(apple_x - head_x)\n distance = math.sqrt( ( apple_y - head_y )**2 + ( apple_x - head_x )**2 )\n tail_length = len(self.Segments)\n direction = self.Direction\n return [apple_y, apple_x, head_y, head_x, dy, dx, distance, tail_length, direction]\n\n def check_apple_position(self):\n again = True\n while again:\n count = 0\n for i in self.Segments:\n if self.Apple == i:\n self.Apple = [random.randint(0, self.BH - 1), random.randint(0, self.BW - 1)]\n count += 1\n if count == 0:\n again = False\n\n def copy_list(self, lst):\n l2 = []\n for i in lst:\n l2.append(list(i))\n return l2\n\n def follow(self):\n for i in range(1, len(self.Segments)):\n self.Segments[i] = list(self.PrevSegs[i-1])\n\n def check_collision_self(self):\n pos0 = list(self.Segments[0])\n for i in range(1,len(self.Segments)):\n if self.Segments[i] == pos0:\n\n if self.DScore <= 50:\n self.Score -= 600\n elif self.DScore > 50 and self.DScore <= 150:\n self.Score -= 450\n elif self.DScore > 150 and self.DScore <= 300:\n self.Score -= 300\n elif self.DScore > 300 and self.DScore <= 600:\n self.Score -= 150\n\n return True\n return False\n\n def check_collision_apple(self):\n if self.Segments[0] == self.Apple:\n self.Segments.append([0,0])\n self.follow()\n self.check_apple_position()\n self.Score += 100\n\n def direction(self, key):\n # w = 0, s = 1, a = 2, d = 3, nothing = 4\n if key == 0 and self.Direction is not 1:\n self.Direction = 0\n elif key == 1 and self.Direction is not 0:\n self.Direction = 1\n elif key == 2 and self.Direction is not 3:\n self.Direction = 2\n elif key == 3 and self.Direction is not 2:\n self.Direction = 3\n elif key == 4:\n pass\n\n def move(self):\n self.PrevSegs = self.copy_list(self.Segments)\n if self.Direction == 0:\n self.up()\n elif self.Direction == 1:\n self.down()\n elif self.Direction == 2:\n self.left()\n elif self.Direction == 3:\n self.right()\n\n self.follow()\n if self.check_collision_self():\n return True\n self.check_collision_apple()\n self.Score -= 1\n self.DScore += 1\n\n return False\n \n def up(self):\n if self.Segments[0][0] == 0:\n self.Segments[0][0] = self.BH - 1\n else:\n self.Segments[0][0] -= 1\n\n def down(self):\n if self.Segments[0][0] == self.BH - 1:\n self.Segments[0][0] = 0\n else:\n self.Segments[0][0] += 1\n\n def left(self):\n if self.Segments[0][1] == 0:\n self.Segments[0][1] = self.BW - 1\n else:\n self.Segments[0][1] -= 1\n\n def right(self):\n if self.Segments[0][1] == self.BW - 1:\n self.Segments[0][1] = 0\n else:\n self.Segments[0][1] += 1 \n\nclass Game:\n def __init__(self, width, height, title, Neuralnet, demo):\n self.WIDTH = width\n self.HEIGHT = height\n self.TITLE = title\n self.Neural_net = Neuralnet\n self.FPS = 10\n self.Demo = demo\n pg.init()\n\n if self.Demo is True:\n self.Screen = pg.display.set_mode((self.WIDTH, self.HEIGHT))\n pg.display.set_caption(self.TITLE)\n\n self.Clock = pg.time.Clock()\n self.Running = True\n\n self.Board = Board(self.WIDTH, self.HEIGHT, 16, 12)\n self.Snake = Snake(16,12)\n\n def get_keys(self, input):\n output = self.Neural_net.feed_forward(input)\n key = np.argmax(output)\n return key\n\n def run(self):\n while self.Running:\n if self.Demo is True:\n self.Clock.tick(self.FPS)\n self.render()\n\n self.events()\n self.update()\n \n return self.Snake.Score\n pg.quit()\n\n def update(self):\n nn_key = self.get_keys(self.Snake.get_data())\n self.Snake.direction(nn_key)\n if self.Snake.move() or self.Snake.DScore >= 600:\n self.Running = False\n self.Board.update(self.Snake)\n \n def events(self):\n for event in pg.event.get():\n if event.type == pg.QUIT: \n self.Running = False\n \n def render(self):\n self.Screen.fill(BLACK)\n self.Board.draw(self.Screen)\n pg.display.flip()\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384698067","text":"import sys\nimport os\nfrom editor_utils import get_formatted_datetime\nfrom pdf2image import convert_from_path\n\n\ndef convert_to_jpeg():\n doc_source = sys.argv[1]\n target_dir = 'C:\\\\Users'\n dir_name = 'auto_print_' + get_formatted_datetime()\n target_dir_name = os.path.join(target_dir, dir_name)\n \n os.mkdir(target_dir_name)\n\n pages = convert_from_path(doc_source)\n\n current_dir = os.path.abspath(os.curdir)\n os.chdir(target_dir_name)\n\n N = len(pages)\n for n in range(N):\n save_str = str(n) + '.jpg'\n pages[n].save(save_str, 'JPEG')\n\n os.chdir(current_dir)\n print('conversion complete...check', target_dir_name, 'for output files') \n\n\nif __name__ == '__main__':\n convert_to_jpeg()\n","sub_path":"auto_printer.py","file_name":"auto_printer.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131050776","text":"from six import text_type\n\nfrom zimsoap.rest import MailRESTClient\nfrom zimsoap.client import ZimbraAbstractClient\nfrom zimsoap.client.account import ZimbraAccountClient\n\nfrom . import methods\n\n\nclass ZimbraMailClient(\n ZimbraAbstractClient,\n methods.contacts.MethodMixin,\n methods.conversations.MethodMixin,\n methods.datasources.MethodMixin,\n methods.filters.MethodMixin,\n methods.folders.MethodMixin,\n methods.messages.MethodMixin,\n methods.permissions.MethodMixin,\n methods.ranking.MethodMixin,\n methods.tasks.MethodMixin):\n \"\"\" Specialized Soap client to access zimbraMail webservice.\n\n API ref is\n http://files.zimbra.com/docs/soap_api//api-reference/zimbraMail/service-summary.html # noqa\n \"\"\"\n NAMESPACE = 'urn:zimbraMail'\n LOCATION = 'service/soap'\n REST_PREAUTH = MailRESTClient\n\n def __init__(self, server_host, server_port='443', *args, **kwargs):\n super(ZimbraMailClient, self).__init__(\n server_host, server_port,\n *args, **kwargs)\n\n def _return_comma_list(self, l):\n \"\"\" get a list and return a string with comma separated list values\n Examples ['to', 'ta'] will return 'to,ta'.\n \"\"\"\n if isinstance(l, (text_type, int)):\n return l\n\n if not isinstance(l, list):\n raise TypeError(l, ' should be a list of integers, \\\nnot {0}'.format(type(l)))\n\n str_ids = ','.join(str(i) for i in l)\n\n return str_ids\n\n def is_session_valid(self):\n # zimbraMail does not have an Auth request, so create a\n # zimbraAccount client to check.\n zac = ZimbraAccountClient(self._server_host, self._server_port)\n zac._session.import_session(self._session.authToken)\n return zac.is_session_valid()\n\n def login(self, user, password):\n # zimbraMail namespace does not have an Auth request\n # We need to authenticate with the 'urn:zimbraAccount' namespace\n self._session.login(user, password, 'urn:zimbraAccount')\n\n def search(self, query, **kwargs):\n \"\"\" Search object in account\n\n :returns: a dic where value c contains the list of results (if there\n is any). Example : {\n 'more': '0',\n 'offset': '0',\n 'sortBy': 'dateDesc',\n 'c': [\n {\n 'id': '-261',\n 'm': {'id': '261',\n 's': '2556',\n 'l': '2'},\n 'u': '0', 'd': '1450714720000',\n 'sf': '1450714720000',\n 'e': {'t': 'f',\n 'd': 'kokopu',\n 'a': 'kokopu@zimbratest3.example.com'},\n 'n': '1',\n 'fr': {'_content': 'Hello there !'},\n 'su': {'_content': 'The subject is cool'}\n }\n ]\n \"\"\"\n\n content = kwargs\n content['query'] = {'_content': query}\n\n return self.request('Search', content)\n","sub_path":"zimsoap/client/mail/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"328383611","text":"from simpledb.util.StreamTokenizer import StreamTokenizer\n\n\nclass TokenizerTest(object):\n keywords = [\"select\", \"from\", \"where\", \"and\", \"insert\", \"into\", \"values\", \"delete\", \"update\", \"set\",\n \"create\", \"table\", \"int\", \"varchar\", \"view\", \"as\", \"index\", \"on\"]\n\n @classmethod\n def main(cls, args):\n s = TokenizerTest.getStringFromUser()\n tok = StreamTokenizer(s)\n tok.ordinaryChar('.')\n tok.lowerCaseMode(True) # ids and keywords are converted to lower case\n while tok.nextToken() != StreamTokenizer.TT_EOF:\n TokenizerTest.printCurrentToken(tok)\n\n @staticmethod\n def getStringFromUser():\n print(\"Enter tokens:\")\n # select a from x,z where b = 3\n s = sys.stdin.readline()\n return s\n\n @staticmethod\n def printCurrentToken(tok):\n if tok.ttype == StreamTokenizer.TT_NUMBER:\n print(\"IntConstant \" + str(tok.nval))\n elif tok.ttype == StreamTokenizer.TT_WORD:\n word = tok.sval\n if TokenizerTest.keywords.count(word) > 0:\n print(\"Keyword \" + word)\n else:\n print(\"Id \" + word)\n elif tok.ttype == '\\'':\n print(\"StringConstant \" + tok.sval)\n else:\n print(\"Delimiter \" + tok.ttype)\n\n\nif __name__ == '__main__':\n import sys\n TokenizerTest.main(sys.argv)\n","sub_path":"simpledb/parse/TokenizerTest.py","file_name":"TokenizerTest.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"305603946","text":"# coding: utf-8\n\nfrom __future__ import division, print_function\nimport os\nos.environ['CUDA_VISIBLE_DEVICES']='0'\n\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nfrom tqdm import trange\n\nfrom model.utils import get_batch_data\nfrom model.utils import parse_anchors, read_class_names, AverageMeter\nfrom model.utils import gpu_nms\nfrom model.utils import get_color_table, plot_one_box\n\nfrom model import yolov3\nimport cv2\nimport time\nimport os\nimport copy\nimport datetime\nfrom bodai_detect import bodai_Model\n\n\n\nparser = argparse.ArgumentParser(description=\"YOLO-V3 test single image test procedure.\")\nparser.add_argument(\"--input_image\", type=str, default=\"/home/zhouzhubin/workspace/project/datasets/cow/JPEGImages/ch04_20190827165732_000654_00000001.png\",\n help=\"The path of the input image.\")\n# parser.add_argument(\"--anchor_path\", type=str, default=\"./data/my_data/cotton_anchors.txt\",\n# help=\"The path of the anchor txt file.\")\nparser.add_argument(\"--anchor_path\", type=str, default=\"./data/my_data/cow_anchors.txt\",\n help=\"The path of the anchor txt file.\")\nparser.add_argument(\"--new_size\", nargs='*', type=int, default=[416, 416], #[5440, 5440],\n help=\"Resize the input image with `new_size`, size format: [width, height]\")\nparser.add_argument(\"--class_name_path\", type=str, default=\"./data/my_data/cow_big_class.txt\",\n help=\"The path of the class names.\")\nparser.add_argument(\"--restore_path\", type=str, default=\"./checkpoint/COW_20210120_model-epoch_99_step_69199_loss_45.1756_lr_4.6042e-05\",\n help=\"The path of the weights to restore.\")\n\nargs, unknown = parser.parse_known_args()\n\nargs.anchors = parse_anchors(args.anchor_path)\nargs.classes = read_class_names(args.class_name_path)\nargs.num_class = len(args.classes)\ncolor_table = get_color_table(args.num_class)\n\n\ndef find_bbox_label(bb_label_data):\n bboxs = []\n labels = []\n data_len = len(bb_label_data)\n for i in range(data_len//5): # label bbox\n bboxs.append((float(bb_label_data[i * 5 + 1]),\n float(bb_label_data[i * 5 + 2]),\n float(bb_label_data[i * 5 + 3]),\n float(bb_label_data[i * 5 + 4])))\n labels.append(bb_label_data[i * 5])\n return bboxs, labels\n\n\ndef inference_img_dir():\n with tf.Session() as sess:\n input_data = tf.placeholder(tf.float32, [1, args.new_size[1], args.new_size[0], 3], name='input_data')\n yolo_model = yolov3(args.num_class, args.anchors)\n with tf.variable_scope('yolov3'):\n pred_feature_maps = yolo_model.forward(input_data, False)\n pred_boxes, pred_confs, pred_probs = yolo_model.predict(pred_feature_maps)\n\n pred_scores = pred_confs * pred_probs\n\n # pred_scores = pred_probs\n\n boxes, scores, labels = gpu_nms(pred_boxes, pred_scores, args.num_class, max_boxes=150, score_thresh=0.2,\n nms_thresh=0.2)\n\n saver = tf.train.Saver()\n saver.restore(sess, args.restore_path)\n\n # txt file\n # txt_data = './data/my_data/bcs_20200429.txt'\n # for line in open(txt_data, 'r').readlines():\n # s = line.strip().split(' ')\n # input_image = s[0]\n # frame = cv2.imread(os.path.join('/home/zhouzhubin/sjht_data/', input_image))\n\n # img_dir\n # img_dir = '/home/zhouzhubin/workspace/project/datasets/cow/JPEGImages/'\n # img_dir = '/home/zhouzhubin/data/cowrecognition/monitor_video/pickdir/0428/042803'\n img_dir = '/home/zhouzhubin/sjht_data/images/gmnnc-bs/gmnnc-bs-2020051204/1'\n # img_dir = '/home/zhouzhubin/NFS_AIDATA/bodyscore/BCS/GH010131'\n # img_dir = '/home/zhouzhubin/NFS_AIDATA/bodyscore/0422/images'\n\n img_list = os.listdir(img_dir)\n for input_image in img_list:\n\n # frame = cv2.imread(args.input_image)\n frame = cv2.imread(os.path.join(img_dir, input_image))\n print(input_image)\n\n start = time.time()\n\n img_ori = frame\n height_ori, width_ori = img_ori.shape[:2]\n\n img = cv2.resize(img_ori, tuple(args.new_size))\n img_show = copy.deepcopy(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = np.asarray(img, np.float32)\n img = img[np.newaxis, :] / 255.\n boxes_, scores_, labels_, pred_confs_, pred_probs_ = sess.run(\n [boxes, scores, labels, pred_confs, pred_probs],\n feed_dict={input_data: img})\n #\n # for i in range(len(boxes_)):\n # x0, y0, x1, y1 = boxes_[i]\n # s = (x1 - x0) * (y1 - y0)\n # if s > 0:\n # plot_one_box(img_show, [x0, y0, x1, y1], label=args.classes[labels_[i]], color=color_table[labels_[i]], conf=scores_[i])\n\n # rescale the coordinates to the original image\n boxes_[:, 0] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 2] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 1] *= (height_ori / float(args.new_size[1]))\n boxes_[:, 3] *= (height_ori / float(args.new_size[1]))\n\n # print(\"box coords:\")\n # print(boxes_)\n # print('*' * 30)\n # print(\"scores:\")\n # print(scores_)\n # print('*' * 30)\n # print(\"labels:\")\n # print(labels_)\n\n for i in range(len(boxes_)):\n x0, y0, x1, y1 = boxes_[i]\n s = (x1 - x0) * (y1 - y0)\n if s > 0:\n plot_one_box(img_ori, [x0, y0, x1, y1], label=args.classes[labels_[i]],\n color=color_table[labels_[i]], conf=scores_[i])\n\n # cv2.imwrite('find.jpg', img_ori)\n # img_ori = cv2.resize(img_ori, (960, 960))\n cv2.namedWindow(\"Detection result\", cv2.WND_PROP_FULLSCREEN)\n end = time.time()\n cv2.imshow('Detection result', img_ori)\n # cv2.imshow('show', img_show)\n print(\"time is %f, number is %d, hair rata is %f, not hair rata is %f\" % (\n (end - start), len(boxes_), len(boxes_) / 36, len(boxes_) / 31))\n # cv2.imwrite('detection_result.jpg', img_ori)\n cv2.waitKey(0)\n\n\ndef inference_txt(txt):\n with tf.Session() as sess:\n input_data = tf.placeholder(tf.float32, [1, args.new_size[1], args.new_size[0], 3], name='input_data')\n yolo_model = yolov3(args.num_class, args.anchors)\n with tf.variable_scope('yolov3'):\n pred_feature_maps = yolo_model.forward(input_data, False)\n pred_boxes, pred_confs, pred_probs = yolo_model.predict(pred_feature_maps)\n\n pred_scores = pred_confs * pred_probs\n\n # pred_scores = pred_probs\n\n boxes, scores, labels = gpu_nms(pred_boxes, pred_scores, args.num_class, max_boxes=150, score_thresh=0.8,\n nms_thresh=0.5)\n\n saver = tf.train.Saver()\n saver.restore(sess, args.restore_path)\n\n # txt file\n # txt_data = './data/my_data/bcs_20200429.txt'\n # for line in open(txt_data, 'r').readlines():\n # s = line.strip().split(' ')\n # input_image = s[0]\n # frame = cv2.imread(os.path.join('/home/zhouzhubin/sjht_data/', input_image))\n\n # img_dir\n\n img_dir = '/home/zhouzhubin/sjht_data/'\n\n data = open(txt, 'r')\n line_datas = data.readlines()\n for line_data in line_datas:\n\n line_list = line_data.strip('\\n').split(' ')\n line_list = line_list[1:] # 去除id\n input_image = line_list[0]\n\n frame = cv2.imread(os.path.join(img_dir, input_image))\n print(input_image)\n\n start = time.time()\n\n img_ori = frame\n height_ori, width_ori = img_ori.shape[:2]\n\n img = cv2.resize(img_ori, tuple(args.new_size))\n img_show = copy.deepcopy(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = np.asarray(img, np.float32)\n img = img[np.newaxis, :] / 255.\n boxes_, scores_, labels_, pred_confs_, pred_probs_ = sess.run(\n [boxes, scores, labels, pred_confs, pred_probs],\n feed_dict={input_data: img})\n #\n # for i in range(len(boxes_)):\n # x0, y0, x1, y1 = boxes_[i]\n # s = (x1 - x0) * (y1 - y0)\n # if s > 0:\n # plot_one_box(img_show, [x0, y0, x1, y1], label=args.classes[labels_[i]], color=color_table[labels_[i]], conf=scores_[i])\n\n # rescale the coordinates to the original image\n boxes_[:, 0] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 2] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 1] *= (height_ori / float(args.new_size[1]))\n boxes_[:, 3] *= (height_ori / float(args.new_size[1]))\n\n bb_label_data = line_list[1:]\n bboxs, labels_GT = find_bbox_label(bb_label_data)\n num = 0\n for bbox in bboxs:\n cv2.rectangle(img_ori, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), [255, 255, 0], 5)\n if labels_GT[num].startswith('b'):\n cv2.putText(img_ori, str(labels_GT[num]), (int(bbox[0]), int(bbox[1]) + 10),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 2)\n elif labels_GT[num].startswith('n'):\n cv2.putText(img_ori, str(labels_GT[num][4:]), (int(bbox[0]), int(bbox[1]) + 10),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 2)\n elif labels_GT[num].startswith('c'):\n cv2.putText(img_ori, str(labels_GT[num][4:]), (int(bbox[0]), int(bbox[1]) + 10),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 2)\n num += 1\n\n for i in range(len(boxes_)):\n x0, y0, x1, y1 = boxes_[i]\n s = (x1 - x0) * (y1 - y0)\n if s > 0:\n plot_one_box(img_ori, [x0, y0, x1, y1], label=args.classes[labels_[i]],\n color=color_table[labels_[i]], conf=scores_[i])\n\n # cv2.imwrite('find.jpg', img_ori)\n # img_ori = cv2.resize(img_ori, (960, 960))\n cv2.namedWindow(\"Detection result\", cv2.WND_PROP_FULLSCREEN)\n end = time.time()\n cv2.imshow('Detection result', img_ori)\n # cv2.imshow('show', img_show)\n print(\"time is %f, number is %d, hair rata is %f, not hair rata is %f\" % (\n (end - start), len(boxes_), len(boxes_) / 36, len(boxes_) / 31))\n # cv2.imwrite('detection_result.jpg', img_ori)\n cv2.waitKey(0)\n\n\ndef cut_pic_from_videos():\n #anchor_path = './data/bodai/bodai_anchors.txt'\n #input_size = [416, 416]\n #model_path = './checkpoint/bodai_0919_model-epoch_99_step_44699_loss_1.8250_lr_4.6042e-05'\n\n #bodai_model = bodai_Model(model_path, 1, input_size, anchor_path, 0.2, 0.2)\n\n\n print(\"Start!!!\")\n with tf.Session() as sess:\n input_data = tf.placeholder(tf.float32, [1, args.new_size[1], args.new_size[0], 3], name='input_data')\n yolo_model = yolov3(args.num_class, args.anchors)\n with tf.variable_scope('yolov3'):\n pred_feature_maps = yolo_model.forward(input_data, False)\n pred_boxes, pred_confs, pred_probs = yolo_model.predict(pred_feature_maps)\n\n pred_scores = pred_confs * pred_probs\n\n # pred_scores = pred_probs\n\n boxes, scores, labels = gpu_nms(pred_boxes, pred_scores, args.num_class, max_boxes=150, score_thresh=0.5,\n nms_thresh=0.45)\n\n saver = tf.train.Saver()\n print(\"start restore\")\n saver.restore(sess, args.restore_path)\n print(\"end restore\")\n\n video_path = '/home/zhouzhubin/NFS_AIDATA/cow_video/cowid/suqian-14-1119/DVR_Examiner_Export_2020-11-25 174020_Job_0002/2020-11-19/part01'\n video_list = os.listdir(video_path)\n print(len(video_list))\n for video in video_list:\n\n if video.endswith('.mp4') or video.endswith('.MP4'):\n video_imgs_path = os.path.join(video_path, \"images\", video[:-4])\n if not os.path.exists(video_imgs_path):\n os.makedirs(video_imgs_path)\n else:\n print(\"This video had save pics!\")\n continue\n\n cap = cv2.VideoCapture(os.path.join(video_path, video))\n\n fps = 0.0\n num = 0\n while True:\n t1 = time.time()\n ret, frame = cap.read()\n\n if not ret:\n print(\"video is over!\")\n break\n if num == 105:\n num = 0\n img_ori = copy.deepcopy(frame)\n height_ori, width_ori = img_ori.shape[:2]\n img = cv2.resize(frame, tuple(args.new_size))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = np.asarray(img, np.float32)\n img = img[np.newaxis, :] / 255.\n boxes_, scores_, labels_, pred_confs_, pred_probs_ = sess.run(\n [boxes, scores, labels, pred_confs, pred_probs],\n feed_dict={input_data: img})\n # box转化\n boxes_[:, 0] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 2] *= (width_ori / float(args.new_size[0]))\n boxes_[:, 1] *= (height_ori / float(args.new_size[1]))\n boxes_[:, 3] *= (height_ori / float(args.new_size[1]))\n for i in range(len(boxes_)):\n x0, y0, x1, y1 = boxes_[i]\n s = (x1 - x0) * (y1 - y0)\n x0 = max(0, x0)\n x1 = max(0, x1)\n y0 = max(0, y0)\n y1 = max(0, y1)\n if s > 0:\n # plot_one_box(img_ori, [x0, y0, x1, y1], label=args.classes[labels_[i]],\n # color=color_table[labels_[i]], conf=scores_[i])\n time_str = datetime.datetime.now().strftime('_%H%M%S_%f')\n img_cut = img_ori[int(y0):int(y1), int(x0):int(x1), :]\n #boxes_bodai, _, _, _, _ = bodai_model.forward(img_cut)\n #if len(boxes_bodai) == 0:\n # continue\n #for box_b in boxes_bodai:\n # x0_b, y0_b, x1_b, y1_b = box_b\n # cv2.rectangle(img, (int(x0_b), int(y0_b)), (int(x1_b), int(y1_b)), [0, 0, 0], 4)\n img_cut_name = video[:-4] + time_str + '.jpg'\n print(img_cut_name)\n try:\n \n cv2.imwrite(os.path.join(video_imgs_path, img_cut_name), img_cut)\n except:\n print(\"img_cut is None!\")\n #cv2.namedWindow(\"Detection result\", cv2.WND_PROP_FULLSCREEN)\n #cv2.imshow('Detection result', img_ori)\n #cv2.waitKey(0)\n num += 1\n cap.release()\n\n\nif __name__ == '__main__':\n # txt = './data/my_data/val_qcj_20200827_data_with_id.txt'\n # inference_txt(txt)\n cut_pic_from_videos()\n","sub_path":"YOLOv3_tensorflow_from_zzb/test_show_result_1.py","file_name":"test_show_result_1.py","file_ext":"py","file_size_in_byte":15966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"506462259","text":"import datetime\nimport numpy as np\nimport plotly\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\nprogrammers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne']\n\nbase = datetime.datetime.today()\ndate_list = [x for x in range(1, 13)]\n\nz = []\n\nfor prgmr in programmers:\n new_row = []\n for date in date_list:\n new_row.append( np.random.poisson() )\n z.append(list(new_row))\n\ndata = [\n go.Heatmap(\n z=z,\n x=date_list,\n y=programmers,\n colorscale='Viridis',\n )\n]\n\nlayout = go.Layout(\n title='GitHub commits per day',\n xaxis = dict(ticks='', nticks=12),\n yaxis = dict(ticks='' )\n)\n\nfig = go.Figure(data=data, layout=layout)\nplotly.offline.plot(fig, filename='datetime-heatmap')","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256603811","text":"import datetime\nimport numpy as np\nfrom sklearn.covariance import GraphLasso\nfrom sklearn.decomposition import PCA as skPCA\nimport pandas as pd\nimport matplotlib\nimport itertools\nfrom sklearn.preprocessing import scale\nimport community\nimport matplotlib.pyplot as plt\nimport os\nimport networkx as nx\nfrom sklearn import cluster, covariance, manifold\nfrom matplotlib import collections\nimport seaborn as sns\n\n\ndef return_top_pca_gene(by_cell_matrix, range_genes = None):\n gene_number = 100\n gene_pca = skPCA(n_components=3)\n np_by_gene = np.asarray(by_cell_matrix.transpose())\n gene_index = by_cell_matrix.index.tolist()\n\n if range_genes is not None:\n start_num= range_genes[0]\n end_num_genes = range_genes[1]\n else:\n start_num = 0\n end_num_genes = min(gene_number, len(gene_index))\n by_gene_trans = gene_pca.fit_transform(np_by_gene)\n Pc_df = pd.DataFrame(gene_pca.components_.T, columns=['PC-1', 'PC-2', 'PC-3'], index=gene_index)\n pca_rank_df = Pc_df.abs().sum(axis=1)\n Pc_sort_df = pca_rank_df.nlargest(len(gene_index))\n top_pca_list = Pc_sort_df.index.tolist()\n new_cell_matrix = by_cell_matrix.ix[top_pca_list[start_num:end_num_genes],:]\n return new_cell_matrix.transpose(), top_pca_list[start_num:end_num_genes]\n\ndef save_network_graph( matrix, labels, filename, title, scale=8, node_weight = None, layout = \"circular\", weight = lambda x: abs(4*x)**(2.5)):\n labels = dict( zip( range( len(labels) ), labels) )\n d = matrix.shape[0]\n D = nx.Graph(matrix)\n weights = [ D[x][y]['weight'] for x,y in D.edges() ]\n large_cutoff = np.mean(weights) + np.std(weights)\n small_cutoff = np.mean(weights) - np.std(weights)\n elarge=[(u,v) for (u,v,d) in D.edges(data=True) if d['weight'] >large_cutoff]\n esmall=[(u,v) for (u,v,d) in D.edges(data=True) if d['weight'] <=small_cutoff]\n #weights = weights/np.max( np.abs( weights ) )\n cmap = plt.get_cmap( \"Reds\" ) #or some other one\n\n fig = plt.figure(figsize=(50,50))\n ax = fig.add_subplot(111)\n if layout == \"circular\":\n \tpos = nx.circular_layout( D, scale =scale )\n elif layout == \"spring\":\n \tpos = nx.spring_layout( D ,scale = scale, iterations = 35 )\n\n bweights = [ 'k'*(z<0) + 'r'*(z>0) for z in weights ]\n width_small = [ weight(w) for w in weights if w <= small_cutoff]\n width_large = [ weight(w) for w in weights if w > large_cutoff]\n nx.draw_networkx_edges(D,pos,edgelist=elarge,\n edge_color= \"green\", width=width_large, )\n nx.draw_networkx_edges(D,pos,edgelist=esmall,width=width_small,alpha=0.5,edge_color=\"red\",style='dashed')\n if node_weight == None:\n nx.draw_networkx_nodes( D, pos, ax=ax, node_size = 1, node_color=\"black\")\n else:\n nx.draw_networkx_nodes( D, pos, ax=ax, node_size = node_weight, node_color=\"black\", alpha=0.4)\n nx.draw_networkx_labels( D, pos,font_size=18, labels = labels, ax = ax)\n plt.axis(\"off\")\n plt.title(title)\n plt.savefig( filename, bbox_inches=\"tight\")\n\npath_to_file = '/Users/iandriver/Downloads/monocle2_5state_groups_all_genes_nocc_scicast_analysis/count_matrix_after_filtering.txt'\n\n\n#load file gene\nby_cell = pd.DataFrame.from_csv(path_to_file, sep='\\t')\nby_gene = by_cell.transpose()\n#create list of genes\ngene_list = by_cell.index.tolist()\n#create cell list\ncell_list = [x for x in list(by_cell.columns.values)]\n\n\ndf_by_gene1 = pd.DataFrame(by_gene, columns=gene_list, index=cell_list)\ndf_by_cell1 = pd.DataFrame(by_cell, columns=cell_list, index=gene_list)\nlog2_df_cell = np.log2(df_by_cell1+1)\nalpha=0.4\nkeep_genes = []\nnum_iterations = 3\ngene_index_list = list(range(0,((num_iterations+1)*100), 100))\n\nfor iter_genes in range(0,num_iterations):\n top_pca_matrix, top_pca_genes = return_top_pca_gene(log2_df_cell,range_genes=[gene_index_list[max(0,iter_genes-1)],gene_index_list[iter_genes+1]])\n mean_expr_dict = {}\n\n gl = covariance.GraphLassoCV()\n gene_data = scale(top_pca_matrix.as_matrix())\n\n gl.fit(gene_data)\n _, labels = cluster.affinity_propagation(gl.covariance_)\n\n n_labels = labels.max()\n names = np.array(top_pca_genes)\n prec_sp = gl.precision_\n matrix1 = -prec_sp + np.diag( np.diagonal( prec_sp) )\n D = nx.Graph(matrix1)\n\n gene_weights_dict ={}\n for n in names:\n gene_weights_dict[n] = 0\n for x,y in D.edges():\n gene1 = names[x]\n gene2 = names[y]\n abs_weight = abs(D[x][y]['weight'])\n gene_weights_dict[gene1] += abs_weight\n gene_weights_dict[gene2] += abs_weight\n\n clust_gene_list = []\n avg_wieght_list = []\n for i in range(n_labels + 1):\n clust_id = \"cluster_\"+str(i+1)\n w_list = [gene_weights_dict[g] for g in names[labels == i]]\n clust_gene_list.append([names[labels == i]])\n avg_wieght_list.append(sum(w_list)/len(w_list))\n print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])))\n if iter_genes == 0:\n threshold = np.mean(avg_wieght_list)-np.std(avg_wieght_list)\n\n for g_list in [clust_gene_list[i] for i,av in enumerate(avg_wieght_list) if av >= threshold]:\n keep_genes.append(np.ravel(g_list))\n\n\nfinal_gene_list = list(set([item for sublist in keep_genes for item in sublist]))\nprint(final_gene_list)\ngene_matrix_log2 = log2_df_cell.T\ntop_matrix = gene_matrix_log2[final_gene_list]\nmean_expr_dict = {}\nfor g in final_gene_list:\n g_expr = top_matrix[g]\n mean_expr_dict[g] = np.mean(g_expr)\n\nnode_weights =[int(500*round(v)) for k,v in mean_expr_dict.items()]\ngl = covariance.GraphLassoCV()\ngene_data = scale(top_matrix.as_matrix())\n\ngl.fit(gene_data)\n_, labels = cluster.affinity_propagation(gl.covariance_)\nn_labels = labels.max()\nnames = np.array(final_gene_list)\n\nprec_sp = gl.precision_\n\nnode_position_model = manifold.LocallyLinearEmbedding(\n n_components=2, eigen_solver='dense', n_neighbors=7)\n\nembedding = node_position_model.fit_transform(gene_data.T).T\n\n\nplt.figure(1, facecolor='w', figsize=(10, 8))\nplt.clf()\nax = plt.axes([0., 0., 1., 1.])\nplt.axis('off')\n\n# Display a graph of the partial correlations\npartial_correlations = gl.precision_.copy()\nd = 1 / np.sqrt(np.diag(partial_correlations))\npartial_correlations *= d\npartial_correlations *= d[:, np.newaxis]\nnon_zero = (np.abs(np.triu(partial_correlations, k=1)) > 0.02)\n\n# Plot the nodes using the coordinates of our embedding\ncm = plt.cm.get_cmap('spectral')\n#cmap = [cm(1.*i/len(embedding[0])) for i in range(len(embedding[0]))]\n\n\nplt.scatter(embedding[0], embedding[1], s=100 * d ** 2, c=labels,\n cmap=cm)\n\n# Plot the edges\nstart_idx, end_idx = np.where(non_zero)\n#a sequence of (*line0*, *line1*, *line2*), where::\n# linen = (x0, y0), (x1, y1), ... (xm, ym)\nsegments = [[embedding[:, start], embedding[:, stop]]\n for start, stop in zip(start_idx, end_idx)]\nvalues = np.abs(partial_correlations[non_zero])\nlc = collections.LineCollection(segments,\n zorder=0, cmap=plt.cm.hot_r,\n norm=plt.Normalize(0, .7 * values.max()))\nlc.set_array(values)\nlc.set_linewidths(15 * values)\nax.add_collection(lc)\n\n# Add a label to each node. The challenge here is that we want to\n# position the labels to avoid overlap with other labels\nfor index, (name, label, (x, y)) in enumerate(\n zip(names, labels, embedding.T)):\n\n dx = x - embedding[0]\n dx[index] = 1\n dy = y - embedding[1]\n dy[index] = 1\n this_dx = dx[np.argmin(np.abs(dy))]\n this_dy = dy[np.argmin(np.abs(dx))]\n if this_dx > 0:\n horizontalalignment = 'left'\n x = x + .002\n else:\n horizontalalignment = 'right'\n x = x - .002\n if this_dy > 0:\n verticalalignment = 'bottom'\n y = y + .002\n else:\n verticalalignment = 'top'\n y = y - .002\n plt.text(x, y, name, size=10,\n horizontalalignment=horizontalalignment,\n verticalalignment=verticalalignment,\n bbox=dict(facecolor='w',\n edgecolor=plt.cm.nipy_spectral(label / float(n_labels)),\n alpha=.6))\n\nplt.xlim(embedding[0].min() - .15 * embedding[0].ptp(),\n embedding[0].max() + .10 * embedding[0].ptp(),)\nplt.ylim(embedding[1].min() - .03 * embedding[1].ptp(),\n embedding[1].max() + .03 * embedding[1].ptp())\n\nplt.savefig(os.path.join(os.path.dirname(path_to_file),'linedraw_graph.pdf'),bbox_inches=\"tight\")\n\ndef community_cluster(cov_sp, symbols):\n\tG = nx.Graph( cov_sp )\n\tpartition = community.best_partition( G )\n\tfor i in set(partition.values() ):\n\t\tprint(\"Community: \",i)\n\t\tmembers = [ symbols[node] for node in partition.keys() if partition[node] == i]\n\t\tprint(members)\n\n\ndef affinity_cluster( cov_sp, symbols):\n\tprint(\"Affinity cluster\")\n\tap = cluster.AffinityPropagation()\n\tap.fit( cov_sp )\n\tlabels = np.array( ap.labels_ )\n\tfor i in set(ap.labels_):\n\t\tprint(\"Community: \",i)\n\t\tmembers = [ symbols[node] for node in np.nonzero( labels == i)[0]]\n\t\tprint(members)\n#community_cluster(gl.covariance_, top_pca_genes)\n#affinity_cluster(gl.covariance_, final_gene_list)\nsave_network_graph( -prec_sp + np.diag( np.diagonal( prec_sp) ), names, os.path.join(os.path.dirname(path_to_file),\"LargeNetworkNo_SP.pdf\"), title=\"spring_sp_prec_test\",layout=\"spring\", scale= 10, node_weight=node_weights, weight = lambda x: abs(5*x)**(2.5))\nsave_network_graph( gl.covariance_, names, os.path.join(os.path.dirname(path_to_file),\"cov_diagram.pdf\"), node_weight=node_weights, title=\"cov_test\", scale = 8, layout = \"spring\" )\nsave_network_graph( gl.precision_, names, os.path.join(os.path.dirname(path_to_file),\"precision.pdf\") , title=\"Precision Matrix Network\", layout=\"spring\", node_weight= node_weights)\n","sub_path":"graphlasso-covarience.py","file_name":"graphlasso-covarience.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30689782","text":"from django import template\n\nfrom customer.helpers.credit import get_total_credit, get_total_credit_letter, STRATEGIES\n\n\ndef has_perm_or_is_owner(user_obj, permissions, instance=None, colleague=None):\n if user_obj.is_superuser:\n return True\n if colleague is not None and colleague:\n if hasattr(instance, 'is_active'):\n return instance.is_active\n else:\n return colleague\n if instance is not None:\n if user_obj == instance.owner:\n if hasattr(instance, 'is_active'):\n return instance.is_active and user_obj.has_perm(permissions)\n else:\n return user_obj.has_perm(permissions)\n if hasattr(instance, 'customer') and not hasattr(instance, 'xpref_id'):\n if user_obj == instance.customer.user or user_obj in instance.colleagues.all():\n return True\n else:\n return False\n elif hasattr(instance, 'req_id') and hasattr(instance.req_id, 'customer'):\n if user_obj == instance.req_id.customer.user \\\n or user_obj == instance.req_id.owner \\\n or user_obj in instance.req_id.colleagues.all():\n return True\n else:\n return False\n elif hasattr(instance, 'xpref_id') and hasattr(instance.xpref_id.req_id, 'customer'):\n if user_obj == instance.xpref_id.req_id.customer.user \\\n or user_obj in instance.xpref_id.req_id.colleagues.all() \\\n or user_obj == instance.xpref_id.req_id.owner:\n return True\n if instance.__class__.__name__ == 'User':\n return user_obj == instance\n if instance.__class__.__name__ == 'Payment':\n return user_obj == instance.owner\n return user_obj.has_perm(permissions)\n\n\nregister = template.Library()\n# register.filter()\n\n\n@register.filter\ndef hash(h, key):\n return h[key]\n\n\n@register.simple_tag()\ndef format_number(date, number):\n from request.helpers import helpers\n return helpers.format_number(date, number)\n\n@register.simple_tag\ndef relative_url(value, field_name, urlencode=None):\n url = '?{}={}'.format(field_name, value)\n if urlencode:\n querystring = urlencode.split('&')\n filtered_querystring = filter(lambda p: p.split('=')[0] != field_name, querystring)\n encoded_querystring = '&'.join(filtered_querystring)\n url = '{}&{}'.format(url, encoded_querystring)\n return url\n\n\n@register.simple_tag\ndef credits(customer):\n credit_total = get_total_credit(customer, STRATEGIES)\n credit_letter = get_total_credit_letter(credit_total)\n context = {\n 'value': credit_total,\n 'letter': credit_letter\n }\n return context\n\n\n@register.filter(name='if_in_list')\ndef if_in_list(value, cl):\n return str(value) in cl\n","sub_path":"app/request/templatetags/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226934669","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 17 16:36:57 2017\n\n@author: Toshiharu\n\nThis script load a previously trained model, and retrain it using new data for\nfine tuning\n\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten, Dropout, Lambda, Cropping2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers import Conv2D\nfrom keras.optimizers import SGD, Adam, RMSprop\nfrom keras.callbacks import EarlyStopping\n\nfrom keras.regularizers import l2\n\nEPOCHS = 20\n\nmodel = Sequential()\nmodel.add(Lambda(lambda x: (x/255-0.5)*2, input_shape=(160,320,3)))\nmodel.add(Cropping2D(cropping=((65,25),(0,0)))) #Cropping top 60 pixels, bottom 25 pixels\n\n# Layer 1\nmodel.add(Conv2D(24,kernel_size=(5,5),activation='relu',subsample=(2,2))) #(75-5+1)/2 = 36\n#model.add(MaxPooling2D(pool_size=(2,2)))\n# Layer 2\nmodel.add(Conv2D(36,kernel_size=(5,5),activation='relu',subsample=(2,2))) #(36-5+1)/2 = 16\n# Layer 3\nmodel.add(Conv2D(48,kernel_size=(5,5),activation='relu',subsample=(2,2))) # (16-5+1)/2 = 6\n# Layer 4\nmodel.add(Conv2D(64,kernel_size=(3,3),activation='relu',subsample=(2,2))) # (6-2+1)/1 = 5\n# Layer 5\nmodel.add(Conv2D(64,kernel_size=(2,2),activation='relu',subsample=(1,1))) # (6-2+1)/1 = 5\n# Full dense layers\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='elu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256, activation='elu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(64, activation='elu'))\n#model.add(Dropout(0.1))\nmodel.add(Dense(1, activation='tanh'))\n#model.add(Dense(1, W_regularizer = l2(0.001)))\n#model.add(Dense(1, init='zero'))\n#model.add(Dense(1, activation='elu',init='zero'))\n\nadam = Adam(lr=1e-03, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.7) \nearly_stopping = EarlyStopping(monitor='val_loss',\n patience=1,\n min_delta=0.00009)\n\nmodel.compile(loss='mse', optimizer = adam)\n\nimport pickle\nimport numpy as np\n\nold_weights = 'track2origin4.h5'\nnew_data = 'track2finetune5.p'\n\nmodel.load_weights(old_weights)\nprint(\"Loaded weights from: \"+ old_weights)\n\ntraining_file = 'G:/Documents/GITHUB/CarND-DataSets/data/' + new_data\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\n \nX_train, y_train = train['features'], train['steering']\n\nimport matplotlib.pyplot as plt\n# Visualizations will be shown in the notebook.\n\nplt.hist(y_train,bins=50)\nplt.show()\n\nmodel.fit(X_train,y_train,validation_split = 0.1, shuffle=True, epochs=EPOCHS,callbacks=[early_stopping])\n\nmodel.save(new_data[:-2] + '.h5')\nprint(\"Saved new trained weights in: \"+ new_data[:-2] + '.h5')","sub_path":"fine_tuning.py","file_name":"fine_tuning.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526329541","text":"import serial\nimport time\n\nser = serial.Serial('/dev/tty.usbmodem1411' ) # open serial port\nprint(ser.name) # check which port was really used\ntime.sleep(2.0)\nser.write('cmd') # write a string\ntime.sleep(.1)\ns = ser.read(5)\nprint(s)\nser.close() # close port\n","sub_path":"SerialRoscoeCommand.py","file_name":"SerialRoscoeCommand.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102434496","text":"import cv2\nimg1 = cv2.imread(r\"EDIZ\\OPENCV\\3D-Matplotlib.png\")\nimg2 = cv2.imread(r\"EDIZ\\OPENCV\\thuglife.png\")\n\nrows,cols,channels = img2.shape\nroi = img1[0:rows,0:cols]\n\nimg2gri = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)\n\nret,mask = cv2.threshold(img2gri,220,255,cv2.THRESH_BINARY_INV)\n\nmask_inv = cv2.bitwise_not(mask)\n\nimg1_bg = cv2.bitwise_and(roi,roi,mask=mask_inv)\n\nimg2_fg = cv2.bitwise_and(img2,img2,mask=mask)\ndst = cv2.add(img1_bg,img2_fg)\nimg1[0:rows,0:cols] = dst\n\ncv2.imshow(\"ilkresim\",img1)\n# add = img1+img2\n\n# add = cv2.add(img1,img2)\n\n# add = cv2.addWeighted(img1,0.6,img2,0.4,0)\n\n\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"EDIZ/OPENCV/opencv5.py","file_name":"opencv5.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569968508","text":"\nfrom __future__ import print_function\nimport os\nimport sys\nfrom subprocess import Popen, PIPE\nimport tempfile\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nclass ShError(Exception):\n def __init__(self, err, out=None, retval=None):\n super().__init__(err)\n self.out = out\n self.retval = retval\n\ndef sh(cmd, join=False, lines=False, fail=True):\n shell = isinstance(cmd, str)\n if shell:\n # Popen with shell=True defaults to /bin/sh so in order to use bash and\n # avoid quoting problems we write cmd into a temp file\n fd, cmd_file = tempfile.mkstemp(prefix='/tmp/sh')\n with open(cmd_file, 'w') as file:\n file.write(cmd)\n os.close(fd)\n cmd = \"/usr/bin/env bash {cmd_file}\".format(cmd_file=cmd_file)\n proc = Popen(cmd, shell=shell, stdout=PIPE, stderr=PIPE)\n out, err = proc.communicate()\n if shell:\n os.unlink(cmd_file)\n out = out.strip()\n if lines is True:\n join = False\n if lines is True or join is not False:\n out = out.split(\"\\n\")\n if join is not False:\n s = join if type(join) is str else ' '\n out = s.join(out)\n if proc.returncode != 0 and fail is True:\n raise ShError(err, out=out, retval=proc.returncode)\n return out\n","sub_path":"paella/utils2.py","file_name":"utils2.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286530620","text":"from flask import Blueprint, jsonify, make_response, request\nfrom flask_api import status\nfrom ..security.sec_utils import token_required, api_key_required\nfrom ..db import db_tweets\n\ntweets = Blueprint('/api/tweets', __name__)\n\n@tweets.route(\"/api/tweets\", methods=[\"GET\"])\n@api_key_required\ndef get_tweets():\n user_id = None\n\n if request.args:\n user_id = request.args[\"userId\"]\n \n # Get Tweets by User Id\n if user_id:\n user_tweets = db_tweets.get_tweets_by_user_id(user_id) \n if user_tweets:\n return make_response(jsonify(user_tweets), status.HTTP_200_OK)\n else:\n return make_response(jsonify({\"message\": \"User not found\"}), status.HTTP_404_NOT_FOUND)\n \n # Get all Tweets\n else:\n result = db_tweets.get_all_tweets()\n if not result:\n return make_response(jsonify({\"message\": \"No results found\"}), status.HTTP_404_NOT_FOUND)\n else:\n return make_response(jsonify(result), status.HTTP_200_OK)\n\n@tweets.route(\"/api/tweets\", methods=[\"POST\"])\n@api_key_required\n@token_required\ndef create_tweet(user_id): \n try:\n data = request.get_json()\n content = data[\"content\"]\n\n new_tweet_id = db_tweets.create_tweet(user_id, content)\n\n new_tweet = db_tweets.get_tweet_by_id(new_tweet_id) \n\n return make_response(jsonify(new_tweet), status.HTTP_200_OK)\n except Exception as e:\n print(e)\n return make_response(\"\", status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n@tweets.route(\"/api/tweets\", methods=[\"DELETE\"])\n@api_key_required\n@token_required\ndef delete_tweet(user_id): \n try:\n data = request.get_json()\n tweet_id = data[\"tweetId\"]\n deleted = db_tweets.delete_tweet(user_id, tweet_id)\n\n if deleted != 1:\n return make_response(\"\", status.HTTP_500_INTERNAL_SERVER_ERROR)\n else:\n return \"\", status.HTTP_204_NO_CONTENT\n except Exception as e:\n print(e)\n return make_response(\"\", status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n@tweets.route(\"/api/tweets\", methods=[\"PATCH\"])\n@api_key_required\n@token_required\ndef update_tweet(user_id):\n try:\n data = request.get_json()\n tweet_id = data[\"tweetId\"]\n content = data[\"content\"]\n\n db_tweets.update_tweet(user_id, tweet_id, content)\n except Exception as e:\n print(e)\n return make_response(\"\", status.HTTP_500_INTERNAL_SERVER_ERROR)\n else:\n tweet = db_tweets.get_brief_tweet_by_id(tweet_id)\n return make_response(jsonify(tweet), status.HTTP_200_OK)","sub_path":"backend/api/routes/tweets.py","file_name":"tweets.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11898808","text":"\nimport glob\nimport torch\nimport torch.nn as nn\nfrom model.loss import FocalLoss\nfrom utils.img_aug import rotate, flip, torch_noise, missing, numpy2tensor\nfrom utils.img_aug import colorjitter, bandjitter\n\n## -------- root directory -------- ## \nroot = \"/home/yons/Desktop/developer-luo/SWatNet\"\n\n# ------------ data paths -------------- #\n# --- scene path for training ---\npaths_as = sorted(glob.glob(root+'/data/s1_ascend/*'))\npaths_des = sorted(glob.glob(root+'/data/s1_descend/*'))\npaths_truth = sorted(glob.glob(root+'/data/s1_truth/*'))\n# --- patch path for validation ---\npaths_patch_val = sorted(glob.glob(root+'/data/val_patches/*'))\n\n## ----------Training configuration------- ##\n## parameter setting\nepoch = 200\nlr = 0.001\nbatch_size = 16\n\n## loss function\nloss_ce = nn.CrossEntropyLoss()\nloss_bce = nn.BCELoss()\nloss_focal = FocalLoss()\n\n## label_smooth\ndef label_smooth(image_label, label_smooth = 0.1):\n label_smooth = 0.1\n image_label = image_label + label_smooth\n image_label = torch.clamp(image_label, label_smooth, 1-label_smooth)\n return image_label\n\n## --------- data pre-processing -------- ##\ns1_min = [-57.78, -70.37, -58.98, -68.47] # as-vv, as-vh, des-vv, des-vh\ns1_max = [25.98, 10.23, 29.28, 17.60] # as-vv, as-vh, des-vv, des-vh\n\ntransforms_tra = [\n colorjitter(prob=0.5),\n bandjitter(prob=0.5),\n rotate(prob=0.3), \n flip(prob=0.3), \n missing(prob=0.3, ratio_max = 0.25),\n numpy2tensor(), \n torch_noise(prob=0.3, std_min=0.005, std_max=0.1),\n ]\n\n","sub_path":"notebooks/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102978023","text":"import os\nfrom PIL import Image,ImageDraw,ImageFont,ImageFilter\nimport random\n\ndef max_file_num(path):\n names = os.listdir(path)\n res = 0\n for name in names:\n index = name.rfind('.')\n name = int(name[:index])\n res = max(name,res)\n return res\n\ndef random_fond(): \n path='/Workspace/font/'\n for root,dirs,files in os.walk(path):\n files\n fond = files[random.randint(0,len(files)-1)]\t \n return path + os.path.sep + fond\n\ndef random_code(lenght=1): \n code = ''\n for char in range(lenght):\n code += chr(random.randint(65,90)) if random.random() > 0.5 else chr(random.randint(48,57))#random.randint(97,122))\n return code\n\ndef random_color(s=1,e=255):\n return (random.randint(s,e),random.randint(s,e),random.randint(s,e))\n\ndef create_img(code,i,path,fond,width=12,height=12):\n image = Image.new('L',(width,height),255)\n font = ImageFont.truetype(fond,15)\n draw = ImageDraw.Draw(image)\n for x in range(width):\n for y in range(height):\n if random.random()>0.95:\n draw.point((x,y),fill=0) #random_color(0,0))\n \n for t in range(1):\n draw.text((t+1,-3),code[t],font=font,fill=0)\n #image = image.filter(ImageFilter.BLUR)\n code = path + os.path.sep + str(i) + '.png'\n image.save(code)\n return code,image\nif __name__ == \"__main__\":\n n = 3000\n for j in range(36*36):\n code = random_code(1)\n path = '/Workspace/data/' + code\n if not os.path.exists(path):\n fmax = 0\n os.makedirs(path)\n else:\n fmax = max_file_num(path)\n for i in range(fmax+1, n):\n\t fond = random_fond()\n\t create_img(code, i+1, path,fond)\n","sub_path":"captcha_generate.py","file_name":"captcha_generate.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"149534149","text":"# https://leetcode.com/problems/add-two-numbers/\n\n\nclass ListNode:\n def __init__(self, val, node=None):\n self.val, self.next = val, node\n\n\ndef main(l1, l2):\n result = ListNode(0)\n current, carry = result, 0\n while l1 or l2:\n value = (l1 and l1.val or 0) + (l2 and l2.val or 0) + carry\n value, carry = value % 10, value // 10\n\n current.next = ListNode(value)\n current = current.next\n\n if l1:\n l1 = l1.next\n\n if l2:\n l2 = l2.next\n\n if carry:\n current.next = ListNode(1)\n\n return result.next\n\n\nif __name__ == '__main__':\n l1 = ListNode(2, ListNode(4, ListNode(3)))\n l2 = ListNode(5, ListNode(6, ListNode(4, ListNode(1))))\n l = main(l1, l2)\n print(l.val)\n print(l.next.val)\n print(l.next.next.val)\n print(l.next.next.next.val)\n","sub_path":"leecode/0002_add_two_numbers.py","file_name":"0002_add_two_numbers.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220450368","text":"# State Space Equation\n# x(k+1) = Ax(k) + bv(k)\n# y(k) = cx(k) + w(k)\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# initialization\nt = range(200)\nx, y = 10, 0\nA, b, c, Dv, Dw = 1, 1, 1, 1, 2\nxh, yh = 0, 0\nP = 0.1\n\n# Simulation\nX, Y = [], []\nfor dt in t:\n v = np.random.randn() * np.sqrt(Dv)\n w = np.random.randn() * np.sqrt(Dw)\n x = A * x + b * v\n y = c * x + w\n X.append(x)\n Y.append(y)\n\n# Estimation\nXh, Yh = [], []\nfor dt in t:\n w = np.random.randn() * np.sqrt(Dw)\n # Step Predict\n xh = A * xh\n P = A * P + b * Dv\n # Step filter\n G = P * c / (c * P + Dw)\n xh = xh + G * (Y[dt] - c * xh)\n P = (1 - G * c) * P\n yh = c * xh + wS\n Xh.append(xh)\n Yh.append(yh)\n\nplt.plot(t, Y, t, Yh)\nplt.show()\n","sub_path":"kalman/z.py","file_name":"z.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610605256","text":"from datetime import datetime\nfrom django.shortcuts import render\nfrom autodocs.example_data.data import JSON1, JSON2\nimport autodocs.advanced_views.logic.JSON_logic as logic\n\n\ndef json2word_view(request):\n if request.method == \"POST\":\n rules = logic.create_json_rules(request)\n response = create_word_document(request, rules)\n return response\n response = render(request, \"converters/JSON2Word.html\")\n return response\n\n\ndef create_word_document(request, rules):\n try:\n from json import loads\n text = str(request.POST[\"text\"])\n\n if text == \"1\":\n data = JSON1\n elif text == \"2\":\n data = JSON2\n else:\n data = loads(text)\n except:\n return render(request, 'converters/JSON2Word.html')\n\n from autodocs.docx_writer import New_Document\n document = New_Document()\n logic.traverse_json(document, data, rules, apply_rule)\n filename = request.POST[\"file_name\"] if request.POST[\"file_name\"] != u\"\" else \"JSON to Word - %s\" % datetime.now().isoformat()\n response = document.create_output(filename)\n return response\n\n\ndef apply_rule(document, data, rule):\n text = logic.replace_json_text_params_with_data(rule[\"rule_text\"], data)\n style_list = logic.text_to_style_list(text)\n\n doc_type = rule[\"text_type\"]\n if doc_type == \"paragraph\":\n segment = document.add_paragraph()\n elif \"heading\" in doc_type:\n segment = document.add_heading(level=int(doc_type.split(\":\")[1]))\n else:\n segment = None\n\n if segment:\n logic.write_style_list_to_word(segment, style_list)\n","sub_path":"src/autodocs/advanced_views/JSON2Word.py","file_name":"JSON2Word.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246307514","text":"import numpy as np\nimport pytest\n\nfrom jina import Document, Request, QueryLang, NdArray\nfrom jina.types.score import NamedScore\nfrom jina.types.sets.chunk import ChunkSet\nfrom jina.types.sets.match import MatchSet\n\n\n@pytest.mark.parametrize('obj', [Document(),\n Request(),\n QueryLang(),\n NamedScore(),\n NdArray(),\n MatchSet([Document()], Document()),\n ChunkSet([Document()], Document())])\ndef test_builtin_str_repr_no_content(obj):\n print(obj)\n print(f'{obj!r}')\n\n\n@pytest.mark.parametrize('obj', [Document(content='123', chunks=[Document(content='abc')]),\n QueryLang({'name': 'FilterQL', 'priority': 1,\n 'parameters': {'lookups': {'tags__label': 'label2'},\n 'traversal_paths': ['r']}}),\n NamedScore(op_name='operation',\n value=10.0,\n ref_id='10' * 16,\n description='score description'),\n NdArray(np.random.random([3, 5]))])\ndef test_builtin_str_repr_has_content(obj):\n print(obj)\n print(f'{obj!r}')\n","sub_path":"tests/unit/types/test_repr_str.py","file_name":"test_repr_str.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266460685","text":"import twitter\nimport json\n\nphrasefile = json.load(open('phrases.json'))\nphrases = phrasefile['phrases']\n\nsecrets = json.load(open('secrets.json'))\napi = twitter.Api(consumer_key=secrets['consumer_key'],\n consumer_secret=secrets['consumer_secret'],\n access_token_key=secrets['access_token_key'],\n access_token_secret=secrets['access_token_secret'])","sub_path":"meanTweeter.py","file_name":"meanTweeter.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484128662","text":"''' author: samtenka\n change: 2019-02-20\n create: 2017-10-07\n descrp: Append summary of SGD and GD losses (on a toy learning task over a range of learning rates) to a file.\n Here, `SGD` means `batch size 1 without replacement`. Our task in particular is to decrease this loss:\n\n loss(data, (weightA, weightB)) = A + (B - A*data)**4 - 3*A**4 \n\n where data is distributed according to a univariate standard normal. Observe that for any fixed A, setting \n B=0 minimizes expected loss. In fact, this minimal expected loss decreases linearly as a function of A. \n However, as A travels away from 0, the dependence of loss on the specific data sample grows. Intuitively,\n for 'good' A, the corresponding optimal B is hard to estimate. Herein lies danger!\n\n To run, type:\n python simulate_death.py 1000 10 0.00 0.005 12 32 experdata_death.txt \n The 1000 gives a number of trials to perform per experimental condition;\n the 10 gives a training set size and number of gradient updates;\n the 0.00 gives a starting learning rate to sweep from;\n the 0.05 gives a ending learning rate to sweep to;\n the 12 gives (one less than) the number of learning rates to sweep through;\n the 32 gives a desired floating point precision (32 or 64);\n the experdata_death.txt gives a filename of a log to which to append.\n'''\n\nimport tensorflow as tf\nimport numpy as np\nfrom tqdm import tqdm\nimport sys \n\nassert(len(sys.argv)==8)\nNB_TRIALS = int(sys.argv[1]) \nINS_SIZE = int(sys.argv[2]) \nMIN_LR = float(sys.argv[3]) \nMAX_LR = float(sys.argv[4]) \nLR_SWEEP = int(sys.argv[5]) \nPRECISION = {32:tf.float32, 64:tf.float64}[int(sys.argv[6])]\nFILE_NM = sys.argv[7]\n\n\n\n################################################################################\n# 0. DATASET BATCHES #\n################################################################################\n\nclass Dataset(object): \n ''' This class provides access to the aforementioned toy dataset via in-sample and out-of-sample batches. It\n allows us to sample a finite training set and from there and to sample with or without replacement. Since our\n learning task involves no labels, `get_batch` and `get_all` each return one array of shape (???, 1).\n '''\n def __init__(self, max_size=1000):\n self.resample_ins(max_size)\n\n def resample_ins(self, ins_size):\n ''' Resample the finite training set. '''\n self.ins_inputs = np.random.randn(ins_size, 1)\n self.ins_size = ins_size\n self.index = 0\n\n def get_batch(self, batch_size, split='ins', opt='sgd', with_replacement=False):\n ''' Return batch, by default from training set. In case the specified optimizer is 'sgd', then `batch_size`\n and `with_replacment` become salient parameters; if the optimizer is 'gd', then the returned batch is the\n same (and of size equal to the number of training points) each time. \n '''\n if split == 'out': \n out_inputs = np.random.randn(max_size, 1)\n return out_inputs \n if opt == 'gd': \n return self.ins_inputs\n if with_replacement:\n indices = np.random.choice(self.ins_size, size)\n return self.ins_inputs[indices]\n if self.index + batch_size > self.ins_size: \n assert(self.index == self.ins_size)\n indices = np.random.shuffle(np.arange(self.ins_size))\n self.ins_inputs = self.ins_inputs[indices] \n self.index = 0\n rtrn = self.ins_inputs[self.index:self.index+batch_size]\n self.index += batch_size\n return rtrn\n\n def get_all(self, split='ins', max_size=1000):\n ''' Return whole in-sample or out-of-sample points. Good for evaluating train and test scores. ''' \n if split == 'out':\n out_inputs = np.random.randn(max_size, 1)\n return out_inputs\n return self.ins_inputs\n\n\n\n################################################################################\n# 1. LEARNING MODEL #\n################################################################################\n\nclass Learner(object):\n ''' Creates, (re)initializes, trains, and evaluates a differentiable learner. '''\n def __init__(self, precision=PRECISION):\n self.create_model(precision)\n self.create_trainer(precision)\n self.session = tf.Session()\n self.initialize_weights(*self.sample_init_weights())\n\n def create_model(self, precision=tf.float32):\n ''' Define the loss landscape as a function of weights and data. '''\n self.Data = tf.placeholder(precision, shape=[None, 1])\n\n self.Weights = tf.get_variable('flattened', shape=[1+1], dtype=precision)\n\n self.WeightsA = self.Weights[0]\n self.WeightsB = self.Weights[1]\n\n self.InitWeightsA = tf.placeholder(precision, shape=[1])\n self.InitWeightsB = tf.placeholder(precision, shape=[1])\n self.Inits = tf.concat([tf.reshape(init, [-1]) for init in [self.InitWeightsA, self.InitWeightsB]], axis=0)\n self.Initializer = tf.assign(self.Weights, self.Inits)\n\n #self.Losses = self.WeightsA - 3*tf.square(tf.square(self.WeightsA)) + tf.square(tf.square(self.WeightsB - tf.multiply(self.WeightsA, self.Data)))\n self.Losses = (\n tf.square(self.WeightsA - 1.0)\n + tf.square(self.WeightsB - 1.0)\n + self.Data * self.WeightsB * tf.exp(self.WeightsA)\n )\n\n\n def create_trainer(self, precision=tf.float32):\n ''' Define the loss and corresponding gradient-based update. The difference between gd and sgd is not codified\n here; instead, the difference lies in the size and correlations between batches we use to train the\n classifier, i.e. in the values assigned to `Data` and `TrueOutputs` at each gradient update step.\n '''\n self.LearningRate = tf.placeholder(dtype=precision)\n\n self.Loss = tf.reduce_mean(self.Losses)\n self.GradientWeights = tf.convert_to_tensor(tf.gradients(self.Loss, self.Weights))[0]\n self.Update = tf.tuple([\n tf.assign(self.Weights, self.Weights - self.LearningRate * self.GradientWeights), \n ])\n\n def sample_init_weights(self): \n ''' Sample weights (as numpy arrays) distributed according to Glorot-Bengio recommended length scales. These\n weights are intended to be initializers. \n '''\n wa = 0.0 + 0.0 * np.random.randn(1)\n ba = 0.0 + 0.0 * np.random.randn(1)\n return (wa, ba)\n\n def initialize_weights(self, wa, ba):\n ''' Initialize weights as a RUNTIME OPERATION, not by creating new graph nodes. '''\n self.session.run(self.Initializer, feed_dict={\n self.InitWeightsA:wa,\n self.InitWeightsB:ba,\n })\n\n def run(self, dataset, ins_time, batch_size, learning_rate, opt='sgd'): \n ''' Compute post-training metrics for given dataset and hyperparameters. Return in-sample loss and\n out-of-sample loss --- in that order. This learning task has no auxilliary metrics such as accuracy. \n '''\n for t in range(ins_time):\n batch_inputs = dataset.get_batch(batch_size=batch_size, split='ins', opt=opt) \n self.session.run([self.Update], feed_dict={\n self.Data:batch_inputs,\n self.LearningRate:learning_rate\n }) \n \n ins_inputs = dataset.get_all('ins') \n out_inputs = dataset.get_all('out') \n ins_los = self.session.run(self.Loss, feed_dict={self.Data:ins_inputs})\n out_los = self.session.run(self.Loss, feed_dict={self.Data:out_inputs})\n return ins_los, out_los\n\n\n\n################################################################################\n# 2. STATISTICS LOGGER #\n################################################################################\n\nclass Logger(object):\n ''' Collects and aggregates the metric scores of each trial. Maintains a dictionary (of score-lists) indexed by\n keys that are intended to represent the experimental conditions yielding those scores.\n '''\n def __init__(self): \n self.scores = {}\n\n def append(self, key, value):\n ''' Log (key, value) pair. Intended typical use: key is tuple describing experimental condition, for instance\n recording learning rate, optimizer type, and so forth; value is individual score TO BE APPENDED TO A LIST. \n '''\n if key not in self.scores:\n self.scores[key] = [] \n self.scores[key].append(value)\n\n def gen_diffs(self): \n ''' From GD and SGD logs, create DIFF log. '''\n for key in list(self.scores.keys()): \n if key[5] != 'gd': continue\n key_ = key[:5] + ('sgd',) + key[6:]\n key__= key[:5] + ('diff',) + key[6:]\n if key_ not in self.scores: continue\n self.scores[key__] = [gd_val-sgd_val for gd_val, sgd_val in zip(self.scores[key], self.scores[key_])] \n\n def get_stats(self, key):\n ''' Compute mean, sample deviation, min, and max '''\n s = np.array(self.scores[key])\n mean = np.mean(s)\n var = np.mean(np.square(s - mean)) * len(s)/(len(s)-1)\n return mean, np.sqrt(var), np.amin(s), np.amax(s)\n\n def write_summary(self, file_nm, key_renderer):\n ''' Compute statistics and append to file. '''\n self.gen_diffs()\n with open(file_nm, 'a') as f: \n for key in self.scores: \n stats = self.get_stats(key)\n f.write('%s:\\t%.9f\\t%.9f\\t%.9f\\t%.9f' % ((key_renderer(*key),)+stats)) \n f.write('\\n')\n\n\n\n################################################################################\n# 3. EXPERIMENT LOOP #\n################################################################################\n\ndef run_experiment(nb_trials, ins_size, ins_time, batch_size, learning_rates):\n ''' Compute the 'eta curve', that is, sgd vs gd test performance as a function of learning rate. Record summary \n statistics by appending to the given filename.\n '''\n dataset = Dataset()\n learner = Learner()\n logger = Logger() \n\n try:\n for learning_rate in learning_rates:\n print('LR =', learning_rate)\n for h in tqdm(range(nb_trials)):\n dataset.resample_ins(ins_size)\n init_weights = learner.sample_init_weights() \n for opt in ('gd', 'sgd'): \n learner.initialize_weights(*init_weights)\n il, ol = learner.run(dataset, ins_time, batch_size, learning_rate, opt) \n logger.append((nb_trials, ins_size, ins_time, batch_size, learning_rate, opt, 'IL'), il)\n logger.append((nb_trials, ins_size, ins_time, batch_size, learning_rate, opt, 'OL'), ol)\n except KeyboardInterrupt:\n pass\n\n logger.write_summary(FILE_NM,\n key_renderer=lambda nb_trials, ins_size, ins_time, batch_size, learning_rate, opt, metric:\n 'NB_TRIALS=%d\\tINS_SIZE=%d\\tINS_TIME=%d\\tBATCH_SIZE=%d\\tLEARNING_RATE=%f\\tOPT=%s\\tMETRIC=%s' %\n (nb_trials, ins_size, ins_time, batch_size, learning_rate, opt, metric) \n )\n\nif __name__=='__main__':\n arith_prog = [MIN_LR + (MAX_LR-MIN_LR)*(float(i)/LR_SWEEP) for i in range(0, LR_SWEEP+1)]\n run_experiment(nb_trials=NB_TRIALS, ins_size=INS_SIZE, ins_time=INS_SIZE, batch_size=1, learning_rates=arith_prog)\n","sub_path":"experiments/simulate_death.py","file_name":"simulate_death.py","file_ext":"py","file_size_in_byte":11966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365193896","text":"\"\"\"Room class managing all room data.\"\"\"\n\nimport logging\n\nfrom aiopvapi.helpers.api_base import ApiEntryPoint\nfrom aiopvapi.helpers.constants import ATTR_NAME, ATTR_COLOR_ID, \\\n ATTR_ICON_ID, ATTR_ROOM\nfrom aiopvapi.helpers.tools import unicode_to_base64\nfrom aiopvapi.resources.room import Room\n\n_LOGGER = logging.getLogger(\"__name__\")\n\nATTR_ROOM_DATA = 'roomData'\n\n\nclass Rooms(ApiEntryPoint):\n api_path = 'api/rooms'\n\n def __init__(self, request):\n super().__init__(request, self.api_path)\n\n # @staticmethod\n # def sanitize_resources(resource):\n # \"\"\"Cleans up incoming room data\n #\n # :param resource: The dict with scene data to be sanitized.\n # :return: Cleaned up room dict.\n # \"\"\"\n # try:\n # for room in resource[ATTR_ROOM_DATA]:\n # room[ATTR_NAME_UNICODE] = base64_to_unicode(room[ATTR_NAME])\n # return resource\n # except (KeyError, TypeError):\n # _LOGGER.debug(\"no room data available\")\n # return None\n\n async def create_room(self, name, color_id=0, icon_id=0):\n name = unicode_to_base64(name)\n data = {\n ATTR_ROOM: {\n ATTR_NAME: name,\n ATTR_COLOR_ID: color_id,\n ATTR_ICON_ID: icon_id\n }\n }\n return await self.request.post(self._base_path, data=data)\n\n def _resource_factory(self, raw):\n return Room(raw, self.request)\n\n @staticmethod\n def _loop_raw(raw):\n for _raw in raw[ATTR_ROOM_DATA]:\n yield _raw\n\n @staticmethod\n def _get_to_actual_data(raw):\n return raw.get('room')","sub_path":"aiopvapi/rooms.py","file_name":"rooms.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20056363","text":"# _*_ coding:utf-8 _*_\n\nfrom data.file import load_data_csv\nfrom matplotlib import pyplot as plt\nfrom scipy.cluster.hierarchy import dendrogram, linkage\nimport numpy as np\nfrom matplotlib.font_manager import FontProperties\nfrom config import get_image_path, get_rusult_path\nimport csv\n\nclass Hie:\n def __init__(self, file_name):\n data_mat, line_index, column_index = load_data_csv(file_name)\n data_np = np.mat(data_mat)\n num = 0\n maps = []\n for line in line_index:\n maps.append([line,num])\n #print(line + ' ' + str(num))\n num += 1\n\n Z = linkage(data_np, 'ward') # ward 离差平方和\n\n font = FontProperties(fname=\"C:\\\\WINDOWS\\\\Fonts\\\\msyh.ttc\", size=14)\n plt.figure(figsize=(50, 10))\n\n plt.title('层次聚类', fontproperties=font)\n plt.xlabel('样本', fontproperties=font)\n plt.ylabel('距离', fontproperties=font)\n dendrogram(Z, leaf_rotation=90, leaf_font_size=8)\n plt.savefig(get_image_path() + file_name + '.png')\n print('聚类完成 已保存为 ' + get_image_path() + file_name + '.png')\n self.create_csv(maps,file_name)\n plt.show()\n\n def create_csv(self, data_head,file_name ):\n result_file_name = get_rusult_path() + '/' + file_name + '_Map.csv'\n try:\n result_file = open(result_file_name, 'w', newline='')\n result_file_writer = csv.writer(result_file)\n result_file_writer.writerows(data_head)\n result_file.close()\n print('对应表保存成功 ')\n except:\n print('failed to save result ')\n\n#\n# h=Hie\n# h(file_name='test')\n","sub_path":"MachineLearning/Clustering/clustering/hierarchical.py","file_name":"hierarchical.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181654454","text":"import numpy as np\n\n\nclass Perceptron:\n def __init__(self, w1, w2, theta):\n self.w1 = w1\n self.w2 = w2\n self.theta = theta\n\n def forward(self, x1, x2):\n if (self.w1 * x1 + self.w2 * x2) >= self.theta:\n return 1\n else:\n return 0\n\n\nx1_list = [1, 1, 0, 0]\nx2_list = [1, 0, 1, 0]\n\nand_gate = Perceptron(1, 1, 1.5)\nnand_gate = Perceptron(-1, -1, -1.5)\nor_gate = Perceptron(1, 1, 0.5)\n\n\ndef xor(x1, x2):\n return and_gate.forward(nand_gate.forward(x1, x2), or_gate.forward(x1, x2))\n\n\nfor x1, x2 in zip(x1_list, x2_list):\n print(\"XOR({0}, {1}) = {2} \".format(x1, x2, xor(x1, x2)))\n","sub_path":"p2_ニューラルネットワーク実装/my_answer/ex1-3.py","file_name":"ex1-3.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"143559309","text":"import os\nfrom yaml_settings import YAMLSettings\nfrom utils import SimpleLine\nfrom colorama import Fore, Back, Style\nimport spotipy.util as util\n\nclass AccessSettings(YAMLSettings):\n YAML = os.path.join(\n os.path.expanduser('~'),\n '.bpemer.yml'\n )\n\n def __init__(self):\n SimpleLine('Accessing yaml settings', Fore.BLACK, Back.GREEN)\n self.load(self.YAML)\n require = {\n 'echonet': {\n 'api_key': 'API Key',\n 'consumer_key': 'Consumer Key',\n 'shared_secret': 'Shared Secret',\n },\n 'spotify': {\n 'client_id': 'Client ID',\n 'client_secret': 'Client Secret',\n 'redirect_uri': 'Redirect URI',\n 'username': 'Spotify Username'\n }\n }\n\n for k in require.keys():\n if not k in self.data.keys():\n self.data[k] = {}\n for j in require[k].keys():\n if not j in self.data[k].keys():\n self.data[k][j] = raw_input(\n Fore.GREEN +\n \"Please enter your %s %s: \" % (\n k,\n require[k][j]\n ) +\n Style.RESET_ALL\n )\n token = util.prompt_for_user_token(\n self.data['spotify']['username'],\n client_id=self.data['spotify']['client_id'],\n client_secret=self.data['spotify']['client_secret'],\n redirect_uri=self.data['spotify']['redirect_uri'],\n scope='playlist-read-private'\n )\n self.data['spotify']['token'] = '%s' % token\n self.save()\n","sub_path":"bpemer/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629182221","text":"\n\n\"\"\"\nQuiero ver si hay correlación local con propiedades que comparten \ncaracteristicas. Por cada propiedad, encuentro las propiedades cercanas,\ny veo la correlación que tienen las variables con el CTR de las propiedades.\nTambién quiero ver qué correlación tiene las diferencias de las variables con \nrespecto al vector promedio, y ver la correlación con la diferencia de CTR. \n\"\"\"\n\n# tipos: 1=casa, 2=depto, 3=oficina\n# modalidad: 1=venta, 2=arriendo\ntipo = 2\nmodalidad = 2\nhab = 2\nban = 2\n\nnnei = 15\nsub = 1\n\n# uso sólo datos con número de dormitorios, baños, dimension util y precio \nidx = np.array([i for i,d in enumerate(DATA_X) if d[9]==tipo and d[10]==modalidad \n if d[1]>0 and d[2]>0 and d[3]>0 and d[8]>0])\n\nfrom sklearn.neighbors import NearestNeighbors\n\nknn_model = NearestNeighbors(nnei, metric='euclidean')\nknn_model.fit(DATA_X[idx,-2:])\n\nidx_sub = idx[::sub]\n\ndistances, indexes = knn_model.kneighbors(DATA_X[idx_sub,-2:])\n\ncc = []\n\nfor i,ii,dd in zip(idx_sub,indexes, distances):\n real_idx = idx[ii]\n X = np.concatenate((DATA_X[real_idx,:],(DATA_X[real_idx,8]/DATA_X[real_idx,3]).reshape(-1,1),dd.reshape(-1,1)),axis=1)\n y = DATA_ctr[real_idx]\n \n mX = X.mean(axis=0)\n mCTR = y.mean()\n \n cc.append(np.corrcoef(np.concatenate((X+np.random.randn(X.shape[0],X.shape[1])*0.001,y.reshape(X.shape[0],-1)), axis=1),rowvar=0)[-1,:])\n\nprint(np.array(cc).mean(axis=0))\n \n\n \n \n\n\n\n\n","sub_path":"OLD/models/CTR_test_local_models.py","file_name":"CTR_test_local_models.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468725961","text":"import json\nimport logging\nimport os\nimport shutil\nimport time\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Dict, List, Union\n\nimport docker\nimport pika\nfrom celery.states import SUCCESS as CSUCCESS\nfrom celery.utils.log import get_task_logger\nfrom sqlalchemy import and_, exc\n\nfrom simcore_sdk import node_ports\nfrom simcore_sdk.models.pipeline_models import (RUNNING, SUCCESS,\n ComputationalPipeline,\n ComputationalTask)\n\nfrom .utils import (DbSettings, DockerSettings, ExecutorSettings,\n RabbitSettings, S3Settings, delete_contents,\n find_entry_point, is_node_ready, wrap_async_call)\n\nlog = get_task_logger(__name__)\nlog.setLevel(logging.DEBUG) # FIXME: set level via config\n\n@contextmanager\ndef session_scope(session_factory):\n \"\"\"Provide a transactional scope around a series of operations\n\n \"\"\"\n session = session_factory()\n try:\n yield session\n except: # pylint: disable=W0702\n log.exception(\"DB access error, rolling back\")\n session.rollback()\n finally:\n session.close()\n\nclass Sidecar:\n def __init__(self):\n # publish subscribe config\n self._pika = RabbitSettings()\n\n # docker client config\n self._docker = DockerSettings()\n\n # object storage config\n self._s3 = S3Settings()\n\n # db config\n self._db = DbSettings()\n\n # current task\n self._task = None\n\n # executor options\n self._executor = ExecutorSettings()\n\n def _create_shared_folders(self):\n for folder in [self._executor.in_dir, self._executor.log_dir, self._executor.out_dir]:\n if not os.path.exists(folder):\n os.makedirs(folder)\n else:\n delete_contents(folder)\n\n def _process_task_input(self, port:node_ports.Port, input_ports:Dict):\n # pylint: disable=too-many-branches\n port_name = port.key\n port_value = wrap_async_call(port.get())\n log.debug(\"PROCESSING %s %s\", port_name, port_value)\n log.debug(type(port_value))\n if str(port.type).startswith(\"data:\"):\n path = port_value\n if not path is None:\n # the filename is not necessarily the name of the port, might be mapped\n mapped_filename = Path(path).name\n input_ports[port_name] = str(port_value)\n final_path = Path(self._executor.in_dir, mapped_filename)\n shutil.copy(str(path), str(final_path))\n log.debug(\"DOWNLOAD successfull from %s to %s via %s\" , str(port_name), str(final_path), str(path))\n else:\n input_ports[port_name] = port_value\n else:\n input_ports[port_name] = port_value\n\n def _process_task_inputs(self):\n \"\"\" Writes input key-value pairs into a dictionary\n\n if the value of any port starts with 'link.' the corresponding\n output ports a fetched or files dowloaded --> @ jsonld\n\n The dictionary is dumped to input.json, files are dumped\n as port['key']. Both end up in /input/ of the container\n \"\"\"\n log.debug('Input parsing for %s and node %s from container', self._task.project_id, self._task.internal_id)\n\n input_ports = dict()\n PORTS = node_ports.ports()\n for port in PORTS.inputs:\n log.debug(port)\n self._process_task_input(port, input_ports)\n\n log.debug('DUMPING json')\n #dump json file\n if input_ports:\n file_name = os.path.join(self._executor.in_dir, 'input.json')\n with open(file_name, 'w') as f:\n json.dump(input_ports, f)\n\n log.debug('DUMPING DONE')\n\n def _pull_image(self):\n log.debug('PULLING IMAGE')\n log.debug('reg %s user %s pwd %s', self._docker.registry, self._docker.registry_user,self._docker.registry_pwd )\n\n try:\n self._docker.client.login(registry=self._docker.registry,\n username=self._docker.registry_user, password=self._docker.registry_pwd)\n log.debug('img %s tag %s', self._docker.image_name, self._docker.image_tag)\n self._docker.client.images.pull(self._docker.image_name, tag=self._docker.image_tag)\n except docker.errors.APIError:\n log.exception(\"Pulling image failed\")\n raise docker.errors.APIError\n\n\n def _log(self, channel: pika.channel.Channel, msg: Union[str, List[str]]):\n log_data = {\"Channel\" : \"Log\",\n \"Node\": self._task.node_id,\n \"Messages\" : msg if isinstance(msg, list) else [msg]\n }\n log_body = json.dumps(log_data)\n channel.basic_publish(exchange=self._pika.log_channel, routing_key='', body=log_body)\n\n def _progress(self, channel, progress):\n prog_data = {\"Channel\" : \"Progress\", \"Node\": self._task.node_id, \"Progress\" : progress}\n prog_body = json.dumps(prog_data)\n channel.basic_publish(exchange=self._pika.progress_channel, routing_key='', body=prog_body)\n \n def _bg_job(self, log_file):\n connection = pika.BlockingConnection(self._pika.parameters)\n\n channel = connection.channel()\n channel.exchange_declare(exchange=self._pika.log_channel, exchange_type='fanout', auto_delete=True)\n channel.exchange_declare(exchange=self._pika.progress_channel, exchange_type='fanout', auto_delete=True)\n \n def _follow(thefile):\n thefile.seek(0,2)\n while self._executor.run_pool: \n line = thefile.readline()\n if not line:\n time.sleep(1)\n continue\n yield line\n\n def _parse_progress(line: str):\n # TODO: This should be 'settings', a regex for every service\n if line.lower().startswith(\"[progress]\"):\n progress = line.lower().lstrip(\"[progress]\").rstrip(\"%\").strip()\n self._progress(channel, progress)\n log.debug('PROGRESS %s', progress)\n elif \"percent done\" in line.lower():\n progress = line.lower().rstrip(\"percent done\")\n try:\n float_progress = float(progress) / 100.0\n progress = str(float_progress)\n self._progress(channel, progress)\n log.debug('PROGRESS %s', progress)\n except ValueError:\n log.exception(\"Could not extract progress from solver\")\n self._log(channel, line)\n\n def _log_accumulated_logs(new_log: str, acc_logs: List[str], time_logs_sent: float):\n # do not overload broker with messages, we log once every 1sec\n TIME_BETWEEN_LOGS_S = 1.0\n acc_logs.append(new_log)\n now = time.monotonic()\n if (now - time_logs_sent) > TIME_BETWEEN_LOGS_S:\n self._log(channel, acc_logs)\n log.debug('LOG %s', acc_logs)\n # empty the logs\n acc_logs = []\n time_logs_sent = now\n return acc_logs,time_logs_sent\n\n\n acc_logs = []\n time_logs_sent = time.monotonic()\n file_path = Path(log_file)\n with file_path.open() as fp:\n for line in _follow(fp):\n if not self._executor.run_pool:\n break\n _parse_progress(line)\n acc_logs, time_logs_sent = _log_accumulated_logs(line, acc_logs, time_logs_sent)\n if acc_logs:\n # send the remaining logs\n self._log(channel, acc_logs)\n log.debug('LOG %s', acc_logs)\n\n # set progress to 1.0 at the end, ignore failures\n progress = \"1.0\"\n self._progress(channel, progress)\n connection.close()\n\n def _process_task_output(self):\n # pylint: disable=too-many-branches\n\n \"\"\" There will be some files in the /output\n\n - Maybe a output.json (should contain key value for simple things)\n - other files: should be named by the key in the output port\n\n Files will be pushed to S3 with reference in db. output.json will be parsed\n and the db updated\n \"\"\"\n PORTS = node_ports.ports()\n directory = self._executor.out_dir\n if not os.path.exists(directory):\n return\n try:\n for root, _dirs, files in os.walk(directory):\n for name in files:\n filepath = os.path.join(root, name)\n # the name should match what is in the db!\n if name == 'output.json':\n log.debug(\"POSTRO FOUND output.json\")\n # parse and compare/update with the tasks output ports from db\n output_ports = dict()\n with open(filepath) as f:\n output_ports = json.load(f)\n task_outputs = PORTS.outputs\n for to in task_outputs:\n if to.key in output_ports.keys():\n wrap_async_call(to.set(output_ports[to.key]))\n else:\n wrap_async_call(PORTS.set_file_by_keymap(Path(filepath)))\n\n except (OSError, IOError) as _e:\n logging.exception(\"Could not process output\")\n\n # pylint: disable=no-self-use\n def _process_task_log(self):\n \"\"\" There will be some files in the /log\n\n - put them all into S3 /logg\n \"\"\"\n return\n #directory = self._executor.log_dir\n #if os.path.exists(directory):\n # for root, _dirs, files in os.walk(directory):\n # for name in files:\n # filepath = os.path.join(root, name)\n # object_name = str(self._task.project_id) + \"/\" + self._task.node_id + \"/log/\" + name\n # # if not self._s3.client.upload_file(self._s3.bucket, object_name, filepath):\n # # log.error(\"Error uploading file to S3\")\n\n def initialize(self, task, user_id):\n self._task = task\n\n HOMEDIR = str(Path.home())\n\n self._docker.image_name = self._docker.registry_name + \"/\" + task.image['name']\n self._docker.image_tag = task.image['tag']\n self._docker.env = []\n\n tails = dict( (name, Path(name, task.job_id).as_posix()) for name in (\"input\", \"output\", \"log\") )\n\n # volume paths for side-car container\n self._executor.in_dir = os.path.join(HOMEDIR, tails['input'])\n self._executor.out_dir = os.path.join(HOMEDIR, tails['output'])\n self._executor.log_dir = os.path.join(HOMEDIR, tails['log'])\n\n # volume paths for car container (w/o prefix)\n self._docker.env = [\"{}_FOLDER=/{}\".format(name.upper(), tail) for name, tail in tails.items()]\n\n # config nodeports\n node_ports.node_config.USER_ID = user_id\n node_ports.node_config.NODE_UUID = task.node_id\n node_ports.node_config.PROJECT_ID = task.project_id\n\n def preprocess(self):\n log.debug('Pre-Processing Pipeline %s and node %s from container', self._task.project_id, self._task.internal_id)\n self._create_shared_folders()\n self._process_task_inputs()\n self._pull_image()\n\n def process(self):\n log.debug('Processing Pipeline %s and node %s from container', self._task.project_id, self._task.internal_id)\n\n self._executor.run_pool = True\n\n # touch output file\n log_file = os.path.join(self._executor.log_dir, \"log.dat\")\n\n Path(log_file).touch()\n fut = self._executor.pool.submit(self._bg_job, log_file)\n\n try:\n docker_image = self._docker.image_name + \":\" + self._docker.image_tag\n self._docker.client.containers.run(docker_image, \"run\",\n detach=False, remove=True,\n volumes = {'services_input' : {'bind' : '/input'},\n 'services_output' : {'bind' : '/output'},\n 'services_log' : {'bind' : '/log'}},\n environment=self._docker.env)\n except docker.errors.ContainerError as _e:\n log.exception(\"Run container returned non zero exit code %s\", str(_e))\n except docker.errors.ImageNotFound as _e:\n log.exception(\"Run container: Image not found\")\n except docker.errors.APIError as _e:\n log.exception(\"Run Container: Server returns error\")\n\n\n time.sleep(1)\n self._executor.run_pool = False\n while not fut.done():\n time.sleep(0.1)\n\n log.debug('DONE Processing Pipeline %s and node %s from container', self._task.project_id, self._task.internal_id)\n\n def run(self):\n connection = pika.BlockingConnection(self._pika.parameters)\n\n channel = connection.channel()\n channel.exchange_declare(exchange=self._pika.log_channel, exchange_type='fanout', auto_delete=True)\n\n msg = \"Preprocessing start...\"\n self._log(channel, msg)\n self.preprocess()\n msg = \"...preprocessing end\"\n self._log(channel, msg)\n\n msg = \"Processing start...\"\n self._log(channel, msg)\n self.process()\n msg = \"...processing end\"\n self._log(channel, msg)\n\n msg = \"Postprocessing start...\"\n self._log(channel, msg)\n self.postprocess()\n msg = \"...postprocessing end\"\n self._log(channel, msg)\n connection.close()\n\n\n def postprocess(self):\n #log.debug('Post-Processing Pipeline %s and node %s from container', self._task.project_id, self._task.internal_id)\n\n self._process_task_output()\n self._process_task_log()\n\n self._task.state = SUCCESS\n _session = self._db.Session()\n try:\n _session.add(self._task)\n _session.commit()\n # log.debug('DONE Post-Processing Pipeline %s and node %s from container', self._task.project_id, self._task.internal_id)\n\n except exc.SQLAlchemyError:\n log.exception(\"Could not update job from postprocessing\")\n _session.rollback()\n finally:\n _session.close()\n\n def inspect(self, celery_task, user_id, project_id, node_id):\n log.debug(\"ENTERING inspect pipeline:node %s: %s\", project_id, node_id)\n # import pdb; pdb.set_trace()\n next_task_nodes = []\n do_run = False\n\n with session_scope(self._db.Session) as _session:\n _pipeline =_session.query(ComputationalPipeline).filter_by(project_id=project_id).one()\n\n graph = _pipeline.execution_graph\n if node_id:\n do_process = True\n # find the for the current node_id, skip if there is already a job_id around\n # pylint: disable=assignment-from-no-return\n query =_session.query(ComputationalTask).filter(and_(ComputationalTask.node_id==node_id,\n ComputationalTask.project_id==project_id, ComputationalTask.job_id==None))\n # Use SELECT FOR UPDATE TO lock the row\n query.with_for_update()\n task = query.one()\n\n if task == None:\n return next_task_nodes\n\n # already done or running and happy\n if task.job_id and (task.state == SUCCESS or task.state == RUNNING):\n log.debug(\"TASK %s ALREADY DONE OR RUNNING\", task.internal_id)\n do_process = False\n\n # Check if node's dependecies are there\n if not is_node_ready(task, graph, _session, log):\n log.debug(\"TASK %s NOT YET READY\", task.internal_id)\n do_process = False\n\n if do_process:\n task.job_id = celery_task.request.id\n _session.add(task)\n _session.commit()\n\n task =_session.query(ComputationalTask).filter(\n and_(ComputationalTask.node_id==node_id,ComputationalTask.project_id==project_id)).one()\n\n if task.job_id != celery_task.request.id:\n # somebody else was faster\n # return next_task_nodes\n pass\n else:\n task.state = RUNNING\n _session.add(task)\n _session.commit()\n\n self.initialize(task, user_id)\n\n do_run = True\n else:\n log.debug(\"NODE id was zero\")\n log.debug(\"graph looks like this %s\", graph)\n\n next_task_nodes = find_entry_point(graph)\n log.debug(\"Next task nodes %s\", next_task_nodes)\n\n celery_task.update_state(state=CSUCCESS)\n\n # now proceed actually running the task (we do that after the db session has been closed)\n if do_run:\n # try to run the task, return empyt list of next nodes if anything goes wrong\n self.run()\n next_task_nodes = list(graph.successors(node_id))\n\n return next_task_nodes\n\n\n# TODO: if a singleton, then use\nSIDECAR = Sidecar()\n\n__all__ = [\n \"SIDECAR\"\n]\n","sub_path":"services/sidecar/src/sidecar/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":17423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32502199","text":"from itsdangerous import TimedJSONWebSignatureSerializer as Serializer\nfrom django.conf import settings\n\n\ndef dumps(json, expires):\n # 加密\n # 1.创建对象\n serializer = Serializer(settings.SECRET_KEY, expires)\n # 2.加密\n json_str = serializer.dumps(json)\n # 3.返回字符串\n return json_str.decode()\n\n\ndef loads(json_str, expires):\n # 解密\n # 1.创建对象\n serializer = Serializer(settings.SECRET_KEY, expires)\n # 2.解密\n try:\n json = serializer.loads(json_str)\n except:\n # 如果字符串被修改,或过期,解密时会抛异常\n return None\n else:\n # 3.返回字典\n return json\n","sub_path":"BoxueGu/apps/utils/bx_signature.py","file_name":"bx_signature.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40639548","text":"'''\nFirst, def a function called distance_from_zero, with one argument (choose any argument name you like).\nIf the type of the argument is either int or float, the function should return the absolute value of the function input.\nOtherwise, the function should return \"Nope\"\n'''\n\ndef distance_from_zero(input):\n if (type(input) == int or type(input) == float):\n return abs(input)\n else:\n return \"Nope\"\n return input\n","sub_path":"Unit_4/Lessons_Functions/Review_Build-In_Functions.py","file_name":"Review_Build-In_Functions.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"617143780","text":"#!/usr/bin/env python\n\"\"\"Decode the bluetooth protocol of Muse\"\"\"\n\n\n\ndef main():\n \"\"\"Decode a bluetooth message from Muse into readable chars\n\n Works for the messages received in 0x000e handle.\n Usually they are a series of packets, that together conform a dictionary (key, value pairs).\"\"\"\n\n # El archivo tiene en cada linea un msje, puede estar comenzado por *, cada byte lo tiene separado por un :\n # llegar y copiar desde wireshark\n # ejemplo:\n # * ab:12:34:ef\n fname = \"debug.txt\"\n with open(fname, \"r\") as f:\n a = f.readlines()\n\n verbose = False\n\n # Decodificar string\n big_string = \"\" # String completo, concatenando cada mensaje\n\n for linea in a: # Recorrer cada mensaje\n ## Trim espacios y *\n l = linea.strip().strip(\"*\")\n\n ## Separar en bytes\n nums = l.split(\":\")\n\n ## Recorrer cada byte\n i = 0 # contador\n add_to_str = True # bool que indica si añadir al string completo\n stop_adding = -1 # posicion en la que se dejo de añadir\n for b in nums:\n # Transformar el byte a numero y a un char legible\n x = int(b, 16)\n c = chr(x)\n\n # El primer byte no es legible (timestamp?, cmd?, no se sabe) --> i > 0\n # En algun momento se llega a una ',' o '}'; significa que la parte importante del msje termino\n if i > 0 and add_to_str:\n if verbose:\n print(c, end=\"\")\n big_string += c\n if c == ',' or c == '}': # msje termino\n # de ahi en adelante es basura, de hecho reusan el string asi que es lo mismo que el anterior\n stop_adding = i\n add_to_str = False\n\n i += 1\n\n\n if verbose:\n print(\"\")\n # if stop_adding != -1:\n # print(\"\\tStopped adding at pos {}\".format(stop_adding))\n\n if verbose:\n # Imprimir cada byte leido y su transformacion a int base 10\n for b in nums:\n c = int(b, 16)\n print(\"\\t{}->{}\".format(b, c))\n print(\"\\n\")\n\n # El bigstring se ve como un dictionary, pares key value:\n # {\"key\": \"value\", ...}\n print(big_string)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"others/decode_bluetooth.py","file_name":"decode_bluetooth.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"234424408","text":"from order import Order\nfrom shipping_cost import ShippingCost\nfrom strategy.fedex_strategy import FedexStrategy\nfrom strategy.postal_strategy import PostalStrategy\nfrom strategy.ups_strategy import UPSStrategy\n\n\n# Test Federal Express shipping\norder = Order()\nstrategy = FedexStrategy()\ncost_calculator = ShippingCost(strategy)\ncost = cost_calculator.shipping_cost(order)\nassert cost == 3.0\n\n# Test UPS shipping\norder = Order()\nstrategy = UPSStrategy()\ncost_calculator = ShippingCost(strategy)\ncost = cost_calculator.shipping_cost(order)\nassert cost == 4.0\n\n# Test Postal Service shipping\norder = Order()\nstrategy = PostalStrategy()\ncost_calculator = ShippingCost(strategy)\ncost = cost_calculator.shipping_cost(order)\nassert cost == 5.0\n","sub_path":"_PYTHON_/topics/design_patterns/strategy/e001_shipping_cost/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583997792","text":"# sys\nimport pickle\nimport pdb\n\n# torch\nimport torch\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nimport numpy as np\n\ntry:\n from utils import utils\n from feeder import tools\nexcept:\n import tools, utils\n\nclass Feeder(torch.utils.data.Dataset):\n \"\"\" Feeder for skeleton-based action recognition\n Arguments:\n data_path: the path to '.npy' data, the shape of data should be (N, C, T, V, M)\n label_path: the path to label\n random_choose: If true, randomly choose a portion of the input sequence\n random_shift: If true, randomly pad zeros at the begining or end of sequence\n window_size: The length of the output sequence\n normalization: If true, normalize input sequence\n debug: If true, only use the first 100 samples\n \"\"\"\n\n def __init__(self,\n data_path_source,\n label_path_source,\n rl_label_path_source,\n num_frame_path_source,\n rl_label_path_target='None',\n data_path_target = 'None',\n num_frame_path_target = 'None',\n random_valid_choose=False,\n random_choose=False,\n random_shift=False,\n random_move=False,\n window_size=-1,\n normalization=False,\n debug=False,\n origin_transfer=False,\n p_interval=1,\n crop_resize=False,\n rand_rotate=0,\n mmap=False,\n ):\n self.debug = debug\n self.data_path_source = data_path_source\n self.label_path_source = label_path_source\n self.rl_label_path_source = rl_label_path_source\n self.num_frame_path_source = num_frame_path_source\n self.data_path_target = data_path_target\n self.rl_label_path_target = rl_label_path_target \n self.num_frame_path_target = num_frame_path_target\n self.random_choose = random_choose\n self.random_valid_choose = random_valid_choose\n self.random_shift = random_shift\n self.random_move = random_move\n self.window_size = window_size\n self.normalization = normalization\n self.origin_transfer = origin_transfer\n self.p_interval = p_interval\n self.crop_resize = crop_resize\n self.rand_rotate = rand_rotate\n self.mmap = mmap\n\n self.load_data()\n if normalization:\n self.get_mean_map()\n\n def load_data(self):\n # data: N C V T M\n\n # load label\n # for source dataset\n if '.pkl' in self.label_path_source:\n try:\n with open(self.label_path_source) as f:\n self.sample_name, self.label = pickle.load(f)\n except:\n # for pickle file from python2\n with open(self.label_path_source, 'rb') as f:\n self.sample_name, self.label = pickle.load(\n f, encoding='latin1')\n # old label format\n elif '.npy' in self.label_path_source:\n self.label = list(np.load(self.label_path_source))\n self.sample_name = [str(i) for i in range(len(self.label))]\n else:\n raise ValueError()\n\n if '.pkl' in self.rl_label_path_source:\n try:\n with open(self.rl_label_path_source) as f:\n self.rl_label_source= pickle.load(f)\n except:\n # for pickle file from python2\n with open(self.rl_label_path_source, 'rb') as f:\n self.rl_label_source = pickle.load(\n f, encoding='latin1')\n else:\n raise ValueError()\n self.rl_label_source=np.array(self.rl_label_source)\n\n # load data\n #source\n if self.mmap == True:\n self.data_source = np.load(self.data_path_source,mmap_mode='r')\n else:\n self.data_source = np.load(self.data_path_source,mmap_mode=None) # directly load all data in memory, it more efficient but memory resource consuming for big file\n # load num of valid frame length\n\n self.valid_frame_num_source = np.load(self.num_frame_path_source)\n\n if self.data_path_target != 'None' : \n if '.pkl' in self.rl_label_path_target:\n try:\n with open(self.rl_label_path_target) as f:\n self.rl_label_target = pickle.load(f)\n except:\n # for pickle file from python2\n with open(self.rl_label_path_target, 'rb') as f:\n self.rl_label_target = pickle.load(\n f, encoding='latin1')\n else:\n raise ValueError()\n self.rl_label_target=np.array(self.rl_label_target)\n\n if self.mmap == True:\n self.data_target = np.load(self.data_path_target,mmap_mode='r')\n else: \n self.data_target = np.load(self.data_path_target,mmap_mode=None)\n self.valid_frame_num_target = np.load(self.num_frame_path_target)\n\n\n\n if self.debug:\n #self.label = self.label[0:100]\n #self.data = self.data[0:100]\n #self.num_frame_path = self.num_frame_path[0:100]\n #self.sample_name = self.sample_name[0:100]\n print('do not support debug!')\n\n self.N_source, self.C, self.T, self.V, self.M = self.data_source.shape\n\n self.coordinate_transfer() #change here \n self.concateData()\n\n def concateData(self):\n if self.data_path_target != 'None' :\n assert self.data_source.shape[1:] == self.data_target.shape[1:]\n self.N_target = self.data_target.shape[0]\n if self.N_source > self.N_target :\n roundtimes = self.N_source//self.N_target\n tail = self.N_source - self.N_target * roundtimes\n #print(self.valid_frame_num_target.shape)\n repeat_target = np.concatenate((np.tile(self.data_target,(roundtimes,1,1,1,1)) , self.data_target[:tail,:,:,:,:]),axis = 0)\n repeat_rl_label_target = np.concatenate((np.tile(self.rl_label_target,roundtimes) , self.rl_label_target[:tail]),axis = 0)\n self.valid_frame_num_target = np.concatenate((np.tile(self.valid_frame_num_target,roundtimes), self.valid_frame_num_target[:tail]),axis = 0)\n assert repeat_target.shape == self.data_source.shape\n self.data = np.concatenate((self.data_source[:,:,:,:,:,None] , repeat_target[:,:,:,:,:,None]),axis = 5)\n #pdb.set_trace()\n self.rl_label = np.concatenate((self.rl_label_source[:,None] , repeat_rl_label_target[:,None]),axis = 1)\n #print(\"see the result : \")\n assert np.sum((self.data[:,:,:,:,:,0] == self.data_source) == 0 ) == 0\n #print(\"see the result : \")\n assert np.sum((self.data[:self.N_target,:,:,:,:,1] == self.data_target) == 0 ) == 0\n else:\n roundtimes = self.N_target//self.N_source\n tail = self.N_target - self.N_source * roundtimes\n #print(self.valid_frame_num_target.shape)\n repeat_source = np.concatenate((np.tile(self.data_source,(roundtimes,1,1,1,1)) , self.data_source[:tail,:,:,:,:]),axis = 0)\n repeat_rl_label_source = np.concatenate((np.tile(self.rl_label_source,roundtimes) , self.rl_label_source[:tail]),axis = 0) \n self.valid_frame_num_source = np.concatenate((np.tile(self.valid_frame_num_source,roundtimes), self.valid_frame_num_source[:tail]),axis = 0)\n self.sample_name = self.sample_name * roundtimes + self.sample_name[:tail]\n self.label = self.label * roundtimes + self.label[:tail]\n self.rl_label = np.concatenate((repeat_rl_label_source[:,None] , self.rl_label_target[:,None]),axis = 1)\n assert repeat_source.shape == self.data_target.shape\n self.data = np.concatenate((repeat_source[:,:,:,:,:,None] , self.data_target[:,:,:,:,:,None]),axis = 5)\n #print(\"see the result : \")\n assert np.sum((self.data[:,:,:,:,:,1] == self.data_target) == 0 ) == 0\n #print(\"see the result : \")\n assert np.sum((self.data[:self.N_source,:,:,:,:,0] == self.data_source) == 0 ) == 0\n\n else: \n self.rl_label = self.rl_label_source[:,None]\n self.data = self.data_source[:,:,:,:,:,None]\n # self.data = np.concatenate((self.data_source[:,:,:,:,:,None] , np.zeros((self.data_source.shape),dtype=np.int8)[:,:,:,:,:,None]),axis = 5) #change here\n # pdb.set_trace()\n assert self.data.shape[:5] == self.data_source.shape\n #print(\"see the result : \")\n assert np.sum((self.data[:,:,:,:,:,0] == self.data_source) == 0 ) == 0\n #print(\"see the result : \")\n # assert np.sum(self.data[:,:,:,:,:,1]) == 0\n \n def coordinate_transfer(self): #change here\n data_numpy_source = self.data_source\n if self.origin_transfer == 2:\n # take joints 3 of each person, as origins of each person\n origin_source = data_numpy_source[:, :, :, 1, :]\n data_numpy_source = data_numpy_source - origin_source[:, :, :, None, :]\n elif self.origin_transfer == 0:\n # take joints 3 of first person, as origins of each person\n origin_source = data_numpy_source[:, :, :, 1, 0]\n data_numpy_source = data_numpy_source - origin_source[:, :, :, None, None]\n elif self.origin_transfer == 1:\n # take joints 3 of second person, as origins of each person\n origin_source = data_numpy_source[:, :, :, 1, 1]\n data_numpy_source = data_numpy_source - origin_source[:, :, :, None, None]\n else:\n # print('no origin transfer')\n pass\n self.data_source = data_numpy_source\n\n if self.data_path_target != 'None' : \n data_numpy_target = self.data_target\n if self.origin_transfer == 2:\n # take joints 3 of each person, as origins of each person\n origin_target = data_numpy_target[:, :, :, 1, :]\n data_numpy_target = data_numpy_target - origin_target[:, :, :, None, :]\n elif self.origin_transfer == 0:\n # take joints 3 of first person, as origins of each person\n origin_target = data_numpy_target[:, :, :, 1, 0]\n data_numpy_target = data_numpy_target - origin_target[:, :, :, None, None]\n elif self.origin_transfer == 1:\n # take joints 3 of second person, as origins of each person\n origin_target = data_numpy_target[:, :, :, 1, 1]\n data_numpy_target = data_numpy_target - origin_target[:, :, :, None, None]\n else:\n # print('no origin transfer')\n pass\n self.data_target = data_numpy_target\n\n\n\n def get_mean_map(self):\n data = self.data\n N, C, T, V, M = data.shape\n self.mean_map = data.mean(\n axis=2, keepdims=True).mean(\n axis=4, keepdims=True).mean(axis=0)\n # mean_map 3,1,25,1\n self.std_map = data.transpose((0, 2, 4, 1, 3)).reshape(\n (N * T * M, C * V)).std(axis=0).reshape((C, 1, V, 1))\n\n self.min_map = (data.transpose(0, 2, 3, 4, 1).reshape(N * T * V * M, C)).min(axis=0)\n self.max_map = (data.transpose(0, 2, 3, 4, 1).reshape(N * T * V * M, C)).max(axis=0)\n self.mean_mean = (data.transpose(0, 2, 3, 4, 1).reshape(N * T * V * M, C)).mean(axis=0)\n\n print('min_map', self.min_map, 'max_map', self.max_map, 'mean', self.mean_mean)\n\n def __len__(self):\n return len(self.label)\n\n def __iter__(self):\n return self\n\n def __getitem__(self, index):\n # get data\n # input: C, T, V, M\n data_numpy = self.data[index]\n rl_label = self.rl_label[index]\n #print(data_numpy.shape)\n # if self.mmap = True, the loaded data_numpy is read-only, and torch.utils.data.DataLoader could load type 'numpy.core.memmap.memmap'\n if self.mmap:\n data_numpy = np.array(data_numpy) # convert numpy.core.memmap.memmap to numpy\n\n label = self.label[index]\n valid_frame_num_source = self.valid_frame_num_source[index]\n if self.data_path_target != 'None':\n valid_frame_num_target = self.valid_frame_num_target[index]\n\n # normalization\n if self.normalization:\n # data_numpy = (data_numpy - self.mean_map) / self.std_map\n # be careful the value is for NTU_RGB-D, for other dataset, please replace with value from function 'get_mean_map'\n if self.origin_transfer == 0:\n min_map, max_map = np.array([-4.9881773, -2.939787, -4.728529]), np.array(\n [5.826573, 2.391671, 4.824233])\n elif self.origin_transfer == 1:\n min_map, max_map = np.array([-5.836631, -2.793758, -4.574943]), np.array([5.2021008, 2.362596, 5.1607])\n elif self.origin_transfer == 2:\n min_map, max_map = np.array([-2.965678, -1.8587272, -4.574943]), np.array(\n [2.908885, 2.0095677, 4.843938])\n else:\n min_map, max_map = np.array([-3.602826, -2.716611, 0.]), np.array([3.635367, 1.888282, 5.209939])\n\n data_numpy = np.floor(255 * (data_numpy - min_map[:, None, None, None]) / \\\n (max_map[:, None, None, None] - min_map[:, None, None, None])) / 255\n\n # processing\n #if self.crop_resize:\n # tmp0 = tools.valid_crop_resize(data_numpy[:,:,:,:,0], valid_frame_num_source, self.p_interval, self.window_size)\n # if self.data_path_target != 'None':\n # tmp1 = tools.valid_crop_resize(data_numpy[:,:,:,:,1], valid_frame_num_target, self.p_interval, self.window_size)\n # data_numpy = np.concatenate((tmp0[:,:,:,:,None] , tmp1[:,:,:,:,None]),axis = 4)\n # else:\n # data_numpy = np.concatenate((tmp0[:,:,:,:,None] , np.zeros((tmp0.shape),dtype = np.float32)[:,:,:,:,None]),axis = 4)\n if self.crop_resize:\n tmp0 = tools.valid_crop_resize(data_numpy[:,:,:,:,0], valid_frame_num_source, self.p_interval, self.window_size)\n if self.data_path_target != 'None':\n #tmp1 = tools.random_get_frame(data_numpy[:,:,:,:,1], valid_frame_num_target, self.p_interval, self.window_size)\n tmp1 = tools.valid_crop_resize(data_numpy[:,:,:,:,1], valid_frame_num_target, self.p_interval, self.window_size)\n data_numpy = np.concatenate((tmp0[:,:,:,:,None] , tmp1[:,:,:,:,None]),axis = 4).astype(np.float32)\n else:\n data_numpy = np.concatenate((tmp0[:,:,:,:,None] , np.zeros((tmp0.shape),dtype = np.float32)[:,:,:,:,None]),axis = 4).astype(np.float32)\n\n if self.rand_rotate > 0:\n data_numpy = tools.rand_rotate(data_numpy, self.rand_rotate)\n\n if self.random_choose:\n data_numpy = tools.random_choose(data_numpy, self.window_size, auto_pad=True)\n\n\n if self.random_valid_choose:\n data_numpy = tools.valid_choose(data_numpy, self.window_size, random_pad = True)\n elif self.window_size > 0 and (not self.crop_resize) and (not self.random_choose):\n data_numpy = tools.valid_choose(data_numpy, self.window_size, random_pad=False)\n\n\n if self.random_shift:\n data_numpy = tools.random_shift(data_numpy)\n\n if self.random_move:\n data_numpy = tools.random_move(data_numpy)\n\n return data_numpy, label, rl_label\n\n def top_k(self, score, top_k):\n rank = score.argsort()\n hit_top_k = [l in rank[i, -top_k:] for i, l in enumerate(self.label)]\n return sum(hit_top_k) * 1.0 / len(hit_top_k)\n\n def crop(seff, data, tw, th):\n _, w, h, _ = data.shape\n x1 = int(round((w - tw) / 2.))\n y1 = int(round((h - th) / 2.))\n return data[:, x1:x1 + tw, y1:y1 + th, :]\n\n\ndef test(data_path, label_path, vid=None):\n import matplotlib.pyplot as plt\n loader = torch.utils.data.DataLoader(\n dataset=Feeder(data_path, label_path),\n batch_size=64,\n shuffle=False,\n num_workers=2,\n )\n\n if vid is not None:\n sample_name = loader.dataset.sample_name\n sample_id = [name.split('.')[0] for name in sample_name]\n index = sample_id.index(vid)\n data, label = loader.dataset[index]\n data = data.reshape((1,) + data.shape)\n\n # for batch_idx, (data, label) in enumerate(loader):\n N, C, T, V, M = data.shape\n\n plt.ion()\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n\n pose, = ax.plot(np.zeros(V * M), np.zeros(V * M), 'g^')\n ax.axis([-1, 1, -1, 1])\n\n for n in range(N):\n for t in range(T):\n x = data[n, 0, t, :, 0]\n y = data[n, 1, t, :, 0]\n z = data[n, 2, t, :, 0]\n pose.set_xdata(x)\n pose.set_ydata(y)\n fig.canvas.draw()\n plt.pause(0.1)\n\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n import numpy as np\n\n data_path = '/home/tys/Desktop/New/data_preparation/NTU_CV_val_data.npy'\n label_path = '/home/tys/Desktop/New/data_preparation/NTU_CV_val_label.pkl'\n dataset = Feeder(data_path, label_path, random_valid_choose=False,\n random_shift=False,\n random_move=False,\n window_size=100,\n normalization=False,\n debug=False,\n origin_transfer=False, # could not work here\n fft=None)\n print(np.bincount(dataset.label))\n\n test(data_path, label_path, vid='S001C002P001R001A058')\n\n\n","sub_path":"feeder_ours/feeder.py","file_name":"feeder.py","file_ext":"py","file_size_in_byte":18103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"41110256","text":"import unittest\nimport json\nimport requests\nfrom datetime import datetime, date\nimport HTML_Crawler as crawler\nfrom HTML_Crawler import articles\n\n\nclass CrawlerTestCase(unittest.TestCase):\n def test_checkJson(self):\n url = 'https://ria.ru/world/'\n html_page = crawler.get_html_page(url)\n articles = crawler.find_articles(html_page)\n print(articles)\n path = './articles.json'\n crawler.publish_report(path, url, articles)\n fh = open('articles.json', 'r')\n data = json.load(fh)\n fh.close()\n date0 = datetime.now()\n date1 = str(date0.date())\n self.assertEqual(data['url'] == '', False)\n self.assertEqual(data['articles'] == '', False)\n for i in data['articles']:\n self.assertEqual(i['title'] == '', False)\n self.assertEqual(data['articles'][0]['authors'] == '', False)\n self.assertEqual(data['creationDate'] == '', False)\n self.assertEqual(data['creationDate'] == date1, True)\n\n def test_checkPage(self):\n self.assertEqual(articles[0] == '', False)\n\n def test_checkUrl(self):\n url = 'https://ria.ru/world/'\n news_request = requests.get(url)\n self.assertEqual(news_request.status_code == 200, True)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(CrawlerTestCase('test_checkJson'))\n suite.addTest(CrawlerTestCase('test_checkPage'))\n suite.addTest(CrawlerTestCase('test_checkUrl'))\n return suite\n\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite())\n","sub_path":"src/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262128683","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 5 14:42:03 2019\n\n@author: adithya\n\"\"\"\nimport bisect as bi\nn=int(input())\nx=list(map(int,input().split(\" \")))\nq=int(input())\ny=[None]*q\nx.sort()\nfor i in range(0,q):\n y[i]=int(input())\n \nfor j in range(0,q):\n print(bi.bisect(x,y[j]))\n","sub_path":"Interesting Drink.py","file_name":"Interesting Drink.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248758777","text":"\"\"\" Generic result saver, to keep track of version, parameters across\n\nHelps to keep order to results when run on multiple machines and server farms\n\n\"\"\"\n\nimport datetime\nimport json\nimport logging\nimport os\nimport pickle\nimport socket\nimport shutil\n\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\nimport phdlib as phd\nfrom phdlib.misc import logger_settings, data_generator, ftp_access, files\nfrom phdlib import settings\n\nlogger = logging.getLogger(__name__)\n\n\nclass LocalResults(object):\n \"\"\" Storage and information class for running functions/simulations etc\n\n Keeps track of runtime (start dt, and end dt), the used settings, the\n revision number of the files used to run the function, the host_name etc.\n\n \"\"\"\n # TODO design results if it makes sense to pass the function vs data\n # TODO might make sense to have also a load function\n suffix_map = {'HDF5': settings.SUFFIX_RES + '.h5',\n 'pickle': settings.SUFFIX_RES + '.p', }\n\n def __init__(self, engine='HDF5', path=settings.RESULTS_PATH):\n \"\"\"\n \n Parameters\n ----------\n engine: str\n which file format to use, either 'pickle' or 'HDF5'.\n Preferred engine is HDF5 (much more robust), however, currently\n only usable with pd.DataFrame as results data and only with\n one table. For multiple table or non pd.DF use pickle engine.\n \"\"\"\n self.start_dt = datetime.datetime.now()\n self.end_dt = None\n self.file = None\n self.engine = engine\n self.suffix = self.suffix_map[engine]\n self.path = path\n\n def save(self, data, parameters, results_name=None, overwrite=False):\n \"\"\" Saves results locally in python readable bytes (pickle)\n\n Additionally, it attaches the current git revision (if available), the\n hostname, and the results_name\n\n Parameters\n ----------\n data: pandas.DataFrame or dict of Frames\n results which are to be saved\n parameters: dict\n settings which were used in the function run\n results_name: str\n name of the result type, which results/project/estimation\n overwrite: bool\n if existing files should be overwritten (if False raise Error)\n\n Returns\n -------\n\n \"\"\"\n\n self.end_dt = datetime.datetime.now()\n end_dt = self.end_dt.strftime('%Y-%m-%d_%H%M%S')\n self.file = self.path.joinpath(\n '_'.join([end_dt, results_name, self.suffix]))\n\n # check if file exits already\n if overwrite is False:\n if self.file.exists():\n logger.error('File {} exists already'.format(str(self.file)))\n raise FileExistsError\n # results dict\n results = {'StartDT': self.start_dt, 'EndDT': self.end_dt,\n 'Results': data, 'Settings': parameters,\n 'FileName': self.file.name,\n 'HostName': socket.gethostname(),\n 'RevisionID': phd.revision_id, 'Name': results_name}\n # save results to dict\n self.save_to_disk(results, engine=self.engine, file=self.file)\n\n @staticmethod\n def save_to_disk(results, file, engine='HDF5'):\n \"\"\" Saves results to local disk\n \n Parameters\n ----------\n results: dict\n \"\"\"\n\n if engine == 'pickle':\n # write file to local results dir\n with open(str(file), 'wb') as fp:\n pickle.dump(results, fp)\n fp.close()\n elif engine == 'HDF5':\n store = pd.HDFStore(str(file))\n data = results.pop('Results')\n\n if isinstance(data, dict):\n for key, value in data.items():\n store['/'.join(['Results', key])] = value\n # save all keys of result tables to settings file\n results['result_tables'] = list(data.keys())\n else:\n if isinstance(data, (pd.DataFrame, pd.Series)) is False:\n store.close()\n raise TypeError('Only pandas.DF or Series can be saved '\n 'with HDF5 table')\n # save just a single table to hd5 store\n store.put('Results', data)\n results['result_tables'] = None\n\n store['meta'] = pd.Series([1])\n store.get_storer('meta').attrs.metadata = results\n store.close()\n\n logger.info('The following results file was saved: {}'.format(\n str(file)))\n\n def delete(self, file=None, raise_error=True):\n \"\"\" Deletes file from disk\n \n Parameters\n ----------\n file: path-like\n full file path to file\n raise_error: bool\n if file does not exists raise error (True) \n\n Returns\n -------\n\n \"\"\"\n\n if file is None:\n file = self.file\n\n if file.exists():\n os.remove(str(file))\n else:\n if raise_error:\n raise FileNotFoundError\n\n @property\n def run_time(self):\n if self.end_dt is None:\n raise RuntimeError('No results yet obtained')\n return self.end_dt - self.start_dt\n\n\nclass LoadLocalResult():\n def __init__(self, file_pattern, conditions=None, since=None,\n which='latest', engine='pickle',\n path=settings.RESULTS_PATH):\n \"\"\"\n\n Parameters\n ----------\n file_pattern\n conditions: dict\n a dict of parameters, key values need to be specified\n since: date-like\n searches only files sent \n \"\"\"\n self._file_pattern = file_pattern\n self._file_names = None\n self._file_name = None\n self._conditions = conditions\n self._since = since\n self.path = path\n self.files_true = None\n if which == 'latest':\n self._latest = 0\n elif which == 'first':\n self._latest = -1\n self.engine = engine\n\n self._select_file()\n\n @staticmethod\n def _infer_engine(file_name):\n \"\"\"\n \n Parameters\n ----------\n file_name: path-like\n file to be loaded\n\n Returns\n -------\n engine: str\n either \"HDF5\" or \"pickle\"\n \"\"\"\n if str(file_name)[-1] == 'p':\n engine = 'pickle'\n else:\n engine = 'HDF5'\n\n return engine\n\n def _select_file(self):\n \"\"\" Selects file from local storage\n\n Returns\n -------\n\n \"\"\"\n # TODO clean-up this function\n dir = files.Directory(self.path)\n matched_files = dir.find_file(self._file_pattern, pattern_loc='any')\n\n if len(matched_files) == 0:\n raise ValueError('No file with pattern {} found'.format(\n self._file_pattern))\n\n elif len(matched_files) > 0:\n matched_files.sort(reverse=True)\n\n if self._since is not None:\n sent_since = list()\n for file in matched_files:\n # load local file\n engine = self._infer_engine(file)\n tmp_results = load_local_result(file, engine=engine,\n path=self.path)\n if tmp_results['StartDT'] >= pd.Timestamp(self._since):\n sent_since.append(file)\n\n matched_files = sent_since\n\n # take the most recent\n if self._conditions is None:\n self.files_true = matched_files\n\n if len(matched_files) > 1:\n logger.warning('More than one file found, using latest')\n self._file_name = matched_files[self._latest]\n elif len(matched_files) == 1:\n self._file_name = matched_files[0]\n\n else:\n self.files_true = list()\n\n for file in matched_files:\n matching = True\n # load local file\n engine = self._infer_engine(file)\n tmp_results = load_local_result(file, engine=engine,\n path=self.path)\n # load parameters of file\n tmp_para = flatten_parameter(tmp_results['Settings'])\n for key, value in self._conditions.items():\n try:\n if tmp_para[key] != value:\n matching = False\n except KeyError:\n matching = False\n\n if matching:\n self.files_true.append(file)\n\n if len(self.files_true) > 1:\n # raise NotImplementedError\n logger.warning('More than one file found, using latest')\n self._file_name = self.files_true[self._latest]\n elif len(self.files_true) == 1:\n self._file_name = self.files_true[self._latest]\n else:\n raise ValueError('No file with pattern {} and '\n 'matching conditions found'.format(\n self._file_pattern))\n\n engine = self._infer_engine(self._file_name)\n self.file = load_local_result(self._file_name, engine=engine,\n path=self.path)\n\n @staticmethod\n def move_results(files, sub_folder, path=settings.RESULTS_PATH):\n \"\"\" Moves results to sub_folder\n\n Parameters\n ----------\n files: list\n list of files to be moved\n sub_folder: str/iterable\n moves file to sub folder of results dir\n \"\"\"\n if isinstance(sub_folder, str):\n sub_folder = [sub_folder]\n target_dir = path.joinpath(*sub_folder)\n\n for file in files:\n source = path.joinpath(file)\n target = target_dir.joinpath(file)\n\n logger.info('Moving file from {} to {}...'.format(target, source))\n shutil.move(str(source), str(target))\n\n @property\n def parameter(self):\n return flatten_parameter(self.file['Settings'])\n\n @property\n def data(self):\n return self.file['Results']\n\n @property\n def end_time(self):\n return self.file['EndDT']\n\n @property\n def start_time(self):\n return self.file['StartDT']\n\n @property\n def host(self):\n return self.file['HostName']\n\n @property\n def revision(self):\n return self.file['RevisionID']\n\n @staticmethod\n def update_parameters(file_name, parameters, overwrite=True):\n \"\"\"\n\n Parameters\n ----------\n file_name: str\n file name of which p\n parameters: dict\n key values of new parameters\n overwrite\n\n Returns\n -------\n\n \"\"\"\n\n file_path = LocalResults.path.joinpath(file_name)\n results = LoadLocalResult(file_pattern=file_name)\n\n for key, value in parameters.items():\n results.parameter[key] = value\n\n LocalResults.save_to_disk(results,file_name)\n print(file_path)\n # check if file exits already\n # if file_path.exists():\n # logger.error('File {} exists already'.format(str(self.file)))\n # raise FileExistsError\n\n # write file to local results dir\n with open(str(file_path), 'wb') as fp:\n pickle.dump(self.file, fp)\n\n\nclass ResultFileFinder:\n \"\"\" Finds local result files matching conditions\n\n \"\"\"\n\n def __init__(self, pattern, parameter=None, since=None,\n path=settings.RESULTS_PATH):\n\n self._pattern = pattern\n self._parameter = parameter\n self._since = since\n self.path = path\n\n # find all files with matching file pattern\n dir = files.Directory(self.path)\n self.pattern_files = dir.find_file(self._pattern, pattern_loc='any')\n\n self._matched_files = None\n\n @property\n def matched_files(self):\n \"\"\" Returns files matching all conditions: pattern + para + since\n\n Returns\n -------\n\n \"\"\"\n if self._matched_files is None:\n self._matched_files = self.find_files()\n if len(self._matched_files) == 0:\n logger.warning('No files found')\n\n return self._matched_files\n\n @property\n def last_match(self):\n return self.matched_files[0]\n\n @property\n def first_match(self):\n return self.first_match[-1]\n\n def date_filter(self, files):\n \"\"\" Filers according to date criteria\n\n Returns\n -------\n\n \"\"\"\n\n date_matching_files = list()\n\n for file in files:\n # load local file\n engine = infer_engine(file)\n tmp_results = load_local_result(file, engine=engine,\n path=self.path)\n if tmp_results['StartDT'] >= pd.Timestamp(self._since):\n date_matching_files.append(file)\n\n return date_matching_files\n\n def parameter_filter(self, files):\n \"\"\" Filters files according to their parameter conditions\n\n Parameters\n ----------\n files\n\n Returns\n -------\n files\n \"\"\"\n parameter_matching_files = list()\n\n for file in files:\n matching = True\n # load local file\n engine = infer_engine(file)\n tmp_results = load_local_result(file, engine=engine,\n path=self.path)\n # load parameters of file\n tmp_para = flatten_parameter(tmp_results['Settings'])\n for key, value in self._parameter.items():\n try:\n if tmp_para[key] != value:\n matching = False\n except KeyError:\n matching = False\n\n if matching:\n parameter_matching_files.append(file)\n\n return parameter_matching_files\n\n def find_files(self):\n \"\"\" Searching all files\n\n Returns\n -------\n files\n \"\"\"\n if len(self.pattern_files) == 0:\n raise ValueError('No file with pattern {} found'.format(\n self._file_pattern))\n self.pattern_files.sort(reverse=True)\n\n files = self.pattern_files.copy()\n\n if self._since is not None:\n logger.info(f'Considering files only after: {self._since}')\n files = self.date_filter(files)\n\n if self._parameter is not None:\n logger.info(f'Filtering files with parameter: {self._parameter}')\n files = self.parameter_filter(files)\n\n logger.info(f'A total of {len(files)} found matching all conditions.')\n\n return files\n\n\ndef infer_engine(file_name):\n \"\"\"\n\n Parameters\n ----------\n file_name: path-like\n file to be loaded\n\n Returns\n -------\n engine: str\n either \"HDF5\" or \"pickle\"\n \"\"\"\n if str(file_name)[-1] == 'p':\n engine = 'pickle'\n else:\n engine = 'HDF5'\n\n return engine\n\n\nclass DBResults(object):\n def _get_non_db(self):\n \"\"\" returns all local results files which are not yet in database\n\n Returns\n -------\n\n \"\"\"\n result_list = list()\n result_files = list()\n result_dir_list = os.listdir(str(settings.RESULTS_PATH))\n\n # get all result files of local dir\n for file_name in result_dir_list:\n if file_name.endswith(settings.SUFFIX_RES):\n result_files.append(file_name)\n\n # get info of current results in database\n result_info = pd.read_sql('results', self.db_con, columns=['FileName'])\n\n for file in result_files:\n # check if file exists already in results table\n if file in result_info['FileName'].values.tolist():\n logger.info('{} already in archived in results'.format(file))\n continue\n\n # open pickled results and to list\n logger.info('Add {} to results_list'.format(file))\n with open(str(settings.RESULTS_PATH.joinpath(file)), 'rb') as fp:\n print(fp)\n result_list.append(pickle.load(fp))\n fp.close()\n\n return result_list\n\n def save_to_db(self):\n pass\n\n def get_results(self):\n pass\n\n def collect_results(self):\n pass\n\n\ndef collect_results(db_con=None):\n \"\"\" Collects results from the local results directory\n :return:\n \"\"\"\n\n result_list = list()\n result_files = list()\n result_dir_list = os.listdir(str(settings.RESULTS_PATH))\n\n # get all result files of local dir\n for file_name in result_dir_list:\n if file_name.endswith(settings.SUFFIX_RES):\n result_files.append(file_name)\n\n # get info of current results in database\n result_info = pd.read_sql('results', db_con, columns=['FileName'])\n\n for file in result_files:\n # check if file exists already in results table\n if file in result_info['FileName'].values.tolist():\n logger.info('{} already in archived in results'.format(file))\n continue\n\n # open pickled results and to list\n logger.info('Add {} to results_list'.format(file))\n with open(str(settings.RESULTS_PATH.joinpath(file)), 'rb') as fp:\n result_list.append(pickle.load(fp))\n fp.close()\n\n return result_list\n\n\ndef save_results_db(result_list, db_con):\n \"\"\" Saves result to the final storage\n\n Storage consists of three parts, SQL (Overview), JSON(Settings) and\n HDF(Results)\n\n Parameters\n ----------\n result_list: list\n a list of results to be stored\n db_con: sqlalchemy.Engine\n a valid sql session\n\n Returns\n -------\n\n \"\"\"\n\n table_columns = ('StartDT', 'EndDT', 'FileName', 'HostName',\n 'RevisionID', 'Name')\n store_hd5 = pd.HDFStore(str(settings.RESULT_HDF5))\n\n for result in result_list:\n # open results and save them to list SQL\n data = dict((k, result[k]) for k in table_columns if k in result)\n pd.DataFrame(data, index=[0]).to_sql('results', db_con,\n if_exists='append',\n index=False)\n\n # obtain IDs and file names (get newly assigned ID)\n id_table = pd.read_sql('results', db_con, columns=['ID', 'FileName'])\n logger.debug(\n 'Cols id-Table: {}, keys in result: {}'.format(id_table.columns,\n result.keys()))\n result_id = id_table[id_table['FileName'] == result['FileName']]\n if len(result_id) > 1:\n raise ValueError('More than one filename in DB not possible')\n result['ID'] = int(result_id.ID.values[0])\n\n # save result data to hdf 5\n logger.info('save results with id {} to database'.format(result['ID']))\n id_string = '_'.join(['ID', str(result['ID'])])\n\n # check if results are dict -> multiple tables\n if isinstance(result['Results'], dict):\n logger.debug('Results are: {}'.format(result['Results']))\n for key, value in result['Results'].items():\n store_hd5['/'.join([id_string, key])] = value\n # save all keys of result tables to settings file\n result['Settings']['result_tables'] = list(\n result['Results'].keys())\n else:\n # save just a single table to hd5 store\n store_hd5['/'.join([id_string, 'result'])] = result['Results']\n result['Settings']['result_tables'] = ['result']\n\n # save settings data\n new_dict = {result['ID']: result['Settings']}\n if settings.RESULT_META_JS.exists():\n with open(str(settings.RESULT_META_JS)) as fp:\n settings_dict = json.load(fp)\n else:\n settings_dict = dict()\n settings_dict.update(new_dict)\n with open(str(settings.RESULT_META_JS), 'w') as fp:\n json.dump(settings_dict, fp)\n\n store_hd5.close()\n\n\ndef archive_files(sub_folder, pattern='Result',\n path=settings.RESULTS_PATH, **conditions):\n \"\"\" Moves files with different conditions to \"archive\"\n\n Parameters\n ----------\n sub_folder: str or iterable\n size\n pattern\n\n Returns\n -------\n\n \"\"\"\n\n conditions = {**conditions}\n files = LoadLocalResult(file_pattern=pattern,\n since='20171101',\n conditions=conditions,\n path=path).files_true\n LoadLocalResult.move_results(files, sub_folder, path=path)\n\n\ndef get_results(result_ids):\n \"\"\" returns the results stored in the local result storages\n\n Parameters\n ----------\n result_ids: list\n list of restult ids\n\n\n Returns\n -------\n dict\n a dict with result_id as key\n \"\"\"\n res = {}\n # open databases json for parameters, and hd5 table for result tables\n results_hd5 = pd.HDFStore(str(settings.RESULT_HDF5), mode='r')\n with open(str(settings.RESULT_META_JS), 'r') as fp:\n results_json = json.load(fp)\n\n # loop through result ids\n for result_id in result_ids:\n # get settings of tables\n settings_dict = results_json[str(result_id)]\n results = dict()\n # load each table in HDF group\n id_string = '_'.join(['ID', str(result_id)])\n for table in settings_dict['result_tables']:\n results[table] = results_hd5['/'.join([id_string, table])]\n\n tmp_res = {'result_data': results, 'settings': settings_dict}\n res[result_id] = tmp_res\n\n results_hd5.close()\n\n return res\n\n\ndef process_results(ftp_update=False):\n \"\"\"The function process results of all computers\n :return:\n \"\"\"\n\n # collect result from server and store results file locally via ftp\n if ftp_update:\n ftp_access.get_result_data()\n\n # create db-connection to store and get data\n db_con = create_engine(settings.SQL_URL)\n\n # collect local result files to list\n result_list = collect_results(db_con)\n\n # save results to long-term storage\n save_results_db(result_list, db_con)\n\n\ndef load_local_result(file_name, engine='pickle', path = settings.RESULTS_PATH):\n \"\"\" Loads file from local drive\n\n Parameters\n ----------\n file_name: str\n name of the file (path is taken from settings)\n engine: str\n either 'pickle' or 'HDF5'\n\n Returns\n -------\n\n \"\"\"\n\n if engine == 'pickle':\n with open(str(path.joinpath(file_name)), 'rb') as fp:\n local_file = pickle.load(fp)\n fp.close()\n\n elif engine == 'HDF5':\n store = pd.HDFStore(str(path.joinpath(file_name)),\n mode='r')\n local_file = dict()\n if '/meta' in store.keys():\n local_file.update(store.get_storer('meta').attrs.metadata)\n else:\n local_file.update(store.get_storer('Results').attrs.metadata)\n # check if tables info is saved (if not older code version)\n if 'result_tables' not in local_file:\n local_file['result_tables'] = None\n if local_file['result_tables'] is None:\n local_file['Results'] = store['Results']\n else:\n data = dict()\n for table in local_file['result_tables']:\n data[table] = store['/'.join(['Results', table])]\n local_file['Results'] = data\n\n store.close()\n\n return local_file\n\n\ndef flatten_parameter(nested_dict):\n \"\"\" Flattens a nested dicts (up to any level) outer keys are lost\n\n However, keys need to be unique otherwise KeyError is raised\n\n Parameters\n ----------\n nested_dict: dict\n with potentially (one level) nested dict\n\n Returns\n -------\n dict\n\n \"\"\"\n\n flat_dict = dict()\n for key, value in nested_dict.items():\n if isinstance(value, dict):\n for key_nested in value.keys():\n if key_nested in nested_dict.keys():\n raise KeyError(\n '\"{}\" already in dict, cannot be flatten'.format(\n key_nested))\n\n flat_dict.update(flatten_parameter(value))\n else:\n flat_dict[key] = value\n\n return flat_dict\n\n\ndef pickle_to_hdf5_results():\n \"\"\" Browses through results folder and transform all files to HDF results\n \n Returns\n -------\n\n \"\"\"\n\n files = LoadLocalResult(file_pattern='.p').files_true\n\n for file in files:\n hdf5_file_name = settings.RESULTS_PATH.joinpath('HDF5').joinpath(\n file[:-2] + '.h5')\n\n results = load_local_result(file_name=file, engine='pickle')\n LocalResults.save_to_disk(results, file=hdf5_file_name)\n\n\ndef main():\n # logging.config.dictConfig(logger_settings.log_set_ups)\n # logger.setLevel('INFO')\n #\n # size = 'large'\n #\n # fw_correction = 'holm'\n #\n # res_path = settings.RESULTS_PATH.joinpath('cross_section_fm_pols')\n # archive_files(sub_folder='trash', path=res_path, fw_correction=fw_correction)\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"phdlib/data/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":25467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"423517592","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('genes', '__first__'),\n ('organisms', '__first__'),\n ('analyze', '0004_auto_20160321_1415'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Activity',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('value', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='Edge',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('weight', models.FloatField()),\n ('gene1', models.ForeignKey(related_name='gene1', on_delete=django.db.models.deletion.PROTECT, to='genes.Gene')),\n ('gene2', models.ForeignKey(related_name='gene2', on_delete=django.db.models.deletion.PROTECT, to='genes.Gene')),\n ],\n ),\n migrations.CreateModel(\n name='MLModel',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(unique=True, max_length=1000)),\n ('directed_g2g_edge', models.BooleanField(default=False)),\n ('organism', models.ForeignKey(to='organisms.Organism', on_delete=django.db.models.deletion.PROTECT)),\n ],\n ),\n migrations.CreateModel(\n name='Node',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('mlmodel', models.ForeignKey(to='analyze.MLModel', on_delete=django.db.models.deletion.PROTECT)),\n ('samples', models.ManyToManyField(to='analyze.Sample', through='analyze.Activity')),\n ],\n ),\n migrations.CreateModel(\n name='Participation',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('gene', models.ForeignKey(to='genes.Gene', on_delete=django.db.models.deletion.PROTECT)),\n ('node', models.ForeignKey(to='analyze.Node', on_delete=django.db.models.deletion.PROTECT)),\n ],\n ),\n migrations.AddField(\n model_name='edge',\n name='mlmodel',\n field=models.ForeignKey(to='analyze.MLModel', on_delete=django.db.models.deletion.PROTECT),\n ),\n migrations.AddField(\n model_name='activity',\n name='node',\n field=models.ForeignKey(to='analyze.Node', on_delete=django.db.models.deletion.PROTECT),\n ),\n migrations.AddField(\n model_name='activity',\n name='sample',\n field=models.ForeignKey(to='analyze.Sample', on_delete=django.db.models.deletion.PROTECT),\n ),\n migrations.AlterUniqueTogether(\n name='participation',\n unique_together=set([('node', 'gene')]),\n ),\n migrations.AlterUniqueTogether(\n name='node',\n unique_together=set([('name', 'mlmodel')]),\n ),\n migrations.AlterUniqueTogether(\n name='edge',\n unique_together=set([('mlmodel', 'gene1', 'gene2')]),\n ),\n migrations.AlterUniqueTogether(\n name='activity',\n unique_together=set([('sample', 'node')]),\n ),\n ]\n","sub_path":"adage/analyze/migrations/0005_auto_20160915_1523.py","file_name":"0005_auto_20160915_1523.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612405152","text":"from flask import Flask\nfrom flask_restful import Resource, Api\n\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nimport requests\nimport re\n\n# Import the fixer\nfrom werkzeug.contrib.fixers import ProxyFix\n\n\napp = Flask(__name__)\n# Use the fixer\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\napi = Api(app)\n\nclass UnicomCard(Resource):\n def get(self, card_id):\n pattern = re.compile(r'^\\d{9,}\\S$')\n match = pattern.match(card_id)\n\n if match:\n # log\n handler = RotatingFileHandler('card_api.log', maxBytes=10000, backupCount=1)\n handler.setLevel(logging.INFO)\n app.logger.addHandler(handler)\n app.logger.warning('card_id: ' + card_id)\n\n url = 'http://www.un10646.com/tools/common.ashx?action=get_cardInfo'\n data = {\"search_id\": card_id}\n response = requests.post(url, data=data)\n\n # remove logHandler\n app.logger.removeHandler(handler)\n\n return response.json(), 200, {'Access-Control-Allow-Origin': '*'}\n\n else:\n return {\"msg\": \"card_id error\"}, 400, {'Access-Control-Allow-Origin': '*'}\n\n\napi.add_resource(UnicomCard, '/')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"unicomApi.py","file_name":"unicomApi.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255522060","text":"import typing\n\nfrom django.db import models\n\nfrom drf_spectacular.drainage import warn\nfrom drf_spectacular.extensions import OpenApiFilterExtension\nfrom drf_spectacular.plumbing import (\n build_array_type, build_basic_type, build_parameter_type, follow_field_source, get_view_model,\n is_basic_type,\n)\nfrom drf_spectacular.types import OpenApiTypes\nfrom drf_spectacular.utils import OpenApiParameter\n\n# Underspecified filter fields for which heuristics are performed. Serves\n# as an explicit list of all remaining/partially-handled filter fields.\n# ----------------------------------------------------------------------------\n# 'AllValuesFilter', # for no DB hit skip choices\n# 'AllValuesMultipleFilter', # for no DB hit skip choices, multi handled\n# 'ChoiceFilter', # enum handled\n# 'DateRangeFilter', # TODO not sure how this one works exactly\n# 'LookupChoiceFilter', # TODO not sure how this one works exactly\n# 'ModelChoiceFilter', # enum handled\n# 'ModelMultipleChoiceFilter', # enum,multi handled\n# 'MultipleChoiceFilter', # enum,multi handled\n# 'RangeFilter', # min/max handled\n# 'TypedChoiceFilter', # enum handled\n# 'TypedMultipleChoiceFilter', # enum,multi handled\n\n\nclass DjangoFilterExtension(OpenApiFilterExtension):\n target_class = 'django_filters.rest_framework.DjangoFilterBackend'\n\n def get_schema_operation_parameters(self, auto_schema, *args, **kwargs):\n model = get_view_model(auto_schema.view)\n if not model:\n return []\n\n filterset_class = self.target.get_filterset_class(auto_schema.view, model.objects.none())\n if not filterset_class:\n return []\n\n result = []\n for field_name, filter_field in filterset_class.base_filters.items():\n result += self.resolve_filter_field(\n auto_schema, model, filterset_class, field_name, filter_field\n )\n return result\n\n def resolve_filter_field(self, auto_schema, model, filterset_class, field_name, filter_field):\n from django_filters import filters\n\n unambiguous_mapping = {\n filters.CharFilter: OpenApiTypes.STR,\n filters.BooleanFilter: OpenApiTypes.BOOL,\n filters.DateFilter: OpenApiTypes.DATE,\n filters.DateTimeFilter: OpenApiTypes.DATETIME,\n filters.IsoDateTimeFilter: OpenApiTypes.DATETIME,\n filters.TimeFilter: OpenApiTypes.TIME,\n filters.UUIDFilter: OpenApiTypes.UUID,\n filters.DurationFilter: OpenApiTypes.DURATION,\n filters.OrderingFilter: OpenApiTypes.STR,\n filters.TimeRangeFilter: OpenApiTypes.TIME,\n filters.DateFromToRangeFilter: OpenApiTypes.DATE,\n filters.IsoDateTimeFromToRangeFilter: OpenApiTypes.DATETIME,\n filters.DateTimeFromToRangeFilter: OpenApiTypes.DATETIME,\n }\n if isinstance(filter_field, tuple(unambiguous_mapping)):\n for cls in filter_field.__class__.__mro__:\n if cls in unambiguous_mapping:\n schema = build_basic_type(unambiguous_mapping[cls])\n break\n elif isinstance(filter_field, (filters.NumberFilter, filters.NumericRangeFilter)):\n # NumberField is underspecified by itself. try to find the\n # type that makes the most sense or default to generic NUMBER\n if filter_field.method:\n schema = self._build_filter_method_type(filterset_class, filter_field)\n if schema['type'] not in ['integer', 'number']:\n schema = build_basic_type(OpenApiTypes.NUMBER)\n else:\n model_field = self._get_model_field(filter_field, model)\n if isinstance(model_field, (models.IntegerField, models.AutoField)):\n schema = build_basic_type(OpenApiTypes.INT)\n elif isinstance(model_field, models.FloatField):\n schema = build_basic_type(OpenApiTypes.FLOAT)\n elif isinstance(model_field, models.DecimalField):\n schema = build_basic_type(OpenApiTypes.NUMBER) # TODO may be improved\n else:\n schema = build_basic_type(OpenApiTypes.NUMBER)\n elif filter_field.method:\n # try to make best effort on the given method\n schema = self._build_filter_method_type(filterset_class, filter_field)\n else:\n # last resort is to lookup the type via the model field.\n model_field = self._get_model_field(filter_field, model)\n if isinstance(model_field, models.Field):\n try:\n schema = auto_schema._map_model_field(model_field, direction=None)\n except Exception as exc:\n warn(\n f'Exception raised while trying resolve model field for django-filter '\n f'field \"{field_name}\". Defaulting to string (Exception: {exc})'\n )\n schema = build_basic_type(OpenApiTypes.STR)\n else:\n # default to string if nothing else works\n schema = build_basic_type(OpenApiTypes.STR)\n\n # primary keys are usually non-editable (readOnly=True) and map_model_field correctly\n # signals that attribute. however this does not apply in this context.\n schema.pop('readOnly', None)\n # enrich schema with additional info from filter_field\n enum = schema.pop('enum', None)\n if 'choices' in filter_field.extra:\n enum = [c for c, _ in filter_field.extra['choices']]\n if enum:\n schema['enum'] = sorted(enum, key=str)\n\n description = schema.pop('description', None)\n if filter_field.extra.get('help_text', None):\n description = filter_field.extra['help_text']\n elif filter_field.label is not None:\n description = filter_field.label\n\n # parameter style variations based on filter base class\n if isinstance(filter_field, filters.BaseCSVFilter):\n schema = build_array_type(schema)\n field_names = [field_name]\n explode = False\n style = 'form'\n elif isinstance(filter_field, filters.MultipleChoiceFilter):\n schema = build_array_type(schema)\n field_names = [field_name]\n explode = True\n style = 'form'\n elif isinstance(filter_field, (filters.RangeFilter, filters.NumericRangeFilter)):\n try:\n suffixes = filter_field.field_class.widget.suffixes\n except AttributeError:\n suffixes = ['min', 'max']\n field_names = [\n f'{field_name}_{suffix}' if suffix else field_name for suffix in suffixes\n ]\n explode = None\n style = None\n else:\n field_names = [field_name]\n explode = None\n style = None\n\n return [\n build_parameter_type(\n name=field_name,\n required=filter_field.extra['required'],\n location=OpenApiParameter.QUERY,\n description=description,\n schema=schema,\n explode=explode,\n style=style\n )\n for field_name in field_names\n ]\n\n def _build_filter_method_type(self, filterset_class, filter_field):\n if callable(filter_field.method):\n filter_method = filter_field.method\n else:\n filter_method = getattr(filterset_class, filter_field.method)\n\n try:\n filter_method_hints = typing.get_type_hints(filter_method)\n except: # noqa: E722\n filter_method_hints = {}\n\n if 'value' in filter_method_hints and is_basic_type(filter_method_hints['value']):\n return build_basic_type(filter_method_hints['value'])\n else:\n return build_basic_type(OpenApiTypes.STR)\n\n def _get_model_field(self, filter_field, model):\n path = filter_field.field_name.split('__')\n return follow_field_source(model, path)\n","sub_path":"drf_spectacular/contrib/django_filters.py","file_name":"django_filters.py","file_ext":"py","file_size_in_byte":8112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432686178","text":"from math import sqrt\n\ndef quad(a, b, c):\n # check no soln\n proto_disc = (b ** 2) - (4 * a * c)\n if proto_disc > 0:\n disc = sqrt((b ** 2) - (4 * a * c))\n x1 = ((-1 * b) + disc) / (2 * a)\n x2 = ((-1 * b) - disc) / (2 * a)\n return(str(x1) + \" and \" + str(x2))\n elif proto_disc == 0:\n disc = sqrt((b ** 2) - (4 * a * c))\n x1 = ((-1 * b) + disc) / (2 * a)\n return str(x1)\n else:\n return \"No solution.\"\n\n","sub_path":"cogs/utils/formulas.py","file_name":"formulas.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176883905","text":"import sys\nsys.path.append('../')\nfrom Methods import powerMethod as pm\n\ndef solve():\n\tmatrix = [[6, 5, -5],\n\t\t\t [2, 6, -2],\n\t\t\t [2, 5, -1]]\n\tvector = [-1, 1, 1]\n\tsteps = 28\n\tprint(\"\\nLargest eigenvalue:\",pm.apply(matrix, vector, steps))\n\nif __name__ == \"__main__\":\n solve()\n","sub_path":"Problems/problem4a.py","file_name":"problem4a.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359914018","text":"#coding=utf-8\n# 上传文件到sh.config.UPLOAD_IMAGE_PATH目录\n# 通常只允许编辑在后台上传文件,不允许用户自己上传文件\n# 允许修改现有文件,根据是否有model_id字段来判断是insert还是update\nimport web\nimport site_helper as sh\n\n# 允许上传的文件MIME列表,无法识别MIME的一律不允许上传\nALLOW_TYPES = ['text/', 'image/', 'application/x-rar-compressed',\n 'application/x-compressed', 'application/x-gzip', 'application/x-zip-compressed',\n 'application/zip', 'multipart/x-zip', 'application/msword',\n 'application/excel', 'application/vnd.ms-excel', 'application/x-excel',\n 'application/x-msexcel', 'application/vnd.openxmlformats-officedocument.',\n 'application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint',\n 'application/x-mspowerpoint', 'application/pdf', 'application/octet-stream',]\n\nclass UploadFile:\n\n def POST(self):\n inputs = self.inputs()\n model = sh.model('File')\n\n if not inputs.get('model_id', ''):\n model.insert(inputs)\n else:\n exists = model.get(inputs.model_id)\n assert exists is not None\n model.update(inputs.model_id, inputs)\n return sh.refresh()\n\n def inputs(self):\n def __processDocFile(inputs):\n if inputs.has_key('doc_file'):\n doc_file = inputs.doc_file\n if isinstance(doc_file, (str, dict)) or not doc_file.filename:\n del inputs.doc_file\n else:\n if any([doc_file.type.startswith(t) for t in ALLOW_TYPES]):\n inputs.doc_file = sh.storage(dict(filename = doc_file.filename,\n value = doc_file.value, type = doc_file.type))\n elif len(doc_file.type) == 0:\n return sh.alert('上传失败,无法识别此文件的类型')\n else:\n return sh.alert('上传失败,不允许上传此类型的文件: MIME=' + doc.file.type)\n return inputs\n return __processDocFile(web.input(doc_file={}))\n","sub_path":"web/cgi/editorcontroller/UploadFile.py","file_name":"UploadFile.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118349756","text":"import urllib\nimport time\nimport simplejson as json\nfrom bs4 import BeautifulSoup\nfrom outagetools import updatetime, FixedOffset\nfrom datetime import datetime\nimport psycopg2\nimport sys\n\n\ncompany = 'ACE'\n#connect to the database\nconn = psycopg2.connect(\"dbname=nsl_outages user=nsl_out password=powerout\")\ncur = conn.cursor()\n#set the timestamp that will be used in our next two scrapes\ntimestamp = time.time()\n#assign a timestamp for when we accessed the data. This timestamp is passed into the python script from the bash script where it is created\ntimestamp2 = datetime.strptime(\" \".join(sys.argv[1:]),'%a %b %d %H:%M:%S %Z %Y')\n#writer = open('ace.csv','wb')\n#writer.write('company,updated,timestamp,county,muni,outage,totalcustomers\\r')\n\n#scrape the directory where the data is stored\nurl1 ='http://stormcenter.atlanticcityelectric.com.s3.amazonaws.com/data/interval_generation_data/metadata.xml?timestamp=%d' % timestamp\nurlpart = urllib.urlopen(url1)\nurlpart = urlpart.read()\nsoup = BeautifulSoup(urlpart)\n#extract the directory from the xml structure\nurlfrag = soup.find('directory').text\n#get the update time from the urlfrag variable\nupdate = updatetime(urlfrag)\n\n#insert the directory into the url for the next scrape\nurl ='http://stormcenter.atlanticcityelectric.com.s3.amazonaws.com/data/interval_generation_data/'+urlfrag+'/report.js?timestamp=%d' % timestamp\nfile = urllib.urlopen(url)\nfile = file.read()\nfile = json.loads(file)\n\n#begin parsing the data, need to figure out if ACE reports their data by the county level only\nareas = file['file_data']['curr_custs_aff']['areas']\n#ACE reports their entire coverage area as one level in the json file\nfor area in areas:\n counties = area['areas']\n for county in counties:\n countyname = county['area_name']\n customers = county['total_custs']\n outages = county['custs_out']\n row = [company,update,timestamp2,countyname,str(outages),str(customers)]\n cur.execute(\"INSERT INTO tracker_ace(company,updated,timestamp,county,outage,customers) VALUES(%s,%s,%s,%s,%s,%s)\",(row[0],row[1],row[2],row[3],row[4],row[5]))\n conn.commit()\n\ncur.close()\nconn.close()\n #writer.write(company+','+update+','+timestamp2+','+countyname+','+muni+','+str(outages)+','+str(customers)+'\\r')\n#writer.close()","sub_path":"ace.py","file_name":"ace.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503540928","text":"'''\nCreated on Oct 10, 2016\n\n@author: sudipta\n'''\n###\n### Define a simple nextDay procedure, that assumes\n### every month has 30 days.\n###\n### For example:\n### nextDay(1999, 12, 30) => (2000, 1, 1)\n### nextDay(2013, 1, 30) => (2013, 2, 1)\n### nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days)\n###\n\n# def daysBetweenDates(year1, month1, day1, year2, month2, day2):\n# \"\"\"Returns the days between two dates\"\"\"\n# day = 0\n# if (year1 == year2) and (month1 == month2) and (day1 == day2):\n# return 0\n# elif (year1 == year2) and (month1 == month2):\n# return day2-day1 \n# else:\n# while True:\n# year1,month1,day1 = nextDay(year1, month1, day1)\n# day = day+1\n# if (year1 == year2) and (month1 == month2) and (day1 == day2):\n# break\n# return day\n\ndef nextDay(year, month, day):\n \"\"\"Simple version: assume every month has 30 days\"\"\"\n if day < daysInMonth(year, month):\n return year, month, day + 1\n else:\n if month == 12:\n return year + 1, 1, 1\n else:\n return year, month + 1, 1\n\ndef dateIsBefore(year1,month1,day1,year2,month2,day2):\n \"\"\"Returns True if year1-month1-day1 is before \n year2-month2-day2. Otherwise, returns False.\"\"\"\n if year1 < year2:\n return True\n if year1 == year2:\n if month1 < month2:\n return True\n if month1 == month2:\n return day1 < day2\n return False\n\n\ndef daysInMonth(year,month):\n \"\"\"Returns the days of a month of a given year\"\"\"\n if month == 1: # Jan\n return 31\n if month == 2: # Feb\n if isLeapYear(year):\n return 29\n else:\n return 28\n if month == 3: # March\n return 31\n if month == 4: # April\n return 30 \n if month == 5: # May\n return 31\n if month == 6: # June\n return 30\n if month == 7: # July\n return 31\n if month == 8: # Aug\n return 31\n if month == 9: # Sep\n return 30\n if month == 10: # Oct\n return 31\n if month == 11: # Nov\n return 30\n if month == 12: # Dec\n return 31\n \ndef isLeapYear(year):\n if (year%4 == 0 and year%100 !=0) or (year%400 ==0):\n return True\n else:\n return False\n\n# Udacity Professor way of solving daysBetweenDates\ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\n \"\"\"Returns the number of days between year1/month1/day1 and\n year2/month2/day2. Assumes inputs are valid dates in\n Gegorian calender, and the first date is not after the second.\"\"\"\n \n # program defensively! Add an assertion if the input is not valid!\n assert not dateIsBefore(year2, month2, day2, year1, month1, day1), \"Invalid Input, the first date is not after the second.\"\n \n days = 0\n while dateIsBefore(year1, month1, day1, year2, month2, day2):\n year1,month1,day1 = nextDay(year1, month1, day1)\n days += 1\n \n print(days)\n return days\n \ndef test():\n test_cases = [((2012,9,30,2012,10,30),30), \n ((2012,1,1,2013,1,1),366),\n ((2012,9,1,2012,9,4),3)]\n \n for (args, answer) in test_cases:\n result = daysBetweenDates(*args)\n if result != answer:\n print (\"Test with data:\", args, \"failed\")\n else:\n print (\"Test case passed!\")\n\ntest() \n\n# print(nextDay(1999, 12, 30)) # => (2000, 1, 1)\n# print(nextDay(2013, 1, 30)) # => (2013, 2, 1)\n# print(nextDay(2012, 12, 30)) # => (2013, 1, 1) ","sub_path":"Python/daysOld.py","file_name":"daysOld.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169196989","text":"# Q: Given two strings, decide if one is a permutation of the other\n\n# using extra DS --> O(n) time, plus extra space\ndef isPermutationDS(str1, str2):\n\n if len(str1) != len(str2) or str1 == str2:\n return 'NO'\n\n permutation = [i for i in str1]\n\n for i in str2:\n try:\n permutation.remove(i)\n except ValueError:\n return 'NO'\n\n if len(permutation) == 0:\n return 'YES'\n\n return 'NO'\n\n\n# O(n log n) if we can sort strings and then compare. requires moding strings\ndef isPermutationSort(str1, str2):\n if len(str1) != len(str2) or str1 == str2:\n return 'NO'\n\n str1 = ''.join(sorted(str1))\n str2 = ''.join(sorted(str2))\n\n if str1 == str2:\n return 'YES'\n\n return 'NO'\n\n\nstr1 = 'abs'\nstr2 = 'asb'\nstr3 = 'absdcdsdfs'\nstr4 = 'bsa'\nprint(isPermutationDS(str1, str2))\nprint(isPermutationDS(str1, str3))\nprint(isPermutationDS(str1, str4))\nprint(isPermutationSort(str1, str2))\nprint(isPermutationSort(str1, str3))\nprint(isPermutationSort(str1, str4))\n","sub_path":"1-Strings/strings2.py","file_name":"strings2.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222170634","text":"# Runtime: 96ms\n# Your runtime beats 89.83% of python submissions.\n\nclass Solution(object):\n def convert(self, s, numRows):\n \"\"\"\n :type s: str\n :type numRows: int\n :rtype: str\n \"\"\"\n if numRows == 1:\n return s\n zigzag = {}\n for num in range(0, 2 * numRows - 2):\n zigzag[num] = []\n for index, letter in enumerate(s):\n position = index % (2 * numRows - 2)\n if position in zigzag:\n zigzag[position].append(letter)\n ans = ''\n for letter in zigzag[0]:\n ans += letter\n for num in range(1, numRows - 1):\n for index, letter in enumerate(zigzag[num]):\n ans += letter\n if index < len(zigzag[2 * numRows - 2 - num]):\n ans += zigzag[2 * numRows - 2 - num][index]\n for letter in zigzag[numRows - 1]:\n ans += letter\n return ans\n","sub_path":"1-10/6_zigzag_conversion.py","file_name":"6_zigzag_conversion.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449416255","text":"\n\nfrom xai.brain.wordbase.verbs._sink import _SINK\n\n#calss header\nclass _SINKING(_SINK, ):\n\tdef __init__(self,): \n\t\t_SINK.__init__(self)\n\t\tself.name = \"SINKING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"sink\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_sinking.py","file_name":"_sinking.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432185689","text":"import os\nfrom django.core.wsgi import get_wsgi_application\nos.environ['DJANGO_SETTINGS_MODULE'] = 'RbiCloud.settings'\napplication = get_wsgi_application()\nimport datetime\nimport time\nimport json\nimport paho.mqtt.client as mqtt\nfrom cloud import models\n\n# THINGSBOARD_HOST = \"127.0.0.1\"\nTHINGSBOARD_HOST = \"demo.thingsboard.io\"\n\ndef SubDATA():\n try:\n print(\"go SubDATA\")\n client = mqtt.Client()\n # client.username_pw_set(\"$K6BEkJp2NbDSNjq87VVe\")\n client.username_pw_set(\"Xl3AXEbRsuAvctwHLzFA\")\n client.connect(THINGSBOARD_HOST, 1883)\n client.on_connect = on_connect\n client.on_message = on_message\n rc = 0\n while rc == 0:\n rc = client.loop()\n print('Result code: ' + str(rc))\n except Exception as e:\n print(e)\n\ndef PushData():\n try:\n data1 = {\"send_data = json.dumps(data1)\":12}\n # THINGSBOARD_HOST = \"demo.thingsboard.io\"\n client = mqtt.Client()\n # client.username_pw_set(\"$K6BEkJp2NbDSNjq87VVe\")\n client.username_pw_set(\"Xl3AXEbRsuAvctwHLzFA\")\n client.connect(THINGSBOARD_HOST, 1883)\n client.publish('v1/devices/me/attributes', json.dumps(data1))\n time.sleep(5)\n except Exception as e:\n print(e)\n\n\ndef on_connect(client, userdata, flags, rc):\n\n try:\n print(\"on_connect\")\n client.subscribe('v1/devices/me/attributes', 0)\n print(\"Result code \" + str(rc))\n if(rc == 0):\n print(\"Result code \" + str(rc) + \": good connection\")\n else:\n print(\"Result code \" + str(rc) + \": authentication error\")\n except Exception as e:\n print(e)\n\n\n\ndef on_message(client, userdata, msg):\n try:\n print(\"on_message\")\n payload = msg.payload.decode()\n data = json.loads(payload)\n print(data)\n print(data['TOKEN'])\n sensor = models.ZSensor.objects.filter(Token=data['TOKEN'])[0].idsensor\n print(sensor)\n package = models.PackageSensor(idsensor_id=sensor,package=json.dumps(data['Value']))\n package.save()\n except Exception as e:\n print(e)\n print(\"No sensor\")\n\n\nif __name__==\"__main__\":\n print (\"go main\")\n SubDATA()\n # PushData()","sub_path":"cloud/regularverification/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"120618239","text":"from astropy.time import Time\nfrom astropy.io import fits as pf\nimport glob\nimport numpy as np\nimport numbits\nimport time\nimport bifrost as bf\nimport bifrost.pipeline as bfp\nfrom bifrost.dtype import string2numpy\nimport numbits\n\nfrom loguru import logger\n\ndef parse_metafits(filename):\n \"\"\" Parse a metafits file and return a python dictionary \n \n Args:\n filename (str): Path to metafits file\n \n Returns:\n hdr (dict): Dictionary of metafits header:value cards. \n \n Notes:\n Combines COMMENT and HISTORY lines, and ignores FITS-specific keywords.\n \"\"\"\n mf = pf.open(filename)\n mf_hdr = mf[0].header\n hdr = {}\n comment, history = '', ''\n for key, val in mf_hdr.items():\n if key in ('SIMPLE', 'BITPIX', 'NAXIS', 'EXTEND'):\n pass\n elif key == 'COMMENT':\n comment += val + ' '\n elif key == 'HISTORY':\n history += val + ' '\n else:\n hdr[key] = val \n hdr['COMMENT'] = comment\n hdr['HISTORY'] = history\n return hdr\n\n\ndef generate_filelist_from_metafits(filename):\n \"\"\" Generate a list of data files from metafits file \n \n Args:\n filename (str): Path to metafits file\n \n Returns:\n filelist (list): list of dat files corresponding to metafits file. \n \n \"\"\"\n hdr = parse_metafits(filename)\n n_coarse_chan = len(hdr['CHANNELS'].split(','))\n fl = sorted(glob.glob(filename.replace('_metafits.fits', '*.dat')))\n fl = fl[:12]\n \n if len(fl) != n_coarse_chan:\n logger.warning(\"Warning: Number of coarse channels does not match number of dat files.\")\n return fl\n\n\nclass MwaVcsReader(object):\n \"\"\" A file reader for MWA VCS data.\n \n Args:\n filename_or_filelist (str/list): Name of metafits file to open, or list of metafits files\n This will treat all of these as one 'sequence' and concatenate\n together as if one big stream.\n N_time_per_frame (int): Number of time samples to read in each frame. \n Should evenly divide N_time_per_file\n N_time_per_file (int): Total number of time samples in file (default is 10,000)\n \"\"\"\n def __init__(self, filename_or_filelist):\n \n super(MwaVcsReader, self).__init__()\n \n if isinstance(filename_or_filelist, str):\n self.obs_list = [filename_or_filelist,]\n self.n_obs = 1\n else:\n self.obs_list = filename_or_filelist\n self.n_obs = len(filename_or_filelist)\n \n self.obs_count = 0\n self.frame_count = 0\n \n # Currently hardcoded values, 10,000 timesteps per file (one second)\n self.n_frame_per_obs = 100\n self.n_time_per_frame = 100\n \n self._open_next_obs()\n \n itensor = self.header['_tensor']\n \n self.dtype = string2numpy(itensor['dtype'])\n self.frame_shape = np.copy(itensor['shape'])\n self.frame_shape[0] = np.abs(self.frame_shape[0])\n self.frame_size = np.prod(self.frame_shape) * (self.dtype.itemsize)\n \n # Here 'gulp' is how much to read from a single file\n # Whereas 'frame' is how big the full array is (includes N_coarse_chan axis)\n self.dat_gulp_shape = list(self.frame_shape[2:])\n self.dat_gulp_size = np.prod(self.dat_gulp_shape) * (self.dtype.itemsize // 2) # We will unpack 4-bit ci4 to 8-bit ci8\n \n # Create a temporary contiguous array to reuse.\n # Unpacks using numbits to int8, extra axis for real/imag\n self._data = bf.ndarray(np.ndarray(shape=list(self.frame_shape[1:]), dtype=self.dtype), dtype='ci8')\n\n def _open_dat_files(self, idx):\n \"\"\" Internal method to open file handlers for dat file list\"\"\"\n # Generate a list of datafiles\n self.current_datlist = generate_filelist_from_metafits(self.obs_list[idx])\n \n # Create filehandlers\n self.current_datobjs = []\n for fn in self.current_datlist:\n self.current_datobjs.append(open(fn, 'rb'))\n \n def _close_dat_files(self):\n \"\"\" Internal method to close any open dat files \"\"\"\n for fh in self.current_datobjs:\n fh.close() \n self.frame_count = 0\n \n def _read_header(self):\n \"\"\" Read metafits header and convert to bifrost header.\n \n Specifically, need to generate the '_tensor' from the FITS header.\n Currently there are some hardcoded values -- could use header callback to avoid this.\n \"\"\"\n \n mf_header = parse_metafits(self.obs_list[self.obs_count])\n N_coarse_chan = len(self.current_datlist)\n N_fine_chan = 128\n N_station = mf_header['NINPUTS'] // 2\n N_pol = 2\n N_time = self.n_time_per_frame\n \n t0 = Time(mf_header['GPSTIME'], format='gps').unix\n dt = 100e-6\n \n f0_coarse = mf_header['FREQCENT'] - mf_header['BANDWDTH'] / 2\n df_coarse = 1.28 # 1.28 MHz coarse channel \n df_fine = 0.01 # 10 kHz fine channel\n \n self.header = {\n '_tensor': {'dtype': 'ci8', # Note raw data are 4-bit, but bifrost doesn't support ci4 so we use ci9=8\n 'shape': [-1, N_coarse_chan, N_time, N_fine_chan, N_station, N_pol],\n 'labels': ['time', 'coarse_channel', 'frame', 'fine_channel', 'station', 'pol'],\n 'units': ['s', 'MHz', 's', 'MHz', '', ''],\n 'scales': [[t0, dt * N_time],\n [f0_coarse, df_coarse], \n [0, dt],\n [0, df_fine],\n [0,0], \n [0,0]]\n },\n 'name': mf_header['FILENAME'] + '_'+ str(self.obs_count),\n 'source_name': mf_header['FILENAME'], \n 'telescope': mf_header['TELESCOP'], \n 'ra': mf_header['RA'],\n 'dec': mf_header['DEC'],\n 'metafits': mf_header\n }\n return self.header\n \n def _open_next_obs(self):\n \"\"\" Internal method to open next observation \"\"\"\n logger.info(\"%i/%i: opening %s\" % (self.obs_count+1, self.n_obs, self.obs_list[self.obs_count]))\n if self.obs_count > 0:\n self._close_dat_files()\n self._open_dat_files(idx=self.obs_count) \n self.header = self._read_header()\n self.obs_count += 1\n\n def _read_data(self):\n \"\"\" Internal method to read next data frame \"\"\"\n \n if self.frame_count < self.n_frame_per_obs:\n for ii, fh in enumerate(self.current_datobjs):\n d_packed = np.fromfile(fh, count=self.dat_gulp_size, dtype='int8')\n d_unpacked = numbits.unpack(d_packed, 4).view(self.dtype).reshape(self.dat_gulp_shape)\n self._data[ii] = d_unpacked\n self.frame_count += 1\n return self._data\n else:\n return np.ndarray(shape=0, dtype=self.dtype)\n \n def read_frame(self):\n \"\"\" Read next frame of data \"\"\"\n logger.debug(\"Reading frame %i ...\" % self.frame_count)\n d = self._read_data()\n if d.size == 0 and self.frame_count == self.n_frame_per_obs:\n if self.obs_count == self.n_obs:\n logger.info(\"End of file data stream\")\n d = np.array([0]) # End of data stream\n else:\n logger.debug(\"Opening next observation\")\n self._open_next_obs()\n d = self._read_data()\n return d\n \n def read(self):\n d = self.read_frame()\n return d\n\n def close(self):\n \"\"\" Close all open files \"\"\"\n self._close_dat_files()\n \n def __enter__(self):\n return self\n\n def __exit__(self, type, value, tb):\n self.close()\n\n \nclass MwaVcsReadBlock(bfp.SourceBlock):\n def __init__(self, filelist, gulp_nframe=1, *args, **kwargs):\n super(MwaVcsReadBlock, self).__init__(filelist, gulp_nframe, *args, **kwargs)\n\n def create_reader(self, filename):\n logger.info(f\"Reading {filename}...\")\n return MwaVcsReader(filename)\n\n def on_sequence(self, ireader, filename):\n ohdr = ireader.header\n return [ohdr]\n\n def on_data(self, reader, ospans):\n indata = reader.read()\n odata = ospans[0].data\n logger.debug(\"MWA VCS reader on_data called, reading data block\")\n if np.prod(indata.shape) == np.prod(odata.shape[1:]):\n ospans[0].data[0] = indata\n return [1]\n else:\n # EOF or truncated block\n return [0]\n\n\ndef read_vcs_block(filename, *args, **kwargs):\n \"\"\" Block for reading binary data from file and streaming it into a bifrost pipeline\n Args:\n filenames (list): A list of filenames to open\n \"\"\"\n return MwaVcsReadBlock(filename, *args, **kwargs)\n","sub_path":"blocks/read_vcs_sub.py","file_name":"read_vcs_sub.py","file_ext":"py","file_size_in_byte":9162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268157349","text":"from django import template\n\nfrom datetime import date\n\nregister = template.Library()\n\n\n@register.simple_tag(name=\"BizzFuzz\")\ndef bizzfuzz(value):\n if value.random_val % 3 == 0 and value.random_val % 5 == 0:\n return \"BizzFuzz\"\n elif value.random_val % 3 == 0:\n return \"Bizz\"\n elif value.random_val % 5 == 0:\n return \"Fuzz\"\n else:\n return value.random_val\n\n\ndef calculate_age(born):\n today = date.today()\n return today.year - born.year - ((today.month, today.day) < (born.month, born.day))\n\n\n@register.simple_tag(name=\"Eligible\")\ndef eligible(value):\n if value.birthday:\n if calculate_age(value.birthday) > 13:\n return \"allowed\"\n else:\n return \"blocked\"\n else:\n return \"blocked\"\n","sub_path":"milo/templatetags/user_extras.py","file_name":"user_extras.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524145340","text":"import urllib.request as urllib2\nimport json\nfrom time import sleep, time\nimport cv2\nimport numpy as np\nimport os\n\n\nclass SensorException(Exception):\n def __init__(self, sensor):\n \"\"\"\n Sensor's exception in case it's not switched on\n :param sensor: specific sensor\n \"\"\"\n super().__init__(\"Error: Sensor {} is not switched on\".format(sensor))\n\n\nclass Motion:\n def __init__(self, ip_add, port=\"8080\", how_many_tries=3, interval=1):\n \"\"\"\n Class' constructor\n :param ip_add: user ip address\n :param port: user port\n :param how_many_tries: how many measurements\n :param interval: time between measurement\n countOffline: amount of tries for offline checking\n \"\"\"\n self.ip_address = ip_add\n self.port = port\n self.how_many_tries = how_many_tries\n self.interval = interval\n self.countOffline = 0\n\n def isAppWorking(self):\n \"\"\"\n Verifies if the application is working\n :return: \"True\" if application is working, and \"False\" if application is not working\n \"\"\"\n try:\n url = urllib2.urlopen(\"http://\" + self.ip_address + \":\" + self.port + \"/sensors.json?sense=motion\")\n except urllib2.URLError as err:\n self.countOffline = self.countOffline + 1;\n print(\"Message isAppWorking():\", err.reason, \" \", self.countOffline)\n else:\n data = json.load(url)\n self.countOffline = 0\n if len(data) == 0:\n raise SensorException('motion')\n\n if (self.countOffline > 2):\n print(\"Message isAppWorking(): Application is not working\")\n return False\n else:\n return True\n\n def motionData(self):\n \"\"\"\n Returns data from the sensor\n :return: \"[data]\" if application is working and data url exists, \"[]\" if data url does not exist\n \"\"\"\n list = []\n try:\n for y in range(0, self.how_many_tries):\n url = urllib2.urlopen(\"http://\" + self.ip_address + \":\" + self.port + \"/sensors.json?sense=motion\")\n data = json.load(url)\n list.append(data)\n sleep(self.interval)\n except urllib2.URLError as err:\n pass\n\n return list\n\n def savePicture(self):\n \"\"\"\n\n :return: \"tmp_url\" into temporary image if application is working and data url exists,\n and \"\" if data url does not exist\n \"\"\"\n self._createFolder('./tmp_img/')\n tmp_url = ''\n try:\n url = \"http://\" + self.ip_address + \":\" + self.port + \"/shot.jpg\"\n imgResp = urllib2.urlopen(url)\n imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)\n img = cv2.imdecode(imgNp, -1)\n tmp_url = \"./tmp_img/\" + str(int(time())) + \".jpg\"\n cv2.imwrite(tmp_url, img)\n except urllib2.URLError as err:\n pass\n\n return tmp_url\n\n def _createFolder(self, directory):\n \"\"\"\n Creates folder for temporary images\n :param directory: temporary name of the folder\n \"\"\"\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Error: Creating directory. ' + directory)\n","sub_path":"motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422849487","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom configparser import ConfigParser\nimport requests\nimport os\nfrom PIL import Image, ImageTk\n\nurl = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid={}'\n\n\n\ndef get_api():\n config_file = \"weather_app/config.ini\"\n config = ConfigParser()\n config.read(config_file)\n api_key = config['api_key']['key']\n return api_key\n\n\ndef search():\n global img\n city = city_text.get()\n weather = get_infos(city)\n if weather:\n Location[\"text\"] = \"{}, {}\".format(weather[0], weather[1])\n img[\"file\"] = 'weather_app\\\\icons\\\\{}.png'.format(weather[4])\n Temperature[\"text\"] = \"{:.2f}°C, {:.2f}°F\".format(weather[2], weather[3])\n Weather[\"text\"] = \"{}\".format(weather[5])\n else:\n messagebox.showerror(\"Error\", \"Cannot find the {}\".format(city))\n\n\ndef get_infos(city):\n result = requests.get(url.format(city, get_api()))\n if result:\n json = result.json()\n city = json[\"name\"]\n temp_kelvin = json[\"main\"][\"temp\"]\n temp_celsius = temp_kelvin - 273.15\n temp_far = (temp_kelvin - 273.15) * 9/5 + 32\n country = json[\"sys\"][\"country\"]\n icon = json[\"weather\"][0][\"icon\"]\n weather = json[\"weather\"][0][\"main\"]\n final = (city, country, temp_celsius, temp_far, icon, weather)\n return final\n else:\n return None\n\n\nroot = Tk()\nblank_space = \" \"\nroot.title(90*blank_space+\"Weather Checker\")\nroot.geometry(\"700x350\")\nroot.iconphoto(False, PhotoImage(file='weather_app\\\\icons\\\\weather.png'))\n\n\ncity_text = StringVar()\ncity_entry = Entry(root, textvariable=city_text)\ncity_entry.pack()\n\nSearch = Button(root, text=\"Search Weather\", command=search)\nSearch.pack()\n\nLocation = Label(root, text=\"\", font=(\"bold\", 18))\nLocation.pack(pady=8)\n\nimg = PhotoImage(file= \"\")\nImage = Label(root, image = img)\nImage.pack()\n\n\nTemperature = Label(root, text=\"\")\nTemperature.pack()\n\nWeather = Label(root, text='', font =(\"Bold\", 11))\nWeather.pack()\n\nroot.mainloop()","sub_path":"weather_app/weather_app.py","file_name":"weather_app.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112081168","text":"\"\"\"bbgo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\njs_info_dict = {\n 'packages': ('',),\n}\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(\n r'^jsi18n-debug/$',\n 'django.views.i18n.javascript_catalog',\n js_info_dict,\n ),\n url(\n r'^.*/jsi18n/$',\n 'jsi18ncache.views.javascript_catalog',\n js_info_dict,\n ),\n url(r'^', include('django.contrib.auth.urls')),\n url(r'^', include('portal.urls')),\n url(r'^accounts/', include('accounts.urls', namespace='accounts')),\n url(r'^msgs/', include('msgs.urls', namespace='msgs')),\n url(r'^blogs/', include('blogs.urls', namespace='blogs')),\n url(r'^boards/', include('boards.urls', namespace='boards')),\n url(r'^teams/', include('teams.urls', namespace='teams')),\n url(r'^spams/', include('spams.urls', namespace='spams')),\n url(r'^api/', include('core.apiurls', namespace='api')),\n url(r'^vaults/', include('vaults.urls', namespace='vaults')),\n url(r'^recipes/', include('recipes.urls', namespace='recipes')),\n url(r'^a/', include('aliases.urls', namespace='aliases')),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif 'django_summernote' in settings.INSTALLED_APPS:\n urlpatterns.append(url(r'^summernote/', include('django_summernote.urls')))\nif 'rosetta' in settings.INSTALLED_APPS:\n urlpatterns.append(url(r'^trans/', include('rosetta.urls')))\n","sub_path":"bbgo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274842297","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport os\r\nimport glob\r\nimport cv2\r\nimport sys\r\nimport argparse\r\n\r\n# First, pass the path of the image\r\nfiles = []\r\nfor file in glob.glob(\"img_test/ok/*.jpg\"):\r\n files.append(file)\r\ncorrect_vals = np.zeros((1, 2))\r\n#filename = image_path +'/' +'cat.372.jpg'\r\nnum_channels = 3\r\nname_classes = ['NG', 'OK']\r\nsess = tf.Session()\r\nsaver = tf.train.import_meta_graph('save/Flash.meta')\r\n\r\nsaver.restore(sess, tf.train.latest_checkpoint('save/'))\r\ngraph = tf.get_default_graph()\r\n\r\ny_pred = graph.get_tensor_by_name(\"y_pred:0\")\r\n\r\nx = graph.get_tensor_by_name(\"x:0\")\r\ny_true = graph.get_tensor_by_name(\"y_true:0\")\r\n# gte number of classs\r\ny_test_images = np.zeros((1, len(os.listdir('img_train'))))\r\n\r\nTP = 0\r\nFP = 0\r\nFN = 0\r\nTN = 0\r\n\r\nfor filename in files:\r\n images = []\r\n image = cv2.imread(filename)\r\n # image = cv2.resize(image, (180, 240),0,0, cv2.INTER_LINEAR)\r\n images.append(image)\r\n images = np.array(images, dtype=np.uint8)\r\n images = images.astype('float32')\r\n images = np.multiply(images, 1.0/255.0)\r\n x_batch = images.reshape(1, 180, 240, num_channels)\r\n feed_dict_testing = {x: x_batch, y_true: y_test_images}\r\n result = sess.run(y_pred, feed_dict=feed_dict_testing)\r\n print(result, end=\" \")\r\n fn = str(filename)\r\n li = fn.split(\"\\\\\")\r\n print(li[1], end=\" \")\r\n if(result[0][1] > 0.5):\r\n TP += 1\r\n FN += 1\r\n print('OK')\r\n else:\r\n FP += 1\r\n TN += 1\r\n print('NG')\r\n\r\nprint(\"total = \", len(files), \" TP=\", TP, \" FP=\", FP, \" TN=\", TN, \" FN=\", FN)\r\n","sub_path":"CNN/CNN_Flash_180_240/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52234778","text":"import asyncio\nimport datetime\nimport logging\nimport warnings\nfrom enum import Enum\n\nfrom pytaps.transportProperties import get_protocols, PreferenceLevel\n\ncolors = {\n \"red\": \"\\x1b[31;1m\",\n \"green\": \"\\x1b[32;1m\",\n \"yellow\": \"\\x1b[33;1m\",\n \"blue\": \"\\x1b[34;1m\",\n \"magenta\": \"\\x1b[35;1m\",\n \"cyan\": \"\\x1b[36;1m\",\n \"grey\": \"\\x1b[37;1m\",\n \"white\": \"\\x1b[38;1m\"\n}\n\n\nclass ConnectionState(Enum):\n ESTABLISHING = 0\n ESTABLISHED = 1\n CLOSING = 2\n CLOSED = 3\n\n\ndef print_time(msg=\"\", color=\"red\"):\n warnings.warn(\"\\x1b[31;1mprint_time is deprecated, switch to a logger (e.g. with setup_logger()).\\x1b[0m\", DeprecationWarning, 2)\n print(str(datetime.datetime.now()) + \": \" + msg, color)\n\n\ndef color_emit(emit):\n def new(*args):\n level = args[0].levelno\n if level == logging.CRITICAL:\n color = \"red\"\n elif level == logging.WARNING:\n color = \"yellow\"\n elif level == logging.INFO:\n color = \"green\"\n else:\n color = \"white\"\n args[0].levelname = f'{colors[color]}{args[0].levelname}\\x1b[0m'\n return emit(*args)\n return new\n\n\ndef setup_logger(module, color=\"white\"):\n logger = logging.getLogger(module)\n logger.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n ch.setFormatter(logging.Formatter(f'%(asctime)s - {colors[color]}%(name)s \\x1b[0m- %(levelname)s: %(message)s'))\n ch.emit = color_emit(ch.emit)\n logger.addHandler(ch)\n return logger\n\n\ndef create_candidates(connection):\n \"\"\" Decides which protocols are candidates and then orders them\n according to the TAPS interface draft\n \"\"\"\n # Get the protocols know to the implementation from transportProperties\n available_protocols = get_protocols()\n\n # At the beginning, all protocols are candidates\n candidate_protocols = dict([(row[\"name\"], list((0, 0)))\n for row in available_protocols])\n\n # Iterate over all available protocols and over all properties\n for protocol in available_protocols:\n for transport_property in connection.transport_properties.properties:\n # If a protocol has a prohibited property remove it\n if (connection.transport_properties.properties[transport_property]\n is PreferenceLevel.PROHIBIT):\n if (protocol[transport_property] is True and\n protocol[\"name\"] in candidate_protocols):\n del candidate_protocols[protocol[\"name\"]]\n # If a protocol doesnt have a required property remove it\n if (connection.transport_properties.properties[transport_property]\n is PreferenceLevel.REQUIRE):\n if (protocol[transport_property] is False and\n protocol[\"name\"] in candidate_protocols):\n del candidate_protocols[protocol[\"name\"]]\n # Count how many PREFER properties each protocol has\n if (connection.transport_properties.properties[transport_property]\n is PreferenceLevel.PREFER):\n if (protocol[transport_property] is True and\n protocol[\"name\"] in candidate_protocols):\n candidate_protocols[protocol[\"name\"]][0] += 1\n # Count how many AVOID properties each protocol has\n if (connection.transport_properties.properties[transport_property]\n is PreferenceLevel.AVOID):\n if (protocol[transport_property] is True and\n protocol[\"name\"] in candidate_protocols):\n candidate_protocols[protocol[\"name\"]][1] -= 1\n\n # Sort candidates by number of PREFERs and then by AVOIDs on ties\n sorted_candidates = sorted(candidate_protocols.items(),\n key=lambda value: (value[1][0],\n value[1][1]), reverse=True)\n\n return sorted_candidates\n\n\n# Define our own sleep function which keeps track of its running calls\n# so we can cancel them once the Connection is established\n# https://stackoverflow.com/questions/37209864/interrupt-all-asyncio-sleep-currently-executing\nclass SleepClassForRacing:\n tasks = set()\n\n async def sleep(self, delay, result=None, *, loop=None):\n coro = asyncio.sleep(delay, result=result, loop=loop)\n task = asyncio.ensure_future(coro)\n self.tasks.add(task)\n try:\n return await task\n except asyncio.CancelledError:\n return result\n finally:\n self.tasks.remove(task)\n\n def cancel_all(self):\n for task in self.tasks:\n task.cancel()\n","sub_path":"pytaps/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222992518","text":"\n'''\n* Program #: Message Class\n* Programmer: Jeremy Lee\n* Due: 08/1/16\n* CS 3A, summer 2016\n* Description: This class creates a collection of messages using the mailbox class.\n'''\nimport message\nimport mailbox\n\nmessage1 = message.Message(\"Bob\", \"Santa\")\nmessage1.append(\"For Christmas, I would like:\")\nmessage1.append(\"Video Games\")\nmessage1.append(\"World peace\")\n\nmessage2 = message.Message(\"Bob\", \"Santa\")\nmessage2.append(\"Merry Christmas to my best friend\")\nmessage2.append(\"I am wishing you blessings and joy this Christmas.\")\n\n\nbox = mailbox.MailBox()\nbox.addMessage(message1)\nbox.addMessage(message2)\nfor i in range(0, box.getSize()):\n print(box.getMessage(i))\n","sub_path":"Assignment5/mailbox_demo.py","file_name":"mailbox_demo.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581464520","text":"# Copyright 2019 Google LLC. All Rights Reserved.\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\"\"\"Chicago taxi example using TFX.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport logging\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout)\nimport os\nfrom code2flow.code2flow import Code2Flow\nfrom tfx.utils import channel\nfrom tfx.utils.types import TfxArtifact\n\n# \ncode2flow = Code2Flow(target=Code2Flow.LOCAL,\n trigger_new_run=False,\n pipeline_changed=True,\n assets_changed=True,\n pipeline_name=\"custom_head_component_pipeline\",\n root_directory_cluster=os.getenv(\"TFX_SRC_DIR\", \"/tfx-src\"),\n cluster_host=\"localhost:8080\",\n number_of_gpus=0 # keep in mind that you have to manually start enough GPU in the cluster\n )\n\n# import the component (must happen this way because the path will change depending on deployment target).\n# the component_name must be equal to the directory name holding the component file (component.py),\n# but can be any string\ncustom_component = code2flow.import_custom_component(component_name=\"custom_upstream_component\",\n path_to_calling_file=__file__)\n\n_taxi_root = code2flow.assets_root\n_tfx_root = os.path.join(_taxi_root, 'tfx')\n_data_root = os.path.join(_taxi_root, 'data')\n_metadata_db_root = os.path.join(_tfx_root, 'metadata')\n\n\ndef _create_pipeline():\n \"\"\"Implements an example pipeline with a custom head component\"\"\"\n\n input_artifact = TfxArtifact(type_name=\"RandomTypeNameForInput\")\n input_artifact.uri = os.path.join(_data_root, \"input_example.txt\")\n\n input_channel = channel.Channel(artifacts=[input_artifact], type_name=\"RandomTypeNameForInput\")\n\n my_first_awesome_component = custom_component.CustomHeadComponent(input_example=input_channel,\n string_execution_parameter=\"My awesome string\",\n integer_execution_parameter=42)\n\n return code2flow.create_pipeline(\n components=[\n my_first_awesome_component\n ],\n enable_cache=True,\n metadata_db_root=_metadata_db_root\n )\n\n\n# Deploy\n_ = code2flow.deploy(_create_pipeline())\n","sub_path":"Custom_Head_Component/custom_head_component_pipeline.py","file_name":"custom_head_component_pipeline.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543960773","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport torch\nfrom random import gauss, uniform\n\n\ndef make_rand_vector(dims):\n vec = [np.random.normal(0, 0.12) for i in range(dims)]\n\n return vec\n\n\ndef rand_vec(dim, z):\n vec = [uniform(0, 1) for i in range(dim - 1)]\n mag = 1 - z ** 2\n y = [x / mag for x in vec] + [z]\n z = sum([x ** 2 for x in y])\n print(z)\n\n\ndef draw_ball(z=np.linspace(-1, 1, 50)):\n bag = []\n for x in z:\n r = np.sqrt(1 - x ** 2)\n theta = np.linspace(-180, 180, 20)\n for t in theta:\n ys = r * np.sin(np.pi * t / 180.)\n xs = r * np.cos(np.pi * t / 180.)\n bag.append([x, xs, ys])\n return bag\n\n\ndef drawSphere(xCenter, yCenter, zCenter, r):\n # draw sphere\n u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:10j]\n x = np.cos(u) * np.sin(v)\n y = np.sin(u) * np.sin(v)\n z = np.cos(v)\n # shift and scale sphere\n x = r * x + xCenter\n y = r * y + yCenter\n z = r * z + zCenter\n return (x, y, z)\n\n\nbag = []\n# bag.append(draw_ball())\nfrom NVLL.util.util import GVar\n\nfor n in range(5):\n x = make_rand_vector(3)\n x = np.asarray(x)\n tmp = []\n for _ in range(20):\n y = np.random.normal(x, 0.1)\n print(y)\n tmp.append(y)\n bag.append(tmp)\n\nfig = plt.figure(figsize=(5, 5))\nax = fig.add_subplot(111, projection='3d')\n\n(xs, ys, zs) = drawSphere(0, 0, 0, 1)\nax.plot_wireframe(xs, ys, zs, color=\"black\", linestyle=\":\", lw=0.75)\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\n\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n\na = Arrow3D([0, 0], [0, 0],\n [-1.2, 1.2], mutation_scale=7,\n lw=1, arrowstyle=\"-|>\", color=\"black\")\nb = Arrow3D([-1.2, 1.2], [0, 0], [0, 0],\n mutation_scale=7,\n lw=1, arrowstyle=\"-|>\", color=\"black\")\nc = Arrow3D([0, 0], [-1.2, 1.2], [0, 0],\n mutation_scale=7,\n lw=1, arrowstyle=\"-|>\", color=\"black\")\nax.add_artist(a)\nax.add_artist(b)\nax.add_artist(c)\n\n# For each set of style and range settings, plot n random points in the box\n# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\nbank_color = ['b', 'r', 'g', 'c', 'm']\nbank_marker = ['.', 'o', 'v', '^', '<']\nfor idx, group in enumerate(bag):\n c = bank_color[idx]\n m = '.'\n mean_x = 0\n mean_y = 0\n mean_z = 0\n for point in group:\n xs, ys, zs = point\n mean_x += xs\n\n mean_y += ys\n mean_z += zs\n ax.scatter(xs, ys, zs, c=c, marker=m)\n mean_x /= len(group)\n mean_y /= len(group)\n mean_z /= len(group)\n line = Arrow3D([0, mean_x], [0, mean_y], [0, mean_z],\n mutation_scale=10,\n lw=1.5, arrowstyle=\"-|>\", color=c)\n\n ax.add_artist(line)\n\n# for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:\n# xs = randrange(n, 23, 32)\n# ys = randrange(n, 0, 100)\n# zs = randrange(n, zlow, zhigh)\n# ax.scatter(xs, ys, zs, c=c, marker=m)\n# ax.set_axis_on()\nax.set_axis_off()\n\nstart, end = ax.get_xlim()\nax.xaxis.set_ticks(np.arange(-1, 1.5, 0.5))\nax.yaxis.set_ticks(np.arange(-1, 1.5, 0.5))\nax.zaxis.set_ticks(np.arange(-1, 1.5, 0.5))\n\n# make the panes transparent\nax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\nax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\nax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n# make the grid lines transparent\nax.xaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\nax.yaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\nax.zaxis._axinfo[\"grid\"]['color'] = (1, 1, 1, 0)\n\n# ax.set_xlabel('X')\n# ax.set_ylabel('Y')\n# ax.set_zlabel('Z')\n# fig.set_size_inches(5, 5)\nfig.savefig('gauss.pdf', transparent=True)\nplt.show()\n","sub_path":"NVLL/visual/draw_gauss_ball.py","file_name":"draw_gauss_ball.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244600727","text":"# -*- coding:utf-8 -*-\nimport numpy as np\n__author__ = 'Administrator'\n\nclass MyOrdinaryLinear():\n\n def fit_by_matrix(self, X, y):\n self.matrix_method(X, y)\n\n def fit_by_sgd(self,X, y, alpha=0.01, max_iters=1000, epsilon=0.0001):\n self.sgd_method(X, y, alpha, max_iters, epsilon)\n\n def matrix_method(self, X, y):\n \"\"\"\n 采用矩阵求解方法\n :param X:\n :param y:\n :return:\n \"\"\"\n X = np.array(X)\n X_rows = X.shape[0]\n X = np.column_stack((np.ones(X_rows), X)) # 在X矩阵插入第0列数据,方便求解截距\n y = np.array(y)\n w = np.linalg.inv(X.T.dot(X)).dot(X.T.dot(y))\n self.coef_ = w[1:]\n self.intercept_ = w[0]\n return self\n\n def sgd_method(self, X, y, alpha, max_iters, epsilon):\n \"\"\"\n 随机梯度下降法\n :param X:\n :param y:\n :param alpha:\n :return:\n \"\"\"\n X = np.array(X)\n X_rows = X.shape[0] # 样本个数\n X = np.column_stack((np.ones(X_rows), X)) # 在X矩阵插入第0列数据,方便求解截距\n X_cols = X.shape[1] # 特征的个数/维度\n theta = np.zeros(X_cols)\n error_before = 0\n error_after = 0\n\n for nums in range(max_iters):\n for i in range(X_rows):\n diff = X[i].dot(theta) - y[i]\n theta = theta - alpha * diff * X[i, :]\n\n for i in range(X_rows):\n error_after += (X[i].dot(theta) - y[i])**2 / 2\n\n if abs(error_before - error_after) < epsilon:\n break\n\n # 更新\n error_before = error_after\n\n self.coef_ = theta[1:]\n self.intercept_ = theta[0]","sub_path":"regression/linearmodel/myordinaryleastsquares.py","file_name":"myordinaryleastsquares.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"231690337","text":"'''\nCreated on 20-sep.-2015\n\n@author: jasperdelaey\n'''\nimport socket\nimport sys\nimport time\nimport random\nserver = \"burstfire.uk.eu.gamesurge.net\" #settings\nchannel = \"#limittheory\"\nbotnick = \"Cha0zzBot\"\n\nirc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket\nirc.connect((server, 6667)) #connects to the server\nirc.send(\"USER \"+ botnick +\" \"+ botnick +\" \"+ botnick +\" :This is a fun bot!\\n\") #user authentication\nirc.send(\"NICK \"+ botnick +\"\\n\") #sets nick\nirc.send(\"PRIVMSG nickserv :iNOOPE\\r\\n\") #auth\n\nconnected = False\nsleep = False\ncheercount=0\nhailcount=0\nwavecount=0\n\ncommands =[\"!nick\", \"!quit\", \"!help\", \"!join\", \"!sleep\", \"!wake\"]\ngreetings = [\"Hi\", \"Hello\", \"Hey\", \"Greetings\"]\n\ndef sendmsg(msg):\n channel = text.split()[2]\n irc.send(\"PRIVMSG \"+ channel +\" :\"+ msg +\"\\n\")\n \ndef sleepwatch():\n if \":!sleep\" in text:\n global sleep\n sleep = True\n sendmsg(\"zzzz\")\n\ndef wakewatch():\n if \":!wake\" in text:\n global sleep\n sleep = False\n sendmsg(\"I'm awake now.\")\n \ndef changechannel():\n if \":!join\" in text:\n chan = text.split()[4]\n irc.send(\"JOIN \" + chan + \"\\r\\n\")\n if \":!leave\" in text:\n chan = text.split()[4]\n irc.send(\"LEAVE \" + chan + \"\\r\\n\")\n \ndef changenick():\n if \":!nick\" in text:\n global botnick\n botnick = text.split()[4]\n irc.send(\"NICK \" + botnick +\"\\n\")\n \ndef greetingwatch():\n greetings2 = greetings\n name = text.split(\"!\")[0].strip(\":\")\n for i in greetings:\n if text.lower().find(i.lower() + \" \" + botnick.lower()) != -1:\n sendmsg(random.choice(greetings2) + \" \"+ name)\n if text.lower().find(\"join\") !=-1 and text.find(\"@\") !=-1 and text.lower().find(botnick.lower()) == -1 and text.find(\":!\") == -1:\n print('join')\n print(name)\n print(random.choice(greetings2))\n sendmsg(random.choice(greetings2) + \" \" + name) \n \ndef textwatch():\n name = text.split(\"!\")[0].strip(\":\")\n global cheercount\n global hailcount\n global wavecount\n if text.find(\"o/\") != -1 and text.find(\"\\o/\") == -1 and text.find(\"/o/\") == -1:\n if wavecount < 1:\n sendmsg(\"o/\")\n wavecount +=1\n if wavecount ==2:\n wavecount =0\n if text.lower().find(\"ciao\") != -1:\n sendmsg(\"Ciao \" + name)\n if text.find(\"\\o/\") != -1:\n if cheercount <1:\n sendmsg(\"\\o/\")\n cheercount +=1\n if cheercount == 2:\n cheercount = 0\n if text.lower().find(botnick.lower()) != -1 and text.find(\"sing\") != -1 and text.find(\"song\") != -1:\n print(\"success\")\n sendmsg(\"It's called Daisy.\")\n sendmsg(\"Daisy ... Daisy ...\")\n sendmsg(\"Give me your answer, do.\")\n sendmsg(\"I'm half crazy ...\")\n sendmsg(\"all for the love of you.\")\n if text.lower().find(\"all hail\") != -1:\n if hailcount <1:\n sendmsg(\"All hail! /o/\")\n hailcount +=1\n if hailcount == 2:\n hailcount =0\n if text.lower().find(botnick.lower()+\"?\") != -1:\n sendmsg(\"You talkin' to me?\")\n if text.lower().find(botnick.lower()) !=-1 and text.find(\"tell\") !=-1:\n name = text.split(\"!\")[0].strip(\":\")\n name1 = text.split()[5]\n message_list = text.split()[6:]\n message=\" \".join(message_list)\n sendmsg(name1 + \", \" + name + \" wanted me to tell you \" + \"'\" +message + \"'\" )\n \ndef helpwatch():\n if \":!help\" in text:\n commands_str = \", \".join(str(i) for i in commands)\n sendmsg(\"The available commands are \" + commands_str)\n \ndef quitwatch():\n if \":!quit\" in text:\n sendmsg(\"I'm going, ciao.\")\n irc.send(\"QUIT\" + \"\\n\")\n \n\nwhile 1: #puts it in a loop\n text = irc.recv(1024) #receive the text\n print(text) #print text to console\n\n if text.find('PING') != -1: #check if 'PING' is found\n irc.send('PONG ' + text.split() [1] + '\\r\\n') #returnes 'PONG' back to the server (prevents pinging out!)\n\n if connected == False:\n irc.send(\"JOIN \" + channel + \"\\r\\n\") \n \n if sleep == False:\n changenick()\n textwatch()\n helpwatch()\n greetingwatch()\n changechannel()\n sleepwatch()\n wakewatch()\n quitwatch()","sub_path":"Cha0zzB0t.py","file_name":"Cha0zzB0t.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"540369639","text":"# APIKEY: BQYvYOBEZWH2ymkvKTC3tbDRgprmFeOY -> for test only\nimport requests\nimport re\nimport pandas as pd\nfrom graphene import ObjectType, String, Schema\nfrom past.builtins import execfile\nfrom . import settings as settings\nsettings = settings.settings()\nexecfile(settings.loader('utilities'))\nexecfile(settings.loader('blockchain'))\n\nframeworkInfo = settings.getFrameworkInfo()\nCONNECTION_STRING = frameworkInfo['ConnectionString']['connectionString']\nETHERSCAN_APIKEY = frameworkInfo['APIKeys']['etherscan']\nBSCSCAN_APIKEY = frameworkInfo['APIKeys']['bscscan']\nBITQUERY_APIKEY = frameworkInfo['APIKeys']['bitquery']\n\nclass bitQuery:\n \n def ___init__(self, name, tables):\n self.name = name\n \n\n def runQuery(self, query): # A simple function to use requests.post to make the API call.\n _bitQueryApiKey = BITQUERY_APIKEY\n headers = {'X-API-KEY': _bitQueryApiKey}\n request = requests.post('https://graphql.bitquery.io/',\n json={'query': query}, headers=headers)\n if request.status_code == 200:\n return request.json()\n else:\n raise Exception('Query failed and return code is {}. {}'.format(request.status_code,\n query)) \n \n\nclass query(ObjectType):\n \n def ___init__(self, name, tables):\n self.name = name\n \n def dexTradeByProtocol(self):\n query = \"\"\"\n {\n ethereum {\n dexTrades(options: {limit: 100, desc: \"count\"}) {\n count\n protocol\n }\n }\n }\n \"\"\"\n return query\n \n def getEvents(self, _address, _eventName, _limit, _network = 'ethereum'):\n \n # Encoding _network for bitquery syntax\n networkEncoded = 'ethereum'\n \n if _network == 'ethereum': networkEncoded = 'ethereum' #By default network is already ethereum\n if _network == 'bsc': networkEncoded = 'ethereum(network: {})'.format(_network)\n \n \n _address = '\"{}\"'.format(_address)\n _eventName = '\"{}\"'.format(_eventName)\n _limit = '{}'.format(_limit)\n query = \"\"\"\n {\n \"\"\"+networkEncoded+\"\"\" {\n smartContractEvents(options: {desc: \"block.height\", limit: \"\"\"+_limit+\"\"\"},\n smartContractEvent: {is: \"\"\"+_eventName+\"\"\"},\n smartContractAddress: \n {is: \"\"\"+_address+\"\"\"}) {\n block {\n height\n timestamp {\n iso8601\n unixtime\n }\n }\n arguments {\n value\n argument\n }\n }\n }\n }\n \"\"\"\n\n return query\n \n def getTransactionsFromAddress(self, _network, _address, _limit):\n _network = '{}'.format(_network)\n _address = '\"{}\"'.format(_address)\n _limit = '{}'.format(_limit)\n \n query = \"\"\"\n {\n ethereum(network: \"\"\"+_network+\"\"\") {\n smartContractCalls(\n options: {desc: \"block.timestamp.time\", limit: \"\"\"+_limit+\"\"\", offset: 0}\n date: {since: null, till: null}\n height: {gt: 0}\n smartContractAddress: {is: \"\"\"+_address+\"\"\"}\n ) {\n block {\n timestamp {\n time(format: \"%Y-%m-%d %H:%M:%S\")\n }\n height\n }\n smartContractMethod {\n name\n signatureHash\n }\n address: caller {\n address\n annotation\n }\n transaction {\n hash\n }\n gasValue\n external\n amount\n }\n }\n }\n \"\"\"\n \n return query","sub_path":"classes/.ipynb_checkpoints/bitQuery_v1_0_0_0-checkpoint.py","file_name":"bitQuery_v1_0_0_0-checkpoint.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63943937","text":"import argparse\nimport time\nimport math\nimport torch\nimport torch.nn as nn\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.utils.data import DataLoader\nfrom model import NextSentenceTask, BertModel, BertEmbedding\nfrom utils import run_demo, run_ddp, wrap_up\n\n\ndef process_raw_data(whole_data, args):\n processed_data = []\n for _idx in range(len(whole_data)):\n item = whole_data[_idx]\n if isinstance(item, list):\n item = torch.tensor(item)\n if len(item) > 1:\n # idx to split the text into two sentencd\n split_idx = torch.randint(1, len(item), size=(1, 1)).item()\n # Index 2 means same sentence label. Initial true int(1)\n processed_data.append([item[:split_idx], item[split_idx:], 1])\n # Random shuffle data to have args.frac_ns next sentence set up\n shuffle_idx1 = torch.randperm(len(processed_data))\n shuffle_idx2 = torch.randperm(len(processed_data))\n num_shuffle = int(len(processed_data) * args.frac_ns)\n shuffle_zip = list(zip(shuffle_idx1, shuffle_idx2))[:num_shuffle]\n for (i, j) in shuffle_zip:\n processed_data[i][1] = processed_data[j][0]\n processed_data[i][2] = int(0) # Switch same sentence label to false 0\n return processed_data\n\n\ndef collate_batch(batch, args, cls_id, sep_id, pad_id):\n # Fix sequence length to args.bptt with padding or trim\n seq_list = []\n tok_type = []\n same_sentence_labels = []\n for item in batch:\n qa_item = torch.cat([item[0], torch.tensor([sep_id]).long(), item[1], torch.tensor([sep_id]).long()])\n if qa_item.size(0) > args.bptt:\n qa_item = qa_item[:args.bptt]\n elif qa_item.size(0) < args.bptt:\n qa_item = torch.cat((qa_item,\n torch.tensor([pad_id] * (args.bptt -\n qa_item.size(0)))))\n seq_list.append(qa_item)\n _tok_tp = torch.ones((qa_item.size(0)))\n _idx = min(len(item[0]) + 1, args.bptt)\n _tok_tp[:_idx] = 0.0\n tok_type.append(_tok_tp)\n same_sentence_labels.append(item[2])\n seq_input = torch.stack(seq_list).long().t().contiguous()\n seq_input = torch.cat((torch.tensor([[cls_id] * seq_input.size(1)]).long(), seq_input))\n tok_type = torch.stack(tok_type).long().t().contiguous()\n tok_type = torch.cat((torch.tensor([[0] * tok_type.size(1)]).long(), tok_type))\n return seq_input, tok_type, torch.tensor(same_sentence_labels).long().contiguous()\n\n\ndef evaluate(data_source, model, device, criterion, cls_id, sep_id, pad_id, args):\n model.eval()\n total_loss = 0.\n batch_size = args.batch_size\n dataloader = DataLoader(data_source, batch_size=batch_size, shuffle=True,\n collate_fn=lambda b: collate_batch(b, args, cls_id, sep_id, pad_id))\n with torch.no_grad():\n for idx, (seq_input, tok_type, target_ns_labels) in enumerate(dataloader):\n if args.parallel == 'DDP':\n seq_input = seq_input.to(device[0])\n tok_type = tok_type.to(device[0])\n target_ns_labels = target_ns_labels.to(device[0])\n else:\n seq_input = seq_input.to(device)\n tok_type = tok_type.to(device)\n target_ns_labels = target_ns_labels.to(device)\n seq_input = seq_input.transpose(0, 1) # Wrap up by DDP or DataParallel\n ns_labels = model(seq_input, token_type_input=tok_type)\n loss = criterion(ns_labels, target_ns_labels)\n total_loss += loss.item()\n return total_loss / (len(data_source) // batch_size)\n\n\ndef train(train_dataset, model, train_loss_log, device, optimizer, criterion,\n epoch, scheduler, cls_id, sep_id, pad_id, args, rank=None):\n model.train()\n total_loss = 0.\n start_time = time.time()\n batch_size = args.batch_size\n dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True,\n collate_fn=lambda b: collate_batch(b, args, cls_id, sep_id, pad_id))\n train_loss_log.append(0.0)\n for idx, (seq_input, tok_type, target_ns_labels) in enumerate(dataloader):\n if args.parallel == 'DDP':\n seq_input = seq_input.to(device[0])\n tok_type = tok_type.to(device[0])\n target_ns_labels = target_ns_labels.to(device[0])\n else:\n seq_input = seq_input.to(device)\n tok_type = tok_type.to(device)\n target_ns_labels = target_ns_labels.to(device)\n optimizer.zero_grad()\n seq_input = seq_input.transpose(0, 1) # Wrap up by DDP or DataParallel\n ns_labels = model(seq_input, token_type_input=tok_type)\n loss = criterion(ns_labels, target_ns_labels)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n optimizer.step()\n total_loss += loss.item()\n if idx % args.log_interval == 0 and idx > 0:\n cur_loss = total_loss / args.log_interval\n elapsed = time.time() - start_time\n if (rank is None) or rank == 0:\n train_loss_log[-1] = cur_loss\n print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:05.5f} | '\n 'ms/batch {:5.2f} | '\n 'loss {:8.5f} | ppl {:5.2f}'.format(epoch, idx,\n len(train_dataset) // batch_size,\n scheduler.get_last_lr()[0],\n elapsed * 1000 / args.log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\n\ndef run_main(args, rank=None):\n # Set the random seed manually for reproducibility.\n torch.manual_seed(args.seed)\n if args.parallel == 'DDP':\n n = torch.cuda.device_count() // args.world_size\n device = list(range(rank * n, (rank + 1) * n))\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n vocab = torch.load(args.save_vocab)\n cls_id = vocab.stoi['']\n pad_id = vocab.stoi['']\n sep_id = vocab.stoi['']\n\n if args.dataset == 'WikiText103':\n from torchtext.experimental.datasets import WikiText103\n train_dataset, valid_dataset, test_dataset = WikiText103(vocab=vocab)\n elif args.dataset == 'BookCorpus':\n from data import BookCorpus\n train_dataset, valid_dataset, test_dataset = BookCorpus(vocab, min_sentence_len=60)\n\n if rank is not None:\n chunk_len = len(train_dataset.data) // args.world_size\n train_dataset.data = train_dataset.data[(rank * chunk_len):((rank + 1) * chunk_len)]\n\n if args.checkpoint != 'None':\n model = torch.load(args.checkpoint)\n else:\n embed_layer = BertEmbedding(len(vocab), args.emsize)\n pretrained_bert = BertModel(len(vocab), args.emsize, args.nhead, args.nhid, args.nlayers, embed_layer, args.dropout)\n pretrained_bert.load_state_dict(torch.load(args.bert_model))\n model = NextSentenceTask(pretrained_bert)\n\n if args.parallel == 'DDP':\n model = model.to(device[0])\n model = DDP(model, device_ids=device)\n else:\n model = model.to(device)\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.SGD(model.parameters(), lr=args.lr)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.1)\n best_val_loss = None\n train_loss_log, val_loss_log = [], []\n\n for epoch in range(1, args.epochs + 1):\n epoch_start_time = time.time()\n train(process_raw_data(train_dataset, args), model, train_loss_log, device, optimizer,\n criterion, epoch, scheduler, cls_id, sep_id, pad_id, args, rank)\n val_loss = evaluate(process_raw_data(valid_dataset, args), model, device, criterion,\n cls_id, sep_id, pad_id, args)\n val_loss_log.append(val_loss)\n\n if (rank is None) or (rank == 0):\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s '\n '| valid loss {:8.5f} | '.format(epoch,\n (time.time() - epoch_start_time),\n val_loss))\n print('-' * 89)\n if not best_val_loss or val_loss < best_val_loss:\n if rank is None:\n with open(args.save, 'wb') as f:\n torch.save(model, f)\n elif rank == 0:\n with open(args.save, 'wb') as f:\n torch.save(model.state_dict(), f)\n best_val_loss = val_loss\n else:\n scheduler.step()\n if args.parallel == 'DDP':\n rank0_devices = [x - rank * len(device) for x in device]\n device_pairs = zip(rank0_devices, device)\n map_location = {'cuda:%d' % x: 'cuda:%d' % y for x, y in device_pairs}\n model.load_state_dict(torch.load(args.save, map_location=map_location))\n test_loss = evaluate(process_raw_data(test_dataset, args), model, device, criterion,\n cls_id, sep_id, pad_id, args)\n if rank == 0:\n wrap_up(train_loss_log, val_loss_log, test_loss, args, model.module, 'ns_loss.txt', 'ns_model.pt')\n else:\n with open(args.save, 'rb') as f:\n model = torch.load(f)\n\n test_loss = evaluate(process_raw_data(test_dataset, args), model, device, criterion,\n cls_id, sep_id, pad_id, args)\n wrap_up(train_loss_log, val_loss_log, test_loss, args, model, 'ns_loss.txt', 'ns_model.pt')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Question-Answer fine-tuning task')\n parser.add_argument('--dataset', type=str, default='WikiText103',\n help='dataset used for next sentence task')\n parser.add_argument('--lr', type=float, default=0.25,\n help='initial learning rate')\n parser.add_argument('--clip', type=float, default=0.1,\n help='gradient clipping')\n parser.add_argument('--epochs', type=int, default=5,\n help='upper epoch limit')\n parser.add_argument('--batch_size', type=int, default=24, metavar='N',\n help='batch size')\n parser.add_argument('--bptt', type=int, default=128,\n help='max. sequence length for the next-sentence pair')\n parser.add_argument('--min_sentence_len', type=int, default=60,\n help='min. sequence length for the raw text tokens')\n parser.add_argument('--seed', type=int, default=312216194,\n help='random seed')\n parser.add_argument('--cuda', action='store_true',\n help='use CUDA')\n parser.add_argument('--log-interval', type=int, default=600, metavar='N',\n help='report interval')\n parser.add_argument('--checkpoint', type=str, default='None',\n help='path to load the checkpoint')\n parser.add_argument('--save', type=str, default='ns_bert.pt',\n help='path to save the bert model')\n parser.add_argument('--save-vocab', type=str, default='torchtext_bert_vocab.pt',\n help='path to save the vocab')\n parser.add_argument('--bert-model', type=str, default='mlm_bert.pt',\n help='path to save the pretrained bert')\n parser.add_argument('--frac_ns', type=float, default=0.5,\n help='fraction of not next sentence')\n parser.add_argument('--parallel', type=str, default='None',\n help='Use DataParallel/DDP to train model')\n parser.add_argument('--world_size', type=int, default=8,\n help='the world size to initiate DPP')\n parser.add_argument('--emsize', type=int, default=768,\n help='size of word embeddings')\n parser.add_argument('--nhid', type=int, default=3072,\n help='number of hidden units per layer')\n parser.add_argument('--nlayers', type=int, default=12,\n help='number of layers')\n parser.add_argument('--nhead', type=int, default=12,\n help='the number of heads in the encoder/decoder of the transformer model')\n parser.add_argument('--dropout', type=float, default=0.2,\n help='dropout applied to layers (0 = no dropout)')\n args = parser.parse_args()\n\n if args.parallel == 'DDP':\n run_demo(run_ddp, run_main, args)\n else:\n run_main(args)\n","sub_path":"examples/BERT/ns_task.py","file_name":"ns_task.py","file_ext":"py","file_size_in_byte":12722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"8271615","text":"from six.moves.urllib.parse import urljoin, unquote\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\n\n\nclass BaseTestFormgrade(object):\n \"\"\"Do NOT add any test cases to this base class. This class is for helper\n functions ONLY. If you add test cases, it will break the tests in\n test_formgrader.py and/or test_gradebook.py!\n\n \"\"\"\n\n def formgrade_url(self, url=\"\"):\n return urljoin(self.manager.base_formgrade_url, url).rstrip(\"/\")\n\n def notebook_url(self, url=\"\"):\n return urljoin(self.manager.base_notebook_url, url).rstrip(\"/\")\n\n def _check_url(self, url):\n if not url.startswith(\"http\"):\n url = self.formgrade_url(url)\n assert unquote(self.browser.current_url.rstrip(\"/\")) == url\n\n def _check_breadcrumbs(self, *breadcrumbs):\n # check that breadcrumbs are correct\n elements = self.browser.find_elements_by_css_selector(\"ul.breadcrumb li\")\n assert tuple([e.text for e in elements]) == breadcrumbs\n\n # check that the active breadcrumb is correct\n element = self.browser.find_element_by_css_selector(\"ul.breadcrumb li.active\")\n assert element.text == breadcrumbs[-1]\n\n def _click_link(self, link_text, partial=False):\n if partial:\n element = self.browser.find_element_by_partial_link_text(link_text)\n else:\n element = self.browser.find_element_by_link_text(link_text)\n element.click()\n\n def _wait_for_element(self, element_id, time=10):\n return WebDriverWait(self.browser, time).until(\n EC.presence_of_element_located((By.ID, element_id))\n )\n\n def _wait_for_visibility_of_element(self, element_id, time=10):\n return WebDriverWait(self.browser, time).until(\n EC.visibility_of_element_located((By.ID, element_id))\n )\n\n def _wait_for_gradebook_page(self, url):\n self._wait_for_element(\"gradebook\")\n self._check_url(url)\n\n def _get(self, url, retries=5):\n try:\n self.browser.get(url)\n except TimeoutException:\n if retries == 0:\n raise\n else:\n print(\"Failed to load '{}', trying again...\".format(url))\n self._get(url, retries=retries - 1)\n\n def _load_gradebook_page(self, url):\n self._get(self.formgrade_url(url))\n self._wait_for_gradebook_page(url)\n\n def _wait_for_notebook_page(self, url):\n self._wait_for_element(\"notebook-container\")\n self._check_url(url)\n\n def _wait_for_formgrader(self, url, retries=5):\n page_loaded = lambda browser: browser.execute_script(\n \"\"\"\n if (!(typeof MathJax !== \"undefined\" && MathJax !== undefined && MathJax.loaded)) {\n return false;\n }\n\n if (!(typeof formgrader !== \"undefined\" && formgrader !== undefined)) {\n return false;\n }\n\n if (!(formgrader.grades !== undefined && formgrader.grades.loaded)) {\n return false;\n }\n\n if (!(formgrader.comments !== undefined && formgrader.comments.loaded)) {\n return false;\n }\n\n if (!(typeof autosize !== \"undefined\" && autosize !== undefined)) {\n return false;\n }\n\n return true;\n \"\"\")\n try:\n self._wait_for_element(\"notebook-container\")\n WebDriverWait(self.browser, 10).until(page_loaded)\n except TimeoutException:\n if retries == 0:\n raise\n else:\n print(\"Failed to load formgrader (url '{}'), trying again...\".format(url))\n self._get(self.browser.current_url)\n self._wait_for_formgrader(url, retries=retries - 1)\n\n self._check_url(url)\n","sub_path":"nbgrader/tests/formgrader/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507235715","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n\ndef love10():\n x = np.linspace(-2, 2, 1000)\n f = np.sqrt(2 * np.sqrt(np.power(x, 2)) - np.power(x, 2))\n g = np.arcsin(np.abs(x) - 1) - math.pi/2\n plt.plot(x, f, color='red', linewidth=2)\n plt.plot(x, g, color='red', linewidth=2)\n\n plt.title('LOVE')\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n love10()\n\n","sub_path":"love10.py","file_name":"love10.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"406422542","text":"import csv\n\nimport pymongo\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom pymongo import MongoClient\n\nfrom .forms import UserForm, UserProfileInfoForm\n\n\n@login_required\ndef special(request):\n return HttpResponse(\"You are logged in !\")\n\n@login_required\ndef user_logout(request):\n print(\"Logged OUt\")\n logout(request)\n return HttpResponseRedirect(reverse('index'))\n\n\n# Employee Registration\ndef employee_registeration(request):\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n profile_form = UserProfileInfoForm(data=request.POST)\n # print('rushi',profile_form.designation)\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n profile = profile_form.save(commit=False)\n profile.user = user\n profile.username = user\n profile.save()\n print(\"profile saved successfully\") # Console log\n return render(request, 'home.html', {})\n else:\n print(user_form.errors, profile_form.errors)\n error = \"user already registered\"\n else:\n user_form = UserForm()\n profile_form = UserProfileInfoForm()\n error = \"\"\n return render(request, 'registration/employee_signup.html', {\n 'user_form': user_form,\n 'profile_form': profile_form,\n 'error' : error\n })\n\n\n# Candidate_upload\n@login_required\ndef candidate_upload(request):\n if request.method == 'POST':\n collection = None\n try:\n #Create connection between database and user\n con = MongoClient()\n db = con[\"tnp_management\"]\n collection = db[\"registration_candidate\"]\n\n print(\"Connection established successfully\") #Console log\n except Exception as e:\n print(e) # Console log\n return render(request, 'registration/candidate_upload.html', {\"error\": \"Connection Failed\"})\n\n #For single student\n if 'single' in request.POST:\n print(\"single student data upload\")\n try:\n # To handle None values\n live_backlog = request.POST.get(\"live_backlog\")\n if live_backlog == None:\n live_backlog = False\n else:\n live_backlog = True\n\n data_dic = {\n \"_id\": request.POST.get(\"pnr\"),\n \"name\": request.POST.get(\"name\"),\n \"gender\": request.POST.get(\"Gender\"),\n \"aadhar_number\": request.POST.get(\"aadhaarcard\"),\n \"email\": request.POST.get(\"email\"),\n \"primary_mobile\": request.POST.get(\"primary_mobile\"),\n \"secondary_mobile\": request.POST.get(\"secondary_mobile\"),\n \"tenth\": request.POST.get(\"percentage\"),\n \"diploma_12\": request.POST.get(\"percentage1\"),\n \"engineering\": request.POST.get(\"marks\"),\n \"college_name\": request.POST.get(\"clgname\"),\n \"branch\": request.POST.get(\"branch\"),\n \"live_backlog\": live_backlog,\n \"placed\": request.POST.get(\"placed\"),\n \"eligible\" : request.POST.get(\"placed\"),\n \"round1\" : request.POST.get(\"placed\"),\n \"round2\" : request.POST.get(\"placed\"),\n \"round3\" : request.POST.get(\"placed\"),\n \"round4\" : request.POST.get(\"placed\"),\n \"round5\" : request.POST.get(\"placed\"),\n \"round6\" : request.POST.get(\"placed\"),\n \"round7\" : request.POST.get(\"placed\"),\n \"round8\" : request.POST.get(\"placed\"),\n }\n rec = collection.insert_one(data_dic)\n print(\"inserted_record\")\n print(rec)\n return HttpResponse(\"candidate Uploaded Successfully\")\n\n except Exception as e:\n print({\"exeption\": e})\n return render(request, 'registration/candidate_upload.html',\n {\"error\": \"PNR number is already registered\"})\n\n elif 'multiple' in request.POST:\n error_data= []\n try:\n print(\"multiple student data upload\")\n csv_file = request.FILES[\"csv_file\"]\n if not csv_file.name.endswith('.csv'):\n return HttpResponse('File is not CSV type. Please upload csv file')\n\n file_data = csv_file.read().decode(\"UTF-8\")\n lines = file_data.split(\"\\n\")\n # loop over the lines and save them in db. If error , store as string and then display\n for line in lines:\n try:\n if line == '':\n continue\n fields = line.split(\",\")\n data_dict = {}\n data_dict[\"_id\"] = fields[0]\n data_dict[\"name\"] = fields[1]\n data_dict[\"gender\"] = fields[2]\n data_dict[\"aadhar_number\"] = fields[3]\n data_dict[\"email\"] = fields[4]\n data_dict[\"primary_mobile\"] = fields[5]\n data_dict[\"secondary_mobile\"] = fields[6]\n data_dict[\"tenth\"] = fields[7]\n data_dict[\"diploma_12\"] = fields[8]\n data_dict[\"college_name\"] = fields[9]\n if fields[10] == \"Computer Engineering\":\n fields[10] = \"computer\"\n elif fields[10] == 'Information Engineering':\n fields[10] = 'information technology'\n elif fields[10] == 'E&TC Engineering':\n fields[10] = 'entc'\n elif fields[10] == \"Production Engineering\":\n fields[10] = \"production\"\n elif fields[10] == 'Instrumentation Engineering':\n fields[10] = 'instrumentation'\n elif fields[10] == 'Civil Engineering':\n fields[10] = 'civil'\n elif fields[10] == 'Mechanical Engineering':\n fields[10] = 'mechanical'\n data_dict[\"branch\"] = fields[10]\n data_dict[\"engineering\"] = fields[11]\n if fields[12]:\n data_dict[\"live_backlog\"] = True\n else:\n data_dict[\"live_backlog\"] = False\n data_dict[\"placed\"] = fields[13]\n data_dict[\"eligible\"] = fields[13]\n data_dict[\"round1\"] = fields[13]\n data_dict[\"round2\"] = fields[13]\n data_dict[\"round3\"] = fields[13]\n data_dict[\"round4\"] = fields[13]\n data_dict[\"round5\"] = fields[13]\n data_dict[\"round6\"] = fields[13]\n data_dict[\"round7\"] = fields[13]\n data_dict[\"round8\"] = fields[13]\n rec = collection.insert_one(data_dict)\n print(\"inserted_record\")\n print(rec)\n except pymongo.errors.DuplicateKeyError as ex:\n data_list = []\n data_list.append(fields[0])\n data_list.append(fields[1])\n data_list.append(fields[2])\n data_list.append(fields[3])\n data_list.append(fields[4])\n data_list.append(fields[5])\n data_list.append(fields[6])\n data_list.append(fields[7])\n data_list.append(fields[8])\n data_list.append(fields[9])\n if fields[10] == \"Computer Engineering\":\n fields[10] = \"computer\"\n elif fields[10] == 'Information Engineering':\n fields[10] = 'information technology'\n elif fields[10] == 'E&TC Engineering':\n fields[10] = 'entc'\n elif fields[10] == \"Production Engineering\":\n fields[10] = \"production\"\n elif fields[10] == 'Instrumentation Engineering':\n fields[10] = 'instrumentation'\n elif fields[10] == 'Civil Engineering':\n fields[10] = 'civil'\n elif fields[10] == 'Mechanical Engineering':\n fields[10] = 'mechanical'\n data_list.append(fields[10])\n data_list.append(fields[11])\n if fields[12]:\n data_list.append(True)\n else:\n data_list.append(False)\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n data_list.append(fields[13])\n error_data.append(data_list)\n with open('other_files/Duplicate Record.csv', 'w') as f:\n writer = csv.writer(f)\n for row in error_data:\n writer.writerow(row)\n f.close()\n return HttpResponse(\"Candidate Uploaded Successfully.
Duplicate PRN stored in Duplicate Record.csv.
No. of Duplicate records are \"+str(len(error_data)))\n except Exception as e:\n print(\"exception\",e,type(e))\n return HttpResponse(\"Unable to upload the file. Error in file\"+str(e))\n\n else:\n return render(request, 'registration/candidate_upload.html', {})\n","sub_path":"registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"182814583","text":"from django.core.urlresolvers import reverse_lazy\nfrom django.db import models\nfrom core.jqgrid import JqGrid\n\nclass RegisteredGolfers(models.Model):\n active = models.BooleanField()\n registration_id = models.IntegerField(primary_key=True)\n checkedin = models.BooleanField()\n last_name = models.CharField()\n first_name = models.CharField()\n gender = models.CharField()\n email = models.CharField()\n cell_phone = models.CharField()\n cell_phone_provider_id = models.IntegerField()\n regTeamName = models.CharField()\n flight_name = models.CharField()\n flight_id = models.IntegerField()\n tee_name = models.CharField()\n tee_id = models.IntegerField()\n tee2_name = models.CharField()\n tee2_id = models.IntegerField()\n ghin_number = models.CharField()\n ghin_active = models.BooleanField()\n HCPIndex = models.IntegerField()\n HIManualOverride = models.BooleanField()\n HCP = models.IntegerField()\n HCP2 = models.IntegerField()\n playerfee_team_net = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_individual_net = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_skins = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_ctp = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_ld = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_ci = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_sandies = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_team_gross = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_individual_gross = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_house = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_team_net_front9 = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_team_net_back9 = models.DecimalField(max_digits=6, decimal_places=2)\n playerfee_birdies_and_bigskins = models.DecimalField(max_digits=6, decimal_places=2)\n teamfee_net = models.DecimalField(max_digits=6, decimal_places=2)\n\n\nclass JobRegistrationsGrid(JqGrid):\n model = None\n extra_config = {\n 'autowidth': False,\n 'forcefit': False,\n 'shrinkToFit': False,\n 'jsonReader': {'repeatitems': False, 'id': 'registration_id'},\n 'rowNum': 200,\n 'loadonce': True,\n 'rowList': [10, 25, 50, 100, 200],\n 'sortname': 'last_name',\n 'viewrecords': True,\n 'sortorder': \"asc\",\n 'sortable': True,\n 'altRows': False,\n 'gridview': True,\n 'height': 'auto',\n 'footerrow': True,\n 'userDataOnFooter': False,\n 'rownumWidth': 34,\n # 'width': 800,\n #'multikey': 'ctrlKey',\n #'multiboxonly': True,\n #'multiselect': True,\n #'toolbar': [False, 'bottom'],\n # 'userData': None,\n 'rownumbers': True,\n }\n fields = [\n 'active',\n 'registration_id',\n 'checkedin',\n 'last_name',\n 'first_name',\n 'gender',\n 'email',\n 'cell_phone',\n 'cell_phone_provider_id',\n 'tee_id',\n 'ghin_number',\n 'ghin_active',\n 'HCPIndex',\n 'HIManualOverride',\n 'HCP',\n 'playerfee_team_net',\n 'playerfee_individual_net',\n 'playerfee_skins',\n 'playerfee_ctp',\n 'playerfee_ld',\n 'playerfee_ci',\n 'playerfee_sandies',\n 'playerfee_team_gross',\n 'playerfee_individual_gross',\n 'playerfee_house',\n 'playerfee_team_net_front9',\n 'playerfee_team_net_back9',\n 'playerfee_birdies_and_bigskins',\n 'teamfee_net',\n 'regTeamName',\n 'flight_id'\n ]\n url = reverse_lazy('registrations:jobregistrations_grid_handler')\n editurl = reverse_lazy('registrations:jq_editjobregistration')\n caption = 'Registrants'\n colmodel_overrides = {\n 'active': {'formatter':'checkbox', 'align': 'center', 'label': 'Active?', 'width': '50', 'edittype': 'checkbox', 'editoptions': { \"value\": \"True:False\", \"defaultValue\": \"True\" }},\n 'registration_id': {'editable': False, 'hidden': True},\n 'email': {'label': 'EMail', 'editable': True, 'hidden': True, 'editrules': { \"edithidden\": True, \"required\": True}},\n 'checkedin': {'formatter':'checkbox', 'align': 'center', 'label': 'CI?', 'width': '30', 'edittype': 'checkbox', 'editoptions': { \"value\": \"True:False\" }},\n 'last_name': {'label': 'Last', 'width': '80', 'editoptions': {\"readonly\": \"readonly\"}, 'sortable': True},\n 'first_name': {'label': 'First', 'width': '60', 'editoptions': {\"readonly\": \"readonly\"}},\n 'gender': {'editable': True, 'hidden': True, 'label': 'M-F', 'align': 'center', 'width': '30', 'editrules': { \"edithidden\": True}, 'edittype': 'select', 'formatter': 'select', 'editoptions': { \"value\": \"M:M;F:F\" }},\n 'cell_phone': {'label': 'Cell Phone', 'editable': True, 'hidden': True, 'editrules': { \"edithidden\": True}},\n 'cell_phone_provider_id': {'label': 'Cell Provider', 'editable': True, 'hidden': True, 'editrules': { \"edithidden\": True}, 'edittype': 'select', 'formatter': 'select', 'editoptions': ''},\n 'flight_id': {'editable': False, 'hidden': True},\n 'tee_id': {'label': 'Tee', 'align': 'center', 'width': '110', 'edittype': 'select', 'formatter': 'select', 'editoptions': '', 'editrules': { \"required\": True}},\n 'ghin_number': {'label': 'GHIN#', 'align': 'center', 'width': '48'},\n 'ghin_active': {'formatter':'checkbox', 'align': 'center', 'label': 'GHIN Active?', 'width': '75', 'editable': False},\n 'HCPIndex': {'label': 'HCP-I', 'formatter':'number', 'formatoptions':{\"decimalPlaces\": 1}, 'align': 'right', 'width': '48', 'sorttype': 'float'},\n 'HIManualOverride': {'formatter':'checkbox', 'align': 'center', 'label': 'Override?', 'width': '60', 'edittype': 'checkbox', 'editoptions': { \"value\": \"True:False\" }},\n 'HCP': {'editable': False, 'label': 'HCP', 'align': 'center', 'width': '48', 'sorttype': 'int'},\n 'playerfee_team_net': {'label': '$T(net)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_individual_net': {'label': '$I(net)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_skins': {'label': '$Skins', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_ctp': {'label': '$CTP', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_ld': {'label': '$LD', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_ci': {'label': '$CI', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_sandies': {'label': '$Sandies', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_team_gross': {'label': '$T(gross)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_individual_gross': {'label': '$I(gross)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_house': {'label': '$House', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_team_net_front9': {'label': '$T(netOut)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_team_net_back9': {'label': '$T(netIn)', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'playerfee_birdies_and_bigskins': {'label': '$BigSkins', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'teamfee_net': {'label': '$TeamNet', 'formatter':'currency', 'formatoptions':{\"prefix\": \"$\"}, 'align': 'center', 'width': '60', 'hidden': True, 'editable': False},\n 'regTeamName': {'label': 'Team', 'width': '120'}\n }","sub_path":"registrations/jqgrid.py","file_name":"jqgrid.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"94259988","text":"from matplotlib import pyplot as plt\r\nimport numpy as np\r\nproduct=['laptop','printer','router']\r\nreena=[10,25,15]\r\nveena=[5,30,12]\r\nx=np.arange(len(product))\r\nplt.bar(x,reena,label='reena',width=0.25)\r\nplt.bar(x+0.25,veena,label='veena',width=0.25)\r\nplt.xticks(x,product)\r\nplt.title('sales per')\r\nplt.xlabel(\"product\")\r\nplt.ylabel(\"price\")\r\nplt.legend()\r\nplt.grid()\r\nplt.show()","sub_path":"irshad dir/kamal/demo_python/python/L12/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629918570","text":"from model.CanonicalExpression import CanonicalExpression\nfrom model.CanonicalItem import CanonicalItem\nfrom model.Terminal import Terminal\nfrom util.Util import Util\n\n\nclass CanonicalItems:\n def __init__(self, container, firstFollow):\n initialRule = container.getList()[0]\n self.container = container\n self.firstFollow = firstFollow\n self.items = [\n CanonicalItem(0, [CanonicalExpression(initialRule[0], initialRule[1], 0, Terminal('$'))], self.container,\n self.firstFollow)]\n self.crtIdentifier = 0\n self.lastUsedIdentifier = 0\n self.start()\n\n def start(self):\n for item in self.items:\n item.expand()\n self.createNewItems(item)\n\n def createNewItems(self, item):\n expressionGroups = self.groupExpressions(item.expressions)\n for key in expressionGroups:\n newCanonicalExpressions = []\n for i in range(len(expressionGroups[key])):\n if expressionGroups[key][i].dotPosition < len(expressionGroups[key][i].rightPart):\n newCanonicalExpressions.append(CanonicalExpression(expressionGroups[key][i].leftPart,\n expressionGroups[key][i].rightPart,\n expressionGroups[key][i].dotPosition + 1,\n expressionGroups[key][i].prediction))\n newCanonicalItem = CanonicalItem(self.lastUsedIdentifier + 1,\n newCanonicalExpressions,\n self.container,\n self.firstFollow)\n newCanonicalItem.expand()\n indexOfItem = Util.indexOfItem(newCanonicalItem, self.items)\n if indexOfItem == -1:\n self.lastUsedIdentifier += 1\n self.items.append(newCanonicalItem)\n item.addNext(item.id, expressionGroups[key][0].getElementBeforeDot(), self.lastUsedIdentifier)\n else:\n item.addNext(item.id, expressionGroups[key][0].getElementBeforeDot(),\n self.items[self.items.index(newCanonicalItem)].id)\n\n def groupExpressions(self, expressions):\n groupedExpressions = {}\n for e in expressions:\n if e.dotPosition < len(e.rightPart):\n crtElement = e.getElementBeforeDot()\n if not crtElement.c in groupedExpressions.keys():\n groupedExpressions[crtElement.c] = [e]\n else:\n groupedExpressions[crtElement.c].append(e)\n return groupedExpressions\n\n\n def __str__(self):\n res = \"\"\n for i in self.items:\n res += str(i)\n return res\n","sub_path":"service/CanonicalItems.py","file_name":"CanonicalItems.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53222253","text":"#!/usr/bin/env python3\n# Author: Massimo Bourquin\n# Contact: massimo.bourquin@unil.ch\n# Arguments\n# python3 Delta-GC.py M_P_alignment.xmfa ['genome1', 'genome2'] window-size threshold-of-uncertainty-to-drop-window [region of : interest]\n\nclass Scaffold:\n def __init__(self, beginning, end, scaffold):\n self.beginning = beginning\n self.end = end\n self.scaffold = scaffold\n\nclass AlignmentScaffold:\n def __init__(self, aln_scaffold_number, beginning, end, ref_sequence, alt_sequence):\n self.aln_scaffold_number = aln_scaffold_number\n self.beginning = beginning\n self.end = end\n self.ref_sequence = ref_sequence\n self.alt_sequence = alt_sequence\n\ndef AbsoluteValue(value):\n try:\n if value < 0:\n return(value * -1)\n else:\n return(value)\n except:\n return('nan')\n\ndef GetGenomeScaffoldsSize(reference_genome):\n from Bio import SeqIO\n\n scaffold_dict = dict()\n scaffold_list = list()\n\n with open(reference_genome) as genome:\n total_length = 0\n for record in SeqIO.parse(genome, 'fasta'):\n beginning = total_length\n length = len(record.seq)\n end = beginning + length\n\n total_length += len(record.seq)\n\n scaffold_dict[record.id] = Scaffold(beginning = beginning, end = end, scaffold = record.id)\n scaffold_list.append(record.id)\n\n return(scaffold_dict, scaffold_list)\n\ndef ParseMauve(alignment_file):\n from Bio import AlignIO\n\n # Separate pairs of sequences\n with open(alignment_file) as file:\n alignment = AlignIO.parse(file, 'mauve')\n aln_scaffold_count = 0\n\n aln_scaffold_dict = dict()\n aln_scaffold_list = list()\n\n for aln_scaffold in alignment:\n\n if len(aln_scaffold) == 2:\n aln_scaffold_count += 1\n\n ref_scaffold = aln_scaffold[0]\n alt_scaffold = aln_scaffold[1]\n\n ref_id = ref_scaffold.id.split('/')\n ref_beginning = int(ref_id[-1].split('-')[0])\n ref_end = int(ref_id[-1].split('-')[-1])\n\n ref_sequence = ref_scaffold.seq\n alt_sequence = alt_scaffold.seq\n\n aln_scaffold_list.append(aln_scaffold_count)\n aln_scaffold_dict[aln_scaffold_count] = AlignmentScaffold(aln_scaffold_count, ref_beginning, ref_end, ref_sequence, alt_sequence)\n\n else:\n break\n\n return(aln_scaffold_dict, aln_scaffold_list)\n\ndef GetIdentity(ref_sequence, alt_sequence):\n identity_count = 0\n seq_length = len(ref_sequence)\n\n for i in range(0, len(ref_sequence)):\n if ref_sequence[i] == alt_sequence[i]:\n identity_count += 1\n else:\n continue\n\n try:\n identity = identity_count / seq_length\n except:\n identity = 'nan'\n\n return(identity)\n\ndef GetGC(sequence):\n acount = sequence.count('A')\n ccount = sequence.count('C')\n gcount = sequence.count('G')\n tcount = sequence.count('T')\n\n try:\n gc_content = (gcount + ccount) / (acount + ccount + gcount + tcount)\n except:\n gc_content = 'nan'\n\n return(gc_content)\n\ndef GetUncertainty(sequence):\n ncount = sequence.count('-') + sequence.count('?') + sequence.count('N')\n length = len(sequence)\n\n try:\n uncertainty = ncount / length\n except:\n uncertainty = 'nan'\n return(uncertainty)\n\ndef sliding_window(sequence1, sequence2, window_size, length):\n\n windows_list = list()\n identity_list = list()\n uncertainty1_list = list()\n uncertainty2_list = list()\n gc1_list = list()\n gc2_list = list()\n delta_gc_list = list()\n window_count = 0\n\n # Sliding-window core part\n for window in range(0, length, window_size):\n sw_begin = window\n sw_end = window + window_size\n window1 = sequence1[sw_begin:sw_end]\n window2 = sequence2[sw_begin:sw_end]\n window_count += 1\n\n windows_list.append(window_count)\n identity_list.append(GetIdentity(window1, window2))\n uncertainty1_list.append(GetUncertainty(window1))\n uncertainty2_list.append(GetUncertainty(window2))\n gc1 = GetGC(window1)\n gc2 = GetGC(window2)\n gc1_list.append(gc1)\n gc2_list.append(gc2)\n try:\n delta_gc = gc1 - gc2\n except:\n delta_gc = 'nan'\n delta_gc_list.append(delta_gc)\n\n return(windows_list, identity_list, uncertainty1_list, uncertainty2_list, gc1_list, gc2_list, delta_gc_list)\n\ndef Main(reference_genome, alignment_file, window_size):\n\n print(\"Parsing reference genome...\")\n parse_reference = GetGenomeScaffoldsSize(reference_genome)\n scaffold_dict = parse_reference[0]\n scaffold_list = parse_reference[1]\n print(\"Done!\")\n\n print(\"Parsing alignment...\")\n parse_mauve = ParseMauve(alignment_file)\n aln_scaffold_dict = parse_mauve[0]\n aln_scaffold_list = parse_mauve[1]\n print(\"Done!\")\n\n print(\"Writing results...\")\n # Create output file\n output_file = open('Delta_GC.csv', 'w')\n output_file.write(''.join(['Scaffold', '\\t',\n 'Alignment_scaffold', '\\t',\n 'Window_number','\\t',\n 'Beginning', '\\t',\n 'End', '\\t',\n 'Delta_GC', '\\t',\n 'Absolute_Delta_GC', '\\t',\n 'GC1', '\\t',\n 'GC2', '\\t',\n 'Identity', '\\t',\n 'Uncertainty', '\\t',\n 'Uncertainty1', '\\t',\n 'Uncertainty2', '\\n']))\n\n # Iterate through each scaffold\n for scaffold in scaffold_list:\n\n scaffold_beginning = scaffold_dict[scaffold].beginning\n scaffold_end = scaffold_dict[scaffold].end\n\n\n for aln_scaffold in aln_scaffold_list:\n\n aln_scaffold_count = aln_scaffold_dict[aln_scaffold].aln_scaffold_number\n aln_scaffold_beginning = aln_scaffold_dict[aln_scaffold_count].beginning\n aln_scaffold_end = aln_scaffold_dict[aln_scaffold_count].end\n aln_scaffold_length = aln_scaffold_end - aln_scaffold_beginning\n\n aln_scaffold_ref_seq = aln_scaffold_dict[aln_scaffold_count].ref_sequence\n aln_scaffold_alt_seq = aln_scaffold_dict[aln_scaffold_count].alt_sequence\n\n\n # If the alignment scaffold is in the scaffold: process\n if aln_scaffold_beginning > scaffold_beginning and aln_scaffold_end < scaffold_end:\n\n # Process the alignment scaffold\n aln_scaffold_results = sliding_window(aln_scaffold_ref_seq, aln_scaffold_alt_seq, window_size, aln_scaffold_length)\n\n # Create lists to store the results\n windows_list = aln_scaffold_results[0]\n identity_list = aln_scaffold_results[1]\n uncertainty1_list = aln_scaffold_results[2]\n uncertainty2_list = aln_scaffold_results[3]\n gc1_list = aln_scaffold_results[4]\n gc2_list = aln_scaffold_results[5]\n delta_gc_list = aln_scaffold_results[6]\n\n # Iterate through the result lists\n for i in range(0, len(windows_list)):\n\n # Add the results to the file\n beginning = aln_scaffold_beginning + (i * window_size)\n end = aln_scaffold_beginning + (i * window_size) + window_size\n output_file.write(''.join([str(scaffold.replace('Scaffold', '')).replace('Contig', '10'), '\\t',\n str(aln_scaffold_count), '\\t',\n str(windows_list[i]),'\\t',\n str(beginning), '\\t',\n str(end), '\\t',\n str(delta_gc_list[i]), '\\t',\n str(AbsoluteValue(delta_gc_list[i])), '\\t',\n str(gc1_list[i]), '\\t',\n str(gc2_list[i]), '\\t',\n str(identity_list[i]), '\\t',\n str((uncertainty1_list[i] + uncertainty2_list[i]) / 2), '\\t',\n str(uncertainty1_list[i]), '\\t',\n str(uncertainty2_list[i]), '\\n']))\n # Remove the aln_scaffold processed:\n aln_scaffold_list.remove(aln_scaffold)\n\n else:\n continue\n print(\"Done!\")\n\nimport sys\nargs = sys.argv\nreference_genome = args[1]\nalignment_file = args[2]\nwindow_size = int(args[3])\n\nMain(reference_genome, alignment_file, window_size)\n","sub_path":"Delta-GC.py","file_name":"Delta-GC.py","file_ext":"py","file_size_in_byte":8924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274122636","text":"import math\nimport random\nimport pprint\nimport basebot\n\nclass Robot(basebot.BaseBot):\n\n def act(self, game):\n robots = game['robots']\n locs = self.adjacents()\n \n if self.player_id == 0:\n self.color = \"RED\"\n self.TARGET = (9,3)\n else:\n self.color = \"GREEN\"\n self.TARGET = (9,15)\n\n #~ print \"%6s %s, possibles: %s\" % (self.color, self.location, locs)\n \n #~ if self.location in basebot.SPAWN_COORDS:\n #~ print \"I, Robot, am at a spawn location\"\n \n # no squares with our bots. enemy bots are fine, we kill them\n #~ locs = [loc for loc in locs if (not robots.get(loc) or (robots.get(loc)['player_id'] != self.player_id))]\n \n # only squares closer to the center\n #~ locs = [loc for loc in locs if center_distance(loc) < center_distance(self.location)]\n\n valid_choices = []\n \n for loc in locs:\n \n ## don't go there, as we will be crushed by new spawns\n if loc in basebot.SPAWN_COORDS:\n continue\n \n ## already occupied\n if loc in robots and robots[loc]['player_id'] == self.player_id:\n continue\n\n valid_choices.append(loc)\n \n ## stay put\n if not valid_choices: \n return ['guard']\n \n loc = random.choice(valid_choices)\n if robots.get(loc):\n return ['attack', loc]\n \n #~ print \"\\tMOVE %s\" % (loc,)\n \n return ['move', loc]\n \n \n","sub_path":"bots/random_aggressive.py","file_name":"random_aggressive.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611300499","text":"#\n# @lc app=leetcode.cn id=200 lang=python3\n#\n# [200] 岛屿数量\n#\n\n# @lc code=start\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n def dfs(i, j, grid, m, n):\n if grid[i][j]=='0' or i<0 or i>=m or j<0 or j>=n:\n return\n grid[i][j] = '0'\n if i-1>=0:\n dfs(i-1, j, grid, m, n)\n if i+1=0:\n dfs(i, j-1, grid, m, n)\n if j+1 currentMax:\r\n currentMax = responseLength\r\n pp_max.append(currentMax)\r\n maxLengths.append(pp_max)\r\n return maxLengths\r\n\r\ndef calculateMeanSpans(data_ppLists, headers):\r\n meanSpans = []\r\n IDIndex = readIndex(headers, ID_columnName)\r\n correctIndex = readIndex(headers, correct_columnName)\r\n screenIndex = readIndex(headers, ScreenName_columnName)\r\n valueIndex = readIndex(headers, value_columnName)\r\n incorrectIndex = readIndex(headers, incorrect_columnName)\r\n for participant in data_ppLists:\r\n pp_meanSpan = []\r\n firstRow = participant[0]\r\n ID = firstRow[IDIndex]\r\n pp_meanSpan.append(ID)\r\n pp_trials = []\r\n for row in participant:\r\n if row[screenIndex] == responseScreenName:\r\n responseValue = row[valueIndex]\r\n responseLength = len(responseValue)\r\n trial = [row[correctIndex], row[incorrectIndex], responseLength]\r\n pp_trials.append(trial)\r\n meanSpan_Base = startingNBACK - 0.5\r\n counter = startingNBACK + 1\r\n while counter < 16:\r\n counterCorrect = 0\r\n counterIncorrect = 0\r\n counterTotal = 0\r\n for trial in pp_trials:\r\n if trial[2] == counter:\r\n counterCorrect = counterCorrect + int(trial[0])\r\n counterIncorrect = counterIncorrect + int(trial[1])\r\n counterTotal = counterTotal + 1\r\n try:\r\n addition = (counterCorrect/(counterCorrect + counterIncorrect))\r\n meanSpan_Base = meanSpan_Base + addition\r\n except:\r\n meanSpan_Base = meanSpan_Base\r\n counter += 1\r\n pp_meanSpan.append(meanSpan_Base)\r\n meanSpans.append(pp_meanSpan)\r\n return meanSpans\r\n\r\n\r\ndef calculateTEmeasures(data_ppLists, headers):\r\n TEmeasures = []\r\n IDindex = readIndex(headers, ID_columnName)\r\n correctIndex = readIndex(headers, correct_columnName)\r\n incorrectIndex = readIndex(headers, incorrect_columnName)\r\n screenIndex = readIndex(headers, ScreenName_columnName)\r\n valueIndex = readIndex(headers, value_columnName)\r\n for participant in data_ppLists:\r\n TEm = []\r\n IncorrectInARow = 0\r\n lastIncorrectLength = 0\r\n lastCorrectLength = 0\r\n TT_Count = 0\r\n firstRow = participant[0]\r\n participantID = firstRow[IDindex]\r\n TEm.append(participantID)\r\n for row in participant:\r\n if IncorrectInARow < 2:\r\n if row[screenIndex] == responseScreenName:\r\n TT_Count += 1\r\n if row[incorrectIndex] == '1':\r\n incorrect_value = row[valueIndex]\r\n incorrectLength = len(incorrect_value)\r\n if IncorrectInARow == 0:\r\n IncorrectInARow = 1\r\n lastIncorrectLength = incorrectLength\r\n elif IncorrectInARow == 1:\r\n if incorrectLength == lastIncorrectLength:\r\n IncorrectInARow = 2\r\n else:\r\n IncorrectInARow = 1\r\n lastIncorrectLength = incorrectLength\r\n elif row[correctIndex] == '1':\r\n IncorrectInARow = 0\r\n correct_value = row[valueIndex]\r\n CorrectLength = len(correct_value)\r\n if CorrectLength > lastCorrectLength:\r\n lastCorrectLength = CorrectLength\r\n else:\r\n break\r\n TEm.append(lastCorrectLength)\r\n TEm.append(TT_Count)\r\n TEmeasures.append(TEm)\r\n return TEmeasures\r\n\r\n\r\ndef compileOutputs(maxLengths, meanSpans, TEmeasures):\r\n output = []\r\n output.append(headerList)\r\n for row in maxLengths:\r\n output.append(row)\r\n for line in meanSpans:\r\n ID = line[0]\r\n for row in output:\r\n if ID == row[0]:\r\n row.append(line[1])\r\n for point in TEmeasures:\r\n ID = point[0]\r\n for row in output:\r\n if ID == row[0]:\r\n row.append(point[1])\r\n row.append(point[2])\r\n np.savetxt(\"DST_output.txt\", output, fmt='%s', delimiter=',')\r\n\r\n \r\n\r\n\r\n\"\"\"\r\nMAIN LOOP\r\n\"\"\"\r\n\r\n\r\nfile = 'data_exp_51687-v9_task-fpfx.csv'\r\nheaders, data = readFile(file)\r\ndata_ppLists = seperateParticipants(data, headers)\r\nmaxLengths = calculateMaxLength(data_ppLists, headers)\r\nmeanSpans = calculateMeanSpans(data_ppLists, headers)\r\nTEmeasures = calculateTEmeasures(data_ppLists, headers)\r\ncompileOutputs(maxLengths, meanSpans, TEmeasures)\r\n","sub_path":"DST_processing.py","file_name":"DST_processing.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"22558418","text":"'''\r\nFor a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object (associative array in PHP, Dictionary in C#, Map in Java).\r\n\r\nFor example:\r\n\r\nwater = 'H2O'\r\nparse_molecule(water) # return {H: 2, O: 1}\r\n\r\nvar fremy_salt = 'K4[ON(SO3)2]2'\r\nparse_molecule(fremySalt) # return {K: 4, O: 14, N: 2, S: 4}\r\nAs you can see, some formulas have brackets in them. The index outside the brackets tells you that you have to multiply count of each atom inside the bracket on this index. For example, in Fe(NO3)2 you have one iron atom, two nitrogen atoms and six oxygen atoms.\r\n\r\nNote that brackets may be round, square or curly and can also be nested. Index after the braces is optional.\r\n'''\r\nfrom collections import Counter\r\nimport re\r\ndef parse_molecule (formula):\r\n atom_list = [letter for letter in formula]\r\n atom_dict = dict(zip(atom_list, range(0,len(atom_list))))\r\n\r\n distinct_atoms = []\r\n for letter, index in zip(formula, range(0,len(formula))):\r\n if letter.islower():\r\n distinct_atoms.append(formula[index-1]+letter)\r\n elif letter.isalpha() and index+1 <= len(formula):\r\n if letter == atom_list[-1]:\r\n if letter.isupper():\r\n distinct_atoms.append(letter)\r\n elif letter != atom_list[-1] and formula[index+1].islower():\r\n continue\r\n else:\r\n distinct_atoms.append(letter)\r\n\r\n count_dict = dict(Counter(distinct_atoms))\r\n\r\n print(formula)\r\n for letter, index in zip(formula, range(0,len(formula))):\r\n if letter.isdigit():\r\n if formula[index-1].isupper():\r\n count_dict[formula[index-1]] *= int(letter)\r\n elif formula[index-1].islower():\r\n actual = formula[index-2]+formula[index-1]\r\n count_dict[actual] *= int(letter)\r\n \r\n \r\n \r\n\r\n \r\n \r\n print(count_dict)\r\n\r\n \r\n\r\n\r\ntrain = 'K4[ON(SO3)2]2'\r\nmagnesium_hydroxide = 'Mg2(OH)2O2'\r\nmg_h = magnesium_hydroxide\r\nparse_molecule(mg_h)\r\n\r\n","sub_path":"learn14.py","file_name":"learn14.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354463342","text":"a=int(input())\r\nd={}\r\nfor i in range(1,a+1):\r\n x1=input() \r\n x2=float(input()) \r\n d[x1]=x2 \r\nv=d.values()\r\nsec=sorted(list(set(v)))\r\nsec=sec[1]\r\nlow=[] \r\nfor i,j in d.items(): \r\n if j==sec: \r\n low.append(i)\r\n else:\r\n \tpass\r\nlow.sort()\r\nfor i in low:\r\n print(i)\r\n\r\n\r\ninput\r\n5\r\nHarry\r\n37.21\r\nBerry\r\n37.21\r\nTina\r\n37.2\r\nAkriti\r\n41\r\nHarsh\r\n39\r\n\r\n\r\noutput\r\nBerry\r\nHarry","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625857483","text":"# PyPoll.py\n# The data we need to retrieve\n# 1. The total number of votes cast\n# 2. The complete list of candidates who received votes\n# 3. The percentage of votes each candidate won\n# 4. The total number of votes each candidate won\n# 5. The winner of the election based on popular vote\n\n#Assign a variable for the file to load and the path.\nfile_to_load = 'Resources/election_results.csv'\n#Open the election results and read the file.\nwith open(file_to_load) as election_data:\n\n#To do: perform analysis\n print(election_data)\n#Close the file.\n\n","sub_path":"Resources/PyPoll.py","file_name":"PyPoll.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4947559","text":"\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\ndriver = webdriver.Firefox(executable_path= r\"C:\\Users\\johnl\\Downloads\\snake\\tester,py.py\" )\r\ndriver.get(\"https://www.python.org\")\r\nassert \"Python\" in driver.title\r\nelem = driver.find_element_by_name(\"q\")\r\nelem.clear()\r\nelem.send_keys(\"pycon\")\r\nelem.send_keys(Keys.RETURN)\r\nassert \"No Results found.\" not in driver.page_source\r\ndriver.quit()\r\n","sub_path":"tester,py.py","file_name":"tester,py.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652401232","text":"import cProfile\nimport logging\nimport os\nimport tempfile\nimport time\nfrom itertools import chain\n\nfrom snuba.util import settings_override\nfrom snuba.utils.metrics.backends.dummy import DummyMetricsBackend\nfrom snuba.utils.streams.kafka import KafkaMessage, TopicPartition\n\n\nlogger = logging.getLogger('snuba.perf')\n\n\ndef get_messages(events_file):\n \"Create a fake Kafka message for each JSON event in the file.\"\n messages = []\n raw_events = open(events_file).readlines()\n for raw_event in raw_events:\n messages.append(\n KafkaMessage(\n TopicPartition('events', 1),\n 0,\n raw_event.encode('utf-8')\n ),\n )\n return messages\n\n\ndef run(events_file, dataset, repeat=1,\n profile_process=False, profile_write=False):\n \"\"\"\n Measures the write performance of a dataset\n \"\"\"\n\n from snuba.consumer import ConsumerWorker\n from snuba.clickhouse.native import ClickhousePool\n\n for statement in dataset.get_dataset_schemas().get_create_statements():\n ClickhousePool().execute(statement)\n\n consumer = ConsumerWorker(\n dataset=dataset,\n producer=None,\n replacements_topic=None,\n metrics=DummyMetricsBackend(),\n )\n\n messages = get_messages(events_file)\n messages = chain(*([messages] * repeat))\n processed = []\n\n def process():\n with settings_override({'DISCARD_OLD_EVENTS': False}):\n for message in messages:\n result = consumer.process_message(message)\n if result is not None:\n processed.append(result)\n\n def write():\n consumer.flush_batch(processed)\n\n time_start = time.time()\n if profile_process:\n filename = tempfile.NamedTemporaryFile(\n prefix=os.path.basename(events_file) + '.process.',\n suffix='.pstats',\n delete=False,\n ).name\n cProfile.runctx('process()', globals(), locals(), filename=filename)\n logger.info('Profile Data: %s', filename)\n else:\n process()\n time_write = time.time()\n if profile_write:\n filename = tempfile.NamedTemporaryFile(\n prefix=os.path.basename(events_file) + '.write.',\n suffix='.pstats',\n delete=False,\n ).name\n cProfile.runctx('write()', globals(), locals(), filename=filename)\n logger.info('Profile Data: %s', filename)\n else:\n write()\n time_finish = time.time()\n\n format_time = lambda t: (\"%.2f\" % t).rjust(10, ' ')\n\n time_to_process = (time_write - time_start) * 1000\n time_to_write = (time_finish - time_write) * 1000\n time_total = (time_finish - time_start) * 1000\n num_events = len(processed)\n\n logger.info(\"Number of events: %s\" % str(num_events).rjust(10, ' '))\n logger.info(\"Total: %sms\" % format_time(time_total))\n logger.info(\"Total process: %sms\" % format_time(time_to_process))\n logger.info(\"Total write: %sms\" % format_time(time_to_write))\n logger.info(\"Process event: %sms/ea\" % format_time(time_to_process / num_events))\n logger.info(\"Write event: %sms/ea\" % format_time(time_to_write / num_events))\n","sub_path":"snuba/perf.py","file_name":"perf.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"347399085","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom .forms import UserRegistrationForm, ProfileUpdateForm\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\nfrom django.conf import settings\nfrom .models import *\nfrom calculations.models import Allocation\nfrom django.views.generic import ListView, DetailView, UpdateView\n\n# Create your views here.\n'''\n@get_money_per_ward method.\n\nThis method is responsible for getting the money allocated to each ward\n'''\ndef get_money_per_ward():\n\tfield = 'amount_allocated'\n\tobj = Allocation.objects.first()\n\tmoney = 0\n\n\tif obj:\n\t\tmoney = int(getattr(obj, field) / 30)\n\t\treturn money\n\telse:\t\n\t\treturn 0\n'''\nEnd of @get_money_per_ward method\n'''\n\n'''\n@get_money_by_county method.\n\nThis method is responsible for getting the total amount of money allocated by the county Gov't\n'''\ndef get_money_by_county():\n\tfield = 'amount_allocated'\n\tobj = Allocation.objects.first()\n\tmoney = 0\n\n\tif obj:\n\t\tmoney = int(getattr(obj, field))\n\t\treturn money\n\t\t\n\treturn money\n'''\nEnd of @get_money_by_county method\n'''\n\n'''\n@notice_render method\n\nThis method adds notices to the defined context\n'''\ndef notice_render():\n\tfrom .models import Notice, User\n\tfrom application.models import Application\n\n\tnotices = Notice.objects.all()\n\tstaff_notices = Notice.objects.filter(category=\"staff\")\n\tnormal_notices = Notice.objects.filter(category=\"normal\")\n\talloc = Allocation.objects.all()\n\n\tapplicants = Application.objects.all()\n\tstaffs = User.objects.all()\n\tadmins = User.objects.filter(is_superuser=True)\n\tqualified = Application.objects.filter(is_qualified='awarded')\n\n\tmoney_per_ward = get_money_per_ward()\n\tmoney_by_county = get_money_by_county()\n\n\n\tcontext = {\n\t\t'alloc' : alloc,\n\t\t'notices' : notices,\n\t\t'staff_notices' : staff_notices,\n\t\t'normal_notices' : normal_notices,\n\t\t'applicants' : applicants,\n\t\t'staffs' : staffs,\n\t\t'admins' : admins,\n\t\t'qualified' : qualified,\n\t\t'money_per_ward' : money_per_ward,\n\t\t'money_by_county' : money_by_county,\n\t}\n\n\treturn context\n'''\nEnd of @notice_render method\n'''\n\nnotice_objects = notice_render()\n\n'''\n@home method.\n\nThis method renders the default home page\n'''\ndef home(request):\n\tcontext = {\n\t\t'title': 'Home'\n\t}\n\n\tcontext.update(notice_objects)\n\n\treturn render(request, 'users/home.html', context)\n'''\nEnd of @home method\n'''\n\n'''\n@register method\n\nThis method is responsible for registering new users into the system\n'''\n@user_passes_test(lambda u: u.is_superuser)\ndef register(request):\n\tif request.method == 'POST':\n\t\tform = UserRegistrationForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, f'User Created Successfully')\n\t\t\treturn redirect('home')\n\telse:\n\t\tform=UserRegistrationForm()\n\n\tcontext = {\n\t\t'title': 'Register User',\n\t\t'form': form,\n\t}\n\n\treturn render(request, 'users/register.html', context)\n'''\nEnd of @register method\n'''\n\n'''\n@profile method.\n\nThis method renders the profile of the currently logged in user\n'''\n@login_required\ndef profile(request):\n\tif request.method == 'POST':\n\t\tform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, f'Profile Updated Successfully')\n\t\t\treturn redirect('profile')\n\n\n\telse:\n\t\tform = ProfileUpdateForm(instance=request.user)\n\n\tcontext = {\n\t\t'title' : 'Update Profile',\n\t\t'form' : form,\n\t}\n\n\tcontext.update(notice_objects)\n\n\treturn render(request, 'users/profile.html', context)\n'''\nEnd of @profile method\n'''\n\n'''\n@UsersListView class.\n\nThis class is responsible for listing all users in the system\n'''\nclass UsersListView(ListView):\n\tmodel = User\n\tcontext_object_name = 'users'\n\textra_context = {\n\t\t'title': 'Users',\n\t}\n\n\textra_context.update(notice_objects)\n\n\tdef get_context_data(self, **kwargs):\n\t context = super(UsersListView, self).get_context_data(**kwargs)\n\t context['admin_users'] = User.objects.filter(is_superuser=True)\n\t return context\n'''\nEnd of @UsersListView class\n'''\n\n'''\n@UsersDetailView class\n\nThis class is responsible for listing the details of a particular user\n'''\nclass UsersDetailView(DetailView):\n\tmodel = User\n\textra_context = {\n\t\t'title': 'User Details',\n\t}\n\n\textra_context.update(notice_objects)\n\n'''\nEnd of @UsersDetailView class\n'''","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127408593","text":"\"\"\"\nColorHelper.\n\nCopyright (c) 2015 - 2017 Isaac Muse \nLicense: MIT\n\"\"\"\nimport sublime\nfrom textwrap import dedent\nimport platform\nimport mdpopups\nimport base64\nimport importlib\n\nRE_COLOR_START = r\"(?i)(?:\\b(?', '>')\n return txt\n\n\ndef log(*args):\n \"\"\"Log.\"\"\"\n\n text = ['\\nColorHelper: ']\n for arg in args:\n text.append(str(arg))\n text.append('\\n')\n print(''.join(text))\n\n\ndef debug(*args):\n \"\"\"Log if debug enabled.\"\"\"\n\n if sublime.load_settings(\"color_helper.sublime-settings\").get('debug', False):\n log(*args)\n\n\ndef get_line_height(view):\n \"\"\"Get the line height.\"\"\"\n\n height = view.line_height()\n settings = sublime.load_settings(\"color_helper.sublime-settings\")\n\n return int((height / 2.0) if LINE_HEIGHT_WORKAROUND and settings.get('line_height_workaround', False) else height)\n\n\ndef get_rules(view):\n \"\"\"Get auto-popup scope rule.\"\"\"\n\n rules = view.settings().get(\"color_helper.scan\")\n\n return rules if rules is not None and rules.get(\"enabled\", False) else None\n\n\ndef get_scope(view, rules, skip_sel_check=False):\n \"\"\"Get auto-popup scope rule.\"\"\"\n\n scopes = None\n if rules is not None:\n scopes = ','.join(rules.get('scan_scopes', []))\n sels = view.sel()\n if not skip_sel_check:\n if len(sels) == 0 or not scopes or view.score_selector(sels[0].begin(), scopes) == 0:\n scopes = None\n return scopes\n\n\ndef get_favs():\n \"\"\"Get favorites object.\"\"\"\n\n bookmark_colors = sublime.load_settings('color_helper.palettes').get(\"favorites\", [])\n return {\"name\": \"Favorites\", \"colors\": bookmark_colors}\n\n\ndef save_palettes(palettes, favs=False):\n \"\"\"Save palettes.\"\"\"\n\n s = sublime.load_settings('color_helper.palettes')\n if favs:\n s.set('favorites', palettes)\n else:\n s.set('palettes', palettes)\n sublime.save_settings('color_helper.palettes')\n\n\ndef save_project_palettes(window, palettes):\n \"\"\"Save project palettes.\"\"\"\n\n data = window.project_data()\n if data is None:\n data = {'color_helper_palettes': palettes}\n else:\n data['color_helper_palettes'] = palettes\n window.set_project_data(data)\n\n\ndef get_palettes():\n \"\"\"Get palettes.\"\"\"\n\n return sublime.load_settings('color_helper.palettes').get(\"palettes\", [])\n\n\ndef get_project_palettes(window):\n \"\"\"Get project palettes.\"\"\"\n data = window.project_data()\n if data is None:\n data = {}\n return data.get('color_helper_palettes', [])\n\n\ndef get_project_folders(window):\n \"\"\"Get project folder.\"\"\"\n data = window.project_data()\n if data is None:\n data = {'folders': [{'path': f} for f in window.folders()]}\n return data.get('folders', [])\n\n\ndef merge_rules(a, b):\n \"\"\"Merge two rules.\"\"\"\n c = a.copy()\n c.update(b)\n return c\n\n\ndef get_settings_rules():\n \"\"\"Read rules from settings and allow overrides.\"\"\"\n\n s = sublime.load_settings('color_helper.sublime-settings')\n rules = s.get(\"color_rules\", [])\n user_rules = s.get(\"user_color_rules\", [])\n names = {rule[\"name\"]: i for i, rule in enumerate(rules) if \"name\" in rule}\n for urule in user_rules:\n name = urule.get(\"name\")\n if name is not None and name in names:\n index = names[name]\n rules[index] = merge_rules(rules[index], urule)\n else:\n rules.append(urule)\n return rules\n\n\ndef get_settings_colors():\n \"\"\"Read color classes from settings and allow overrides.\"\"\"\n\n s = sublime.load_settings('color_helper.sublime-settings')\n classes = s.get(\"color_classes\", {})\n user_classes = s.get(\"user_color_classes\", {})\n for k, v in user_classes.items():\n if k not in classes:\n classes[k] = v\n else:\n classes[k] = merge_rules(classes[k], v)\n return classes\n","sub_path":"color_helper_util.py","file_name":"color_helper_util.py","file_ext":"py","file_size_in_byte":8038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228790619","text":"import os\n\ndef images(allfile):\n images = list(filter(lambda x: x.endswith(\".jpg\"), allfile))\n images.extend(list(filter(lambda x: x.endswith(\".png\"), allfile)))\n images.extend(list(filter(lambda x: x.endswith(\".jpeg\"), allfile)))\n return images\n\ndef everything(allfile):\n return allfile\n\ndef getFolder(files):\n folders = []\n for fl in files:\n if os.path.isdir(fl):\n folders.append(fl)\n return folders\n\ndef joinpath(direct, filelist):\n newfolderlist = []\n for folder in filelist:\n newfolderlist.append(os.path.join(direct, folder))\n return newfolderlist\n\n\ndef spider(startdir=None, file_filter=everything):\n \"\"\"This function search and indexing of all image in all folder in start folder\"\"\"\n fileindir = os.listdir(startdir)\n if startdir == None:\n startdir = ''\n fileindir = joinpath(startdir, fileindir)\n right_files = file_filter(fileindir)\n folderindir = getFolder(fileindir)\n # print(images)\n # print(folderindir)\n if len(folderindir) == 0:\n if len(right_files) == 0:\n return None\n else:\n return right_files\n\n new_right_files = map(spider, folderindir)\n for right_file in new_right_files:\n if right_file != None:\n right_files.extend(image)\n return right_files\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"194473768","text":"from ._tksheet_vars import *\r\nfrom ._tksheet_other_classes import *\r\n\r\nfrom collections import defaultdict, deque\r\nfrom itertools import islice, repeat, accumulate, chain, product, cycle\r\nfrom math import floor, ceil\r\nfrom tkinter import ttk\r\nimport bisect\r\nimport csv as csv_module\r\nimport io\r\nimport pickle\r\nimport re\r\nimport tkinter as tk\r\nimport zlib\r\n# for mac bindings\r\nfrom platform import system as get_os\r\n\r\n\r\nclass ColumnHeaders(tk.Canvas):\r\n def __init__(self,\r\n parentframe = None,\r\n main_canvas = None,\r\n row_index_canvas = None,\r\n max_colwidth = None,\r\n max_header_height = None,\r\n default_header = None,\r\n header_align = None,\r\n header_bg = None,\r\n header_border_fg = None,\r\n header_grid_fg = None,\r\n header_fg = None,\r\n header_selected_cells_bg = None,\r\n header_selected_cells_fg = None,\r\n header_selected_columns_bg = \"#5f6368\",\r\n header_selected_columns_fg = \"white\",\r\n header_select_bold = True,\r\n drag_and_drop_bg = None,\r\n header_hidden_columns_expander_bg = None,\r\n column_drag_and_drop_perform = True,\r\n measure_subset_header = True,\r\n resizing_line_fg = None):\r\n tk.Canvas.__init__(self,parentframe,\r\n background = header_bg,\r\n highlightthickness = 0)\r\n\r\n self.disp_text = {}\r\n self.disp_high = {}\r\n self.disp_grid = {}\r\n self.disp_fill_sels = {}\r\n self.disp_col_exps = {}\r\n self.disp_resize_lines = {}\r\n self.hidd_text = {}\r\n self.hidd_high = {}\r\n self.hidd_grid = {}\r\n self.hidd_fill_sels = {}\r\n self.hidd_col_exps = {}\r\n self.hidd_resize_lines = {}\r\n \r\n self.centre_alignment_text_mod_indexes = (slice(1, None), slice(None, -1))\r\n self.c_align_cyc = cycle(self.centre_alignment_text_mod_indexes)\r\n self.parentframe = parentframe\r\n self.column_drag_and_drop_perform = column_drag_and_drop_perform\r\n self.being_drawn_rect = None\r\n self.extra_motion_func = None\r\n self.extra_b1_press_func = None\r\n self.extra_b1_motion_func = None\r\n self.extra_b1_release_func = None\r\n self.extra_double_b1_func = None\r\n self.ch_extra_begin_drag_drop_func = None\r\n self.ch_extra_end_drag_drop_func = None\r\n self.extra_rc_func = None\r\n self.selection_binding_func = None\r\n self.shift_selection_binding_func = None\r\n self.drag_selection_binding_func = None\r\n self.default_hdr = default_header.lower()\r\n self.max_cw = float(max_colwidth)\r\n self.max_header_height = float(max_header_height)\r\n self.current_height = None # is set from within MainTable() __init__ or from Sheet parameters\r\n self.MT = main_canvas # is set from within MainTable() __init__\r\n self.RI = row_index_canvas # is set from within MainTable() __init__\r\n self.TL = None # is set from within TopLeftRectangle() __init__\r\n self.header_fg = header_fg\r\n self.header_grid_fg = header_grid_fg\r\n self.header_border_fg = header_border_fg\r\n self.header_selected_cells_bg = header_selected_cells_bg\r\n self.header_selected_cells_fg = header_selected_cells_fg\r\n self.header_selected_columns_bg = header_selected_columns_bg\r\n self.header_selected_columns_fg = header_selected_columns_fg\r\n self.header_hidden_columns_expander_bg = header_hidden_columns_expander_bg\r\n self.select_bold = header_select_bold\r\n self.drag_and_drop_bg = drag_and_drop_bg\r\n self.resizing_line_fg = resizing_line_fg\r\n self.align = header_align\r\n self.width_resizing_enabled = False\r\n self.height_resizing_enabled = False\r\n self.double_click_resizing_enabled = False\r\n self.col_selection_enabled = False\r\n self.drag_and_drop_enabled = False\r\n self.rc_delete_col_enabled = False\r\n self.rc_insert_col_enabled = False\r\n self.hide_columns_enabled = False\r\n self.measure_subset_hdr = measure_subset_header\r\n self.dragged_col = None\r\n self.visible_col_dividers = []\r\n self.col_height_resize_bbox = tuple()\r\n self.cell_options = {}\r\n self.rsz_w = None\r\n self.rsz_h = None\r\n self.new_col_height = 0\r\n self.currently_resizing_width = False\r\n self.currently_resizing_height = False\r\n self.basic_bindings()\r\n \r\n def basic_bindings(self, enable = True):\r\n if enable:\r\n self.bind(\"\", self.mouse_motion)\r\n self.bind(\"\", self.b1_press)\r\n self.bind(\"\", self.b1_motion)\r\n self.bind(\"\", self.b1_release)\r\n self.bind(\"\", self.double_b1)\r\n self.bind(get_rc_binding(), self.rc)\r\n else:\r\n self.unbind(\"\")\r\n self.unbind(\"\")\r\n self.unbind(\"\")\r\n self.unbind(\"\")\r\n self.unbind(\"\")\r\n self.unbind(get_rc_binding())\r\n\r\n def set_height(self, new_height, set_TL = False):\r\n self.current_height = new_height\r\n self.config(height = new_height)\r\n if set_TL:\r\n self.TL.set_dimensions(new_h = new_height)\r\n\r\n def enable_bindings(self, binding):\r\n if binding == \"column_width_resize\":\r\n self.width_resizing_enabled = True\r\n if binding == \"column_height_resize\":\r\n self.height_resizing_enabled = True\r\n if binding == \"double_click_column_resize\":\r\n self.double_click_resizing_enabled = True\r\n if binding == \"column_select\":\r\n self.col_selection_enabled = True\r\n if binding == \"drag_and_drop\":\r\n self.drag_and_drop_enabled = True\r\n if binding == \"hide_columns\":\r\n self.hide_columns_enabled = True\r\n\r\n def disable_bindings(self, binding):\r\n if binding == \"column_width_resize\":\r\n self.width_resizing_enabled = False\r\n if binding == \"column_height_resize\":\r\n self.height_resizing_enabled = False\r\n if binding == \"double_click_column_resize\":\r\n self.double_click_resizing_enabled = False\r\n if binding == \"column_select\":\r\n self.col_selection_enabled = False\r\n if binding == \"drag_and_drop\":\r\n self.drag_and_drop_enabled = False\r\n if binding == \"hide_columns\":\r\n self.hide_columns_enabled = False\r\n\r\n def check_mouse_position_width_resizers(self, event):\r\n x = self.canvasx(event.x)\r\n y = self.canvasy(event.y)\r\n ov = None\r\n for x1, y1, x2, y2 in self.visible_col_dividers:\r\n if x >= x1 and y >= y1 and x <= x2 and y <= y2:\r\n ov = self.find_overlapping(x1, y1, x2, y2)\r\n break\r\n return ov\r\n\r\n def rc(self, event):\r\n self.focus_set()\r\n if self.MT.identify_col(x = event.x, allow_end = False) is None:\r\n self.MT.deselect(\"all\")\r\n self.ch_rc_popup_menu.tk_popup(event.x_root, event.y_root)\r\n elif self.col_selection_enabled and not self.currently_resizing_width and not self.currently_resizing_height:\r\n c = self.MT.identify_col(x = event.x)\r\n if c < len(self.MT.col_positions) - 1:\r\n if self.MT.col_selected(c):\r\n if self.MT.rc_popup_menus_enabled:\r\n self.ch_rc_popup_menu.tk_popup(event.x_root, event.y_root)\r\n else:\r\n if self.MT.single_selection_enabled and self.MT.rc_select_enabled:\r\n self.select_col(c, redraw = True)\r\n elif self.MT.toggle_selection_enabled and self.MT.rc_select_enabled:\r\n self.toggle_select_col(c, redraw = True)\r\n if self.MT.rc_popup_menus_enabled:\r\n self.ch_rc_popup_menu.tk_popup(event.x_root, event.y_root)\r\n if self.extra_rc_func is not None:\r\n self.extra_rc_func(event)\r\n\r\n def shift_b1_press(self, event):\r\n x = event.x\r\n c = self.MT.identify_col(x = x)\r\n if self.drag_and_drop_enabled or self.col_selection_enabled and self.rsz_h is None and self.rsz_w is None:\r\n if c < len(self.MT.col_positions) - 1:\r\n c_selected = self.MT.col_selected(c)\r\n if not c_selected and self.col_selection_enabled:\r\n c = int(c)\r\n currently_selected = self.MT.currently_selected()\r\n if currently_selected and currently_selected[0] == \"column\":\r\n min_c = int(currently_selected[1])\r\n self.MT.delete_selection_rects(delete_current = False)\r\n if c > min_c:\r\n self.MT.create_selected(0, min_c, len(self.MT.row_positions) - 1, c + 1, \"cols\")\r\n elif c < min_c:\r\n self.MT.create_selected(0, c, len(self.MT.row_positions) - 1, min_c + 1, \"cols\")\r\n else:\r\n self.select_col(c)\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n if self.shift_selection_binding_func is not None:\r\n self.shift_selection_binding_func((\"shift_select_columns\", tuple(sorted(self.MT.get_selected_cols()))))\r\n elif c_selected:\r\n self.dragged_col = c\r\n\r\n def create_resize_line(self, x1, y1, x2, y2, width, fill, tag):\r\n if self.hidd_resize_lines:\r\n t, sh = self.hidd_resize_lines.popitem()\r\n self.coords(t, x1, y1, x2, y2)\r\n if sh:\r\n self.itemconfig(t, width = width, fill = fill, tag = tag)\r\n else:\r\n self.itemconfig(t, width = width, fill = fill, tag = tag, state = \"normal\")\r\n self.lift(t)\r\n else:\r\n t = self.create_line(x1, y1, x2, y2, width = width, fill = fill, tag = tag)\r\n self.disp_resize_lines[t] = True\r\n\r\n def delete_resize_lines(self):\r\n self.hidd_resize_lines.update(self.disp_resize_lines)\r\n self.disp_resize_lines = {}\r\n for t, sh in self.hidd_resize_lines.items():\r\n if sh:\r\n self.itemconfig(t, state = \"hidden\")\r\n self.hidd_resize_lines[t] = False\r\n\r\n def mouse_motion(self, event):\r\n if not self.currently_resizing_height and not self.currently_resizing_width:\r\n x = self.canvasx(event.x)\r\n y = self.canvasy(event.y)\r\n mouse_over_resize = False\r\n if self.width_resizing_enabled:\r\n ov = self.check_mouse_position_width_resizers(event)\r\n if ov is not None:\r\n for itm in ov:\r\n tgs = self.gettags(itm)\r\n if \"v\" == tgs[0]:\r\n break\r\n c = int(tgs[1])\r\n self.rsz_w = c\r\n self.config(cursor = \"sb_h_double_arrow\")\r\n mouse_over_resize = True\r\n else:\r\n self.rsz_w = None\r\n if self.height_resizing_enabled and not mouse_over_resize:\r\n try:\r\n x1, y1, x2, y2 = self.col_height_resize_bbox[0], self.col_height_resize_bbox[1], self.col_height_resize_bbox[2], self.col_height_resize_bbox[3]\r\n if x >= x1 and y >= y1 and x <= x2 and y <= y2:\r\n self.config(cursor = \"sb_v_double_arrow\")\r\n self.rsz_h = True\r\n mouse_over_resize = True\r\n else:\r\n self.rsz_h = None\r\n except:\r\n self.rsz_h = None\r\n if not mouse_over_resize:\r\n self.MT.reset_mouse_motion_creations()\r\n if self.extra_motion_func is not None:\r\n self.extra_motion_func(event)\r\n \r\n def b1_press(self, event = None):\r\n self.focus_set()\r\n self.MT.unbind(\"\")\r\n x1, y1, x2, y2 = self.MT.get_canvas_visible_area()\r\n if self.check_mouse_position_width_resizers(event) is None:\r\n self.rsz_w = None\r\n if self.width_resizing_enabled and self.rsz_w is not None:\r\n self.currently_resizing_width = True\r\n x = self.MT.col_positions[self.rsz_w]\r\n line2x = self.MT.col_positions[self.rsz_w - 1]\r\n self.create_resize_line(x, 0, x, self.current_height, width = 1, fill = self.resizing_line_fg, tag = \"rwl\")\r\n self.MT.create_resize_line(x, y1, x, y2, width = 1, fill = self.resizing_line_fg, tag = \"rwl\")\r\n self.create_resize_line(line2x, 0, line2x, self.current_height,width = 1, fill = self.resizing_line_fg, tag = \"rwl2\")\r\n self.MT.create_resize_line(line2x, y1, line2x, y2, width = 1, fill = self.resizing_line_fg, tag = \"rwl2\")\r\n elif self.height_resizing_enabled and self.rsz_w is None and self.rsz_h is not None:\r\n self.currently_resizing_height = True\r\n y = event.y\r\n if y < self.MT.hdr_min_rh:\r\n y = int(self.MT.hdr_min_rh)\r\n self.new_col_height = y\r\n self.create_resize_line(x1, y, x2, y, width = 1, fill = self.resizing_line_fg, tag = \"rhl\")\r\n elif self.MT.identify_col(x = event.x, allow_end = False) is None:\r\n self.MT.deselect(\"all\")\r\n elif self.col_selection_enabled and self.rsz_w is None and self.rsz_h is None:\r\n c = self.MT.identify_col(x = event.x)\r\n if c < len(self.MT.col_positions) - 1:\r\n if self.MT.single_selection_enabled:\r\n self.select_col(c, redraw = True)\r\n elif self.MT.toggle_selection_enabled:\r\n self.toggle_select_col(c, redraw = True)\r\n if self.extra_b1_press_func is not None:\r\n self.extra_b1_press_func(event)\r\n \r\n def b1_motion(self, event):\r\n x1, y1, x2, y2 = self.MT.get_canvas_visible_area()\r\n if self.width_resizing_enabled and self.rsz_w is not None and self.currently_resizing_width:\r\n x = self.canvasx(event.x)\r\n size = x - self.MT.col_positions[self.rsz_w - 1]\r\n if not size <= self.MT.min_cw and size < self.max_cw:\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n line2x = self.MT.col_positions[self.rsz_w - 1]\r\n self.create_resize_line(x, 0, x, self.current_height, width = 1, fill = self.resizing_line_fg, tag = \"rwl\")\r\n self.MT.create_resize_line(x, y1, x, y2, width = 1, fill = self.resizing_line_fg, tag = \"rwl\")\r\n self.create_resize_line(line2x, 0, line2x, self.current_height,width = 1, fill = self.resizing_line_fg, tag = \"rwl2\")\r\n self.MT.create_resize_line(line2x, y1, line2x, y2, width = 1, fill = self.resizing_line_fg, tag = \"rwl2\")\r\n elif self.height_resizing_enabled and self.rsz_h is not None and self.currently_resizing_height:\r\n evy = event.y\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n if evy > self.current_height:\r\n y = self.MT.canvasy(evy - self.current_height)\r\n if evy > self.max_header_height:\r\n evy = int(self.max_header_height)\r\n y = self.MT.canvasy(evy - self.current_height)\r\n self.new_col_height = evy\r\n self.MT.create_resize_line(x1, y, x2, y, width = 1, fill = self.resizing_line_fg, tag = \"rhl\")\r\n else:\r\n y = evy\r\n if y < self.MT.hdr_min_rh:\r\n y = int(self.MT.hdr_min_rh)\r\n self.new_col_height = y\r\n self.create_resize_line(x1, y, x2, y, width = 1, fill = self.resizing_line_fg, tag = \"rhl\")\r\n elif self.drag_and_drop_enabled and self.col_selection_enabled and self.MT.anything_selected(exclude_cells = True, exclude_rows = True) and self.rsz_h is None and self.rsz_w is None and self.dragged_col is not None:\r\n x = self.canvasx(event.x)\r\n if x > 0 and x < self.MT.col_positions[-1]:\r\n x = event.x\r\n wend = self.winfo_width()\r\n xcheck = self.xview()\r\n if x >= wend - 0 and len(xcheck) > 1 and xcheck[1] < 1:\r\n if x >= wend + 15:\r\n self.MT.xview_scroll(2, \"units\")\r\n self.xview_scroll(2, \"units\")\r\n else:\r\n self.MT.xview_scroll(1, \"units\")\r\n self.xview_scroll(1, \"units\")\r\n self.check_xview()\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True)\r\n elif x <= 0 and len(xcheck) > 1 and xcheck[0] > 0:\r\n if x >= -15:\r\n self.MT.xview_scroll(-1, \"units\")\r\n self.xview_scroll(-1, \"units\")\r\n else:\r\n self.MT.xview_scroll(-2, \"units\")\r\n self.xview_scroll(-2, \"units\")\r\n self.check_xview()\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True)\r\n col = self.MT.identify_col(x = event.x)\r\n sels = self.MT.get_selected_cols()\r\n selsmin = min(sels)\r\n if col in sels:\r\n xpos = self.MT.col_positions[selsmin]\r\n else:\r\n if col < selsmin:\r\n xpos = self.MT.col_positions[col]\r\n else:\r\n xpos = self.MT.col_positions[col + 1]\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n self.create_resize_line(xpos, 0, xpos, self.current_height, width = 3, fill = self.drag_and_drop_bg, tag = \"dd\")\r\n self.MT.create_resize_line(xpos, y1, xpos, y2, width = 3, fill = self.drag_and_drop_bg, tag = \"dd\")\r\n elif self.MT.drag_selection_enabled and self.col_selection_enabled and self.rsz_h is None and self.rsz_w is None:\r\n end_col = self.MT.identify_col(x = event.x)\r\n currently_selected = self.MT.currently_selected()\r\n if end_col < len(self.MT.col_positions) - 1 and currently_selected:\r\n if currently_selected[0] == \"column\":\r\n start_col = currently_selected[1]\r\n if end_col >= start_col:\r\n rect = (0, start_col, len(self.MT.row_positions) - 1, end_col + 1, \"cols\")\r\n func_event = tuple(range(start_col, end_col + 1))\r\n elif end_col < start_col:\r\n rect = (0, end_col, len(self.MT.row_positions) - 1, start_col + 1, \"cols\")\r\n func_event = tuple(range(end_col, start_col + 1))\r\n if self.being_drawn_rect != rect:\r\n self.MT.delete_selection_rects(delete_current = False)\r\n self.MT.create_selected(*rect)\r\n self.being_drawn_rect = rect\r\n if self.drag_selection_binding_func is not None:\r\n self.drag_selection_binding_func((\"drag_select_columns\", func_event))\r\n xcheck = self.xview()\r\n if event.x > self.winfo_width() and len(xcheck) > 1 and xcheck[1] < 1:\r\n try:\r\n self.MT.xview_scroll(1, \"units\")\r\n self.xview_scroll(1, \"units\")\r\n except:\r\n pass\r\n self.check_xview()\r\n elif event.x < 0 and self.canvasx(self.winfo_width()) > 0 and xcheck and xcheck[0] > 0:\r\n try:\r\n self.xview_scroll(-1, \"units\")\r\n self.MT.xview_scroll(-1, \"units\")\r\n except:\r\n pass\r\n self.check_xview()\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = False)\r\n if self.extra_b1_motion_func is not None:\r\n self.extra_b1_motion_func(event)\r\n\r\n def check_xview(self):\r\n xcheck = self.xview()\r\n if xcheck and xcheck[0] < 0:\r\n self.MT.set_xviews(\"moveto\", 0)\r\n elif len(xcheck) > 1 and xcheck[1] > 1:\r\n self.MT.set_xviews(\"moveto\", 1)\r\n \r\n def b1_release(self, event = None):\r\n self.MT.bind(\"\", self.MT.mousewheel)\r\n if self.width_resizing_enabled and self.rsz_w is not None and self.currently_resizing_width:\r\n self.currently_resizing_width = False\r\n new_col_pos = self.coords(\"rwl\")[0]\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n size = new_col_pos - self.MT.col_positions[self.rsz_w - 1]\r\n if size < self.MT.min_cw:\r\n new_row_pos = ceil(self.MT.col_positions[self.rsz_w - 1] + self.MT.min_cw)\r\n elif size > self.max_cw:\r\n new_col_pos = floor(self.MT.col_positions[self.rsz_w - 1] + self.max_cw)\r\n increment = new_col_pos - self.MT.col_positions[self.rsz_w]\r\n self.MT.col_positions[self.rsz_w + 1:] = [e + increment for e in islice(self.MT.col_positions, self.rsz_w + 1, len(self.MT.col_positions))]\r\n self.MT.col_positions[self.rsz_w] = new_col_pos\r\n self.MT.recreate_all_selection_boxes()\r\n self.MT.refresh_dropdowns()\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n elif self.height_resizing_enabled and self.rsz_h is not None and self.currently_resizing_height:\r\n self.currently_resizing_height = False\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n self.set_height(self.new_col_height,set_TL = True)\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n if self.drag_and_drop_enabled and self.col_selection_enabled and self.MT.anything_selected(exclude_cells = True, exclude_rows = True) and self.rsz_h is None and self.rsz_w is None and self.dragged_col is not None:\r\n self.delete_resize_lines()\r\n self.MT.delete_resize_lines()\r\n x = event.x\r\n c = self.MT.identify_col(x = x)\r\n orig_selected_cols = self.MT.get_selected_cols()\r\n if self.MT.all_columns_displayed and c != self.dragged_col and c is not None and c not in orig_selected_cols and len(orig_selected_cols) != len(self.MT.col_positions) - 1:\r\n orig_selected_cols = sorted(orig_selected_cols)\r\n if len(orig_selected_cols) > 1:\r\n orig_min = orig_selected_cols[0]\r\n orig_max = orig_selected_cols[1]\r\n start_idx = bisect.bisect_left(orig_selected_cols, self.dragged_col)\r\n forward_gap = get_index_of_gap_in_sorted_integer_seq_forward(orig_selected_cols, start_idx)\r\n reverse_gap = get_index_of_gap_in_sorted_integer_seq_reverse(orig_selected_cols, start_idx)\r\n if forward_gap is not None:\r\n orig_selected_cols[:] = orig_selected_cols[:forward_gap]\r\n if reverse_gap is not None:\r\n orig_selected_cols[:] = orig_selected_cols[reverse_gap:]\r\n colsiter = orig_selected_cols.copy()\r\n rm1start = colsiter[0]\r\n rm1end = colsiter[-1] + 1\r\n rm2start = rm1start + (rm1end - rm1start)\r\n rm2end = rm1end + (rm1end - rm1start)\r\n totalcols = len(colsiter)\r\n extra_func_success = True\r\n if c >= len(self.MT.col_positions) - 1:\r\n c -= 1\r\n c_ = int(c)\r\n if self.ch_extra_begin_drag_drop_func is not None:\r\n try:\r\n self.ch_extra_begin_drag_drop_func((\"begin_column_header_drag_drop\", tuple(orig_selected_cols), int(c)))\r\n except:\r\n extra_func_success = False\r\n if extra_func_success:\r\n if self.column_drag_and_drop_perform:\r\n if self.MT.all_columns_displayed:\r\n if rm1start > c:\r\n for rn in range(len(self.MT.data_ref)):\r\n try:\r\n self.MT.data_ref[rn] = (self.MT.data_ref[rn][:c] +\r\n self.MT.data_ref[rn][rm1start:rm1start + totalcols] +\r\n self.MT.data_ref[rn][c:rm1start] +\r\n self.MT.data_ref[rn][rm1start + totalcols:])\r\n except:\r\n continue\r\n if not isinstance(self.MT.my_hdrs, int) and self.MT.my_hdrs:\r\n try:\r\n self.MT.my_hdrs = (self.MT.my_hdrs[:c] +\r\n self.MT.my_hdrs[rm1start:rm1start + totalcols] +\r\n self.MT.my_hdrs[c:rm1start] +\r\n self.MT.my_hdrs[rm1start + totalcols:])\r\n except:\r\n pass\r\n else:\r\n for rn in range(len(self.MT.data_ref)):\r\n try:\r\n self.MT.data_ref[rn] = (self.MT.data_ref[rn][:rm1start] +\r\n self.MT.data_ref[rn][rm1start + totalcols:c + 1] +\r\n self.MT.data_ref[rn][rm1start:rm1start + totalcols] +\r\n self.MT.data_ref[rn][c + 1:])\r\n except:\r\n continue\r\n if not isinstance(self.MT.my_hdrs, int) and self.MT.my_hdrs:\r\n try:\r\n self.MT.my_hdrs = (self.MT.my_hdrs[:rm1start] +\r\n self.MT.my_hdrs[rm1start + totalcols:c + 1] +\r\n self.MT.my_hdrs[rm1start:rm1start + totalcols] +\r\n self.MT.my_hdrs[c + 1:])\r\n except:\r\n pass\r\n else:\r\n pass\r\n # drag and drop columns when some are hidden disabled until correct code written\r\n cws = [int(b - a) for a, b in zip(self.MT.col_positions, islice(self.MT.col_positions, 1, len(self.MT.col_positions)))]\r\n if rm1start > c:\r\n cws = (cws[:c] +\r\n cws[rm1start:rm1start + totalcols] +\r\n cws[c:rm1start] +\r\n cws[rm1start + totalcols:])\r\n else:\r\n cws = (cws[:rm1start] +\r\n cws[rm1start + totalcols:c + 1] +\r\n cws[rm1start:rm1start + totalcols] +\r\n cws[c + 1:])\r\n self.MT.col_positions = list(accumulate(chain([0], (width for width in cws))))\r\n self.MT.deselect(\"all\")\r\n if (c_ - 1) + totalcols > len(self.MT.col_positions) - 1:\r\n new_selected = tuple(range(len(self.MT.col_positions) - 1 - totalcols, len(self.MT.col_positions) - 1))\r\n self.MT.create_selected(0, len(self.MT.col_positions) - 1 - totalcols, len(self.MT.row_positions) - 1, len(self.MT.col_positions) - 1, \"cols\")\r\n else:\r\n if rm1start > c:\r\n new_selected = tuple(range(c_, c_ + totalcols))\r\n self.MT.create_selected(0, c_, len(self.MT.row_positions) - 1, c_ + totalcols, \"cols\")\r\n else:\r\n new_selected = tuple(range(c_ + 1 - totalcols, c_ + 1))\r\n self.MT.create_selected(0, c_ + 1 - totalcols, len(self.MT.row_positions) - 1, c_ + 1, \"cols\")\r\n self.MT.create_current(0, int(new_selected[0]), type_ = \"col\", inside = True)\r\n if self.MT.undo_enabled:\r\n self.MT.undo_storage.append(zlib.compress(pickle.dumps((\"move_cols\",\r\n int(orig_selected_cols[0]),\r\n int(new_selected[0]),\r\n int(new_selected[-1]),\r\n sorted(orig_selected_cols)))))\r\n colset = set(colsiter)\r\n popped_ch = {t1: t2 for t1, t2 in self.cell_options.items() if t1 in colset}\r\n popped_cell = {t1: t2 for t1, t2 in self.MT.cell_options.items() if t1[1] in colset}\r\n popped_col = {t1: t2 for t1, t2 in self.MT.col_options.items() if t1 in colset}\r\n \r\n popped_ch = {t1: self.cell_options.pop(t1) for t1 in popped_ch}\r\n popped_cell = {t1: self.MT.cell_options.pop(t1) for t1 in popped_cell}\r\n popped_col = {t1: self.MT.col_options.pop(t1) for t1 in popped_col}\r\n\r\n self.cell_options = {t1 if t1 < rm1start else t1 - totalcols: t2 for t1, t2 in self.cell_options.items()}\r\n self.cell_options = {t1 if t1 < c_ else t1 + totalcols: t2 for t1, t2 in self.cell_options.items()}\r\n\r\n self.MT.col_options = {t1 if t1 < rm1start else t1 - totalcols: t2 for t1, t2 in self.MT.col_options.items()}\r\n self.MT.col_options = {t1 if t1 < c_ else t1 + totalcols: t2 for t1, t2 in self.MT.col_options.items()}\r\n\r\n self.MT.cell_options = {(t10, t11 if t11 < rm1start else t11 - totalcols): t2 for (t10, t11), t2 in self.MT.cell_options.items()}\r\n self.MT.cell_options = {(t10, t11 if t11 < c_ else t11 + totalcols): t2 for (t10, t11), t2 in self.MT.cell_options.items()}\r\n\r\n newcolsdct = {t1: t2 for t1, t2 in zip(colsiter, new_selected)}\r\n for t1, t2 in popped_ch.items():\r\n self.cell_options[newcolsdct[t1]] = t2\r\n\r\n for t1, t2 in popped_col.items():\r\n self.MT.col_options[newcolsdct[t1]] = t2\r\n\r\n for (t10, t11), t2 in popped_cell.items():\r\n self.MT.cell_options[(t10, newcolsdct[t11])] = t2\r\n\r\n self.MT.refresh_dropdowns()\r\n \r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n if self.ch_extra_end_drag_drop_func is not None:\r\n self.ch_extra_end_drag_drop_func((\"end_column_header_drag_drop\", tuple(orig_selected_cols), new_selected, int(c)))\r\n self.dragged_col = None\r\n self.currently_resizing_width = False\r\n self.currently_resizing_height = False\r\n self.rsz_w = None\r\n self.rsz_h = None\r\n self.being_drawn_rect = None\r\n self.mouse_motion(event)\r\n if self.extra_b1_release_func is not None:\r\n self.extra_b1_release_func(event)\r\n\r\n def double_b1(self, event = None):\r\n self.focus_set()\r\n if self.double_click_resizing_enabled and self.width_resizing_enabled and self.rsz_w is not None and not self.currently_resizing_width:\r\n col = self.rsz_w - 1\r\n self.set_col_width(col)\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n elif self.col_selection_enabled and self.rsz_h is None and self.rsz_w is None:\r\n c = self.MT.identify_col(x = event.x)\r\n if c < len(self.MT.col_positions) - 1:\r\n if self.MT.single_selection_enabled:\r\n self.select_col(c, redraw = True)\r\n elif self.MT.toggle_selection_enabled:\r\n self.toggle_select_col(c, redraw = True)\r\n self.mouse_motion(event)\r\n self.rsz_w = None\r\n if self.extra_double_b1_func is not None:\r\n self.extra_double_b1_func(event)\r\n\r\n def highlight_cells(self, c = 0, cells = tuple(), bg = None, fg = None, redraw = False):\r\n if bg is None and fg is None:\r\n return\r\n if cells:\r\n for c_ in cells:\r\n if c_ not in self.cell_options:\r\n self.cell_options[c_] = {}\r\n self.cell_options[c_]['highlight'] = (bg, fg)\r\n else:\r\n if c not in self.cell_options:\r\n self.cell_options[c] = {}\r\n self.cell_options[c]['highlight'] = (bg, fg)\r\n if redraw:\r\n self.MT.main_table_redraw_grid_and_text(True, False)\r\n\r\n def select_col(self, c, redraw = False, keep_other_selections = False):\r\n c = int(c)\r\n ignore_keep = False\r\n if keep_other_selections:\r\n if self.MT.col_selected(c):\r\n self.MT.create_current(0, c, type_ = \"col\", inside = True)\r\n else:\r\n ignore_keep = True\r\n if ignore_keep or not keep_other_selections:\r\n self.MT.delete_selection_rects()\r\n self.MT.create_current(0, c, type_ = \"col\", inside = True)\r\n self.MT.create_selected(0, c, len(self.MT.row_positions) - 1, c + 1, \"cols\")\r\n if redraw:\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n if self.selection_binding_func is not None:\r\n self.selection_binding_func((\"select_column\", int(c)))\r\n\r\n def toggle_select_col(self, column, add_selection = True, redraw = True, run_binding_func = True, set_as_current = True):\r\n if add_selection:\r\n if self.MT.col_selected(column):\r\n self.MT.deselect(c = column, redraw = redraw)\r\n else:\r\n self.add_selection(c = column, redraw = redraw, run_binding_func = run_binding_func, set_as_current = set_as_current)\r\n else:\r\n if self.MT.col_selected(column):\r\n self.MT.deselect(c = column, redraw = redraw)\r\n else:\r\n self.select_col(column, redraw = redraw)\r\n\r\n def add_selection(self, c, redraw = False, run_binding_func = True, set_as_current = True):\r\n c = int(c)\r\n if set_as_current:\r\n create_new_sel = False\r\n current = self.MT.get_tags_of_current()\r\n if current:\r\n if current[0] == \"Current_Outside\":\r\n create_new_sel = True\r\n self.MT.create_current(0, c, type_ = \"col\", inside = True)\r\n if create_new_sel:\r\n r1, c1, r2, c2 = tuple(int(e) for e in current[1].split(\"_\") if e)\r\n self.MT.create_selected(r1, c1, r2, c2, current[2] + \"s\")\r\n self.MT.create_selected(0, c, len(self.MT.row_positions) - 1, c + 1, \"cols\")\r\n if redraw:\r\n self.MT.main_table_redraw_grid_and_text(redraw_header = True, redraw_row_index = True)\r\n if self.selection_binding_func is not None and run_binding_func:\r\n self.selection_binding_func((\"select_column\", int(c)))\r\n\r\n def set_col_width(self, col, width = None, only_set_if_too_small = False, displayed_only = False, recreate = True, return_new_width = False):\r\n if col < 0:\r\n return\r\n qconf = self.MT.txt_measure_canvas.itemconfig\r\n qbbox = self.MT.txt_measure_canvas.bbox\r\n qtxtm = self.MT.txt_measure_canvas_text\r\n if width is None:\r\n w = self.MT.min_cw\r\n if displayed_only:\r\n x1, y1, x2, y2 = self.MT.get_canvas_visible_area()\r\n start_row, end_row = self.MT.get_visible_rows(y1, y2)\r\n else:\r\n start_row, end_row = 0, None\r\n if self.MT.all_columns_displayed:\r\n data_col = col\r\n else:\r\n data_col = self.MT.displayed_columns[col]\r\n try:\r\n if isinstance(self.MT.my_hdrs, int):\r\n txt = self.MT.data_ref[self.MT.my_hdrs][data_col]\r\n else:\r\n txt = self.MT.my_hdrs[data_col if self.measure_subset_hdr else col]\r\n if txt:\r\n qconf(qtxtm, text = txt, font = self.MT.my_hdr_font)\r\n b = qbbox(qtxtm)\r\n hw = b[2] - b[0] + 5\r\n else:\r\n hw = self.MT.min_cw\r\n except:\r\n if self.default_hdr == \"letters\":\r\n hw = self.MT.GetHdrTextWidth(num2alpha(data_col)) + 5\r\n elif self.default_hdr == \"numbers\":\r\n hw = self.MT.GetHdrTextWidth(f\"{data_col + 1}\") + 5\r\n else:\r\n hw = self.MT.GetHdrTextWidth(f\"{data_col + 1} {num2alpha(data_col)}\") + 5\r\n for rn, r in enumerate(islice(self.MT.data_ref, start_row, end_row), start_row):\r\n try:\r\n if isinstance(r[data_col], str):\r\n txt = r[data_col]\r\n else:\r\n txt = f\"{r[data_col]}\"\r\n except:\r\n txt = \"\"\r\n if txt:\r\n qconf(qtxtm, text = txt, font = self.MT.my_font)\r\n b = qbbox(qtxtm)\r\n tw = b[2] - b[0] + 25 if (rn, data_col) in self.MT.cell_options and 'dropdown' in self.MT.cell_options[(rn, data_col)] else b[2] - b[0] + 5\r\n if tw > w:\r\n w = tw\r\n elif (rn, data_col) in self.MT.cell_options and 'dropdown' in self.MT.cell_options[(rn, data_col)]:\r\n tw = 20\r\n if tw > w:\r\n w = tw\r\n if w > hw:\r\n new_width = w\r\n else:\r\n new_width = hw\r\n else:\r\n new_width = int(width)\r\n if new_width <= self.MT.min_cw:\r\n new_width = int(self.MT.min_cw)\r\n elif new_width > self.max_cw:\r\n new_width = int(self.max_cw)\r\n if only_set_if_too_small:\r\n if new_width <= self.MT.col_positions[col + 1] - self.MT.col_positions[col]:\r\n return self.MT.col_positions[col + 1] - self.MT.col_positions[col]\r\n if return_new_width:\r\n return new_width\r\n else:\r\n new_col_pos = self.MT.col_positions[col] + new_width\r\n increment = new_col_pos - self.MT.col_positions[col + 1]\r\n self.MT.col_positions[col + 2:] = [e + increment for e in islice(self.MT.col_positions, col + 2, len(self.MT.col_positions))]\r\n self.MT.col_positions[col + 1] = new_col_pos\r\n if recreate:\r\n self.MT.recreate_all_selection_boxes()\r\n self.MT.refresh_dropdowns()\r\n\r\n def set_width_of_all_cols(self, width = None, only_set_if_too_small = False, recreate = True):\r\n if width is None:\r\n if self.MT.all_columns_displayed:\r\n iterable = range(self.MT.total_data_cols())\r\n else:\r\n iterable = range(len(self.MT.displayed_columns))\r\n self.MT.col_positions = list(accumulate(chain([0], (self.set_col_width(cn, only_set_if_too_small = only_set_if_too_small, recreate = False, return_new_width = True) for cn in iterable))))\r\n elif width is not None:\r\n if self.MT.all_columns_displayed:\r\n self.MT.col_positions = list(accumulate(chain([0], (width for cn in range(self.MT.total_data_cols())))))\r\n else:\r\n self.MT.col_positions = list(accumulate(chain([0], (width for cn in range(len(self.MT.displayed_columns))))))\r\n if recreate:\r\n self.MT.recreate_all_selection_boxes()\r\n self.MT.refresh_dropdowns()\r\n\r\n def GetLargestWidth(self, cell):\r\n return max(cell.split(\"\\n\"), key = self.MT.GetTextWidth)\r\n\r\n def align_cells(self, columns = [], align = \"global\"):\r\n if isinstance(columns, int):\r\n cols = [columns]\r\n else:\r\n cols = columns\r\n if align == \"global\":\r\n for c in cols:\r\n if c in self.cell_options and 'align' in self.cell_options[c]:\r\n del self.cell_options[c]['align']\r\n else:\r\n for c in cols:\r\n if c not in self.cell_options:\r\n self.cell_options[c] = {}\r\n self.cell_options[c]['align'] = align\r\n\r\n def redraw_highlight_get_text_fg(self, fc, sc, c, c_2, c_3, selected_cols, selected_rows, actual_selected_cols, hlcol):\r\n if hlcol in self.cell_options and 'highlight' in self.cell_options[hlcol] and c in actual_selected_cols:\r\n if self.cell_options[hlcol]['highlight'][0] is not None:\r\n c_1 = self.cell_options[hlcol]['highlight'][0] if self.cell_options[hlcol]['highlight'][0].startswith(\"#\") else Color_Map_[self.cell_options[hlcol]['highlight'][0]]\r\n self.redraw_highlight(fc + 1,\r\n 0,\r\n sc,\r\n self.current_height - 1,\r\n fill = (f\"#{int((int(c_1[1:3], 16) + int(c_3[1:3], 16)) / 2):02X}\" +\r\n f\"{int((int(c_1[3:5], 16) + int(c_3[3:5], 16)) / 2):02X}\" +\r\n f\"{int((int(c_1[5:], 16) + int(c_3[5:], 16)) / 2):02X}\"),\r\n outline = \"\",\r\n tag = \"s\")\r\n tf = self.header_selected_columns_fg if self.cell_options[hlcol]['highlight'][1] is None or self.MT.display_selected_fg_over_highlights else self.cell_options[hlcol]['highlight'][1]\r\n elif hlcol in self.cell_options and 'highlight' in self.cell_options[hlcol] and (c in selected_cols or selected_rows):\r\n if self.cell_options[hlcol]['highlight'][0] is not None:\r\n c_1 = self.cell_options[hlcol]['highlight'][0] if self.cell_options[hlcol]['highlight'][0].startswith(\"#\") else Color_Map_[self.cell_options[hlcol]['highlight'][0]]\r\n self.redraw_highlight(fc + 1,\r\n 0,\r\n sc,\r\n self.current_height - 1,\r\n fill = (f\"#{int((int(c_1[1:3], 16) + int(c_2[1:3], 16)) / 2):02X}\" +\r\n f\"{int((int(c_1[3:5], 16) + int(c_2[3:5], 16)) / 2):02X}\" +\r\n f\"{int((int(c_1[5:], 16) + int(c_2[5:], 16)) / 2):02X}\"),\r\n outline = \"\",\r\n tag = \"s\")\r\n tf = self.header_selected_cells_fg if self.cell_options[hlcol]['highlight'][1] is None or self.MT.display_selected_fg_over_highlights else self.cell_options[hlcol]['highlight'][1]\r\n elif c in actual_selected_cols:\r\n tf = self.header_selected_columns_fg\r\n elif c in selected_cols or selected_rows:\r\n tf = self.header_selected_cells_fg\r\n elif hlcol in self.cell_options and 'highlight' in self.cell_options[hlcol]:\r\n if self.cell_options[hlcol]['highlight'][0] is not None:\r\n self.redraw_highlight(fc + 1, 0, sc, self.current_height - 1, fill = self.cell_options[hlcol]['highlight'][0], outline = \"\", tag = \"s\")\r\n tf = self.header_fg if self.cell_options[hlcol]['highlight'][1] is None else self.cell_options[hlcol]['highlight'][1]\r\n else:\r\n tf = self.header_fg\r\n return tf, self.MT.my_hdr_font\r\n\r\n def redraw_highlight(self, x1, y1, x2, y2, fill, outline, tag):\r\n if self.hidd_high:\r\n t, sh = self.hidd_high.popitem()\r\n self.coords(t, x1, y1, x2, y2)\r\n if sh:\r\n self.itemconfig(t, fill = fill, outline = outline, tag = tag)\r\n else:\r\n self.itemconfig(t, fill = fill, outline = outline, tag = tag, state = \"normal\")\r\n self.lift(t)\r\n self.disp_high[t] = True\r\n else:\r\n self.disp_high[self.create_rectangle(x1, y1, x2, y2, fill = fill, outline = outline, tag = tag)] = True\r\n\r\n def redraw_text(self, x, y, text, fill, font, anchor, tag):\r\n if self.hidd_text:\r\n t, sh = self.hidd_text.popitem()\r\n self.coords(t, x, y)\r\n if sh:\r\n self.itemconfig(t, text = text, fill = fill, font = font, anchor = anchor)\r\n else:\r\n self.itemconfig(t, text = text, fill = fill, font = font, anchor = anchor, state = \"normal\")\r\n self.lift(t)\r\n else:\r\n t = self.create_text(x, y, text = text, fill = fill, font = font, anchor = anchor, tag = tag)\r\n self.disp_text[t] = True\r\n return t\r\n\r\n def redraw_gridline(self, x1, y1, x2, y2, fill, width, tag):\r\n if self.hidd_grid:\r\n t, sh = self.hidd_grid.popitem()\r\n self.coords(t, x1, y1, x2, y2)\r\n if sh:\r\n self.itemconfig(t, fill = fill, width = width, tag = tag)\r\n else:\r\n self.itemconfig(t, fill = fill, width = width, tag = tag, state = \"normal\")\r\n self.disp_grid[t] = True\r\n else:\r\n self.disp_grid[self.create_line(x1, y1, x2, y2, fill = fill, width = width, tag = tag)] = True\r\n\r\n def redraw_hidden_col_expander(self, x1, y1, x2, y2, fill, outline, tag):\r\n if self.hidd_col_exps:\r\n t, sh = self.hidd_col_exps.popitem()\r\n self.coords(t, x1, y1, x2, y2)\r\n if sh:\r\n self.itemconfig(t, fill = fill, outline = outline, tag = tag)\r\n else:\r\n self.itemconfig(t, fill = fill, outline = outline, tag = tag, state = \"normal\")\r\n self.lift(t)\r\n self.disp_col_exps[t] = True\r\n else:\r\n t = self.create_rectangle(x1, y1, x2, y2, fill = fill, outline = outline, tag = tag)\r\n self.disp_col_exps[t] = True\r\n self.tag_bind(t, \"\", self.click_expander)\r\n\r\n def click_expander(self, event = None):\r\n c = self.MT.identify_col(x = event.x, allow_end = False)\r\n if c is not None and self.rsz_w is None and self.rsz_h is None:\r\n disp = sorted(self.MT.displayed_columns)\r\n col = self.MT.displayed_columns[c]\r\n idx = disp.index(col)\r\n ins = idx + 1\r\n if idx == len(disp) - 1:\r\n total = self.MT.total_data_cols()\r\n newcols = list(range(col + 1, total))\r\n self.MT.displayed_columns[ins:ins] = newcols\r\n else:\r\n newcols = list(range(disp[idx] + 1, disp[idx + 1]))\r\n self.MT.displayed_columns[ins:ins] = newcols\r\n self.MT.insert_col_positions(idx, len(newcols))\r\n self.MT.hidd_col_expander_idxs.discard(col)\r\n\r\n def redraw_grid_and_text(self, last_col_line_pos, x1, x_stop, start_col, end_col, selected_cols, selected_rows, actual_selected_cols):\r\n self.configure(scrollregion = (0,\r\n 0,\r\n last_col_line_pos + self.MT.empty_horizontal,\r\n self.current_height))\r\n self.hidd_text.update(self.disp_text)\r\n self.disp_text = {}\r\n self.hidd_high.update(self.disp_high)\r\n self.disp_high = {}\r\n self.hidd_grid.update(self.disp_grid)\r\n self.disp_grid = {}\r\n self.hidd_col_exps.update(self.disp_col_exps)\r\n self.disp_col_exps = {}\r\n self.visible_col_dividers = []\r\n x = self.MT.col_positions[start_col]\r\n self.redraw_gridline(x, 0, x, self.current_height, fill = self.header_grid_fg, width = 1, tag = \"fv\")\r\n self.col_height_resize_bbox = (x1, self.current_height - 2, x_stop, self.current_height)\r\n yend = self.current_height - 5\r\n for c in range(start_col + 1, end_col):\r\n x = self.MT.col_positions[c]\r\n if self.width_resizing_enabled:\r\n self.visible_col_dividers.append((x - 2, 1, x + 2, yend))\r\n self.redraw_gridline(x, 0, x, self.current_height, fill = self.header_grid_fg, width = 1, tag = (\"v\", f\"{c}\"))\r\n if self.hide_columns_enabled and len(self.MT.displayed_columns) > c and self.MT.displayed_columns[c] in self.MT.hidd_col_expander_idxs:\r\n self.redraw_hidden_col_expander(self.MT.col_positions[c + 1] - 2, 2, self.MT.col_positions[c + 1] - 6, self.current_height - 2, fill = self.header_hidden_columns_expander_bg, outline = \"\",\r\n tag = (\"hidd\", f\"{c}\"))\r\n top = self.canvasy(0)\r\n if self.MT.hdr_fl_ins + self.MT.hdr_half_txt_h - 1 > top:\r\n incfl = True\r\n else:\r\n incfl = False\r\n c_2 = self.header_selected_cells_bg if self.header_selected_cells_bg.startswith(\"#\") else Color_Map_[self.header_selected_cells_bg]\r\n c_3 = self.header_selected_columns_bg if self.header_selected_columns_bg.startswith(\"#\") else Color_Map_[self.header_selected_columns_bg]\r\n for c in range(start_col, end_col - 1):\r\n fc = self.MT.col_positions[c]\r\n sc = self.MT.col_positions[c + 1]\r\n if self.MT.all_columns_displayed:\r\n dcol = c\r\n else:\r\n dcol = self.MT.displayed_columns[c]\r\n tf, font = self.redraw_highlight_get_text_fg(fc, sc, c, c_2, c_3, selected_cols, selected_rows, actual_selected_cols, dcol)\r\n\r\n if dcol in self.cell_options and 'align' in self.cell_options[dcol]:\r\n cell_alignment = self.cell_options[dcol]['align']\r\n elif dcol in self.MT.col_options and 'align' in self.MT.col_options[dcol]:\r\n cell_alignment = self.MT.col_options[dcol]['align']\r\n else:\r\n cell_alignment = self.align\r\n\r\n try:\r\n if isinstance(self.MT.my_hdrs, int):\r\n lns = self.MT.data_ref[self.MT.my_hdrs][dcol].split(\"\\n\") if isinstance(self.MT.data_ref[self.MT.my_hdrs][dcol], str) else f\"{self.MT.data_ref[self.MT.my_hdrs][dcol]}\".split(\"\\n\")\r\n else:\r\n lns = self.MT.my_hdrs[dcol].split(\"\\n\") if isinstance(self.MT.my_hdrs[dcol], str) else f\"{self.MT.my_hdrs[dcol]}\".split(\"\\n\")\r\n except:\r\n if self.default_hdr == \"letters\":\r\n lns = (num2alpha(c), )\r\n elif self.default_hdr == \"numbers\":\r\n lns = (f\"{c + 1}\", )\r\n else:\r\n lns = (f\"{c + 1} {num2alpha(c)}\", )\r\n \r\n if cell_alignment == \"center\":\r\n mw = sc - fc - 1\r\n if fc + 5 > x_stop or mw <= 5:\r\n continue\r\n x = fc + floor((sc - fc) / 2)\r\n y = self.MT.hdr_fl_ins\r\n if incfl:\r\n txt = lns[0]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = \"center\", tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n tl = len(txt)\r\n tmod = ceil((tl - int(tl * (mw / wd))) / 2)\r\n txt = txt[tmod - 1:-tmod]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n self.c_align_cyc = cycle(self.centre_alignment_text_mod_indexes)\r\n while wd[2] - wd[0] > mw:\r\n txt = txt[next(self.c_align_cyc)]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n self.coords(t, x, y)\r\n if len(lns) > 1:\r\n stl = int((top - y) / self.MT.hdr_xtra_lines_increment) - 1\r\n if stl < 1:\r\n stl = 1\r\n y += (stl * self.MT.hdr_xtra_lines_increment)\r\n if y + self.MT.hdr_half_txt_h - 1 < self.current_height:\r\n for i in range(stl, len(lns)):\r\n txt = lns[i]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = cell_alignment, tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n tl = len(txt)\r\n tmod = ceil((tl - int(tl * (mw / wd))) / 2)\r\n txt = txt[tmod - 1:-tmod]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n self.c_align_cyc = cycle(self.centre_alignment_text_mod_indexes)\r\n while wd[2] - wd[0] > mw:\r\n txt = txt[next(self.c_align_cyc)]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n self.coords(t, x, y)\r\n y += self.MT.hdr_xtra_lines_increment\r\n if y + self.MT.hdr_half_txt_h - 1 > self.current_height:\r\n break\r\n \r\n elif cell_alignment == \"e\":\r\n mw = sc - fc - 5\r\n x = sc - 5\r\n if x > x_stop or mw <= 5:\r\n continue\r\n y = self.MT.hdr_fl_ins\r\n if incfl:\r\n txt = lns[0]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = cell_alignment, tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n txt = txt[len(txt) - int(len(txt) * (mw / wd)):]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n while wd[2] - wd[0] > mw:\r\n txt = txt[1:]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n if len(lns) > 1:\r\n stl = int((top - y) / self.MT.hdr_xtra_lines_increment) - 1\r\n if stl < 1:\r\n stl = 1\r\n y += (stl * self.MT.hdr_xtra_lines_increment)\r\n if y + self.MT.hdr_half_txt_h - 1 < self.current_height:\r\n for i in range(stl, len(lns)):\r\n txt = lns[i]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = cell_alignment, tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n txt = txt[len(txt) - int(len(txt) * (mw / wd)):]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n while wd[2] - wd[0] > mw:\r\n txt = txt[1:]\r\n self.itemconfig(t, text = txt)\r\n wd = self.bbox(t)\r\n y += self.MT.hdr_xtra_lines_increment\r\n if y + self.MT.hdr_half_txt_h - 1 > self.current_height:\r\n break\r\n \r\n elif cell_alignment == \"w\":\r\n mw = sc - fc - 5\r\n x = fc + 5\r\n if x > x_stop or mw <= 5:\r\n continue\r\n y = self.MT.hdr_fl_ins\r\n if incfl:\r\n txt = lns[0]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = cell_alignment, tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n nl = int(len(txt) * (mw / wd))\r\n self.itemconfig(t, text = txt[:nl])\r\n wd = self.bbox(t)\r\n while wd[2] - wd[0] > mw:\r\n nl -= 1\r\n self.dchars(t, nl)\r\n wd = self.bbox(t)\r\n if len(lns) > 1:\r\n stl = int((top - y) / self.MT.hdr_xtra_lines_increment) - 1\r\n if stl < 1:\r\n stl = 1\r\n y += (stl * self.MT.hdr_xtra_lines_increment)\r\n if y + self.MT.hdr_half_txt_h - 1 < self.current_height:\r\n for i in range(stl, len(lns)):\r\n txt = lns[i]\r\n t = self.redraw_text(x, y, text = txt, fill = tf, font = font, anchor = cell_alignment, tag = \"t\")\r\n wd = self.bbox(t)\r\n wd = wd[2] - wd[0]\r\n if wd > mw:\r\n nl = int(len(txt) * (mw / wd))\r\n self.itemconfig(t, text = txt[:nl])\r\n wd = self.bbox(t)\r\n while wd[2] - wd[0] > mw:\r\n nl -= 1\r\n self.dchars(t, nl)\r\n wd = self.bbox(t)\r\n y += self.MT.hdr_xtra_lines_increment\r\n if y + self.MT.hdr_half_txt_h - 1 > self.current_height:\r\n break\r\n \r\n self.redraw_gridline(x1, self.current_height - 1, x_stop, self.current_height - 1, fill = self.header_border_fg, width = 1, tag = \"h\")\r\n for t, sh in self.hidd_text.items():\r\n if sh:\r\n self.itemconfig(t, state = \"hidden\")\r\n self.hidd_text[t] = False\r\n for t, sh in self.hidd_high.items():\r\n if sh:\r\n self.itemconfig(t, state = \"hidden\")\r\n self.hidd_high[t] = False\r\n for t, sh in self.hidd_grid.items():\r\n if sh:\r\n self.itemconfig(t, state = \"hidden\")\r\n self.hidd_grid[t] = False\r\n for t, sh in self.hidd_col_exps.items():\r\n if sh:\r\n self.itemconfig(t, state = \"hidden\")\r\n self.hidd_col_exps[t] = False\r\n \r\n def GetCellCoords(self, event = None, r = None, c = None):\r\n pass\r\n\r\n \r\n","sub_path":"tksheet/_tksheet_column_headers.py","file_name":"_tksheet_column_headers.py","file_ext":"py","file_size_in_byte":60321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"589773701","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User, AbstractUser, Group\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\n\nfrom pref.apps.map.models import Region\nfrom pref.apps.organizations.models import Organization\n\n\nclass PrefUser(AbstractUser):\n patronymic = models.CharField(\n max_length=100,\n verbose_name='Отчество',\n blank=True,\n )\n organization = models.ForeignKey(\n Organization,\n verbose_name='Организация',\n null=True,\n )\n position = models.CharField(\n max_length=100,\n verbose_name='Должность',\n blank=True,\n )\n region = models.ForeignKey(\n Region,\n null=True,\n blank=True,\n verbose_name='Район',\n )\n\n def get_full_name(self):\n full_name = ''\n if self.last_name:\n full_name = self.last_name\n if self.first_name:\n full_name += ' ' + self.first_name\n if self.patronymic:\n full_name += ' ' + self.patronymic\n return full_name.strip()\n\n def get_abbreviated_name(self):\n abbr_name = ''\n if self.last_name:\n abbr_name = self.last_name\n if self.first_name:\n abbr_name += ' ' + self.first_name[0] + '.'\n if self.patronymic:\n abbr_name += self.patronymic[0] + '.'\n return abbr_name.strip()\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n # if self.region and Group.objects.get(name='Префектура') \\\n # in self.groups.all():\n # raise ValidationError('Пользователь не может одновременно принад'\n # 'лежать к району и к группе \"Префектура\"')\n super(PrefUser, self).save(force_insert=force_insert,\n force_update=force_update,\n using=using,\n update_fields=update_fields)\n","sub_path":"pref/apps/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567236457","text":"MENU_PROMPT = \"\\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: \"\nmovie_store = [\n {'title': 'Matrix', 'director': ' Lana Wachowski', 'release': int(1999)},\n {'title': 'Midnight in Paris', 'director': 'Woody Alen', 'release': int(2011)},\n {'title': 'Lego: The Movie', 'director': 'Phil Lord', 'release': int(2014)},\n {'title': 'Lassie', 'director': 'Charles Sturridge', 'release': int(2004)}\n]\n\n\ndef add():\n movie = {'title': input(\"Please enter the title of the movie\\n\"),\n 'director': input('Please enter the director of the movie\\n'),\n 'release': int(input('Please enter the year the movie was released\\n'))}\n\n movie_store.append(movie)\n\n\ndef listing():\n for film in movie_store:\n print('Title: ' + film['title'] + ' Director: ' + film['director'] + ' Release year: ' + str(film['release']))\n\n\ndef find():\n what = input(\"Which movie are you looking for?\\n\")\n for film in movie_store:\n if what == film['title']:\n print('Title: ' + film['title'] + ' Director: ' + film['director'] + ' Release year: ' + str(\n film['release']))\n\n\nwhile True:\n var = input(MENU_PROMPT)\n if var == 'a':\n add()\n elif var == 'l':\n listing()\n elif var == \"f\":\n find()\n elif var == \"q\":\n break\n else:\n print('Invalid option, please try again')\n","sub_path":"course_contents/3_first_milestone_project/milestone_1/my_app.py","file_name":"my_app.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37502105","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\ninitial = int(input())\nd = int(input())\nnum = int(input())\ntotal = 0\n\nfor i in range(num):\n now_num = initial+i*d\n if now_num >= 0:\n print(now_num,end=\"\")\n else:\n print(\"({0})\".format(now_num),end=\"\")\n total += now_num\n if i != num-1:\n print(\" + \",end=\"\")\n else:\n print(\" =\",total)","sub_path":"大一/python/3/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580264848","text":"# Author: Bryce Dias\n# Basic CLI Tic Tac Toe\n\nclass TicTacToe:\n\n # variable to dictate size of board\n boardSize = 3\n boardRange = range(0, boardSize)\n\n def __init__(self):\n # initializes an empty game board\n # '0' represents an empty space\n # dynamically initializes square board of size boardSize\n self.board = []\n for i in self.boardRange:\n row = [0] * self.boardSize\n self.board.append(row)\n\n \n def printBoard(self):\n # print(\" a b c ...\")\n colIDs = ' '\n for i in self.boardRange:\n tempChar = str(chr(i+97))\n colIDs += (tempChar + ' ')\n\n print(colIDs)\n for count, row in enumerate(self.board):\n print(count, row)\n\n def IX(self, x, y):\n # x will be a character a, b, or c (column)\n # y is an integer 0, 1, or 2 (row)\n # returns the value at the specified index\n if type(x) == str:\n xindex = ord(x) - 97\n return self.board[y][xindex]\n\n def turn(self, x, y, player):\n # x will be a character a, b, or c (column)\n # y is an integer 0, 1, or 2 (row)\n # move is either 1 or 2 : 1 representing circle, 2 representing X\n \n xindex = ord(x) - 97\n if xindex not in self.boardRange:\n print(x, \"is not a valid column.\")\n print(\"Choose one of the labeled columns. (a, b, c ...)\")\n return False\n elif y not in self.boardRange:\n print(y, \"is not a valid row.\")\n print(\"Choose one of the labeled rows. (1, 2, 3 ...)\")\n return False\n elif 1 <= self.board[y][xindex] <= 2:\n print(\"Player \", self.board[y][xindex], \"has already moved there.\")\n print(\"Try a different spot.\")\n else:\n self.updateBoard(xindex, y, player)\n return True\n\n def updateBoard(self, xindex, y, player):\n self.board[y][xindex] = player\n self.printBoard()\n\n def gameOver(self):\n # checking the rows\n for row in self.board:\n if self.checkWin(row):\n return True, row[0]\n\n # checking the columns\n for col in self.boardRange:\n check = []\n for row in self.board:\n check.append(row[col])\n if self.checkWin(check):\n return True, check[0]\n\n # checking the main diagonal\n check = []\n for index in self.boardRange:\n check.append(self.board[index][index])\n if self.checkWin(check):\n return True, check[0]\n\n # checking the reverse diagonal\n check = []\n for index in self.boardRange:\n j = len(self.boardRange) - index - 1\n check.append(self.board[index][j])\n if self.checkWin(check):\n return True, check[0]\n del(check)\n\n def checkWin(self, check):\n if check.count(check[0]) == len(check) and check[0] != 0:\n return True\n\n\n \n","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"104294504","text":"from __future__ import (absolute_import, division, print_function)\nimport nixio as nix\nimport numpy as np\nimport os\nimport unittest\nfrom .tmp import TempDir\nfrom ..validate import Validate\n\n\nclass TestValidate (unittest.TestCase):\n\n def setUp(self):\n self.tmpdir = TempDir(\"validatetest\")\n self.testfilename = os.path.join(self.tmpdir.path, \"validatetest.nix\")\n self.file = nix.File.open(self.testfilename, nix.FileMode.Overwrite)\n self.block1 = self.file.create_block(\"blk1\", \"blk\")\n self.block2 = self.file.create_block(\"blk2\", \"blk2\")\n for blk in self.block1, self.block2:\n for i in range(2):\n blk.create_group(\"grp{}\".format(i), \"groups\")\n for i in range(4):\n blk.create_data_array(\"da{}\".format(i), \"data_arrays\",\n dtype=\"float\",\n data=(1 + np.random.random(5)))\n for i in range(4):\n blk.create_tag(\"tag{}\".format(i), \"tags\",\n np.random.random(1))\n for i in range(4):\n blk.create_multi_tag(\"mt{}\".format(i), \"multi_tags\",\n blk.data_arrays[i])\n\n self.file.create_section(\"sec1\", \"test\")\n\n self.validator = Validate(self.file)\n self.validator.form_dict()\n\n def tearDown(self):\n self.file.close()\n self.tmpdir.cleanup()\n\n def test_check_file(self):\n assert self.validator.check_file()['file_errors'] == []\n self.file.force_created_at(0)\n res = self.validator.check_file()\n assert res['file_errors'] == [\"date is not set!\"]\n\n def test_check_blocks(self):\n block = self.block1\n assert self.validator.errors['blocks'][0]['errors'] == []\n block._h5group.set_attr(\"name\", None)\n res = self.validator.check_blocks(block, 0)\n assert res['blocks'][0]['errors'] == ['Name of Block is missing']\n block._h5group.set_attr(\"type\", None)\n self.validator.check_blocks(block, 0)\n blkerr = self.validator.errors['blocks'][0]['errors']\n assert blkerr == ['Type of Block is missing',\n 'Name of Block is missing']\n\n def test_check_groups(self):\n group1 = self.block1.groups[0]\n group1._h5group.set_attr(\"name\", None)\n self.validator.check_groups(group1, 0, 0)\n grperr = self.validator.errors['blocks'][0]['groups'][0]['errors']\n assert grperr == ['Name of Group is missing']\n group2 = self.block2.groups[1]\n group2._h5group.set_attr(\"name\", None)\n self.validator.check_groups(group2, 1, 1)\n grperr = self.validator.errors['blocks'][1]['groups'][1]['errors']\n assert grperr == ['Name of Group is missing']\n group2._h5group.set_attr(\"type\", None)\n self.validator.check_groups(group2, 1, 1)\n grperr = self.validator.errors['blocks'][1]['groups'][1]['errors']\n assert grperr == ['Type of Group is missing',\n 'Name of Group is missing']\n\n def test_check_data_arrays(self):\n da1 = self.block1.create_data_array(\"u\", \"something\",\n dtype=int, data=np.random.randint(10, size=(5,5)))\n da1.append_range_dimension([1, 2, 3, 4, 5, 6, 7, 8, 9])\n da1.append_set_dimension()\n da1.dimensions[1].labels = [\"A\", \"B\", \"C\", \"D\"]\n da1._h5group.set_attr(\"unit\", \"abcde\")\n da1._h5group.set_attr(\"type\", None)\n da1._h5group.set_attr(\"expansion_origin\", 0.11) # poly not set\n self.validator.form_dict()\n self.validator.check_data_arrays(da1, 4, 0)\n da_warn1 = 'Type of DataArray is missing'\n da_warn2 = ('In some Range Dimensions, '\n 'the number of ticks differ from the data entries')\n da_warn3 = ('In some Set Dimensions, '\n 'the number of labels differ from the data entries')\n da_warn4 = 'Invalid units'\n da_warn5 = ('Expansion origins exist '\n 'but polynomial coefficients are missing')\n da_err = self.validator.errors['blocks'][0]['data_arrays'][4]['errors']\n assert da_warn1 in da_err\n assert da_warn2 in da_err\n assert da_warn3 in da_err\n assert da_warn4 in da_err\n assert da_warn5 in da_err\n\n da2 = self.block1.data_arrays[1]\n da2.append_set_dimension()\n da2.dimensions[0].labels = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n da2.polynom_coefficients = [0.1, 0.2]\n self.validator.check_data_arrays(da2, 1, 0)\n da_err = self.validator.errors['blocks'][0]['data_arrays'][1]['errors']\n assert da_err == [\"Polynomial coefficients exist but expansion \"\n \"origins are missing\"]\n # Dimension mismatch missed out as change data_extent attr\n # will also change shape\n\n da3 = self.block1.data_arrays[0]\n self.validator.check_data_arrays(da3, 0, 0)\n da_err = self.validator.errors['blocks'][0]['data_arrays'][0]['errors']\n assert da_err == [\"Dimension mismatch\"]\n\n def test_check_tags(self):\n tag1 = self.block1.tags[0]\n tag1.position = []\n self.validator.check_tag(tag1, 0, 0)\n tagerr = self.validator.errors['blocks'][0]['tags'][0]['errors']\n assert tagerr == ['Position is not set!']\n\n tag2 = self.block1.tags[1]\n tag2.units = ['abc']\n self.validator.check_tag(tag2, 1, 0)\n tagerr = self.validator.errors['blocks'][0]['tags'][1]['errors']\n assert tagerr == ['Invalid unit']\n\n tag3 = self.block1.tags[2]\n da1 = self.block1.data_arrays[0]\n da1.append_range_dimension([1, 2, 3, 4, 5, 6, 7, 8, 9])\n da1.dimensions[0]._h5group.set_attr(\"unit\", \"s\")\n da1.append_sampled_dimension(0.5)\n da1.dimensions[1]._h5group.set_attr(\"unit\", \"A\")\n tag3.references.append(da1)\n tag3.units = ['A', 'mV']\n self.validator.check_tag(tag3, 2, 0)\n assert self.validator.errors['blocks'][0]['tags'][2]['errors'] == [\n 'References and tag units mismatched']\n\n tag4 = self.block1.tags[3]\n da2 = self.block1.data_arrays[1]\n da3 = self.block1.data_arrays[2]\n tag4.references.append(da2)\n tag4.references.append(da3)\n tag4.extent = [1, 1]\n tag4.position = [0.5, 0.5]\n self.validator.check_tag(tag4, 3, 0)\n tag_dim_warn1 = (\"Number of extent and dimensionality of reference \"\n \"do not match\")\n tag_dim_warn2 = (\"Number of position and dimensionality of reference \"\n \"do not match\")\n tagerr = self.validator.errors['blocks'][0]['tags'][3]['errors']\n assert tag_dim_warn2 in tagerr\n assert tag_dim_warn1 in tagerr\n\n tag5 = self.block2.tags[0]\n da2 = self.block1.data_arrays[1]\n da2.append_range_dimension([1, 2, 3, 4, 5, 6, 7, 8, 9])\n da2.dimensions[0]._h5group.set_attr(\"unit\", \"s\")\n da2.append_sampled_dimension(0.5)\n da2.dimensions[1]._h5group.set_attr(\"unit\", None)\n tag5.references.append(da2)\n self.validator.check_tag(tag5, 0, 1)\n assert self.validator.errors['blocks'][1]['tags'][0]['errors'] == [\n 'Some dimensions of references have no units']\n\n def test_check_multi_tag(self):\n mt1 = self.block1.multi_tags[0]\n da1 = self.block1.create_data_array(name='test1', array_type='t',\n dtype='float', data=0)\n mt1.extents = da1\n self.validator.check_multi_tag(mt1, 0, 0)\n assert self.validator.errors['blocks'][0]['multi_tags'][0]['errors']\\\n == ['Number of entries in positions and extents do not match']\n\n # test for pos & extent with multiple dimensions\n mt2 = self.block1.multi_tags[1]\n da2 = self.block1.create_data_array(name='test2a', array_type='t',\n dtype='float',\n data=np.random.random((6, 5)))\n da3 = self.block1.create_data_array(name='test2b', array_type='t',\n dtype='float',\n data=np.random.random((5, 8)))\n da4 = self.block1.create_data_array(name='test2c', array_type='t',\n dtype='float',\n data=np.random.random((5, 4)))\n da5 = self.block1.create_data_array(name='test2d', array_type='t',\n dtype='float',\n data=np.random.random((5, 3)))\n mt2.references.append(da2)\n mt2.references.append(da3)\n mt2.positions = da5\n mt2.extents = da4\n self.validator.check_multi_tag(mt2, 1, 0)\n warn1 = \"The number of reference and position entries do not match\"\n warn2 = \"The number of reference and extent entries do not match\"\n # pos-extent-mismatch warning exist but not assert\n # change shape of da4/5 to elim warning\n mterr = self.validator.errors['blocks'][0]['multi_tags'][1]['errors']\n assert warn1 in mterr\n assert warn2 in mterr\n\n # test for pos & extent with only ONE dimensions\n mt3 = self.block1.multi_tags[2]\n da6 = self.block1.create_data_array(name='test3a', array_type='t',\n dtype='float',\n data=np.random.random(5))\n da7 = self.block1.create_data_array(name='test3b', array_type='t',\n dtype='float',\n data=np.random.random((3, 3)))\n mt3.positions = da6\n mt3.extents = da6\n mt3.references.append(da7)\n self.validator.check_multi_tag(mt3, 2, 0)\n mterr = self.validator.errors['blocks'][0]['multi_tags'][2]['errors']\n assert warn1 in mterr\n assert warn2 in mterr\n\n # test for ext and pos dimensionality\n mt4 = self.block1.multi_tags[3]\n da8 = self.block1.create_data_array(name='test3c', array_type='t',\n dtype='float',\n data=np.random.random((5, 3, 4)))\n mt4.positions = da8\n mt4.extents = da8\n self.validator.check_multi_tag(mt4, 3, 0)\n assert \"Positions should not have more than 2 dimensions\" \\\n in self.validator.errors['blocks'][0]['multi_tags'][3]['errors']\n assert \"Extents should not have more than 2 dimensions\" \\\n in self.validator.errors['blocks'][0]['multi_tags'][3]['errors']\n\n # test for units\n mt5 = self.block2.multi_tags[0]\n mt5.units = ['s', 'abc']\n da9 = self.block2.data_arrays[0]\n mt5.references.append(da9)\n da9.append_range_dimension([1, 2, 3, 4, 5, 6, 7, 8, 9])\n da9.dimensions[0]._h5group.set_attr(\"unit\", \"mV\")\n self.validator.check_multi_tag(mt5, 0, 1)\n mtagerr = self.validator.errors['blocks'][1]['multi_tags'][0]['errors']\n assert \"Invalid unit\" in mtagerr\n assert \"References and multi_tag units mismatched\" in mtagerr\n\n # 2nd test for units\n da9.dimensions[0]._h5group.set_attr(\"unit\", \"ms\")\n mt5.units = ['s']\n self.validator.check_multi_tag(mt5, 0, 1)\n mtagerr = self.validator.errors['blocks'][1]['multi_tags'][0]['errors']\n assert mtagerr == []\n\n def test_check_section(self): # only have check for basics now\n sec1 = self.file.sections[0]\n sec1._h5group.set_attr(\"type\", None)\n self.validator.check_section(sec1, 0)\n err = self.validator.errors['sections'][0]['errors']\n assert \"Type of Section is missing\" in err\n\n def test_check_props(self):\n # check1\n section = self.file.sections[0]\n prop = section.create_property(\"prop1\", [1, 2, 3, 4])\n self.validator.form_dict()\n # check2\n prop1 = section.create_property(\"prop2\", values_or_dtype=[1, 2, 3, 4])\n prop1.delete_values()\n prop1._h5group.set_attr('name', None)\n # check3\n prop2 = section.create_property(\"prop3\", values_or_dtype=[1, 2, 3, 4])\n prop2.unit = \"invalidu\"\n self.validator.form_dict()\n self.validator.check_property(prop, 0, 0) # check1\n err = self.validator.errors['sections'][0]['props'][0]['errors']\n assert \"Unit is not set\" in err\n # check2 - nameerr but no uniterr\n self.validator.check_property(prop1, 1, 0)\n err = self.validator.errors['sections'][0]['props'][1]['errors']\n assert err == ['Name is not set!']\n self.validator.check_property(prop2, 2, 0) # check3\n err = self.validator.errors['sections'][0]['props'][2]['errors']\n assert 'Unit is not valid!' in err\n\n def test_check_features(self):\n pass # RuntimeError will be raised, so no need for test\n\n def test_range_dim(self):\n err_dict = self.validator.errors['blocks'][0]['data_arrays']\n # check1\n da1 = self.block1.data_arrays[0]\n rdim1 = da1.append_range_dimension([0.55, 0.10, 0.1])\n # for dims and prop test we need to form_dict again\n self.validator.form_dict()\n rdim1._h5group.set_attr('dimension_type', 'set')\n # check2\n rdim2 = da1.append_range_dimension([])\n rdim2._h5group.set_attr(\"unit\", \"m/s\") # compound unit\n\n self.validator.form_dict()\n self.validator.check_range_dim(rdim1, 0, 0, 0) # check1\n err = err_dict[0]['dimensions'][0]['errors']\n assert \"Dimension type is not correct!\" in err\n assert \"Ticks are not sorted!\" in err\n self.validator.check_range_dim(rdim2, 1, 0, 0) # check2\n err = err_dict[0]['dimensions'][1]['errors']\n assert \"Ticks need to be set for range dimensions\" in err\n assert \"Unit must be atomic, not composite!\" in err\n\n def test_sample_dim(self):\n # check1\n da1 = self.block1.data_arrays[0]\n sdim1 = da1.append_sampled_dimension(sampling_interval=0.5)\n sdim1._h5group.set_attr('dimension_type', 'set')\n sdim1.offset = 0.1\n\n # check2\n sdim2 = da1.append_sampled_dimension(sampling_interval=-0.5)\n sdim2.unit = \"m/s\"\n\n self.validator.form_dict()\n self.validator.check_sampled_dim(sdim1, 0, 0, 0) # check1\n da = self.validator.errors['blocks'][0]['data_arrays'][0]\n err = da['dimensions'][0]['errors']\n assert \"Dimension type is not correct!\" in err\n assert \"Offset is set, but no unit set!\" in err\n self.validator.check_sampled_dim(sdim2, 1, 0, 0) # check2\n err = da['dimensions'][1]['errors']\n assert \"Unit must be atomic, not composite!\" in err\n assert \"SamplingInterval is not set to valid value (> 0)!\" in err\n\n def test_set_dim(self):\n da1 = self.block1.data_arrays[0]\n setdim1 = da1.append_set_dimension()\n setdim1._h5group.set_attr('dimension_type', 'range')\n self.validator.form_dict()\n self.validator.check_set_dim(setdim1, 0, 0, 0)\n da = self.validator.errors['blocks'][0]['data_arrays'][0]\n dimerr = da['dimensions'][0]['errors']\n assert \"Dimension type is not correct!\" in dimerr\n\n def test_sources(self):\n da1 = self.block1.data_arrays[0]\n src1 = self.block1.create_source(\"src1\", \"testing_src\")\n da1.sources.append(src1)\n src1._h5group.set_attr('name', None)\n self.validator.form_dict()\n self.validator.check_sources(src1, 0)\n err = self.validator.errors['blocks'][0]['sources']\n assert \"Name of Source is missing\" in err\n","sub_path":"nixio/test/test_validator.py","file_name":"test_validator.py","file_ext":"py","file_size_in_byte":15848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"195738593","text":"#-*- coding: utf-8 -*-\n\"\"\"This module determines the controller inventory \"\"\"\n__author__ = \"Rosalia Prez, Ernesto L. Saavedra and Yoanni Ordoñes\"\n__copyright__ = \"Copyright 2012-2014, GRHS\"\n__version__ = \"0.2\"\n__email__ = \"tlm@uci.cu\"\n\n\n# import wmi\nfrom drivers_model import Controller\n\n\nnames = ['controller']\n\n# def __obtain_list_ide_controllers(wmiobject):\n# '''This is a method used to obtain the IDE controllers.\n# This method allows to get the IDE controllers using the\n# WMI class Win32_IDEController().\n# Return:\n# It returns a list, like this:\n# [{'name': u'Canal IDE principal', 'creation_date': None,\n# 'controller_device': 'ide', 'version': None,\n# 'manufacturer': u'(Tarjetas controladoras IDE ATA/ATAPI)',\n# 'device_id': u'PCIIDE\\\\IDECHANNEL\\\\4&2F0E351A&0&0'},\n# {'name': u'Canal IDE secundario', 'creation_date': None,\n# 'controller_device': 'ide', 'version': None,\n# 'manufacturer': u'(Tarjetas controladoras IDE ATA/ATAPI)',\n# 'device_id': u'PCIIDE\\\\IDECHANNEL\\\\4&2F0E351A&0&1'}]\n# '''\n# __wmiobject = wmiobject\n# list_controller_ide = __wmiobject.Win32_IDEController()\n# manufacturer = None\n# device_id = None\n# for controller in list_controller_ide:\n# manufacturer = controller.Manufacturer or ''\n# device_id = controller.DeviceID or ''\n# name = controller.Caption or ''\n# Controller.create(\n# manufacturer=manufacturer, device=device_id, name=name)\n\n\n# def __obtain_list_usb_controllers(wmiobject):\n# '''This is a method used to obtain the USB controllers.\n# This method allows to get the USB controllers using the\n# WMI class Win32_USBController().\n# Return:\n# It returns an list, like this:\n# [{'name': u'Controladora de host abierto SiS 7001 PCI a USB',\n# 'creation_date': None, 'controller_device': 'usb',\n# 'version': None, 'manufacturer': u'Silicon Integrated Systems',\n# 'device_id': u'PCI\\\\VEN_1039&DEV_7001&SUBSYS\\\\3&B1BFB68&0&18'},\n# {'name': u'Controladora de host abierto SiS 7001 PCI a USB',\n# 'creation_date': None, 'controller_device': 'usb',\n# 'version': None, 'manufacturer': u'Silicon Integrated Systems',\n# 'device_id': u'PCI\\\\VEN_1039&DEV_7001&SUBSYS\\\\3&B1BFB68&0&19'}]\n# '''\n# __wmiobject = wmiobject\n# list_controller_usb = __wmiobject.Win32_USBController()\n# manufacturer = None\n# device_id = None\n# for controller in list_controller_usb:\n# manufacturer = controller.Manufacturer or ''\n# device_id = controller.DeviceID or ''\n# name = controller.Caption or ''\n# Controller.create(\n# manufacturer=manufacturer, device=device_id, name=name)\n\n\n# def __obtain_list_video_controllers(wmiobject):\n# '''This is a method used to obtain the video controllers.\n# This method allows to get the video controllers using the\n# WMI class Win32_VideoController(),\n# Return:\n# It returns an list, like this:\n# [{'name': u'SiS Mirage 3 Graphics',\n# 'creation_date': u'2010/01/06', 'controller_device': 'video',\n# 'version': u'6.14.10.3910', 'manufacturer': u'SiS',\n# 'device_id': u'VideoController1'}]\n# '''\n# __wmiobject = wmiobject\n# list_controller_video = __wmiobject.Win32_VideoController()\n# manufacturer = None\n# device_id = None\n# for controller in list_controller_video:\n# manufacturer = controller.AdapterCompatibility or ''\n# device_id = controller.DeviceID or ''\n# name = controller.Caption or ''\n# Controller.create(\n# manufacturer=manufacturer, device=device_id, name=name)\n\n\n# def __obtain_list_audio_controllers(wmiobject):\n# '''This is a method used to obtain the audio controllers.\n# This method allows to get the audio controllers using the WMI\n# class Win32_SoundDevice().\n# Return:\n# It returns an list, like this:\n# [{'name': u'Realtek High Definition Audio',\n# 'creation_date': None, 'controller_device': 'audio',\n# 'version': None, 'manufacturer': u'Realtek',\n# 'device_id': u'HDAUDIO\\\\\n# FUNC_01&VEN_10EC&DEV_0662&SUBSYS_105B0D22&REV_1001\\\\\n# 4&2DB0E862&0&0001'}[\n# '''\n# __wmiobject = wmiobject\n# list_controller_audio = __wmiobject.Win32_SoundDevice()\n# manufacturer = None\n# device_id = None\n# for controller in list_controller_audio:\n# manufacturer = controller.Manufacturer or ''\n# device_id = controller.DeviceID or ''\n# name = controller.Caption or ''\n# Controller.create(\n# manufacturer=manufacturer, device=device_id, name=name)\n\n\n# def __obtain_list_network_controllers(wmiobject):\n# '''This is a method used to obtain the network controllers.\n# This method allows to get the network controllers using the\n# WMI class Win32_NetworkAdapter().\n# Return:\n# It returns an list, like this:\n# {'name': u'[00000001] Puerto de infrarrojos',\n# 'creation_date': None, 'controller_device': 'red',\n# 'version': None, 'manufacturer': u'Microsoft',\n# 'device_id': u'1'}\n# '''\n# __wmiobject = wmiobject\n# list_controller_network = __wmiobject.Win32_NetworkAdapter()\n# manufacturer = None\n# device_id = None\n# for controller in list_controller_network:\n# manufacturer = controller.Manufacturer or ''\n# device_id = controller.DeviceID or ''\n# name = controller.Caption or ''\n# Controller.create(\n# manufacturer=manufacturer, device=device_id, name=name)\n\n\ndef save_controllers(controllers):\n \"\"\"This method parses and saves controllers information\n from wmi controllers list\"\"\"\n for controller in controllers:\n manufacturer = '-'\n if 'Manufacturer' in controller.keys:\n manufacturer = controller.Manufacturer\n device_id = controller.DeviceID or '-'\n device_id = device_id.replace('&', '-')\n name = controller.Caption or '-'\n Controller.create(\n manufacturer=manufacturer, device=device_id, name=name)\n\n\ndef inventory(logger, wmiobject):\n '''This method gets the audio, IDE, network, USB and video controllers.'''\n logger.debug('Deleting old controllers saved in database')\n delete = Controller.delete()\n delete.execute()\n controller_types = {\n 'audio': 'Win32_SoundDevice', 'ide': 'Win32_IDEController',\n 'usb': 'Win32_USBController', 'video': 'Win32_VideoController',\n 'network': 'Win32_NetworkAdapter'}\n for met in controller_types:\n logger.debug('Getting information about {} controller'.format(met))\n controllers = getattr(wmiobject, controller_types[met])()\n save_controllers(controllers)\n\n # __obtain_list_audio_controllers(wmiobject)\n # __obtain_list_ide_controllers(wmiobject)\n # __obtain_list_network_controllers(wmiobject)\n # __obtain_list_usb_controllers(wmiobject)\n # __obtain_list_video_controllers(wmiobject)\n\n\ndef select():\n \"\"\"This method gets controller instances in database\"\"\"\n return [c for c in Controller.select().execute()]\n\n\ndef models():\n \"\"\"This method gets controller models\"\"\"\n return [Controller]\n\n\ndef get_obj_from_fields(fields, name):\n \"\"\"This method makes instances from features\"\"\"\n mod = {'controller': Controller}\n return mod[name](**fields)\n\n\ndef get_dependences():\n \"\"\"This method returns the dependences between names for this plugin\"\"\"\n return {}\n","sub_path":"plugins/inventory/plugins/software/windows/drivers/drivers.py","file_name":"drivers.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"308286003","text":"def aniversariantes_de_setembro(dicionario):\n novo_dicionario = {}\n Lista1 = []\n Lista2 = [] #nomes\n for nome, datas in dicionario.items():\n Lista2.append(nomes)\n Lista1.append(datas)\n for i in range(len(Lista1)):\n if Lista1[i][3:5] == \"09\":\n novo_dicionario[Lista2[i]] = Lista1[i]\n return novo_dicionario\n ","sub_path":"backup/user_165/ch76_2019_06_06_23_15_30_983875.py","file_name":"ch76_2019_06_06_23_15_30_983875.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420053742","text":"import cv2\nimport numpy as np\n\nclass Env:\n def __init__(self):\n #self.iter = 0\n self.x = np.matrix([0.,320.])\n self.vr = np.matrix([5.,0.])\n self.vl = np.matrix([-5.,0.])\n\n def call(self):\n \n self.x += self.vr\n im = self.draw(self.x.astype(int))\n #self.iter += 1\n return im\n \n\n def draw(self, x):\n im = np.zeros( (640,700,3), np.uint8)\n r = 10\n im = cv2.rectangle(im, (x[0,0]-r,x[0,1]-r), (x[0,0]+r,x[0,1]+r), (255,0,0), -1)\n cv2.imshow('src2', im)\n return im\n \n\n\nif __name__ == '__main__':\n env = Env()\n c = 0\n \n while(c != ord('q') ):\n im = env.call()\n c = cv2.waitKey(0)\n \n print('exit')","sub_path":"squre.py","file_name":"squre.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356994006","text":"#-*- coding: UTF-8 -*-\nimport os\nimport cv2\nimport random\nimport numpy as np\nimport scipy.misc\nimport tensorflow as tf\nfrom datetime import datetime\nfrom skimage.measure import compare_ssim\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3,4,7\"\n\nclass Model:\n\n def __init__(self):\n\n self.img_shape = (240, 320, 3)\n self.block_h = 24\n self.block_w = 32\n self.block_num = 10\n self.video_size = 25\n\n self.epoch_size = 32\n self.learning_rate = 2e-4\n self.beta1 = 0.5\n\n def lrelu(self, x):\n\n return tf.maximum(x, 0.2*x)\n\n def conv_block(self, x, filters, kernel_size, strides, padding, actv=tf.nn.relu, train=True, name='conv_block'):\n x = tf.layers.conv2d(x, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, name=name+'conv')\n x = tf.layers.batch_normalization(x, momentum=0.99, epsilon=1e-4, scale=True, renorm=False, training=train, axis=-1, name=name+'batch')\n x = actv(x)\n return x\n\n def upsample_block(self, x, filters, kernel_size, strides, padding, actv=tf.nn.relu, train=True, name='upsample_block'):\n x = tf.layers.conv2d_transpose(x, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, name=name+'conv')\n x = tf.layers.batch_normalization(x, momentum=0.99, epsilon=1e-4, scale=True, renorm=False, training=train, axis=-1, name=name+'batch')\n x = actv(x)\n return x\n\n def residual_block(self, x, filters, kernel_size, strides, actv=tf.nn.relu, train=True, name='residual_block'):\n identity_map = x\n\n res = tf.pad(x, [[0, 0], [1, 1], [1, 1], [0, 0]], 'REFLECT')\n res = tf.layers.conv2d(res, filters=filters, kernel_size=kernel_size, strides=strides, padding='VALID', name=name+'conv1')\n res = tf.layers.batch_normalization(res, momentum=0.99, epsilon=1e-4, scale=True, renorm=False, training=train, axis=-1, name=name+'batch1')\n res = tf.nn.relu(res)\n\n res = tf.pad(res, [[0, 0], [1, 1], [1, 1], [0, 0]], 'REFLECT')\n res = tf.layers.conv2d(res, filters=filters, kernel_size=kernel_size, strides=strides, padding='VALID', name=name+'conv2')\n res = tf.layers.batch_normalization(res, momentum=0.99, epsilon=1e-4, scale=True, renorm=False, training=train, axis=-1, name=name+'batch2')\n\n out = tf.add(res, identity_map)\n\n return out\n\n def quantizer(slef, x):\n centers = tf.cast(tf.range(4), tf.float32)\n w_stack = tf.stack([x for _ in range(4)], axis=-1)\n w_hard = tf.cast(tf.argmin(tf.abs(w_stack - centers), axis=-1), tf.float32) + tf.reduce_min(centers)\n smx = tf.nn.softmax(-1.0 * tf.abs(w_stack - centers), dim=-1)\n w_soft = tf.einsum('ijklm,m->ijkl', smx, centers) \n w_bar = tf.stop_gradient(w_hard - w_soft) + w_soft\n return w_bar\n\n def foreground_encoder(self, x, train=True):\n x = tf.reshape(x, [1, self.block_h, self.block_w, 3])\n layer_1 = self.conv_block(x=x, filters=64, kernel_size=5, strides=2, padding='SAME', train=train, name='crop_encoder_1') \n layer_2 = self.residual_block(x=layer_1, filters=64, kernel_size=3, strides=1, train=train, name='crop_encoder_2')\n\n layer_3 = self.conv_block(x=layer_2, filters=128, kernel_size=4, strides=2, padding='SAME', train=train, name='crop_encoder_3') \n layer_4 = self.residual_block(x=layer_3, filters=128, kernel_size=3, strides=1, train=train, name='crop_encoder_4')\n\n\n layer_5 = self.conv_block(x=layer_4, filters=256, kernel_size=4, strides=2, padding='SAME', train=train, name='crop_encoder_5') \n layer_6 = self.residual_block(x=layer_5, filters=256, kernel_size=3, strides=1, train=train, name='crop_encoder_6')\n layer_7 = self.residual_block(x=layer_6, filters=256, kernel_size=3, strides=1, train=train, name='crop_encoder_7')\n layer_8 = self.residual_block(x=layer_7, filters=256, kernel_size=3, strides=1, train=train, name='crop_encoder_8')\n\n layer_8 = tf.pad(layer_8, [[0, 0], [1, 1], [1, 1], [0, 0]], 'REFLECT')\n layer_9 = self.conv_block(x=layer_8, filters=16, kernel_size=3, strides=1, padding='VALID', train=train, name='crop_encoder_9')\n return layer_9\n\n def foreground_decoder(self, x, train=True):\n out = self.conv_block(x=x, filters=128, kernel_size=3, strides=1, padding='SAME', train=train, name='crop_decoder_1') \n out = self.conv_block(x=out, filters=256, kernel_size=3, strides=1, padding='SAME', train=train, name='crop_decoder_2') \n\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_3')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_4')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_5')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_6')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_7')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='crop_decoder_8')\n\n out = self.upsample_block(x=out, filters=256, kernel_size=4, strides=2, padding='SAME', train=train, name='crop_decoder_9') \n out = self.upsample_block(x=out, filters=128, kernel_size=4, strides=2, padding='SAME', train=train, name='crop_decoder_10') \n out = self.upsample_block(x=out, filters=64, kernel_size=5, strides=2, padding='SAME', train=train, name='crop_decoder_11')\n\n out = tf.pad(out, [[0, 0], [1, 1], [1, 1], [0, 0]], 'REFLECT')\n out = tf.layers.conv2d(out, filters=3, kernel_size=3, strides=1, padding='VALID', name='crop_decoder_12')\n out = tf.nn.tanh(out)\n out = tf.reshape(out, [self.block_h, self.block_w, 3])\n return out\n\n def foreground_codec(self, real_img):\n\n x = random.randint(0, self.block_num - 1)\n y = random.randint(0, self.block_num - 1)\n crop_img = real_img[y*self.block_h:(y+1)*self.block_h, x*self.block_w:(x+1)*self.block_w, :]\n\n crop_code = self.foreground_encoder(crop_img)\n quantize = self.quantizer(crop_code)\n res_img = self.foreground_decoder(quantize)\n\n return crop_img, res_img, quantize\n\n def quality_enhance(self, x, train=True):\n out = tf.reshape(x, [1, self.block_h*self.block_num, self.block_w*self.block_num, 3])\n\n out = self.conv_block(x=out, filters=64, kernel_size=5, strides=2, padding='SAME', train=train, name='enhance_1') \n out = self.conv_block(x=out, filters=128, kernel_size=4, strides=2, padding='SAME', train=train, name='enhance_2')\n out = self.conv_block(x=out, filters=256, kernel_size=4, strides=2, padding='SAME', train=train, name='enhance_3')\n\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='enhance_4')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='enhance_5')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='enhance_6')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='enhance_7')\n out = self.residual_block(x=out, filters=256, kernel_size=3, strides=1, train=train, name='enhance_8')\n\n out = self.upsample_block(x=out, filters=256, kernel_size=4, strides=2, padding='SAME', train=train, name='enhance_9') \n out = self.upsample_block(x=out, filters=128, kernel_size=4, strides=2, padding='SAME', train=train, name='enhance_10') \n out = self.upsample_block(x=out, filters=64, kernel_size=5, strides=2, padding='SAME', train=train, name='enhance_11')\n\n out = tf.pad(out, [[0, 0], [1, 1], [1, 1], [0, 0]], 'REFLECT')\n out = tf.layers.conv2d(out, filters=3, kernel_size=3, strides=1, padding='VALID', name='enhance_12')\n out = tf.nn.tanh(out)\n out = tf.reshape(out, [self.block_h*self.block_num, self.block_w*self.block_num, 3])\n return out\n\n def f1(self, real_img, i, j):\n out = self.foreground_encoder(real_img[i*self.block_h:(i+1)*self.block_h, j*self.block_w:(j+1)*self.block_w, :])\n return out\n \n def f2(self, bg_img, codes, i, j):\n quantize = self.quantizer(codes)\n res_img = self.foreground_decoder(quantize)\n ans = tf.subtract(res_img, res_img + 1.0)\n ans = tf.pad(ans, [[i*self.block_h, (self.block_num-1-i)*self.block_h], [j*self.block_w, (self.block_num-1-j)*self.block_w], [0, 0]], 'CONSTANT')\n ans = tf.add(ans, 1.0)\n res_img = tf.pad(res_img, [[i*self.block_h, (self.block_num-1-i)*self.block_h], [j*self.block_w, (self.block_num-1-j)*self.block_w], [0, 0]], 'CONSTANT')\n result = tf.add(res_img, tf.multiply(ans, bg_img))\n return result\n\n def f3(self, bg_img, real_img, i, j):\n codes = self.foreground_encoder(real_img[i*self.block_h:(i+1)*self.block_h, j*self.block_w:(j+1)*self.block_w, :])\n quantize = self.quantizer(codes)\n res_img = self.foreground_decoder(quantize)\n ans = tf.subtract(res_img, res_img + 1.0)\n ans = tf.pad(ans, [[i*self.block_h, (self.block_num-1-i)*self.block_h], [j*self.block_w, (self.block_num-1-j)*self.block_w], [0, 0]], 'CONSTANT')\n ans = tf.add(ans, 1.0)\n res_img = tf.pad(res_img, [[i*self.block_h, (self.block_num-1-i)*self.block_h], [j*self.block_w, (self.block_num-1-j)*self.block_w], [0, 0]], 'CONSTANT')\n result = tf.add(res_img, tf.multiply(ans, bg_img))\n return result\n\n def composite(self, bg_img, real_img, fg_img):\n num = 0\n for i in range(self.block_num):\n for j in range(self.block_num):\n average = tf.reduce_mean(fg_img[i*self.block_h:(i+1)*self.block_h, j*self.block_w:(j+1)*self.block_w])\n # code = tf.cond(tf.greater(average, -0.92), lambda: self.f1(real_img, i, j), lambda: tf.zeros([1, self.block_h/8, self.block_w/8, 16]))\n # bg_img = tf.cond(tf.greater(average, -0.92), lambda: self.f2(bg_img, code, i, j), lambda: bg_img)\n bg_img = tf.cond(tf.greater(average, -0.90), lambda: self.f3(bg_img, real_img, i, j), lambda: bg_img)\n num = tf.cond(tf.greater(average, -0.90), lambda: num + 1, lambda: num)\n return bg_img, num\n\n def discriminator(self, x, train=True):\n x = tf.reshape(x, [1, self.block_h*self.block_num, self.block_w*self.block_num, 3])\n d1 = tf.layers.conv2d(x, filters=64, kernel_size=3, strides=2, padding='SAME', activation=self.lrelu, name='dis_1')\n d2 = self.conv_block(x=d1, filters=128, kernel_size=3, strides=2, padding='SAME', train=train, actv=self.lrelu, name='dis_2')\n d3 = self.conv_block(x=d2, filters=256, kernel_size=3, strides=2, padding='SAME', train=train, actv=self.lrelu, name='dis_3')\n d4 = self.conv_block(x=d3, filters=512, kernel_size=3, strides=2, padding='SAME', train=train, actv=self.lrelu, name='dis_4')\n out = tf.layers.conv2d(d4, filters=1, kernel_size=3, strides=1, padding='SAME', name='dis_5')\n out_sigmoid = tf.sigmoid(out)\n return out_sigmoid, out\n\n def loss_graph_composite(self, real_crop, composite_crop, real_all, composite_all):\n\n G_loss_crop = tf.losses.mean_squared_error(real_crop, composite_crop) \n G_loss_all = tf.losses.mean_squared_error(real_all, composite_all) \n\n G_loss = 16 * G_loss_all\n\n return G_loss\n\n def loss_graph_restruct(self, real, fake, real_all, restruct_all):\n D_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=real, labels=tf.ones_like(real)))\n D_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake, labels=tf.zeros_like(fake)))\n D_loss = D_loss_real + D_loss_fake\n\n G_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake, labels=tf.ones_like(fake)))\n G_loss_similarity = tf.losses.mean_squared_error(real_all, restruct_all) \n\n G_loss = G_loss_fake + 32 * G_loss_similarity\n\n return D_loss, G_loss\n\n def train(self):\n real_imgs = tf.placeholder(tf.float32, self.img_shape, name='real_images')\n bg_imgs = tf.placeholder(tf.float32, self.img_shape, name='bg_images')\n composited_imgs = tf.placeholder(tf.float32, self.img_shape, name='composited_imgs')\n fg_imgs = tf.placeholder(tf.float32, [240, 320], name='fg_images')\n\n with tf.variable_scope('composite_generator', reuse=tf.AUTO_REUSE):\n crop_img, res_img, quantize = self.foreground_codec(real_imgs)\n composite_img, num_block = self.composite(bg_imgs, real_imgs, fg_imgs)\n\n with tf.variable_scope('restruct_generator'):\n restructed_img = self.quality_enhance(composited_imgs)\n\n with tf.variable_scope('discriminator', reuse=tf.AUTO_REUSE):\n D_y, _ = self.discriminator(real_imgs)\n D_Gy, _ = self.discriminator(restructed_img)\n\n # 损失 \n G_loss_com = self.loss_graph_composite(crop_img, res_img, real_imgs, composite_img)\n D_loss, G_loss_res = self.loss_graph_restruct(D_y, D_Gy, real_imgs, restructed_img)\n\n\n train_vars = tf.trainable_variables() # 优化\n\n gen_vars_com = [var for var in train_vars if var.name.startswith('composite_generator')] # 生成器变量\n gen_vars_res = [var for var in train_vars if var.name.startswith('restruct_generator')] # 生成器变量\n dis_vars = [var for var in train_vars if var.name.startswith('discriminator')] # 判别器变量\n\n # 生成器与判别器作为两个网络需要分别优化\n gen_optimizer_com = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1).minimize(G_loss_com, var_list=gen_vars_com)\n gen_optimizer_res = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1).minimize(G_loss_res, var_list=gen_vars_res)\n dis_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1).minimize(D_loss, var_list=dis_vars)\n\n saver = tf.train.Saver()\n \n # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9)\n # with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, \"/home/wulirong/video/Model_old/Final/video.model\")\n\n for epoch in range(self.epoch_size):\n try:\n if os.path.exists('Results/'+str(epoch)+os.sep+'Background/') is False:\n os.makedirs('Results/'+str(epoch)+os.sep+'Background/')\n if os.path.exists('Results/'+str(epoch)+os.sep+'Composite/') is False:\n os.makedirs('Results/'+str(epoch)+os.sep+'Composite/')\n if os.path.exists('Results/'+str(epoch)+os.sep+'Restruct/') is False:\n os.makedirs('Results/'+str(epoch)+os.sep+'Restruct/')\n if os.path.exists('Results/'+str(epoch)+os.sep+'Original/') is False:\n os.makedirs('Results/'+str(epoch)+os.sep+'Original/')\n if os.path.exists('Results/'+str(epoch)+os.sep+'Foreground/') is False:\n os.makedirs('Results/'+str(epoch)+os.sep+'Foreground/')\n file = open('Results/'+str(epoch)+os.sep+'SSIM.txt', mode='a+')\n\n path = \"/home/wulirong/video/dataset/train_HK\"\n videos = os.listdir(path)\n np.random.shuffle(videos)\n num = 0\n\n for video_num in videos:\n video_length = len(os.listdir(path + os.sep + video_num))\n mog = cv2.createBackgroundSubtractorMOG2()\n \n for _ in range(3):\n for i in range(video_length): \n frame = cv2.imread(path + os.sep + video_num + os.sep + str(i) + '.png')\n img_fg = mog.apply(frame)\n\n img_background = mog.getBackgroundImage()\n img_bg = np.array(img_background) / 127.5 - 1.\n mog = cv2.createBackgroundSubtractorMOG2()\n\n for i in range(video_length):\n frame = cv2.imread(path + os.sep + video_num + os.sep + str(i) + '.png')\n img_fg = mog.apply(frame)\n ret, img_fg = cv2.threshold(img_fg, 12, 255, cv2.THRESH_BINARY)\n kernel_open_1 = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n kernel_dilate = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n kernel_open_2 = cv2.getStructuringElement(cv2.MORPH_RECT, (12, 12))\n img_fg = cv2.morphologyEx(img_fg, cv2.MORPH_OPEN, kernel_open_1)\n img_fg = cv2.dilate(img_fg, kernel_dilate, iterations = 1)\n img_fg = cv2.morphologyEx(img_fg, cv2.MORPH_OPEN, kernel_open_2)\n img_fg = np.array(img_fg) / 127.5 - 1.\n frame = np.array(frame) / 127.5 - 1.\n\n #_ = sess.run(gen_optimizer_com, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n #_ = sess.run(gen_optimizer_com, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n\n com_img = sess.run(composite_img, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n\n _ = sess.run(dis_optimizer, feed_dict={real_imgs: frame, composited_imgs: com_img})\n _ = sess.run(gen_optimizer_res, feed_dict={real_imgs: frame, composited_imgs: com_img})\n _ = sess.run(gen_optimizer_res, feed_dict={real_imgs: frame, composited_imgs: com_img})\n _ = sess.run(gen_optimizer_res, feed_dict={real_imgs: frame, composited_imgs: com_img})\n\n if i % 20 == 0: \n loss_d = sess.run(D_loss, feed_dict={real_imgs: frame, composited_imgs: com_img})\n loss_g = sess.run(G_loss_res, feed_dict={real_imgs: frame, composited_imgs: com_img})\n num_block_size = sess.run(num_block, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n print(datetime.now().strftime('%c'), epoch, num, i, 'D:', loss_d, 'G:', loss_g, 'N:', num_block_size)\n #loss_g = sess.run(G_loss_com, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n #num_block_size = sess.run(num_block, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n #print(datetime.now().strftime('%c'), epoch, num, i, 'G:', loss_g, 'N:', num_block_size)\n\n if num == self.video_size - 1:\n com_img = sess.run(composite_img, feed_dict={real_imgs: frame, bg_imgs: img_bg, fg_imgs: img_fg})\n res_img = sess.run(restructed_img, feed_dict={real_imgs: frame, composited_imgs: com_img})\n\n com_ssim = compare_ssim(tf.cast(frame, tf.float32).eval(), tf.cast(com_img, tf.float32).eval(), win_size=5, multichannel=True)\n res_ssim = compare_ssim(tf.cast(frame, tf.float32).eval(), tf.cast(res_img, tf.float32).eval(), win_size=5, multichannel=True)\n file.write(str(epoch)+\": \"+str(com_ssim)+\" \"+str(res_ssim)+\"\\n\")\n file.flush()\n\n img_fg = (np.array(img_fg) + 1.) * 127.5\n com_img = (np.array(com_img) + 1.) * 127.5\n res_img = (np.array(res_img) + 1.) * 127.5\n frame = (np.array(frame) + 1.) * 127.5\n\n cv2.imwrite('Results/'+str(epoch)+os.sep+'Background/'+str(i)+'.png', img_background)\n cv2.imwrite('Results/'+str(epoch)+os.sep+'Foreground/'+str(i)+'.png', img_fg)\n cv2.imwrite('Results/'+str(epoch)+os.sep+'Composite/'+str(i)+'.png', com_img)\n cv2.imwrite('Results/'+str(epoch)+os.sep+'Restruct/'+str(i)+'.png', res_img)\n cv2.imwrite('Results/'+str(epoch)+os.sep+'Original/'+str(i)+'.png', frame)\n\n #scipy.misc.imsave('Results/'+str(epoch)+os.sep+'Background/'+str(i)+'.png', img_background)\n #scipy.misc.imsave('Results/'+str(epoch)+os.sep+'Composite/'+str(i)+'.png', com_img)\n #scipy.misc.imsave('Results/'+str(epoch)+os.sep+'Restruct/'+str(i)+'.png', res_img)\n #scipy.misc.imsave('Results/'+str(epoch)+os.sep+'Original/'+str(i)+'.png', frame)\n num += 1\n num = 0\n\n if epoch % 12 == 11 :\n if os.path.exists(\"/home/wulirong/video/Model/\" + str(epoch) + '/') is False:\n os.makedirs('Model/' + str(epoch) + '/')\n model_path = os.getcwd() + os.sep + 'Model/' + str(epoch) + '/video.model'\n saver.save(sess, model_path)\n\n except:\n if os.path.exists(\"/home/wulirong/video/Model/Temporary/\") is False:\n os.makedirs(\"/home/wulirong/video/Model/Temporary/\")\n model_path = os.getcwd() + os.sep + \"Model/Temporary/video.model\"\n saver.save(sess, model_path)\n\n if os.path.exists(\"/home/wulirong/video/Model/Final/\") is False:\n os.makedirs(\"/home/wulirong/video/Model/Final/\")\n model_path = os.getcwd() + os.sep + \"Model/Final/video.model\"\n saver.save(sess, model_path)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":22326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"93163119","text":"import sys\r\nsys.path.append(\"..\")\r\nimport mysql.connector\r\nfrom database import config\r\nimport datetime\r\n\r\ndb = mysql.connector.connect(\r\n host = config.host,\r\n user = config.user,\r\n passwd = config.passwd,\r\n auth_plugin = config.auth_plugin,\r\n database = config.database_name\r\n)\r\n\r\nmycursor = db.cursor()\r\n\r\n# # create table:\r\n# mycursor.execute(\"CREATE TABLE Strategy (id VARCHAR(50), wt1 DECIMAL, wt2 DECIMAL, last_candle_high DECIMAL, last_candle_low DECIMAL, last_candle_vwap DECIMAL, active_position VARCHAR(50), new_trend VARCHAR(50), last_trend VARCHAR(50), active_trend VARCHAR(50))\")\r\n# mycursor.execute(\"CREATE TABLE trades (id VARCHAR(50), strat_id VARCHAR(50), symbol VARCHAR(50), symbol_pair VARCHAR(50), key_input INT, limit_price_difference FLOAT, leverage INT, input_quantity INT, side VARCHAR(8), stop_loss FLOAT, percent_gain DECIMAL, trade_record_id INT)\")\r\n# mycursor.execute(\"CREATE TABLE trade_records (id INT UNSIGNED, trade_id VARCHAR(16), strat_id VARCHAR(16), symbol_pair VARCHAR(50), side VARCHAR(8), input_quantity INT UNSIGNED, entry_price FLOAT UNSIGNED, exit_price FLOAT UNSIGNED, stop_loss FLOAT UNSIGNED, percent_gain VARCHAR(24), dollar_gain VARCHAR(24), coin_gain VARCHAR(24), total_p_l_dollar VARCHAR(24), total_p_l_coin VARCHAR(24), time VARCHAR(50))\")\r\n\r\n# # describe table details:\r\n# mycursor.execute(\"DESCRIBE Strategy\")\r\n\r\n# for x in mycursor:\r\n# print(x)\r\n\r\n# # insert into table\r\n# mycursor.execute(\"INSERT INTO Strategy () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (\"1_min\", 0.0, 0.0, 0.0, 0.0, 0.0, \"null\", \"null\", \"null\", \"null\"))\r\n# mycursor.execute(\"INSERT INTO Strategy () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (\"9_min\", 0.0, 0.0, 0.0, 0.0, 0.0, \"null\", \"null\", \"null\", \"null\"))\r\n# mycursor.execute(\"INSERT INTO Strategy () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (\"16_min\", 0.0, 0.0, 0.0, 0.0, 0.0, \"null\", \"null\", \"null\", \"null\"))\r\n# mycursor.execute(\"INSERT INTO Strategy () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (\"30_min\", 0.0, 0.0, 0.0, 0.0, 0.0, \"null\", \"null\", \"null\", \"null\"))\r\n# db.commit()\r\n\r\n## Insert Column\r\n# mycursor.execute(\"ALTER TABLE trade_records ADD time VARCHAR(50)\")\r\n# db.commit()\r\n\r\n# mycursor.execute(\"INSERT INTO trades () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", ('bybit_manual', 'empty', 'empty', 'empty', 0, 0.0, 0, 0, 'empty', 0, 0, 0))\r\n# mycursor.execute(\"INSERT INTO trades () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", ('bybit_auto_1', 'empty', 'empty', 'empty', 0, 0.0, 0, 0, 'empty', 0, 0, 0))\r\n# mycursor.execute(\"INSERT INTO trades () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", ('bybit_auto_2', 'empty', 'empty', 'empty', 0, 0.0, 0, 0, 'empty', 0, 0, 0))\r\n# mycursor.execute(\"INSERT INTO trades () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", ('bybit_auto_3', 'empty', 'empty', 'empty', 0, 0.0, 0, 0, 'empty', 0, 0, 0))\r\n# mycursor.execute(\"INSERT INTO trades () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", ('bybit_auto_4', 'empty', 'empty', 'empty', 0, 0.0, 0, 0, 'empty', 0, 0, 0))\r\n\r\n# db.commit()\r\n# mycursor.execute(\"SELECT * FROM Strategy\")\r\n\r\n# Query\r\n# mycursor.execute(\"SELECT * FROM trades WHERE id = 'main'\")\r\n# for x in mycursor:\r\n# print(x)\r\n\r\n# # Query specific\r\n# mycursor.execute(\"SELECT wt1, wt2 FROM Strategy WHERE id = '9_min'\")\r\n\r\n# # Alter / Add\r\n# mycursor.execute(\"ALTER TABLE strategy ADD COLUMN test VARCHAR(50) NOT NULL\")\r\n\r\n# # Alter / Remove\r\n# mycursor.execute(\"ALTER TABLE Strategy DROP test\")\r\n\r\n# # Alter / Change column name\r\n\r\n# mycursor.execute(\"ALTER TABLE Strategy CHANGE name id VARCHAR(50)\")\r\n\r\n\r\n## Update Values\r\ndef updateTableValue(table_name, id_name, column_name, value):\r\n try:\r\n if (isinstance(value, str)):\r\n query = \"UPDATE \" +str(table_name)+ \" SET \" + str(column_name) + \"='\" + str(value) + \"' WHERE id = '\" + str(id_name) + \"'\"\r\n else:\r\n query = \"UPDATE \" +str(table_name)+ \" SET \" + str(column_name) + \"=\" + str(value) + \" WHERE id = '\" + str(id_name) + \"'\"\r\n print(query)\r\n mycursor.execute(query)\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error))\r\n\r\n\r\ndef update_strat_values(id_name, wt1, wt2, last_candle_high, last_candle_low, last_candle_vwap):\r\n try:\r\n query = \"UPDATE strategy SET wt1=\" +str(wt1)+ \", wt2=\" +str(wt2)+ \", last_candle_low=\" +str(last_candle_low)+ \", last_candle_high=\" +str(last_candle_high)+ \", last_candle_vwap=\" +str(last_candle_vwap)+ \" WHERE id = '\" +str(id_name)+ \"'\"\r\n print(query)\r\n mycursor.execute(query)\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error)) \r\n\r\ndef update_strat_trends(id_name, active_position, new_trend, last_trend, active_trend):\r\n try:\r\n query = \"UPDATE strategy SET active_position='\" +str(active_position)+ \"', new_trend='\" +str(new_trend)+ \"', last_trend='\" +str(last_trend)+ \"', active_trend='\" +str(active_trend)+ \"' WHERE id = '\" +str(id_name)+ \"'\"\r\n print(query)\r\n mycursor.execute(query)\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error)) \r\n\r\ndef update_trade_values(id_name, strat_id, symbol, symbol_pair, key_input, limit_price_difference, leverage, input_quantity, side, stop_loss, percent_gain, trade_record_id):\r\n try:\r\n query = \"UPDATE trades SET strat_id='\" +str(strat_id)+ \"', symbol='\" +str(symbol)+ \"', symbol_pair='\" +str(symbol_pair)+ \"', key_input=\" +str(key_input)+ \", limit_price_difference=\" +str(limit_price_difference)+ \", leverage=\" +str(leverage)+ \", input_quantity=\" +str(input_quantity)+ \", side='\" +str(side)+ \"', stop_loss=\" +str(stop_loss)+ \", percent_gain=\" +str(percent_gain)+ \", trade_record_id=\" +str(trade_record_id)+\" WHERE id='\" +str(id_name)+ \"'\" \r\n print(query)\r\n mycursor.execute(query)\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error))\r\n\r\n## Create\r\ndef create_trade_record(trade_record_id, trade_id, strat_id, symbol_pair, side, input_quantity, entry_price, exit_price, stop_loss, percent_gain, dollar_gain, coin_gain, total_p_l_dollar, total_p_l_coin, time):\r\n try:\r\n query = \"INSERT INTO trade_records () VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\r\n print(query)\r\n mycursor.execute(query,(trade_record_id, trade_id, strat_id, symbol_pair, side, input_quantity, entry_price, exit_price, stop_loss, percent_gain, dollar_gain, coin_gain, total_p_l_dollar, total_p_l_coin, time))\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error))\r\n\r\n## Delete \r\ndef delete_trade_records():\r\n try:\r\n query = \"DELETE FROM trade_records\"\r\n print(query)\r\n mycursor.execute(query)\r\n db.commit()\r\n except mysql.connector.Error as error:\r\n print(\"Failed to update record to database: {}\".format(error))\r\n\r\n## View Value\r\ndef viewDbValue(table_name, id_name, column_name):\r\n try: \r\n query = \"SELECT \" + str(column_name) + \" FROM \" +str(table_name)+ \" WHERE id = '\" + str(id_name) + \"'\"\r\n mycursor.execute(query)\r\n result = mycursor.fetchall()\r\n db.commit()\r\n return result[0][0]\r\n except mysql.connector.Error as error:\r\n print(\"Failed to retrieve record from database: {}\".format(error))\r\n\r\ndef view_db_values_multiple(table_name, id_name_1, id_name_2, column_name):\r\n try: \r\n query = \"SELECT \" + str(column_name) + \" FROM \" +str(table_name)+ \" WHERE id = '\" + str(id_name_1) + \"' AND trade_id = '\" + str(id_name_2) + \"'\"\r\n mycursor.execute(query)\r\n result = mycursor.fetchall()\r\n db.commit()\r\n return result[0][0]\r\n except mysql.connector.Error as error:\r\n print(\"Failed to retrieve record from database: {}\".format(error))\r\n\r\n## Get Table Row\r\ndef get_table_pair(table_name, id_name):\r\n try:\r\n kv_dict = {}\r\n column_query = \"SHOW COLUMNS FROM \" + str(table_name)\r\n column_name_result = mycursor.execute(column_query)\r\n column_name_list = mycursor.fetchall()\r\n\r\n row_query = \"Select * FROM \" + str(table_name) + \" WHERE id = '\" + str(id_name) + \"' LIMIT 0,1\"\r\n row_result = mycursor.execute(row_query)\r\n row_list = mycursor.fetchall()\r\n row_list = row_list[0]\r\n\r\n for x in range(len(row_list)): \r\n kv_pair = [(column_name_list[x][0], row_list[x])]\r\n kv_dict.update(kv_pair)\r\n\r\n db.commit()\r\n\r\n return(kv_dict)\r\n\r\n except mysql.connector.Error as error:\r\n print(\"Failed to retrieve record from database: {}\".format(error))\r\n\r\n## Get Table Columns\r\ndef get_table_column_names(table_name):\r\n try:\r\n for x in range(len(returnResult)):\r\n column_name_list.append(returnResult[x][0])\r\n\r\n db.commit()\r\n return(column_name_list)\r\n\r\n except mysql.connector.Error as error:\r\n print(\"Failed to retrieve record from database: {}\".format(error)) \r\n\r\n\r\n\r\n\r\n# updateTableValue('trades', 'main', 'leverage', 0)\r\n# update_strat_values('9_min', 0, 0, 0, 0, 0)\r\n# viewDbValues('9_min', 'wt1')\r\n# mycursor.getUpdateCount()\r\n# print(viewDbValues('9_min', 'wt1'))\r\n# test1 = viewDbValues('9_min', 'wt1')\r\n# create_trade_record('test1', 'BTCUSD', 14.4, 128.5, 932.4, 43.3, 12.3, 77.3, 4.2, 199999.2)\r\n# deleteTradeRecords()\r\n# clearAllTableValues()\r\n\r\n# create_trade_record(0, 'empty', 0, 0, 0, 0, 0, 0, 0, 'empty', 0)\r\n\r\n# test = viewTableRow('trades', 'bybit_btcusd_manual')\r\n\r\n# print(type(test))\r\n# print(test[0][2])\r\n\r\n\r\n# update_trade_values('bybit_manual', '1_min', 'BTC', 'BTCUSD', 0, 0.50, 5, 500, 'empty', 0, 0, 0)","sub_path":"sql_connector.py","file_name":"sql_connector.py","file_ext":"py","file_size_in_byte":9970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99672399","text":"'''\nFramework for expressing transforms from one pattern of Versa links to another\nThis is especially useful if you've used a tool to extract Versa from some data\nsource but would like to tweak the interpretation of that data. It's also useful\nfor mapping from one vocabulary to another.\n\nThe concept is similar to XProc (http://en.wikipedia.org/wiki/XProc). You define\nthe overall transform in terms of transform steps or stages, implemented as\nPython functions. Each function can have inputs, which might be simple Versa\nscalars or even functions in themselves. The outputs are Versa scalars.\n\nThere is also a shared environment across the steps, called the context (`versa.context`).\nThe context includes a resource which is considered the origin for purposes\nof linking, an input Versa model considered to be an overall input to the transform\nand an output Versa model considered to be an overall output.\n'''\n\nimport itertools\nimport functools\nimport logging\n\n#import amara3\nfrom amara3 import iri\n#from amara3.util import coroutine\n\nfrom versa import I, VERSA_BASEIRI, ORIGIN, RELATIONSHIP, TARGET\nfrom versa import util\nfrom versa.util import simple_lookup\nfrom versa import context\n\ntry:\n from datachef.ids import simple_hashstring, FROM_EMPTY_HASH\nexcept ImportError:\n #datachef not installed, but proceed anyway\n #Note: if so they must be providing a different hash key generator, so we might want to provide a way to override this marker\n FROM_EMPTY_HASH = 'AAAAAAAA'\n\nVTYPE_REL = I(iri.absolutize('type', VERSA_BASEIRI))\n\n\n#FIXME: Use __all__\n\nclass resource(object):\n def __init__(self, ctx):\n self._origin = ctx.current_link[ORIGIN]\n self._input_model = ctx.input_model\n self._base = ctx.base\n return\n\n def follow(self, rel):\n return simple_lookup(self._input_model, self._origin, I(iri.absolutize(rel, self._base)))\n\n\n#def vtype():\n# return TYPE_REL\n\n\ndef origin(ctx):\n return resource(ctx.current_link[ORIGIN], ctx.input_model)\n\n\ndef res(arg):\n '''\n Render the argument as an IRI reference\n '''\n def _res(ctx):\n _arg = arg(ctx) if callable(arg) else arg\n return I(arg)\n return _res\n\n\n#Functions that take a prototype link set and generates a transformed link set\n\ndef materialize(ctx, hashidgen=None, existing_ids=None, unique=None, typ=None, new_rel=None, properties=None):\n '''\n Create a new resource related to the origin, with optional, additional links created in the output model\n '''\n properties = properties or {}\n #Just work with the first provided statement, for now\n (o, r, t) = ctx.current_link\n if unique:\n objid = hashidgen.send(unique(ctx))\n else:\n objid = next(hashidgen)\n if objid != I(iri.absolutize(FROM_EMPTY_HASH, ctx.base)):\n ctx.output_model.add(I(o), I(iri.absolutize(new_rel, ctx.base)), I(objid), {})\n if objid not in existing_ids:\n if typ: ctx.output_model.add(I(objid), VTYPE_REL, I(iri.absolutize(typ, ctx.base)), {})\n for k, v in properties.items():\n if callable(v):\n v = v(ctx)\n ctx.output_model.add(I(objid), I(iri.absolutize(k, ctx.base)), v, {})\n return objid\n\n\ndef inverse_materialize(ctx, hashidgen=None, existing_ids=None, unique=None, typ=None, new_rel=None, properties=None):\n '''\n Create a new resource related to the origin\n '''\n properties = properties or {}\n #Just work with the first provided statement, for now\n (o, r, t) = ctx.current_link\n if unique:\n objid = hashidgen.send(unique(ctx))\n else:\n objid = next(hashidgen)\n if objid != I(iri.absolutize(FROM_EMPTY_HASH, ctx.base)):\n ctx.output_model.add(I(objid), I(iri.absolutize(new_rel, ctx.base)), I(o), {})\n if objid not in existing_ids:\n if typ: ctx.output_model.add(I(objid), VTYPE_REL, I(iri.absolutize(typ, ctx.base)), {})\n for k, v in properties.items():\n if callable(v):\n v = v(ctx)\n ctx.output_model.add(I(objid), I(iri.absolutize(k, ctx.base)), v, {})\n return objid\n\n\ndef relabel(ctx, new_rel=None, res=False):\n '''\n Update the label of the relationship to be added to the link space\n '''\n #Just work with the first provided statement, for now\n (o, r, t) = ctx.current_link\n if res: t = I(t)\n ctx.output_model.add(I(o), I(iri.absolutize(new_rel, ctx.base)), t, {})\n return None\n\n\ndef discard(ctx):\n #No op. Just ignore the proposed link set\n return None\n\n\ndef run(pycmds):\n def _run(ctx):\n gdict = {\n 'origin': resource(ctx),\n #'origin': resource(link[ORIGIN], ctx),\n 'target': ctx.current_link[TARGET],\n }\n result = eval(pycmds, gdict)\n return result\n return _run\n\n","sub_path":"tools/py/pipeline/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241395838","text":"import FWCore.ParameterSet.Config as cms\nimport copy\nfrom CommonTools.ParticleFlow.pfParticleSelection_cff import *\n#https://github.com/cms-sw/cmssw/blob/CMSSW_9_2_6_patchX/RecoEgamma/ElectronIdentification/python/Identification/cutBasedElectronID_Summer16_80X_V1_cff.py\n#from RecoEgamma.ElectronIdentification.Identification.cutBasedElectronID_Summer16_80X_V1_cff *\n\n#-----------------------------\n#for cut based electron ids\n#-----------------------------\ndef configureElectronCutIdIso(process) :\n #vertex\n process.selectedPrimaryVertices = cms.EDFilter(\n \"VertexSelector\",\n src = cms.InputTag('offlineSlimmedPrimaryVertices'),\n cut = cms.string(\"isValid & ndof >= 4 & z > -24 & z < +24 & position.Rho < 2.\"),\n filter = cms.bool(False)\n )\n\n #embed electrons\n process.selectedPatElectronsUserEmbedded = cms.EDProducer(\n \"ElectronsUserEmbedded\",\n electronTag = cms.InputTag(\"slimmedElectrons\"),\n vertexTag = cms.InputTag(\"selectedPrimaryVertices\"),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"),\n #rho = cms.InputTag(\"kt6PFJets\", \"rho\"),\n beamSpot = cms.InputTag('offlineBeamSpot'),\n conversionsMiniAOD = cms.InputTag('reducedEgamma:reducedConversions'),\n #eleIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto\"),\n #eleIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose\"),\n eleIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium\")\n #eleIdMap = cms.InputTag(\"egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight\"),\n )\n process.EleEmbedSequence = cms.Sequence(process.selectedPrimaryVertices * process.selectedPatElectronsUserEmbedded)\n\n","sub_path":"Selection/python/ElectronExtra_cff.py","file_name":"ElectronExtra_cff.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"93972259","text":"from typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n cache = {}\n\n def put(self, i, j, size):\n if i not in self.cache:\n self.cache[i] = {}\n\n self.cache[i][j] = size\n\n def get(self, i, j):\n if i not in self.cache:\n return -1\n if j not in self.cache[i]:\n return -1\n return self.cache[i][j]\n\n def largest_square_at(self, i, j, matrix):\n if i >= len(matrix) or j >= len(matrix[0]):\n return 0\n if matrix[i][j] == '0':\n return 0\n\n if self.get(i, j) > -1:\n return self.get(i, j)\n\n contained_size = self.largest_square_at(i + 1, j + 1, matrix)\n if contained_size > 0:\n can_expand = True\n for expand in range(1, contained_size + 1):\n if matrix[i][j + expand] == '0' or matrix[i + expand][j] == '0':\n can_expand = False\n break\n if can_expand:\n contained_size += 1\n self.put(i, j, contained_size)\n return contained_size\n\n potential_size = 1\n while potential_size + i < len(matrix) and potential_size + j < len(matrix[0]):\n has_zero = False\n for ii in range(i, i + potential_size + 1):\n if matrix[ii][j + potential_size] == '0':\n has_zero = True\n break\n if not has_zero:\n for jj in range(j, j + potential_size + 1):\n if matrix[i + potential_size][jj] == '0':\n has_zero = True\n break\n\n if has_zero:\n break\n potential_size += 1\n self.put(i, j, potential_size)\n return potential_size\n\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n self.cache = {}\n max_size = 0\n for i in range(0, len(matrix)):\n for j in range(0, len(matrix[0])):\n max_size = max(self.largest_square_at(i, j, matrix), max_size)\n return max_size ** 2\n\n\nif __name__ == '__main__':\n s = Solution()\n matrix = [[1, 0, 1, 0, 0],\n [1, 0, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 0, 0, 1, 0],\n ]\n\n matrix = [[\"1\", \"0\", \"1\", \"0\", \"0\"], [\"1\", \"0\", \"1\", \"1\", \"1\"], [\"1\", \"1\", \"1\", \"1\", \"1\"],\n [\"1\", \"0\", \"0\", \"1\", \"0\"]]\n\n matrix = [[\"0\", \"1\"]]\n\n matrix = [[\"0\", \"0\", \"0\", \"1\", \"0\", \"1\", \"1\", \"1\"],\n [\"0\", \"1\", \"1\", \"0\", \"0\", \"1\", \"0\", \"1\"],\n [\"1\", \"0\", \"1\", \"1\", \"1\", \"1\", \"0\", \"1\"],\n [\"0\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"],\n [\"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"1\", \"0\"],\n [\"1\", \"1\", \"1\", \"0\", \"0\", \"1\", \"1\", \"1\"],\n [\"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\", \"1\"],\n [\"0\", \"1\", \"0\", \"0\", \"1\", \"1\", \"0\", \"0\"],\n [\"1\", \"0\", \"0\", \"1\", \"0\", \"0\", \"0\", \"0\"]]\n print(s.maximalSquare(matrix))\n","sub_path":"p221.py","file_name":"p221.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216305103","text":"# rebotes.py\n# Ejercicio 1.5: La pelota que rebota\n\naltura = 100\nperdida = 3/5\nrebotes = 10\nrebote = 1\n\nwhile rebote <= rebotes:\n\taltura = altura * perdida\n\tprint(f'{rebote: 3d} {round(altura, 4):7.4f}')\n\trebote = rebote + 1\n","sub_path":"Clase06/rebotes.py","file_name":"rebotes.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"541848143","text":"\ndef rot13(s):\n result = \"\"\n\n # Loop over characters.\n for v in s:\n # Convert to number with ord.\n c = ord(v)\n\n # Shift number back or forward.\n if c >= ord('a') and c <= ord('z'):\n if c > ord('m'):\n c -= 13\n else:\n c += 13\n elif c >= ord('A') and c <= ord('Z'):\n if c > ord('M'):\n c -= 13\n else:\n c += 13\n\n # Append to result.\n result += chr(c)\n\n # Return transformation.\n return result\n\n# Test method.\nif __name__ == '__main__':\n while 1: \n print(\"##################################################################\")\n print(\"# #\")\n print(\"# Author : Oumar Djimé Ratou #\")\n print(\"# Algorithme : ROT13 #\")\n print(\"# #\")\n print(\"##################################################################\")\n\n print()\n\n print(\"***************************************************************************\")\n print(\"************ Chiffrement et dechiffrement de rot13*********************\")\n print(\"************ (C) Chiffrement. *******************\")\n print(\"************ (D) Déchiffrement. *******************\")\n print(\"************ (Q) Quitter. *******************\")\n print(\"***************************************************************************\")\n choix = input(\"Veillez choisir votre choix :\").upper()\n\n if choix == 'C':\n message = input(\"Veillez entrer le message à chiffrer :\")\n print(\"Le message crypté est : {}.\".format(rot13(message)))\n elif choix == 'D': \n message1 = input(\"Veillez entrer le message à déchiffrer :\")\n print(\"Le message decrypté est {}.\".format(rot13(rot13(message1))))\n else:\n print(\"Merci d'avoir utiliser cette programme\")\n break ","sub_path":"rot13.py","file_name":"rot13.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79760708","text":"import numpy as np\nimport pandas as pd\n\nfrom ControlChartTests import *\n\nlon = {\n 'CheckDate' : 'Date when the data was checked'\n , 'col1' : 'Random Numbers in the 0-100 Range'\n , 'col2' : 'Widget Weight'\n , 'col3' : 'Random Data'\n , 'col4' : 'Sine Wave'\n , 'col5' : 'Widget Output'\n }\n\nuni = {\n 'CheckDate' : 'date'\n , 'col1' : 'percent/100'\n , 'col2' : 'grams'\n , 'col3' : 'countitems'\n , 'col4' : 'rotation'\n , 'col5' : 'milliWidgets'\n }\n \ndir = {\n 'col1' : 'D'\n , 'col2' : 'U'\n , 'col3' : 'U'\n , 'col4' : 'X'\n , 'col5' : 'D'\n }\n\ndf = qmut.df_random(length=90) # generate the dataframe\ndf = qmut.df_set_date(df) # set 'Date' as the index\n\nqplt.plotme(df.loc[:,['col1','col2','col3','col4','col5']], units=uni, columnlongnames=lon, desireddirection=dir, plotMR=True)\n\na = df.loc[:,['col1','col2','col3','col4','col5']]\n\ntests = {'A' : testA(a)\n , 'B' : testB(a)\n , 'C' : testC(a)\n }\n","sub_path":"utils_to_add/control_chart_tools/ControlChartplotmeImprovement 2016-12-07/plotmeImprovement.py","file_name":"plotmeImprovement.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568475861","text":"import discord\nfrom discord.ext import commands, tasks\nfrom logger import log\nimport asyncio\n\nclass Events(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print('Ready')\n await self.client.change_presence(status = discord.Status.online)\n await log('Hayasaka is online')\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n await log(f'Hayasaka joined {guild.name} (ID: {guild.id})')\n\n @commands.Cog.listener()\n async def on_guild_remove(self, guild):\n await log(f'Hayasaka left {guild} (ID: {guild.id})')\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n await log(f'{member} (ID: {member.id}) has joined a server')\n\n @commands.Cog.listener()\n async def on_member_remove(self, member):\n await log(f'{member} (ID: {member.id}) has left a server')\n\n @commands.Cog.listener()\n async def on_message(self, msg):\n await log(f'({msg.guild} #{msg.channel}) {msg.author}: {msg.content}', 'm')\n if msg.author == self.client.user or msg.author.bot:\n return\n\n @commands.Cog.listener()\n async def on_typing(self, channel, user, when):\n await log(f'({channel.guild} #{channel.name}) {user} is typing...', 'm')\n\n @commands.Cog.listener()\n async def on_message_delete(self, msg):\n await log(f'({msg.guild} #{msg.channel}) {msg.author}: {msg.content}', 'd')\n\n @commands.Cog.listener()\n async def on_bulk_message_delete(self, msgs):\n for msg in msgs:\n await log(f'({msg.guild} #{msg.channel}) {msg.author}: {msg.content}', 'd')\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.CommandOnCooldown):\n msg = await ctx.channel.send(f'Command on cooldown. Please try again after {error.retry_after:.2f}s.')\n elif isinstance(error, commands.BadArgument):\n msg = await ctx.channel.send('Invalid command argument. Please try again.')\n elif isinstance(error, commands.MissingPermissions):\n msg = await ctx.channel.send('Missing permissions for command.')\n else:\n msg = await ctx.channel.send(error)\n await asyncio.sleep(3)\n await msg.delete()\n\ndef setup(client):\n client.add_cog(Events(client))","sub_path":"cogs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514078894","text":"from itertools import product\nimport numpy as np\nimport random\nclass nnNode:\n def __init__(self, K, Cweights, Dweights, seed):\n self.K = K\n self.seed = seed\n self.u = np.random.rand()\n\n\n def printFeatures(self):\n for f in self.features:\n feat = {\"xhat\": f.xhat, \"cost\": f.cost, \"range\": f.range, \"weight\": f.weight}\n print(feat)\n","sub_path":"1ef/nnNode.py","file_name":"nnNode.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568084959","text":"from physics.vector2 import Vector2\nfrom physics.random_angle import get_random_angle_rad\nfrom physics.forces import calc_velocity_with_f_mpz\nfrom body import Body\nimport random\nimport math\nimport matplotlib.pyplot as plt\n\n\ndef get_star_mass():\n return 1.989e30\n\n\ndef get_random_distance():\n base = random.randrange(250, 1000, 10)\n return base * 10e12\n\n\ndef get_black_hole():\n # The black hole will always be in the center and will not be moving\n position = Vector2(0, 0)\n velocity = Vector2(0, 0)\n mass = 10e35\n return Body(position, velocity, mass)\n\n\ndef get_star():\n mass = get_star_mass()\n velocity = Vector2(0, 0)\n random_angle = get_random_angle_rad()\n distance = get_random_distance()\n\n position = Vector2(0, 0)\n position.x = math.cos(random_angle) * distance\n position.y = math.sin(random_angle) * distance\n\n return Body(position, velocity, mass)\n\n\ndef generate_system(star_amount):\n bodies = []\n\n black_hole = get_black_hole()\n bodies.append(black_hole)\n\n for i in range(star_amount):\n bodies.append(get_star())\n\n # Set starting velocities of stars\n for star in bodies:\n if star is not black_hole:\n vector_between_star_and_black_hole = star.position - black_hole.position\n distance = vector_between_star_and_black_hole.get_length()\n gravitational_force = star.get_gravitational_force_to(black_hole)\n gravitational_magnitude = gravitational_force.get_length()\n velocity_magnitude = calc_velocity_with_f_mpz(gravitational_magnitude, star.mass, distance)\n\n force_direction = vector_between_star_and_black_hole.get_unitvector()\n # The starting velocity will be perpendicular to the direction of the force\n velocity_direction = Vector2(-force_direction.y, force_direction.x)\n star.velocity = velocity_direction * velocity_magnitude\n\n return bodies\n","sub_path":"generators/black_hole_system.py","file_name":"black_hole_system.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58616690","text":"#! python3\n# Chapter 15 Project - Countdown timer with an alarm\n\nimport time, subprocess\n\ntimeLeft = 3\nwhile timeLeft > 0:\n print(timeLeft)\n time.sleep(1)\n timeLeft -= 1\n\n# At the end of the countdown, play a sound file\nsubprocess.Popen(['see', 'alarm.wav'])","sub_path":"Chapter 15/Countdown.py","file_name":"Countdown.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"243813303","text":"import numpy as np\n\n\ndef sensor(location, observe):\n # the sensor model giving probabilities of sensing\n if observe == 'end':\n return int(location == (0, 3) or location == (1, 3))\n if observe == 1:\n if location[1] == 2:\n return 0.9\n if location == (0, 3) or location == (1, 3):\n return 0\n else:\n return 0.1\n if observe == 2:\n if location[1] == 2:\n return 0.1\n if location == (0, 3) or location == (1, 3):\n return 0\n else:\n return 0.9\n\n\ndef sensor2(l, o):\n # test purpose use, always return 1\n return 1\n\n\nclass Pomdp:\n \"\"\"\n An class represents the agent\n \"\"\"\n\n def __init__(self, actions, observations, initial=None):\n self.actions = actions\n self.observations = observations\n if initial is None: # if agent doesn't know initial position\n world = np.ones((3, 4))\n world = world / 9\n world[0, 3] = 0\n world[1, 1] = 0\n world[1, 3] = 0\n print(world)\n self.belief = world\n else: # if agent knows initial position\n world = np.zeros((3, 4))\n world[initial[0], initial[1]] = 1\n print(world)\n self.belief = world\n\n def step(self, action, observe):\n # take one step of the actions, take the observation and update belief\n new_belief = np.zeros((3, 4))\n for i in range(3):\n for j in range(4):\n if i == 1 and j == 1:\n continue\n # get possible states to current updating location\n possible_states = get_adjacent((i, j), action)\n b = 0\n for state in possible_states:\n b += state[1] * self.belief[state[0]]\n new_belief[i, j] = b * sensor((i, j), observe)\n\n self.belief = new_belief\n self.normalize()\n\n def normalize(self):\n # normalize the belief\n self.belief = self.belief / sum(sum(self.belief))\n\n def update(self):\n # take several actions and observations, update belief iteratively\n for i in range(len(self.actions)):\n self.step(self.actions[i], self.observations[i])\n\n def report(self):\n print(self.belief)\n\n\ndef wall_or_terminal(location):\n # return True if grid is wall or terminal state, False if it is non-terminal states\n if iswall(location):\n return True\n return location == (0, 3) or location == (1, 3)\n\n\ndef iswall(location):\n # whether the grid is a wall\n if location[0] < 0 or location[0] > 2:\n return True\n if location[1] < 0 or location[1] > 3:\n return True\n return location == (1, 1)\n\n\ndef get_adjacent(location, action):\n # get possible states from which the agent takes specific action, and its probabilities\n i = location[0]\n j = location[1]\n up = (i - 1, j)\n left = (i, j - 1)\n down = (i + 1, j)\n right = (i, j + 1)\n possible_states = []\n\n if action == 'up':\n if not wall_or_terminal(left):\n possible_states.append((left, 0.1))\n if not wall_or_terminal(right):\n possible_states.append((right, 0.1))\n if not wall_or_terminal(down):\n possible_states.append((down, 0.8))\n p = 0\n if iswall(up):\n p += 0.8\n if iswall(left):\n p += 0.1\n if iswall(right):\n p += 0.1\n # the agent will stop action when reach terminal states\n if not location == (0, 3) and not location == (1, 3):\n possible_states.append((location, p))\n\n if action == 'left':\n if not wall_or_terminal(up):\n possible_states.append((up, 0.1))\n if not wall_or_terminal(down):\n possible_states.append((down, 0.1))\n if not wall_or_terminal(right):\n possible_states.append((right, 0.8))\n p = 0\n if iswall(left):\n p += 0.8\n if iswall(up):\n p += 0.1\n if iswall(down):\n p += 0.1\n # the agent will stop action when reach terminal states\n if not location == (0, 3) and not location == (1, 3):\n possible_states.append((location, p))\n\n if action == 'down':\n if not wall_or_terminal(left):\n possible_states.append((left, 0.1))\n if not wall_or_terminal(right):\n possible_states.append((right, 0.1))\n if not wall_or_terminal(up):\n possible_states.append((up, 0.8))\n p = 0\n if iswall(down):\n p += 0.8\n if iswall(left):\n p += 0.1\n if iswall(right):\n p += 0.1\n # the agent will stop action when reach terminal states\n if not location == (0, 3) and not location == (1, 3):\n possible_states.append((location, p))\n\n if action == 'right':\n if not wall_or_terminal(up):\n possible_states.append((up, 0.1))\n if not wall_or_terminal(down):\n possible_states.append((down, 0.1))\n if not wall_or_terminal(left):\n possible_states.append((left, 0.8))\n p = 0\n if iswall(right):\n p += 0.8\n if iswall(up):\n p += 0.1\n if iswall(down):\n p += 0.1\n # the agent will stop action when reach terminal states\n if not location == (0, 3) and not location == (1, 3):\n possible_states.append((location, p))\n\n return possible_states\n\n\ndef test(actions, obs, initials=None):\n agent = Pomdp(actions, obs, initial=initials)\n agent.update()\n agent.report()\n\n\n# test(['right','right'], [1, 1], initials=(0, 1))\ntest(['up', 'up', 'up'], [2, 2, 2])\ntest(['up', 'up', 'up'], [1, 1, 1])\ntest(['right', 'right', 'up'], [1, 1, 'end'], initials=(0, 1))\ntest(['up', 'right', 'right', 'right'], [2, 2, 1, 1], initials=(2, 0))\n# test(['left', 'left', 'left', 'left', 'left'], [1, 1, 1, 1, 1])\n","sub_path":"POMDP.py","file_name":"POMDP.py","file_ext":"py","file_size_in_byte":5979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531253156","text":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport sklearn_crfsuite\nfrom sklearn_crfsuite import scorers\nfrom sklearn_crfsuite import metrics\nfrom sklearn_crfsuite.metrics import flat_classification_report\n\nfile_path='data/train_2.txt'\n\n\ndef loadInputFile(file_path):\n trainingset = list() # store trainingset [content,content,...]\n position = list() # store position [article_id, start_pos, end_pos, entity_text, entity_type, ...]\n mentions = dict() # store mentions[mention] = Type\n with open(file_path, 'r', encoding='utf8') as f:\n file_text = f.read().encode('utf-8').decode('utf-8-sig')\n datas = file_text.split('\\n\\n--------------------\\n\\n')[:-1]\n for data in datas:\n data = data.split('\\n')\n content = data[0]\n trainingset.append(content)\n annotations = data[1:]\n for annot in annotations[1:]:\n annot = annot.split('\\t') # annot= article_id, start_pos, end_pos, entity_text, entity_type\n position.extend(annot)\n mentions[annot[3]] = annot[4]\n\n return trainingset, position, mentions\n\n\ndef CRFFormatData(trainingset, position, path):\n if (os.path.isfile(path)):\n os.remove(path)\n outputfile = open(path, 'a', encoding='utf-8')\n\n # output file lines\n count = 0 # annotation counts in each content\n tagged = list()\n for article_id in range(len(trainingset)):\n trainingset_split = list(trainingset[article_id])\n while '' or ' ' in trainingset_split:\n if '' in trainingset_split:\n trainingset_split.remove('')\n else:\n trainingset_split.remove(' ')\n start_tmp = 0\n for position_idx in range(0, len(position), 5):\n if int(position[position_idx]) == article_id:\n count += 1\n if count == 1:\n start_pos = int(position[position_idx + 1])\n end_pos = int(position[position_idx + 2])\n entity_type = position[position_idx + 4]\n if start_pos == 0:\n token = list(trainingset[article_id][start_pos:end_pos])\n whole_token = trainingset[article_id][start_pos:end_pos]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n # BIO states\n if token_idx == 0:\n label = 'B-' + entity_type\n else:\n label = 'I-' + entity_type\n\n output_str = token[token_idx] + ' ' + label + '\\n'\n outputfile.write(output_str)\n\n else:\n token = list(trainingset[article_id][0:start_pos])\n whole_token = trainingset[article_id][0:start_pos]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n\n output_str = token[token_idx] + ' ' + 'O' + '\\n'\n outputfile.write(output_str)\n\n token = list(trainingset[article_id][start_pos:end_pos])\n whole_token = trainingset[article_id][start_pos:end_pos]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n # BIO states\n if token[0] == '':\n if token_idx == 1:\n label = 'B-' + entity_type\n else:\n label = 'I-' + entity_type\n else:\n if token_idx == 0:\n label = 'B-' + entity_type\n else:\n label = 'I-' + entity_type\n\n output_str = token[token_idx] + ' ' + label + '\\n'\n outputfile.write(output_str)\n\n start_tmp = end_pos\n else:\n start_pos = int(position[position_idx + 1])\n end_pos = int(position[position_idx + 2])\n entity_type = position[position_idx + 4]\n if start_pos < start_tmp:\n continue\n else:\n token = list(trainingset[article_id][start_tmp:start_pos])\n whole_token = trainingset[article_id][start_tmp:start_pos]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n output_str = token[token_idx] + ' ' + 'O' + '\\n'\n outputfile.write(output_str)\n\n token = list(trainingset[article_id][start_pos:end_pos])\n whole_token = trainingset[article_id][start_pos:end_pos]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n # BIO states\n if token[0] == '':\n if token_idx == 1:\n label = 'B-' + entity_type\n else:\n label = 'I-' + entity_type\n else:\n if token_idx == 0:\n label = 'B-' + entity_type\n else:\n label = 'I-' + entity_type\n\n output_str = token[token_idx] + ' ' + label + '\\n'\n outputfile.write(output_str)\n start_tmp = end_pos\n\n token = list(trainingset[article_id][start_tmp:])\n whole_token = trainingset[article_id][start_tmp:]\n for token_idx in range(len(token)):\n if len(token[token_idx].replace(' ', '')) == 0:\n continue\n\n output_str = token[token_idx] + ' ' + 'O' + '\\n'\n outputfile.write(output_str)\n\n count = 0\n\n output_str = '\\n'\n outputfile.write(output_str)\n ID = trainingset[article_id]\n\n if article_id % 10 == 0:\n print('Total complete articles:', article_id)\n\n # close output file\n outputfile.close()\n\ntrainingset, position, mentions = loadInputFile(file_path)\ndata_path='data/sample.data'\nCRFFormatData(trainingset, position, data_path)\n\ntrainingset2, position2, mentions2 = loadInputFile(\"data/development_2.txt\")\ndata_path2='data/development.data'\nCRFFormatData(trainingset2, position2, data_path2)\n\n\ndef CRF(x_train, y_train, x_test, y_test):\n crf = sklearn_crfsuite.CRF(\n algorithm='lbfgs',\n c1=0.1,\n c2=0.1,\n max_iterations=100,\n all_possible_transitions=True\n )\n print(\"CRF fitting...\")\n crf.fit(x_train, y_train)\n print(\"CRF:\")\n print(crf)\n\n y_pred = crf.predict(x_test)\n print(\"y_pred:\")\n print(y_pred)\n y_pred_mar = crf.predict_marginals(x_test)\n print(\"y_predict_marginals:\")\n print(y_pred_mar)\n\n labels = list(crf.classes_)\n labels.remove('O')\n f1score = metrics.flat_f1_score(y_test, y_pred, average='weighted', labels=labels)\n sorted_labels = sorted(labels,key=lambda name: (name[1:], name[0])) # group B and I results\n print(flat_classification_report(y_test, y_pred, labels=sorted_labels, digits=3))\n\n return y_pred, y_pred_mar, f1score\n\n\n# load pretrained word vectors\n# get a dict of tokens (key) and their pretrained word vectors (value)\n# pretrained word2vec CBOW word vector: https://fgc.stpi.narl.org.tw/activity/videoDetail/4b1141305ddf5522015de5479f4701b1\ndim = 0\nword_vecs = {}\nworking_sign = ['|', '/', '-', '\\\\']\n# open pretrained word vector file\nwith open('data/cna.cbow.cwe_p.tar_g.512d.0.txt') as f:\n for i, line in enumerate(f):\n print(\"\\rLoad pretrained word vectors %s\"%(working_sign[i%len(working_sign)],), end=\"\")\n\n tokens = line.strip().split()\n\n # there 2 integers in the first line: vocabulary_size, word_vector_dim\n if len(tokens) == 2:\n dim = int(tokens[1])\n continue\n\n word = tokens[0]\n vec = np.array([float(t) for t in tokens[1:]])\n word_vecs[word] = vec\n\nprint('\\nvocabulary_size: ',len(word_vecs),' word_vector_dim: ',vec.shape)\n\n# load `train.data` and separate into a list of labeled data of each text\n# return:\n# data_list: a list of lists of tuples, storing tokens and labels (wrapped in tuple) of each text in `train.data`\n# traindata_list: a list of lists, storing training data_list splitted from data_list\n# testdata_list: a list of lists, storing testing data_list splitted from data_list\nfrom sklearn.model_selection import train_test_split\n\n\ndef Dataset(data_path):\n with open(data_path, 'r', encoding='utf-8') as f:\n data = f.readlines() # .encode('utf-8').decode('utf-8-sig')\n data_list, data_list_tmp = list(), list()\n article_id_list = list()\n idx = 0\n for row in data:\n data_tuple = tuple()\n if row == '\\n':\n article_id_list.append(idx)\n idx += 1\n data_list.append(data_list_tmp)\n data_list_tmp = []\n else:\n row = row.strip('\\n').split(' ')\n data_tuple = (row[0], row[1])\n data_list_tmp.append(data_tuple)\n if len(data_list_tmp) != 0:\n data_list.append(data_list_tmp)\n\n # here we random split data into training dataset and testing dataset\n # but you should take `development data` or `test data` as testing data\n # At that time, you could just delete this line,\n # and generate data_list of `train data` and data_list of `development/test data` by this function\n traindata_list, testdata_list, traindata_article_id_list, testdata_article_id_list = \\\n train_test_split(data_list, article_id_list, test_size=0.33, random_state=42)\n\n return data_list, traindata_list, testdata_list, traindata_article_id_list, testdata_article_id_list\n\n# look up word vectors\n# turn each word into its pretrained word vector\n# return a list of word vectors corresponding to each token in train.data\ndef Word2Vector(data_list, embedding_dict):\n embedding_list = list()\n\n # No Match Word (unknown word) Vector in Embedding\n unk_vector=np.random.rand(*(list(embedding_dict.values())[0].shape))\n\n data_list_size = len(data_list)\n for idx_list in range(data_list_size):\n print(\"\\rWord2Vector: %d/%d\"%(idx_list+1, data_list_size), end=\"\")\n embedding_list_tmp = list()\n for idx_tuple in range(len(data_list[idx_list])):\n key = data_list[idx_list][idx_tuple][0] # token\n\n if key in embedding_dict:\n value = embedding_dict[key]\n else:\n value = unk_vector\n embedding_list_tmp.append(value)\n embedding_list.append(embedding_list_tmp)\n\n print()\n return embedding_list\n\n# input features: pretrained word vectors of each token\n# return a list of feature dicts, each feature dict corresponding to each token\ndef Feature(embed_list):\n feature_list = list()\n for idx_list in range(len(embed_list)):\n print(\"\\rFeature: %d/%d\"%(idx_list, len(embed_list)-1), end=\"\")\n\n feature_list_tmp = list()\n for idx_tuple in range(len(embed_list[idx_list])):\n feature_dict = dict()\n for idx_vec in range(len(embed_list[idx_list][idx_tuple])):\n feature_dict['dim_' + str(idx_vec+1)] = embed_list[idx_list][idx_tuple][idx_vec]\n feature_list_tmp.append(feature_dict)\n feature_list.append(feature_list_tmp)\n print()\n\n return feature_list\n\n# get the labels of each tokens in train.data\n# return a list of lists of labels\ndef Preprocess(data_list):\n label_list = list()\n for idx_list in range(len(data_list)):\n print(\"\\rPreprocess: %d/%d\"%(idx_list, len(data_list)-1), end=\"\")\n\n label_list_tmp = list()\n for idx_tuple in range(len(data_list[idx_list])):\n label_list_tmp.append(data_list[idx_list][idx_tuple][1])\n label_list.append(label_list_tmp)\n print()\n\n return label_list\n\n\n# Training\n\ndata_list, traindata_list, testdata_list, traindata_article_id_list, testdata_article_id_list = Dataset(data_path)\n# traindata_list.extend(testdata_list)\n# traindata_article_id_list.extend(testdata_article_id_list)\n\ndata_list2, devdata_list, testdata_list2, devdata_article_id_list, testdata_article_id_list2 = Dataset(data_path2)\ndevdata_list.extend(testdata_list2)\ndevdata_article_id_list.extend(testdata_article_id_list2)\n\n# testdata_list = traindata_list2\n# testdata_article_id_list = traindata_article_id_list2\n\n# Load Word Embedding\ntrainembed_list = Word2Vector(traindata_list, word_vecs)\ntestembed_list = Word2Vector(testdata_list, word_vecs)\ndevembed_list = Word2Vector(devdata_list, word_vecs)\n\n# CRF - Train Data (Augmentation Data)\nprint(\"CRF - Train Data (Augmentation Data)\")\nx_train = Feature(trainembed_list)\ny_train = Preprocess(traindata_list)\n\n# CRF - Test Data (Golden Standard)\nprint(\"CRF - Test Data (Golden Standard)\")\nx_test = Feature(testembed_list)\ny_test = Preprocess(testdata_list)\n\n# CRF - Dev Data (Golden Standard)\n# print(\"CRF - Dev Data (Golden Standard)\")\n# x_test = Feature(devembed_list)\n# y_test = Preprocess(devdata_list)\n\ny_pred, y_pred_mar, f1score = CRF(x_train, y_train, x_test, y_test)\n\n\n# Output data\nprint(\"Output data...\")\noutput = \"article_id\\tstart_position\\tend_position\\tentity_text\\tentity_type\\n\"\ny_pred_size = len(y_pred)\nfor test_id in range(y_pred_size):\n print(\"\\rtest_id: %d/%d\"%(test_id, y_pred_size-1), end=\"\")\n\n pos = 0\n start_pos=None\n end_pos = None\n entity_text = None\n entity_type = None\n\n pred_id_size = len(y_pred[test_id])\n for pred_id in range(pred_id_size):\n print(\"\\r\\tpred_id: %d/%d\" % (pred_id, pred_id_size - 1), end=\"\")\n\n if y_pred[test_id][pred_id][0]=='B':\n start_pos=pos\n entity_type=y_pred[test_id][pred_id][2:]\n elif start_pos is not None \\\n and y_pred[test_id][pred_id][0] == 'I' \\\n and y_pred[test_id][pred_id+1][0] == 'O':\n end_pos=pos\n entity_text=''.join([testdata_list[test_id][position][0]\n for position in range(start_pos,end_pos+1)])\n line=str(testdata_article_id_list[test_id])+'\\t'+str(start_pos)+'\\t'+str(end_pos+1)\\\n +'\\t'+entity_text+'\\t'+entity_type\n output+=line+'\\n'\n pos += 1\nprint()\n\noutput_path='output.tsv'\nwith open(output_path,'w',encoding='utf-8') as f:\n f.write(output)\n\nprint(output)\n","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":15142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348575516","text":"from django.http import HttpResponse\nfrom django.template.loader import render_to_string\nimport hms_app.views.links_left as links_left\nimport json\nimport os\n\n\ndef versions_page(request):\n \"\"\"\n :param request:\n :return:\n \"\"\"\n page_title = \"HMS: Hydrologic Micro Services\"\n keywords = \"HMS, Hydrology, Hydrologic Micro Services, EPA\"\n imports = render_to_string('hms_default_imports.html')\n imports += render_to_string('hms_versions_import.html')\n html = render_to_string('01epa18_default_header.html', {\n 'TITLE': page_title,\n 'URL': str(request.get_host) + request.path,\n 'KEYWORDS': keywords,\n 'IMPORTS': imports,\n 'NOTPUBLIC': False,\n 'DISCLAIMER': None\n }) # Default EPA header\n html += links_left.ordered_list(model='documentation', submodel='version_history')\n vh_path = os.path.join(os.environ['PROJECT_PATH'], 'hms_app', 'views', 'version_history.json')\n with open(vh_path) as f:\n vh = json.load(f)\n page_text = render_to_string(\"04hms_version_history_body.html\", {'VH': vh}, request=request)\n\n html += render_to_string('05hms_body_start.html', {\n 'TITLE': \"HMS Version History\",\n 'DESCRIPTION': page_text\n }) # HMS Workflow main body start\n html += render_to_string('06hms_body_end.html') # HMS Workflow main body end\n html += render_to_string('07hms_splashscripts.html') # EPA splashscripts import\n html += render_to_string('10epa_drupal_footer.html') # Default EPA footer\n response = HttpResponse()\n response.write(html)\n return response","sub_path":"views/version_history.py","file_name":"version_history.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"275190399","text":"\"\"\"\nTests for the auth convenience method\n\"\"\"\n\nfrom unittest.mock import patch, mock_open, call, Mock\nfrom copy import deepcopy\nfrom json import dumps as jdumps\nfrom stat import S_IRUSR, S_IWUSR\n\nimport pytest\n\nfrom vault_anyconfig.vault_anyconfig import VaultAnyConfig\n\n\n@pytest.fixture\ndef gen_vault_creds():\n \"\"\"\n Generates sample vault credentials for use in tests\n \"\"\"\n\n def _gen_vault_creds():\n vault_creds = {\n \"vault_creds\": {\"role_id\": \"test-role-id\", \"secret_id\": \"test-secret-id\", \"auth_method\": \"approle\"}\n }\n return vault_creds\n\n return _gen_vault_creds\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.auth_approle\")\n@patch(\"vault_anyconfig.vault_anyconfig.loads_base\")\ndef test_auto_auth(mock_load, mock_auth_approle, mock_is_authenticated, localhost_client, gen_vault_creds):\n \"\"\"\n Basic test for the auto_auth function\n \"\"\"\n mock_load.return_value = gen_vault_creds()\n mock_is_authenticated.return_value = False\n\n localhost_client.auto_auth(\"config.json\", ac_parser=\"test_parser\")\n\n compare_vault_creds = gen_vault_creds()\n\n mock_load.assert_called_with(\"config.json\", ac_parser=\"test_parser\")\n mock_auth_approle.assert_called_with(\n role_id=compare_vault_creds[\"vault_creds\"][\"role_id\"], secret_id=compare_vault_creds[\"vault_creds\"][\"secret_id\"]\n )\n mock_is_authenticated.assert_called_with()\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\n@patch(\"vault_anyconfig.vault_anyconfig.loads_base\")\ndef test_auto_auth_bad_method(mock_load, mock_is_authenticated, localhost_client, gen_vault_creds):\n \"\"\"\n Test that the exception is thrown as expected when using a bad authentication method\n \"\"\"\n local_vault_creds = gen_vault_creds()\n local_vault_creds[\"vault_creds\"][\"auth_method\"] = \"nothing\"\n mock_load.return_value = local_vault_creds\n mock_is_authenticated.return_value = False\n\n with pytest.raises(NotImplementedError):\n localhost_client.auto_auth(\"config.json\", ac_parser=\"test_parser\")\n\n mock_load.assert_called_with(\"config.json\", ac_parser=\"test_parser\")\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.Client.auth_kubernetes\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\n@patch(\"vault_anyconfig.vault_anyconfig.loads_base\")\ndef test_auto_auth_k8s_method(mock_load, mock_is_authenticated, mock_auth_kubernetes, localhost_client):\n \"\"\"\n Test that the kubernetes method *without* the token path configured is called directly\n \"\"\"\n local_vault_creds = {\"vault_creds\": {\"auth_method\": \"kubernetes\", \"role\": \"test_role\", \"jwt\": \"jwt_string\"}}\n mock_load.return_value = local_vault_creds\n mock_is_authenticated.return_value = False\n\n localhost_client.auto_auth(\"config.json\", ac_parser=\"test_parser\")\n\n mock_load.assert_called_with(\"config.json\", ac_parser=\"test_parser\")\n mock_auth_kubernetes.assert_called_with(role=\"test_role\", jwt=\"jwt_string\")\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.isfile\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.auth_kubernetes\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\n@patch(\"vault_anyconfig.vault_anyconfig.load_base\")\ndef test_auto_auth_k8s_method_token_path(\n mock_load, mock_is_authenticated, mock_auth_kubernetes, mock_isfile, localhost_client\n):\n \"\"\"\n Test that the kubernetes method *with* the token path configured is called with the value from the token file\n \"\"\"\n mock_isfile.return_value = True\n local_vault_creds = {\n \"vault_creds\": {\n \"auth_method\": \"kubernetes\",\n \"role\": \"test_role\",\n \"token_path\": \"/var/run/secrets/kubernetes.io/serviceaccount\",\n }\n }\n mock_load.return_value = local_vault_creds\n mock_is_authenticated.return_value = False\n\n with patch(\"builtins.open\", mock_open(read_data=\"jwt_string\")) as mock_open_handle:\n localhost_client.auto_auth(\"config.json\")\n mock_open_handle.assert_called_once_with(\"/var/run/secrets/kubernetes.io/serviceaccount\", \"r\")\n\n mock_load.assert_called_with(\"config.json\", ac_parser=None)\n mock_auth_kubernetes.assert_called_with(role=\"test_role\", jwt=\"jwt_string\")\n\n\ndef test_auth_with_passthrough():\n \"\"\"\n Tests that the auto_auth will simply be bypassed when using an instance with passthrough\n \"\"\"\n client = VaultAnyConfig()\n assert client.auto_auth(\"config.json\")\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.load_base\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\ndef test_auth_with_already_authenticated(mock_is_authenticated, mock_load, gen_vault_creds, localhost_client):\n \"\"\"\n Tests that the auto_auth will simply be bypassed when the client is already authenticated\n \"\"\"\n mock_load.return_value = gen_vault_creds()\n mock_is_authenticated.return_value = True\n\n assert localhost_client.auto_auth(\"config.json\")\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.Client.is_authenticated\")\ndef test_auth_with_already_authenticated_and_passthrough(mock_is_authenticated):\n \"\"\"\n Tests that the auto_auth will simply be bypassed when using an instance with passthrough set and the client is already authenticated\n \"\"\"\n mock_is_authenticated.return_value = True\n client = VaultAnyConfig()\n assert client.auto_auth(\"config.json\")\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.VaultAnyConfig.auto_auth\")\ndef test_auth_from_file(mock_auto_auth):\n \"\"\"\n Tests that auth_from_file calls auto_auth\n \"\"\"\n client = VaultAnyConfig()\n client.auth_from_file(\"test.json\")\n mock_auto_auth.assert_called_once_with(\"test.json\", ac_parser=None)\n","sub_path":"tests/unit/test_vault_auth.py","file_name":"test_vault_auth.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"375956161","text":"\r\n\r\nfilename = \"input_day12.txt\"\r\ntestfile = \"test_day12.txt\"\r\n\r\ndef parse(file):\r\n return open(file, 'r').read().splitlines()\r\n\r\ndef part1(file):\r\n\r\n direction = 'E'\r\n position = [0,0]\r\n\r\n for entry in file:\r\n if entry[0] == 'E':\r\n position[0]+=int(entry[1:])\r\n elif entry[0] == 'W':\r\n position[0]-=int(entry[1:])\r\n elif entry[0] == 'N':\r\n position[1]+=int(entry[1:])\r\n elif entry[0] == 'S':\r\n position[1]-=int(entry[1:])\r\n\r\n elif entry[0] == 'F':\r\n if direction== 'E':\r\n position[0]+=int(entry[1:])\r\n elif direction == 'W':\r\n position[0]-=int(entry[1:])\r\n elif direction == 'N':\r\n position[1]+=int(entry[1:])\r\n elif direction == 'S':\r\n position[1]-=int(entry[1:])\r\n else:\r\n direction = rotate(direction,entry)\r\n return abs(position[0])+abs(position[1])\r\n\r\ndef rotate(dir,entry):\r\n map90R = {'E':'S', 'S':'W', 'W':'N', 'N':'E' }\r\n map180 = {'E':'W', 'S':'N', 'W':'E', 'N':'S' }\r\n map90L = {'E':'N', 'S':'E', 'W':'S', 'N':'W' }\r\n\r\n if entry[0] == 'R':\r\n if entry[1:] == '90':\r\n return map90R[dir]\r\n elif entry[1:] == '180':\r\n return map180[dir]\r\n elif entry[1:] == '270':\r\n return map90L[dir]\r\n else:\r\n raise AttributeError\r\n else:\r\n if entry[1:] == '90':\r\n return map90L[dir]\r\n elif entry[1:] == '180':\r\n return map180[dir]\r\n elif entry[1:] == '270':\r\n return map90R[dir]\r\n else:\r\n raise AttributeError\r\n\r\ndef part2(file):\r\n\r\n waypoint = [10,1]\r\n position = [0,0]\r\n\r\n for entry in file:\r\n if entry[0] == 'E':\r\n waypoint[0]+=int(entry[1:])\r\n elif entry[0] == 'W':\r\n waypoint[0]-=int(entry[1:])\r\n elif entry[0] == 'N':\r\n waypoint[1]+=int(entry[1:])\r\n elif entry[0] == 'S':\r\n waypoint[1]-=int(entry[1:])\r\n\r\n elif entry[0] == 'F':\r\n position[0]+=waypoint[0]*int(entry[1:])\r\n position[1]+=waypoint[1]*int(entry[1:])\r\n else:\r\n waypoint = rotate_waypoint(waypoint,entry)\r\n return abs(position[0])+abs(position[1])\r\n\r\ndef rotate_waypoint(waypoint,entry):\r\n\r\n if entry[0] == 'R':\r\n if entry[1:] == '90':\r\n return R90(waypoint,entry)\r\n elif entry[1:] == '180':\r\n return R180(waypoint,entry)\r\n elif entry[1:] == '270':\r\n return L90(waypoint,entry)\r\n else:\r\n raise AttributeError\r\n else:\r\n if entry[1:] == '90':\r\n return L90(waypoint,entry)\r\n elif entry[1:] == '180':\r\n return R180(waypoint,entry)\r\n elif entry[1:] == '270':\r\n return R90(waypoint,entry)\r\n else:\r\n raise AttributeError\r\n\r\ndef R90(waypoint,entry):\r\n new_waypoint = [0,0]\r\n new_waypoint[0] = waypoint[1]\r\n new_waypoint[1] = 0-waypoint[0]\r\n return new_waypoint\r\n\r\ndef R180(waypoint,entry):\r\n new_waypoint = [0,0]\r\n new_waypoint[0] = 0-waypoint[0]\r\n new_waypoint[1] = 0-waypoint[1]\r\n return new_waypoint\r\n\r\ndef L90(waypoint,entry):\r\n new_waypoint = [0,0]\r\n new_waypoint[0] = 0-waypoint[1]\r\n new_waypoint[1] = waypoint[0]\r\n return new_waypoint\r\n\r\nif __name__ == \"__main__\":\r\n\r\n test_input = parse(testfile)\r\n input = parse(filename)\r\n\r\n print(part1(test_input))\r\n print(part2(test_input))\r\n\r\n print(part1(input))\r\n print(part2(input))\r\n","sub_path":"day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"358933525","text":"################################################################################\n\n\"\"\"\nPACKAGE \n spell.lib.dummy.tm\nFILE\n tm.py\n \nDESCRIPTION\n TM interface for standalone driver\n\nPROJECT: SPELL\n\n Copyright (C) 2008, 2010 SES ENGINEERING, Luxembourg S.A.R.L.\n\n This file is part of SPELL.\n\n This library is free software: you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, either\n version 3 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License and GNU General Public License (to which the GNU Lesser\n General Public License refers) along with this library.\n If not, see .\n \n\"\"\"\n################################################################################\n\n#*******************************************************************************\n# SPELL imports\n#*******************************************************************************\nfrom spell.utils.log import *\nfrom spell.lib.exception import *\nfrom spell.lang.constants import *\nfrom spell.lang.modifiers import *\nfrom spell.lib.registry import REGISTRY\n\n#*******************************************************************************\n# Local imports\n#*******************************************************************************\n\n#*******************************************************************************\n# System imports\n#*******************************************************************************\nimport os\n\n###############################################################################\n# Module import definition\n\n__all__ = ['TM']\n\n###############################################################################\n# Superclass\nimport spell.lib.adapter.tm\nsuperClass = spell.lib.adapter.tm.TmInterface\n\n###############################################################################\nclass TmInterface( superClass ):\n \n #==========================================================================\n def __init__(self):\n superClass.__init__(self)\n LOG(\"Created\")\n \n #==========================================================================\n def setup(self, ctxConfig, drvConfig):\n superClass.setup(self, ctxConfig, drvConfig)\n LOG(\"Setup standalone TM interface\")\n \n #==========================================================================\n def cleanup(self):\n superClass.cleanup(self)\n LOG(\"Cleanup standalone TM interface\")\n \n #===========================================================================\n def _createTmItem(self, mnemonic, description = \"\"):\n LOG(\"Creating simulated TM item: \" + mnemonic)\n if mnemonic == \"NOTFOUND\":\n raise DriverException(\"Parameter not found\")\n return REGISTRY['SIM'].getTMitem(mnemonic, description)\n \n #==========================================================================\n def _injectItem(self, param, value, config ):\n REGISTRY['SIM'].changeItem(param,value)\n return True\n \n #==========================================================================\n def _refreshItem(self, param, config ):\n name = param.name()\n if name == \"INVALID\":\n param._status = False\n elif name == \"TIMEOUT\":\n import time\n time.sleep(1000)\n\n eng = (config.get(ValueFormat) == ENG)\n \n if eng:\n value = param._engValue\n else:\n value = param._rawValue\n return [value, param._status]\n\n #===========================================================================\n def _setLimit(self, param, limit, value, config ):\n REGISTRY['CIF'].write(\"Set limit for \" + repr(param) + \": \" + repr(limit) + \"=\" + repr(value))\n result = False\n Display(\"Loading limits from a file is not supported\", WARNING)\n return result\n\n #===========================================================================\n def _getLimit(self, param, limit, config ):\n REGISTRY['CIF'].write(\"Get limit for \" + repr(param) + \": \" + repr(limit))\n result = False\n Display(\"Loading limits from a file is not supported\", WARNING)\n return result\n\n #===========================================================================\n def _getLimits(self, param, config ):\n REGISTRY['CIF'].write(\"Get limits for \" + repr(param))\n result = False\n Display(\"Loading limits from a file is not supported\", WARNING)\n return result\n\n #===========================================================================\n def _setLimits(self, param, limits, config ):\n REGISTRY['CIF'].write(\"Set limits for \" + repr(param) + \": \" + repr(limits))\n result = False\n Display(\"Loading limits from a file is not supported\", WARNING)\n return result\n \n #===========================================================================\n def _loadLimits( self, limitsList, useConfig ):\n result = False\n Display(\"Loading limits from a file is not supported\", WARNING)\n return result\n \n################################################################################\n# Interface handle\nTM = TmInterface()\n","sub_path":"spell/tags/1.5.0/drivers/standalone/tm.py","file_name":"tm.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302682984","text":"import subprocess\r\nimport time\r\nimport sys\r\n\r\ndef get_gpu_memory_map():\r\n \"\"\"Get the current gpu usage.\r\n\r\n Returns\r\n -------\r\n usage: dict\r\n Keys are device ids as integers.\r\n Values are memory usage as integers in MB.\r\n \"\"\"\r\n result = subprocess.check_output(\r\n [\r\n 'nvidia-smi', '--query-gpu=memory.free',\r\n '--format=csv,nounits,noheader'\r\n ])\r\n # Convert lines into a dictionary\r\n gpu_memory = [int(x) for x in result.decode(\"utf-8\").strip().split('\\n')]\r\n gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory))\r\n return gpu_memory_map\r\n\r\ndef main():\r\n if len(sys.argv) > 2:\r\n n_gpus = int(sys.argv[2])\r\n else:\r\n n_gpus = 1\r\n\r\n available_gpus = []\r\n while True:\r\n interval = 5 # check every 5 seconds\r\n minimum = int(sys.argv[1])\r\n mm = get_gpu_memory_map()\r\n for k,v in sorted(mm.items(), key = lambda x : x[1], reverse = True):\r\n # print(\"GPU:{} |||| free: {}\".format(k, v))\r\n if v > minimum and (not k in available_gpus):\r\n available_gpus.append(str(k))\r\n if len(available_gpus) >= n_gpus:\r\n print(','.join(available_gpus))\r\n sys.exit(0)\r\n time.sleep(interval) # Delays for 5 seconds.\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"test_cuda_py35.py","file_name":"test_cuda_py35.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592272867","text":"from django.conf.urls import url\r\nfrom robot.views import *\r\n\r\nurlpatterns = [\r\n url(r'^(?P[\\d]+)/sendmsg$', SendMsg.as_view(), name='send_msg'),\r\n url(r'^(?P[\\d]+)/rule/create_or_update$', CreateOrUpdateReplyRuleView.as_view(),\r\n name='create_or_upd_rule'),\r\n url(r'^(?P[\\d]+)/rule/(?P[\\d]+)/delete$', DeleteReplyRuleView.as_view(), name='delete_rule'),\r\n url(r'^(?P[\\d]+)/rule/list$', ReplyRuleListInfoView.as_view(), name='get_rule_list'),\r\n url(r'^(?P[\\d]+)/rule/(?P[\\d]+)/detail$', ReplyRuleDetailInfoView.as_view(),\r\n name='get_rule_detail'),\r\n]\r\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170823273","text":"__author__ = 'Aaron Yang'\n__email__ = 'byang971@usc.edu'\n__date__ = '10/16/2020 5:49 PM'\n\nimport re\nimport json\nimport rltk\n\nSIMILARITY_THRESHOLD = 0.65\nID = 'id'\nTITLE = 'title'\nDATE = 'year'\n\n\ndef read_json(file_path):\n result = dict()\n with open(file_path, 'r', encoding='utf-8') as input_file:\n data = json.loads(input_file.read())\n for item in data:\n result[item[ID]] = (item[TITLE], item[DATE])\n return result\n\n\ndef read_txt(file_path):\n result = list()\n with open(file_path, 'r', encoding='utf-8') as input_file:\n for line in input_file.readlines():\n name1, name2, _ = re.split(\"\\t|\\n\", line)\n result.append((name1, name2))\n\n return result\n\n\ndef compute_similarity(val1, val2, type=None):\n if type == TITLE:\n words1 = set(val1.lower().split(' '))\n words2 = set(val2.lower().split(' '))\n return str(rltk.hybrid_jaccard_similarity(words1, words2))\n elif type == DATE:\n if all([val1, val2]):\n return str(1.0) if val1 == val2 \\\n else str(rltk.levenshtein_similarity(val1, val2))\n else:\n return str(0.5)\n\n\ndef export_2_txt(file_path, data):\n with open(file_path, 'w+', encoding='utf-8') as output_file:\n output_file.writelines(\n [\"\\t\".join(list(item)) + \"\\n\" for item in data])\n\n\nif __name__ == '__main__':\n ds1_file_path = \"./data_source1.json\"\n ds2_file_path = \"./data_source2.json\"\n target_file_path = './same_paper_targets.txt'\n\n ds1_objs = read_json(ds1_file_path)\n ds2_objs = read_json(ds2_file_path)\n\n name_pairs = read_txt(target_file_path)\n\n title_sim_result, year_sim_result = list(), list()\n for name1, name2 in name_pairs:\n obj1 = ds1_objs[name1] if name1 in ds1_objs.keys() else ds2_objs[name1]\n obj2 = ds2_objs[name2] if name2 in ds2_objs.keys() else ds1_objs[name2]\n if obj1 and obj2:\n title_sim_result.append(\n (name1, name2, compute_similarity(obj1[0], obj2[0], type=TITLE)))\n year_sim_result.append(\n (name1, name2, compute_similarity(obj1[1], obj2[1], type=DATE)))\n else:\n title_sim_result.append((name1, name2, \"0\"))\n year_sim_result.append((name1, name2, \"0\"))\n\n title_sim_output_file_path = \"./title_sim_obs.txt\"\n year_sim_output_file_path = \"./years_sim_obs.txt\"\n export_2_txt(title_sim_output_file_path, title_sim_result)\n export_2_txt(year_sim_output_file_path, year_sim_result)\n","sub_path":"ay_hw_6/Bo_Yang_hw06/source/hw06_tasks_1_2_1.py","file_name":"hw06_tasks_1_2_1.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"482346597","text":"\r\ntotalDays = 0\r\ntotalDistance = 0\r\nlastDayRun = 0\r\n\r\nseventhDay = 0\r\nwhile (totalDistance < (110 * 1000 * 1000 + 54 * 1000 + 30 + 2)):\r\n totalDays = totalDays + 1\r\n curDayRun = lastDayRun + 1\r\n seventhDay = seventhDay + 1\r\n totalDaysStr = str(totalDays)\r\n if (seventhDay == 7):\r\n curDayRun = 0\r\n seventhDay = 0\r\n elif (totalDaysStr.count(\"1\") > 0 and totalDaysStr.count(\"3\") > 0):\r\n curDayRun = 0\r\n else:\r\n lastDayRun = curDayRun\r\n totalDistance = totalDistance + curDayRun\r\n\r\nprint(totalDays)\r\n","sub_path":"ScratchPad_PyDev/com.neustar.programming.contest/three/MyMainPyDev2.py","file_name":"MyMainPyDev2.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542285350","text":"import aio_pika\nimport asyncio\nimport contextlib\nimport csv\nfrom datetime import datetime\nimport elasticsearch\nimport io\nimport lazo_index_service\nimport logging\nimport json\nimport os\nimport pickle\nimport prometheus_client\nimport redis\nimport shutil\nfrom tornado.httpclient import AsyncHTTPClient\nimport tornado.ioloop\nfrom tornado.routing import URLSpec\nimport tornado.httputil\nimport tornado.web\nfrom tornado.web import HTTPError, RequestHandler\nimport uuid\nimport zipfile\n\nfrom datamart_augmentation.augmentation import AugmentationError, augment\nfrom datamart_core.common import setup_logging, hash_json, log_future, json2msg\nfrom datamart_core.fscache import cache_get_or_set\nfrom datamart_core.materialize import get_dataset\nimport datamart_profiler\n\nfrom .enhance_metadata import enhance_metadata\nfrom .graceful_shutdown import GracefulApplication, GracefulHandler\nfrom .search import TOP_K_SIZE, ClientError, parse_query, \\\n get_augmentation_search_results, ProfilePostedData\n\n\nlogger = logging.getLogger(__name__)\n\n\nBUCKETS = [0.5, 1.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 300.0, 600.0]\n\nPROM_PROFILE_TIME = prometheus_client.Histogram('req_profile_seconds',\n \"Profile request time\",\n buckets=BUCKETS)\nPROM_PROFILE = prometheus_client.Counter('req_profile_count',\n \"Profile requests\")\nPROM_SEARCH_TIME = prometheus_client.Histogram('req_search_seconds',\n \"Search request time\",\n buckets=BUCKETS)\nPROM_SEARCH = prometheus_client.Counter('req_search_count',\n \"Search requests\")\nPROM_DOWNLOAD_TIME = prometheus_client.Histogram('req_download_seconds',\n \"Download request time\",\n buckets=BUCKETS)\nPROM_DOWNLOAD = prometheus_client.Counter('req_download_count',\n \"Download requests\")\nPROM_DOWNLOAD_ID = prometheus_client.Counter('req_download_id_count',\n \"Download by ID requests\")\nPROM_METADATA_TIME = prometheus_client.Histogram('req_metadata_seconds',\n \"Metadata request time\",\n buckets=BUCKETS)\nPROM_METADATA = prometheus_client.Counter('req_metadata_count',\n \"Metadata requests\")\nPROM_AUGMENT_TIME = prometheus_client.Histogram('req_augment_seconds',\n \"Augment request time\",\n buckets=BUCKETS)\nPROM_AUGMENT = prometheus_client.Counter('req_augment_count',\n \"Augment requests\")\n\n\nclass BaseHandler(RequestHandler):\n \"\"\"Base class for all request handlers.\n \"\"\"\n\n def set_default_headers(self):\n self.set_header('Server', 'Auctus/%s' % os.environ['DATAMART_VERSION'])\n\n def get_json(self):\n type_ = self.request.headers.get('Content-Type', '')\n if not type_.startswith('application/json'):\n self.send_error_json(404, \"Expected JSON\")\n raise HTTPError(400)\n return json.loads(self.request.body.decode('utf-8'))\n\n def send_json(self, obj):\n if isinstance(obj, list):\n obj = {'results': obj}\n elif not isinstance(obj, dict):\n raise ValueError(\"Can't encode %r to JSON\" % type(obj))\n self.set_header('Content-Type', 'application/json; charset=utf-8')\n return self.finish(json.dumps(obj))\n\n def send_error_json(self, status, message):\n logger.info(\"Sending error %s JSON: %s\", status, message)\n self.set_status(status)\n return self.send_json({'error': message})\n\n def prepare(self):\n super(BaseHandler, self).prepare()\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Access-Control-Allow-Methods', 'POST')\n self.set_header('Access-Control-Allow-Headers', 'Content-Type')\n\n def options(self):\n # CORS pre-flight\n self.set_status(204)\n return self.finish()\n\n http_client = AsyncHTTPClient(defaults=dict(user_agent=\"Datamart\"))\n\n\ndef get_data_profile_from_es(es, dataset_id):\n try:\n data_profile = es.get('datamart', dataset_id)['_source']\n except elasticsearch.NotFoundError:\n return None\n\n # Get Lazo sketches from Elasticsearch\n # FIXME: Add support for this in Lazo instead\n for col in data_profile['columns']:\n try:\n sketch = es.get(\n 'lazo',\n '%s__.__%s' % (dataset_id, col['name']),\n )['_source']\n except elasticsearch.NotFoundError:\n pass\n else:\n col['lazo'] = dict(\n n_permutations=int(sketch['n_permutations']),\n hash_values=[int(e) for e in sketch['hash']],\n cardinality=int(sketch['cardinality']),\n )\n\n return data_profile\n\n\nclass Profile(BaseHandler, GracefulHandler, ProfilePostedData):\n @PROM_PROFILE_TIME.time()\n def post(self):\n PROM_PROFILE.inc()\n\n data = self.get_body_argument('data', None)\n if 'data' in self.request.files:\n data = self.request.files['data'][0].body\n elif data is not None:\n data = data.encode('utf-8')\n\n if data is None:\n return self.send_error_json(\n 400,\n \"Please send 'data' as a file, using multipart/form-data\",\n )\n\n logger.info(\"Got profile\")\n\n try:\n data_profile, data_hash = self.handle_data_parameter(data)\n except ClientError as e:\n return self.send_error_json(400, str(e))\n\n return self.send_json(dict(\n data_profile,\n version=os.environ['DATAMART_VERSION'],\n token=data_hash,\n ))\n\n\nclass Search(BaseHandler, GracefulHandler, ProfilePostedData):\n @PROM_SEARCH_TIME.time()\n def post(self):\n PROM_SEARCH.inc()\n\n type_ = self.request.headers.get('Content-type', '')\n data = None\n data_id = None\n data_profile = None\n if type_.startswith('application/json'):\n query = self.get_json()\n elif (type_.startswith('multipart/form-data') or\n type_.startswith('application/x-www-form-urlencoded')):\n # Get the query document\n query = self.get_body_argument('query', None)\n if query is None and 'query' in self.request.files:\n query = self.request.files['query'][0].body.decode('utf-8')\n if query is not None:\n query = json.loads(query)\n\n # Get the data\n data = self.get_body_argument('data', None)\n if 'data' in self.request.files:\n data = self.request.files['data'][0].body\n elif data is not None:\n data = data.encode('utf-8')\n\n # Get a reference to a dataset in the index\n data_id = self.get_body_argument('data_id', None)\n if 'data_id' in self.request.files:\n data_id = self.request.files['data_id'][0].body.decode('utf-8')\n\n # Get the data sketch JSON\n data_profile = self.get_body_argument('data_profile', None)\n if data_profile is None and 'data_profile' in self.request.files:\n data_profile = self.request.files['data_profile'][0].body\n data_profile = data_profile.decode('utf-8')\n if data_profile is not None:\n # Data profile can optionally be just the hash\n if len(data_profile) == 40 and '{' not in data_profile:\n data_profile = self.application.redis.get(\n 'profile:' + data_profile,\n )\n if data_profile:\n data_profile = pickle.loads(data_profile)\n else:\n return self.send_error_json(\n 404,\n \"Data profile token expired\",\n )\n else:\n data_profile = json.loads(data_profile)\n\n elif (type_.startswith('text/csv') or\n type_.startswith('application/csv')):\n query = None\n data = self.request.body\n else:\n return self.send_error_json(\n 400,\n \"Either use multipart/form-data to send the 'query' JSON and \"\n \"'data' file (or 'data_profile' JSON), or use \"\n \"application/json to send a query alone, or use text/csv to \"\n \"send data alone\",\n )\n\n if sum(1 for e in [data, data_id, data_profile] if e is not None) > 1:\n return self.send_error_json(\n 400,\n \"Please only provide one input dataset (either 'data', \" +\n \"'data_id', or 'data_profile')\",\n )\n\n logger.info(\"Got search, content-type=%r%s%s%s%s\",\n type_.split(';')[0],\n ', query' if query else '',\n ', data' if data else '',\n ', data_id' if data_id else '',\n ', data_profile' if data_profile else '')\n\n # parameter: data\n if data is not None:\n try:\n data_profile, _ = self.handle_data_parameter(data)\n except ClientError as e:\n return self.send_error_json(400, str(e))\n\n # parameter: data_id\n if data_id:\n data_profile = get_data_profile_from_es(\n self.application.elasticsearch,\n data_id,\n )\n if data_profile is None:\n return self.send_error_json(400, \"No such dataset\")\n\n # parameter: query\n query_args_main = list()\n query_sup_functions = list()\n query_sup_filters = list()\n tabular_variables = list()\n if query:\n try:\n (\n query_args_main,\n query_sup_functions, query_sup_filters,\n tabular_variables,\n ) = parse_query(query)\n except ClientError as e:\n return self.send_error_json(400, str(e))\n\n # At least one of them must be provided\n if not query_args_main and not data_profile:\n return self.send_error_json(\n 400,\n \"At least one of 'data' or 'query' must be provided\",\n )\n\n if not data_profile:\n hits = self.application.elasticsearch.search(\n index='datamart',\n body={\n 'query': {\n 'bool': {\n 'must': query_args_main,\n },\n },\n },\n size=TOP_K_SIZE,\n )['hits']['hits']\n\n results = []\n for h in hits:\n meta = h.pop('_source')\n results.append(dict(\n id=h['_id'],\n score=h['_score'],\n metadata=meta,\n augmentation={\n 'type': 'none',\n 'left_columns': [],\n 'left_columns_names': [],\n 'right_columns': [],\n 'right_columns_names': []\n },\n supplied_id=None,\n supplied_resource_id=None\n ))\n else:\n results = get_augmentation_search_results(\n self.application.elasticsearch,\n self.application.lazo_client,\n data_profile,\n query_args_main,\n query_sup_functions,\n query_sup_filters,\n tabular_variables,\n ignore_datasets=[data_id] if data_id is not None else [],\n )\n results = [enhance_metadata(result) for result in results]\n\n # Private API for the frontend, don't want clients to rely on it\n if self.get_query_argument('_parse_sample', ''):\n for result in results:\n sample = result['metadata'].get('sample', None)\n if sample:\n result['sample'] = list(csv.reader(io.StringIO(sample)))\n\n return self.send_json(results)\n\n\nclass RecursiveZipWriter(object):\n def __init__(self, write):\n self._write = write\n self._zip = zipfile.ZipFile(self, 'w')\n\n def write_recursive(self, src, dst=''):\n if os.path.isdir(src):\n for name in os.listdir(src):\n self.write_recursive(os.path.join(src, name),\n dst + '/' + name if dst else name)\n else:\n self._zip.write(src, dst)\n\n def write(self, data):\n self._write(data)\n return len(data)\n\n def flush(self):\n return\n\n def close(self):\n self._zip.close()\n\n\nclass BaseDownload(BaseHandler):\n def read_format(self):\n format = self.get_query_argument('format', 'csv')\n format_options = {}\n for n, v in self.request.query_arguments.items():\n if n.startswith('format_'):\n if len(v) != 1:\n self.send_error_json(\n 400,\n \"Multiple occurrences of format option %r\" % n[7:],\n )\n raise HTTPError(400)\n format_options[n[7:]] = self.decode_argument(v[0])\n return format, format_options\n\n async def send_dataset(self, dataset_id, metadata,\n format='csv', format_options=None):\n materialize = metadata.get('materialize', {})\n\n # If there's a direct download URL\n if ('direct_url' in materialize and\n format == 'csv' and not materialize.get('convert')):\n if format_options:\n return self.send_error_json(400, \"Invalid output options\")\n # Redirect the client to it\n logger.info(\"Sending redirect to direct_url\")\n return self.redirect(materialize['direct_url'])\n else:\n # We want to catch exceptions from get_dataset(), without catching\n # exceptions from inside the with block\n # https://docs.python.org/3/library/contextlib.html#catching-exceptions-from-enter-methods\n stack = contextlib.ExitStack()\n try:\n dataset_path = stack.enter_context(\n get_dataset(\n metadata, dataset_id,\n format=format, format_options=format_options,\n )\n )\n except Exception:\n await self.send_error_json(500, \"Materializer reports failure\")\n raise\n with stack:\n if zipfile.is_zipfile(dataset_path):\n self.set_header('Content-Type', 'application/zip')\n self.set_header(\n 'Content-Disposition',\n 'attachment; filename=\"%s.zip\"' % dataset_id)\n logger.info(\"Sending ZIP...\")\n else:\n self.set_header('Content-Type', 'application/octet-stream')\n self.set_header('X-Content-Type-Options', 'nosniff')\n self.set_header('Content-Disposition',\n 'attachment; filename=\"%s\"' % dataset_id)\n logger.info(\"Sending file...\")\n with open(dataset_path, 'rb') as fp:\n BUFSIZE = 40960\n buf = fp.read(BUFSIZE)\n while buf:\n self.write(buf)\n if len(buf) != BUFSIZE:\n break\n buf = fp.read(BUFSIZE)\n await self.flush()\n return self.finish()\n\n\nclass DownloadId(BaseDownload, GracefulHandler):\n @PROM_DOWNLOAD_TIME.time()\n def get(self, dataset_id):\n PROM_DOWNLOAD_ID.inc()\n\n format, format_options = self.read_format()\n\n # Get materialization data from Elasticsearch\n try:\n metadata = self.application.elasticsearch.get(\n 'datamart', dataset_id\n )['_source']\n except elasticsearch.NotFoundError:\n return self.send_error_json(404, \"No such dataset\")\n\n return self.send_dataset(dataset_id, metadata, format, format_options)\n\n\nclass Download(BaseDownload, GracefulHandler, ProfilePostedData):\n @PROM_DOWNLOAD_TIME.time()\n def post(self):\n PROM_DOWNLOAD.inc()\n\n type_ = self.request.headers.get('Content-type', '')\n\n task = None\n data = None\n format, format_options = self.read_format()\n if type_.startswith('application/json'):\n task = self.get_json()\n elif (type_.startswith('multipart/form-data') or\n type_.startswith('application/x-www-form-urlencoded')):\n task = self.get_body_argument('task', None)\n if task is None and 'task' in self.request.files:\n task = self.request.files['task'][0].body.decode('utf-8')\n if task is not None:\n task = json.loads(task)\n data = self.get_body_argument('data', None)\n if 'data' in self.request.files:\n data = self.request.files['data'][0].body\n elif data is not None:\n data = data.encode('utf-8')\n if 'format' in self.request.files:\n return self.send_error_json(\n 400,\n \"Sending 'format' in the POST data is no longer \"\n \"supported, please use query parameters\",\n )\n if task is None:\n return self.send_error_json(\n 400,\n \"Either use multipart/form-data to send the 'data' file and \"\n \"'task' JSON, or use application/json to send 'task' alone\",\n )\n\n logger.info(\"Got POST download %s data\",\n \"without\" if data is None else \"with\")\n\n # materialize augmentation data\n metadata = task['metadata']\n\n if not data:\n return self.send_dataset(\n task['id'], metadata, format, format_options,\n )\n else:\n # data\n try:\n data_profile, _ = self.handle_data_parameter(data)\n except ClientError as e:\n return self.send_error_json(400, str(e))\n\n # first, look for possible augmentation\n search_results = get_augmentation_search_results(\n es=self.application.elasticsearch,\n lazo_client=self.application.lazo_client,\n data_profile=data_profile,\n query_args_main=None,\n query_sup_functions=None,\n query_sup_filters=None,\n tabular_variables=None,\n dataset_id=task['id'],\n union=False\n )\n\n if not search_results:\n return self.send_error_json(\n 400,\n \"The Datamart dataset referenced by 'task' cannot augment \"\n \"'data'\",\n )\n\n task = search_results[0]\n\n with get_dataset(metadata, task['id'], format='csv') as newdata:\n # perform augmentation\n logger.info(\"Performing half-augmentation with supplied data\")\n new_path = augment(\n io.BytesIO(data),\n newdata,\n data_profile,\n task,\n return_only_datamart_data=True\n )\n # FIXME: This always sends in D3M format\n\n # send a zip file\n self.set_header('Content-Type', 'application/zip')\n self.set_header(\n 'Content-Disposition',\n 'attachment; filename=\"augmentation.zip\"')\n logger.info(\"Sending ZIP...\")\n writer = RecursiveZipWriter(self.write)\n writer.write_recursive(new_path)\n writer.close()\n shutil.rmtree(os.path.abspath(os.path.join(new_path, '..')))\n\n\nclass Metadata(BaseHandler, GracefulHandler):\n @PROM_METADATA_TIME.time()\n def get(self, dataset_id):\n PROM_METADATA.inc()\n\n es = self.application.elasticsearch\n try:\n metadata = es.get('datamart', dataset_id)['_source']\n except elasticsearch.NotFoundError:\n # Check alternate index\n try:\n record = es.get('pending', dataset_id)['_source']\n except elasticsearch.NotFoundError:\n return self.send_error_json(404, \"No such dataset\")\n else:\n result = {\n 'id': dataset_id,\n 'status': record['status'],\n 'metadata': record['metadata'],\n }\n if 'error' in record:\n result['error'] = record['error']\n else:\n result = {\n 'id': dataset_id,\n 'status': 'indexed',\n 'metadata': metadata,\n }\n result = enhance_metadata(result)\n\n return self.send_json(result)\n\n head = get\n\n\nclass Augment(BaseHandler, GracefulHandler, ProfilePostedData):\n @PROM_AUGMENT_TIME.time()\n def post(self):\n PROM_AUGMENT.inc()\n\n type_ = self.request.headers.get('Content-type', '')\n if not type_.startswith('multipart/form-data'):\n return self.send_error_json(400, \"Use multipart/form-data to send \"\n \"the 'data' file and 'task' JSON\")\n\n task = self.get_body_argument('task', None)\n if task is None and 'task' in self.request.files:\n task = self.request.files['task'][0].body.decode('utf-8')\n if task is None:\n return self.send_error_json(400, \"Missing 'task' JSON\")\n task = json.loads(task)\n\n data = self.get_body_argument('data', None)\n if data is not None:\n data = data.encode('utf-8')\n elif 'data' in self.request.files:\n data = self.request.files['data'][0].body\n\n data_id = self.get_body_argument('data_id', None)\n if 'data_id' in self.request.files:\n data_id = self.request.files['data_id'][0].body.decode('utf-8')\n\n columns = self.get_body_argument('columns', None)\n if 'columns' in self.request.files:\n columns = self.request.files['columns'][0].body.decode('utf-8')\n if columns is not None:\n columns = json.loads(columns)\n\n logger.info(\"Got augmentation, content-type=%r\", type_.split(';')[0])\n\n # data\n if data_id is not None and data is not None:\n return self.send_error_json(\n 400,\n \"Please only provide one input dataset \" +\n \"(either 'data' or 'data_id')\",\n )\n elif data_id is not None:\n data_profile = get_data_profile_from_es(\n self.application.elasticsearch,\n data_id,\n )\n data_hash = None\n if data_profile is None:\n return self.send_error_json(400, \"No such dataset\")\n elif data is not None:\n try:\n data_profile, data_hash = self.handle_data_parameter(data)\n except ClientError as e:\n return self.send_error_json(400, str(e))\n else:\n return self.send_error_json(400, \"Missing 'data'\")\n\n # materialize augmentation data\n metadata = task['metadata']\n\n # no augmentation task provided -- will first look for possible augmentation\n if 'augmentation' not in task or task['augmentation']['type'] == 'none':\n logger.info(\"No task, searching for augmentations\")\n search_results = get_augmentation_search_results(\n es=self.application.elasticsearch,\n lazo_client=self.application.lazo_client,\n data_profile=data_profile,\n query_args_main=None,\n query_sup_functions=None,\n query_sup_filters=None,\n tabular_variables=None,\n dataset_id=task['id'],\n union=False\n )\n\n if search_results:\n # get first result\n task = search_results[0]\n logger.info(\"Using first of %d augmentation results: %r\",\n len(search_results), task['id'])\n else:\n return self.send_error_json(400,\n \"The Datamart dataset referenced \"\n \"by 'task' cannot augment 'data'\")\n\n key = hash_json(\n task=task,\n supplied_data=data_hash or data_id,\n version=os.environ['DATAMART_VERSION'],\n columns=columns,\n )\n\n def create_aug(cache_temp):\n try:\n with contextlib.ExitStack() as stack:\n # Get augmentation data\n newdata = stack.enter_context(\n get_dataset(metadata, task['id'], format='csv'),\n )\n # Get input data if it's a reference to a dataset\n if data_id:\n data_file = stack.enter_context(\n get_dataset(data_profile, data_id, format='csv'),\n )\n else:\n data_file = io.BytesIO(data)\n # Perform augmentation\n logger.info(\"Performing augmentation with supplied data\")\n augment(\n data_file,\n newdata,\n data_profile,\n task,\n columns=columns,\n destination=cache_temp,\n )\n except AugmentationError as e:\n return self.send_error_json(400, str(e))\n\n with cache_get_or_set('/cache/aug', key, create_aug) as path:\n # send a zip file\n self.set_header('Content-Type', 'application/zip')\n self.set_header(\n 'Content-Disposition',\n 'attachment; filename=\"augmentation.zip\"')\n logger.info(\"Sending ZIP...\")\n writer = RecursiveZipWriter(self.write)\n # FIXME: This will write the whole thing to Tornado's buffer\n # Maybe compressing to disk and streaming that file is better?\n writer.write_recursive(path)\n writer.close()\n\n return self.finish()\n\n\nclass Upload(BaseHandler):\n async def post(self):\n if 'file' in self.request.files:\n file = self.request.files['file'][0]\n metadata = dict(\n filename=file.filename,\n name=self.get_body_argument('name', None),\n source='upload',\n materialize=dict(identifier='datamart.upload',\n date=datetime.utcnow().isoformat() + 'Z'),\n )\n description = self.get_body_argument('description', None)\n if description:\n metadata['description'] = description\n dataset_id = 'datamart.upload.%s' % uuid.uuid4().hex\n\n # Write file to shared storage\n dataset_dir = os.path.join('/datasets', dataset_id)\n os.mkdir(dataset_dir)\n try:\n with open(os.path.join(dataset_dir, 'main.csv'), 'wb') as fp:\n fp.write(file.body)\n except Exception:\n shutil.rmtree(dataset_dir)\n raise\n elif self.get_body_argument('address', None):\n # Check the URL\n address = self.get_body_argument('address')\n response = await self.http_client.fetch(address, raise_error=False)\n if response.code != 200:\n return self.send_error_json(\n 400, \"Invalid URL ({} {})\".format(\n response.code, response.reason,\n ),\n )\n\n # Metadata with 'direct_url' in materialization info\n metadata = dict(\n name=self.get_body_argument('name', None),\n source='upload',\n materialize=dict(identifier='datamart.url',\n direct_url=address,\n date=datetime.utcnow().isoformat() + 'Z'),\n )\n description = self.get_body_argument('description', None)\n if description:\n metadata['description'] = description\n dataset_id = 'datamart.url.%s' % uuid.uuid4().hex\n else:\n return self.send_error_json(400, \"No file\")\n\n # Add to alternate index\n self.application.elasticsearch.index(\n 'pending',\n dict(\n status='queued',\n metadata=metadata,\n date=datetime.utcnow().isoformat(),\n source='upload',\n materialize=metadata['materialize'],\n ),\n id=dataset_id,\n )\n\n # Publish to the profiling queue\n await self.application.profile_exchange.publish(\n json2msg(\n dict(\n id=dataset_id,\n metadata=metadata,\n ),\n # Lower priority than on-demand datasets, but higher than base\n priority=1,\n ),\n '',\n )\n\n return self.send_json({'id': dataset_id})\n\n\nclass Statistics(BaseHandler):\n def get(self):\n return self.send_json({\n 'recent_discoveries': self.application.recent_discoveries,\n 'sources_counts': self.application.sources_counts,\n })\n\n\nclass Version(BaseHandler):\n def get(self):\n return self.send_json({\n 'version': os.environ['DATAMART_VERSION'].lstrip('v'),\n 'min_profiler_version': datamart_profiler.__version__,\n })\n\n\nclass Health(BaseHandler):\n def get(self):\n if self.application.is_closing:\n self.set_status(503, reason=\"Shutting down\")\n return self.finish('shutting down')\n else:\n return self.finish('ok')\n\n\nclass Application(GracefulApplication):\n def __init__(self, *args, es, redis_client, lazo, **kwargs):\n super(Application, self).__init__(*args, **kwargs)\n\n self.is_closing = False\n\n self.elasticsearch = es\n self.redis = redis_client\n self.lazo_client = lazo\n self.nominatim = os.environ['NOMINATIM_URL']\n self.channel = None\n\n log_future(asyncio.get_event_loop().create_task(self._amqp()), logger)\n\n async def _amqp(self):\n connection = await aio_pika.connect_robust(\n host=os.environ['AMQP_HOST'],\n port=int(os.environ['AMQP_PORT']),\n login=os.environ['AMQP_USER'],\n password=os.environ['AMQP_PASSWORD'],\n )\n self.channel = await connection.channel()\n await self.channel.set_qos(prefetch_count=1)\n\n # Declare profiling exchange (to publish datasets via upload)\n self.profile_exchange = await self.channel.declare_exchange(\n 'profile',\n aio_pika.ExchangeType.FANOUT,\n )\n\n # Start statistics-fetching coroutine\n self.sources_counts = {}\n self.recent_discoveries = []\n log_future(\n asyncio.get_event_loop().create_task(self.update_statistics()),\n logger,\n should_never_exit=True,\n )\n\n async def update_statistics(self):\n http_client = AsyncHTTPClient()\n while True:\n try:\n # Get counts from coordinator\n response = await http_client.fetch(\n 'http://coordinator:8003/api/statistics',\n )\n statistics = json.loads(response.body.decode('utf-8'))\n except Exception:\n logger.exception(\"Can't get statistics from coordinator\")\n else:\n self.sources_counts = statistics['sources_counts']\n self.recent_discoveries = statistics['recent_discoveries']\n\n await asyncio.sleep(60)\n\n def log_request(self, handler):\n if handler.request.path == '/health':\n return\n super(Application, self).log_request(handler)\n\n\ndef make_app(debug=False):\n es = elasticsearch.Elasticsearch(\n os.environ['ELASTICSEARCH_HOSTS'].split(',')\n )\n redis_client = redis.Redis(host=os.environ['REDIS_HOST'])\n lazo_client = lazo_index_service.LazoIndexClient(\n host=os.environ['LAZO_SERVER_HOST'],\n port=int(os.environ['LAZO_SERVER_PORT'])\n )\n\n return Application(\n [\n URLSpec('/profile', Profile, name='profile'),\n URLSpec('/search', Search, name='search'),\n URLSpec('/download/([^/]+)', DownloadId, name='download_id'),\n URLSpec('/download', Download, name='download'),\n URLSpec('/metadata/([^/]+)', Metadata, name='metadata'),\n URLSpec('/augment', Augment, name='augment'),\n URLSpec('/upload', Upload, name='upload'),\n URLSpec('/statistics', Statistics, name='statistics'),\n URLSpec('/version', Version, name='version'),\n URLSpec('/health', Health, name='health'),\n ],\n debug=debug,\n es=es,\n redis_client=redis_client,\n lazo=lazo_client\n )\n\n\ndef main():\n setup_logging()\n debug = os.environ.get('DEBUG') not in (None, '', 'no', 'off', 'false')\n prometheus_client.start_http_server(8000)\n logger.info(\"Startup: apiserver %s\", os.environ['DATAMART_VERSION'])\n if debug:\n logger.error(\"Debug mode is ON\")\n\n app = make_app(debug)\n app.listen(8002, xheaders=True, max_buffer_size=2147483648)\n loop = tornado.ioloop.IOLoop.current()\n loop.start()\n","sub_path":"apiserver/apiserver/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":34577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578735492","text":"\"\"\"\n2. Написать программу сложения и умножения двух шестнадцатеричных чисел.\nПри этом каждое число представляется как массив, элементы которого это цифры\nчисла. Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и\n[‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’],\nпроизведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].\n\"\"\"\n\n\ndef hex_operations(num1, num2):\n \"\"\"\n Производит сложение и умножения двух шестнадцатеричных чисел.\n При этом каждое число представляется как массив, элементы которого это цифры\n числа.\n \"\"\"\n\n # lambda-функция переводит данные из типа список в тип int(16)\n list_to_hex = lambda x: int(''.join(x), 16)\n\n num1_int = list_to_hex(num1)\n num2_int = list_to_hex(num2)\n\n nums_sum = list(f\"{num1_int + num2_int:X}\")\n nums_mult = list(f\"{num1_int * num2_int:X}\")\n\n return nums_sum, nums_mult\n\n\nif __name__ == '__main__':\n mass1 = ['A', '2']\n mass2 = ['C', '4', 'F']\n print(hex_operations(mass1, mass2)) # Выводит (['C', 'F', '1'], ['7', 'C', '9', 'F', 'E'])\n\n","sub_path":"Lesson_5/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245885317","text":"# -*- coding: utf-8 -*-\n\n# SIMPLE STATISTICAL PROFILER for Python\n# https://github.com/bdarnell/plop\n\n# To profile an entire Python script, run:\n# python -m plop.collector myscript.py\n# This will write the profile to `./profiles/[timestamp]`. Add `-f flamegraph` for flamegraph output.\n\n# To use the viewer for the default .plop output format, run:\n# python -m plop.viewer --datadir=demo/profiles\n# and go to http://localhost:8888. For .flame format, see https://github.com/brendangregg/FlameGraph\n\n\ndef my_func():\n a = [1] * (10 ** 6)\n b = [2] * (2 * 10 ** 7)\n del b\n return a\n\n\n# Perform profiling\nmy_func()\n","sub_path":"examples/10_plop.py","file_name":"10_plop.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446242529","text":"# Copyright (c) 2020 Anastasiia Birillo, Elena Lyulina\n\nfrom __future__ import annotations\n\nimport math\nfrom typing import Tuple\n\nfrom src.main.util.log_util import log_and_raise_error\nfrom src.main.solution_space.consts import USERS_NUMBER\nfrom src.main.solution_space.serialized_code import AnonTree\nfrom src.main.canonicalization.diffs.gumtree import GumTreeDiff\nfrom src.main.solution_space.path_finder.path_finder import log\nfrom src.main.solution_space.path_finder_test_system import doc_param\nfrom src.main.canonicalization.canonicalization import are_asts_equal\nfrom src.main.solution_space.measured_tree.measured_tree import IMeasuredTree\n\n\nclass MeasuredTreeV7(IMeasuredTree):\n _age_w = 0.15\n _exp_w = 0.15\n _diffs_w = 0.5\n _users_w = -0.5\n _rollback_w = 4.0\n _rate_w = 0.3\n _structure_w = 6.5\n\n # def _IMeasuredTree__init_diffs_number_and_rollback_probability(self) -> None:\n # self._diffs_number, delete_edits = GumTreeDiff \\\n # .get_diffs_and_delete_edits_numbers(self.user_tree.tree_file, self.candidate_tree.tree_file)\n # self._rollback_probability = delete_edits\n\n def _IMeasuredTree__init_diffs_number_and_rollback_probability(self) -> None:\n if are_asts_equal(self._user_tree.tree, self._candidate_tree.tree):\n self._diffs_number = math.inf\n self._rollback_probability = 0\n else:\n diffs_number, delete_edits = GumTreeDiff \\\n .get_diffs_and_delete_edits_numbers(self.user_tree.tree_file, self.candidate_tree.tree_file)\n self._diffs_number = diffs_number if diffs_number != 0 else math.inf\n self._rollback_probability = 0 if diffs_number == 0 else delete_edits / diffs_number\n\n @doc_param(_diffs_w, _users_w, _rate_w, _rollback_w, _age_w, _exp_w, _structure_w)\n def _IMeasuredTree__calculate_distance_to_user(self) -> Tuple[float, str]:\n \"\"\"\n Finds distance as weighted sum of:\n 1. diffs_number, weight: {0}\n 2. users_count, weight: {1}\n 3. rate reducing, weight: {2}\n 4. rollback probability, weight: {3}\n 5. same structure, weight: {6}\n 6. (if possible) abs difference between age, weight: {4}\n 7. (if possible) abs difference between exp, weight: {5}\n \"\"\"\n distance = self._diffs_w * self._diffs_number \\\n + self._users_w * self.users_number / USERS_NUMBER[self._task] \\\n + self._rate_w * (self.user_tree.rate - self.candidate_tree.rate) \\\n + self._rollback_w * self.rollback_probability \\\n + self._structure_w * (self.user_tree.ast_structure - self.candidate_tree.ast_structure)\n distance_info = f'(diffs: {self._diffs_w} * {self._diffs_number}) + ' \\\n f'(users: {self._users_w} * {self.users_number} / {USERS_NUMBER[self._task]}) + ' \\\n f'(rate: {self._rate_w} * ({self.user_tree.rate} - {self.candidate_tree.rate})) + ' \\\n f'(rollback: {self._rollback_w} * {self.rollback_probability}) + ' \\\n f'(structure: {self._structure_w} * {self.user_tree.ast_structure - self.candidate_tree.ast_structure})'\n\n trees = [self.user_tree, self.candidate_tree]\n if AnonTree.have_non_empty_attr('_age_median', trees):\n distance += self._age_w * abs(self.user_tree.age_median - self.candidate_tree.age_median)\n distance_info += f' + (age: {self._age_w} * |{self.user_tree.age_median} - {self.candidate_tree.age_median}|)'\n if AnonTree.have_non_empty_attr('_experience_median', trees):\n distance += self._exp_w * abs(self.user_tree.experience_median - self.candidate_tree.experience_median)\n distance_info += f' + (exp: {self._exp_w} * |{self.user_tree.experience_median} - {self.candidate_tree.experience_median}|)'\n\n return distance, distance_info\n\n def __lt__(self, o: object):\n \"\"\"\n 1. If o is not an instance of class, raise an error\n 2. Compare distance\n \"\"\"\n if not isinstance(o, MeasuredTreeV7):\n log_and_raise_error(f'The object {o} is not {self.__class__} class', log)\n return self._distance_to_user < o._distance_to_user\n","sub_path":"src/main/solution_space/measured_tree/measured_tree_v_7.py","file_name":"measured_tree_v_7.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"477585751","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Tasvirci by OsmanDE\n# github.com/OsmanDE/Tasvirci\n\nfrom photogrid_dialog import Ui_GridDialog\nfrom gridsetup_dialog import Ui_GridSetupDialog\nfrom PyQt5.QtCore import Qt, QObject, pyqtSignal, QRect, QPoint\nfrom PyQt5.QtGui import QPixmap, QPainter, QImageReader, QPen\nfrom PyQt5.QtWidgets import QApplication, QLabel, QDialog, QHBoxLayout, QSizePolicy, QFileDialog, QMessageBox\n\nhelptext = '''Resim koymak için bir resim thumbnaili seç. Seçtiğin fotoğrafı koymak için boş kutulardan birine tıkla.\n\nEğer gridi daha farklı resimlerden oluşturmak istiyorsan fotoğraf ekleme kısmını seç.\n\nYeni bir resim seçerek eski resmi kaldırabilirsin.'''\n\nclass GridDialog(QDialog, Ui_GridDialog):\n def __init__(self, pixmap, parent):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n self.resize(1020, 640)\n layout = QHBoxLayout(self.scrollAreaWidgetContents)\n layout.setContentsMargins(0, 0, 0, 0)\n self.gridPaper = GridPaper(self)\n layout.addWidget(self.gridPaper)\n self.thumbnailGr = ThumbnailGroup(self)\n thumbnail = Thumbnail(pixmap, self.frame)\n self.verticalLayout.addWidget(thumbnail)\n thumbnail.select(True)\n thumbnail.clicked.connect(self.gridPaper.setPhoto)\n self.thumbnailGr.append(thumbnail)\n self.configureBtn.clicked.connect(self.configure)\n self.addPhotoBtn.clicked.connect(self.addPhoto)\n self.checkAddBorder.clicked.connect(self.gridPaper.toggleBorder)\n self.helpBtn.clicked.connect(self.showHelp)\n self.gridPaper.photo = pixmap\n\n def configure(self):\n dialog = GridSetupDialog(self)\n if dialog.exec_()==1:\n self.gridPaper.paperW = dialog.paperW\n self.gridPaper.paperH = dialog.paperH\n self.gridPaper.rows = dialog.rows\n self.gridPaper.cols = dialog.cols\n self.gridPaper.W = dialog.W\n self.gridPaper.H = dialog.H\n self.gridPaper.DPI = dialog.DPI\n self.gridPaper.setupGrid()\n\n def addPhoto(self):\n filefilter = \"JPEG Images (*.jpg *jpeg);;PNG Images (*.png);;All Files (*)\"\n filepath, sel_filter = QFileDialog.getOpenFileName(self, 'Seyahatname - Resmi Aç', '', filefilter) \n if filepath == '' : return\n image_reader = QImageReader(filepath)\n image_reader.setAutoTransform(True)\n pm = QPixmap.fromImageReader(image_reader)\n if not pm.isNull() :\n thumbnail = Thumbnail(pm, self.frame)\n self.verticalLayout.addWidget(thumbnail)\n thumbnail.clicked.connect(self.gridPaper.setPhoto)\n self.thumbnailGr.append(thumbnail)\n\n def accept(self):\n # Create final grid when ok is clicked\n self.gridPaper.createFinalGrid()\n QDialog.accept(self)\n\n def showHelp(self):\n global helptext\n QMessageBox.about(self, 'Nasıl Grid Oluştururum?', helptext)\n\nclass Thumbnail(QLabel):\n clicked = pyqtSignal(QPixmap)\n def __init__(self, pixmap, parent):\n QLabel.__init__(self, parent)\n self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.photo = pixmap\n self.setPixmap(pixmap.scaledToWidth(100))\n \n def mousePressEvent(self, ev):\n self.clicked.emit(self.photo)\n\n def select(self, select):\n if select:\n pm = self.photo.scaledToWidth(100)\n painter = QPainter(pm)\n pen = QPen(Qt.blue)\n pen.setWidth(4)\n painter.setPen(pen)\n painter.drawRect(2, 2 , 100-4, pm.height()-4)\n painter.end()\n self.setPixmap(pm)\n else:\n self.setPixmap(self.photo.scaledToWidth(100))\n\nclass ThumbnailGroup(QObject):\n def __init__(self, parent):\n QObject.__init__(self, parent)\n self.thumbnails = []\n\n def append(self, thumbnail):\n self.thumbnails.append(thumbnail)\n thumbnail.clicked.connect(self.selectThumbnail)\n\n def selectThumbnail(self):\n for thumbnail in self.thumbnails:\n thumbnail.select(False)\n self.sender().select(True)\n\nclass GridPaper(QLabel):\n def __init__(self, parent):\n QLabel.__init__(self, parent)\n self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.setMouseTracking(True)\n self.pixmap_dict = {}\n self.add_border = True\n self.DPI = 300\n self.paperW, self.paperH = 1800, 1200\n self.W, self.H = 413, 531\n self.cols, self.rows = 4, 2 \n self.setupGrid()\n\n def setupGrid(self):\n self.boxes = [] \n self.spacingX, self.spacingY = (self.paperW-self.cols*self.W)/(self.cols+1), (self.paperH-self.rows*self.H)/(self.rows+1)\n screenDPI = QApplication.desktop().logicalDpiX()\n self.scale = screenDPI/self.DPI\n w, h = self.W*self.scale, self.H*self.scale\n spacing_x, spacing_y = self.spacingX*self.scale, self.spacingY*self.scale\n for i in range(self.cols*self.rows):\n row, col = i//self.cols, i%self.cols \n box = QRect(spacing_x+col*(spacing_x+w), spacing_y+row*(spacing_y+h), w-1, h-1)\n self.boxes.append(box)\n fg = QPixmap(self.paperW*self.scale, self.paperH*self.scale)\n fg.fill()\n painter = QPainter(fg)\n for box in self.boxes:\n painter.drawRect(box)\n painter.end()\n self.setPixmap(fg)\n\n def setPhoto(self, pixmap):\n self.photo = pixmap\n\n def toggleBorder(self, ok):\n self.add_border = ok\n grid = self.pixmap()\n painter = QPainter(grid)\n for index in self.pixmap_dict:\n topleft = self.boxes[index].topLeft()\n pm = self.pixmap_dict[index].scaled(self.W*self.scale, self.H*self.scale, 1, 1)\n painter.drawPixmap(topleft, pm)\n if ok: painter.drawRect(topleft.x(), topleft.y(), pm.width()-1, pm.height()-1)\n painter.end()\n self.setPixmap(grid)\n\n def mouseMoveEvent(self, ev):\n for box in self.boxes:\n if box.contains(ev.pos()):\n self.setCursor(Qt.PointingHandCursor)\n return\n self.setCursor(Qt.ArrowCursor)\n\n def mousePressEvent(self, ev):\n blank_pm = QPixmap(self.W*self.scale, self.H*self.scale)\n blank_pm.fill()\n for box in self.boxes:\n if box.contains(ev.pos()):\n topleft = box.topLeft()\n pm = self.photo.scaled(self.W*self.scale, self.H*self.scale, 1, 1)\n bg = self.pixmap()\n painter = QPainter(bg)\n painter.drawPixmap(topleft, blank_pm)\n painter.drawPixmap(topleft, pm)\n if self.add_border:\n painter.drawRect(topleft.x(), topleft.y(), pm.width()-1, pm.height()-1)\n painter.end()\n self.setPixmap(bg)\n self.pixmap_dict[self.boxes.index(box)] = self.photo\n break\n\n def createFinalGrid(self):\n self.photo_grid = QPixmap(self.paperW, self.paperH)\n self.photo_grid.fill()\n painter = QPainter(self.photo_grid)\n for index in self.pixmap_dict:\n row, col = index//self.cols, index%self.cols\n topleft = QPoint(self.spacingX+col*(self.spacingX+self.W), self.spacingY+row*(self.spacingY+self.H))\n pm = self.pixmap_dict[index].scaled(self.W, self.H, 1, 1)\n painter.drawPixmap(topleft, pm)\n if self.add_border:\n painter.drawRect(topleft.x(), topleft.y(), pm.width()-1, pm.height()-1)\n painter.end()\n\n\nclass GridSetupDialog(QDialog, Ui_GridSetupDialog):\n def __init__(self, parent):\n QDialog.__init__(self, parent)\n self.setupUi(self)\n\n def accept(self):\n units = [1, 1/2.54, 1/25.4]\n DPI = self.spinDPI.value()\n unit_mult = units[self.paperSizeUnit.currentIndex()]\n paperW = self.spinPaperWidth.value()*unit_mult*DPI\n paperH = self.spinPaperHeight.value()*unit_mult*DPI\n W, H = self.spinPhotoWidth.value()*DPI/2.54, self.spinPhotoHeight.value()*DPI/2.54\n rows1, cols1 = int(paperH//H), int(paperW//W)\n rows2, cols2 = int(paperW//H), int(paperH//W)\n if rows1*cols1 >= rows2*cols2:\n self.paperW = paperW\n self.paperH = paperH\n self.rows = rows1\n self.cols = cols1\n else:\n self.paperW = paperH\n self.paperH = paperW\n self.rows = rows2\n self.cols = cols2\n self.W = W\n self.H = H\n self.DPI = DPI\n QDialog.accept(self)\n","sub_path":"photogrid.py","file_name":"photogrid.py","file_ext":"py","file_size_in_byte":8684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241398491","text":"import socket\nimport threading\nimport traceback\nimport loop_players as lp\nimport pygame as pg\n\n#Inserindo variáveis necessarias\nWIDTH, HEIGHT = 1366, 768\nscreen = pg.display.set_mode((WIDTH, HEIGHT))\n\nWHITE = (255, 255, 255)\nBABYBLUE = (216, 227, 250)\nBLACK = (0, 0, 0)\nBLUE = (5, 17, 44)\nDARKBLUE = (66, 191, 254)\n\nBORDERWIDTH = 1\n\nFPS = 100\n\n\ndef cw(name_player,room): \n #HOSTPORT = ('200.239.165.217', 17010)\n HOSTPORT = ('localhost', 12000)\n \n # encode/decode mensanges para o servidor\n def messageDecode(data):\n decoded = data.decode()\n t = int(decoded[0]) # primeiro byte e o tipo\n b = decoded[1:] # resto e o corpo\n \n return t, b\n \n def messageEncode(messageType, messageBody):\n return bytes(str(messageType) + messageBody, 'utf-8')\n \n # classe que represneta o servidor\n class Server (threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.socket = None\n \n def connectServer(self, ip, port):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((ip, port))\n \n def run(self):\n self.isRunning = True\n while self.isRunning:\n data = self.socket.recv(2048) # esperando por ate 2048 bytes...\n messageType, messageBody = messageDecode(data)\n \n # a decodificacao e feita por meio do 'messageType'\n if messageType == 1: # mensagem\n print(messageBody)\n \n def send(self, data):\n self.socket.sendall(data)\n \n def closeServer(self):\n self.isRunning = False\n \n server = Server()\n \n server.connectServer(HOSTPORT[0], HOSTPORT[1])\n server.start()\n \n username = name_player\n nroom = room\n \n if \".\" in username:\n username = username.replace(\".\",\"\")\n \n usernamenroom = username + '.' + nroom\n \n server.send(messageEncode(1, usernamenroom))\n \n data = server.socket.recv(2048) # esperando por ate 2048 bytes...\n messageType, messageBody = messageDecode(data)\n if messageBody == 'kika':\n server.closeServer()\n\n print('Entrando...')\n lp.loop_players(FPS, screen, WHITE, BLACK, BABYBLUE, BLUE, DARKBLUE, BORDERWIDTH, WIDTH, HEIGHT, True, False)\n\n ''' \n while True:\n try:\n msg = input('Digite a mensagem: ')\n if msg == 'sair':\n server.send(messageEncode(3, msg))\n else:\n server.send(messageEncode(2, msg))\n \n except Exception as e:\n print(traceback.format_exc())\n ''' \n server.closeServer()\n server.join()\n","sub_path":"program/cw2.py","file_name":"cw2.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"318200575","text":"import configparser\nimport os\nimport select\nimport socket\nimport sys\nimport json\nimport threading\nimport time\nfrom PyQt5.QtWidgets import QApplication, QMessageBox\nfrom PyQt5.QtCore import QTimer\nfrom server.server_ui import MainWindow, HistoryWindow, ConfigWindow, gui_create_model, create_stat_model\nimport logs.log_configs.server_log_config\nimport logging\nfrom logs.log_configs.server_log_config import stream_handler # - для теста в консоли.\nfrom decorators import log\n\nfrom common.default_conf import *\nfrom common.utils import get_message, send_message\n\nfrom metaclasses import ServerVerifier\n\nfrom server.server_db import ServerStorage\n\nlogger = logging.getLogger('messengerapp_server')\n\n# stream_handler.setLevel(logging.INFO) # - для теста в консоли.\n\n# Флаг о том, что был подключён новый пользователь нужен, чтобы не мучать базу данных\n# постоянными запросами на обновление\nnew_connection = False\nconnection_lock = threading.Lock()\n\n\n# дескриптор на проверку порта\nclass CheckPort:\n def __set__(self, instance, value):\n try:\n if not 1024 < value < 65536:\n raise ValueError\n except ValueError:\n logger.critical('В качастве порта может быть указано только число в диапазоне от 1024 до 65535.')\n sys.exit(1)\n instance.__dict__[self.my_attr] = value\n\n def __set_name__(self, owner_class, my_attr):\n self.my_attr = my_attr\n\n\nclass Server (threading.Thread, metaclass=ServerVerifier):\n\n port = CheckPort()\n\n def __init__(self, listen_address, listen_port, server_database):\n self.address = listen_address\n self.port = listen_port\n self.clients = []\n self.messages = []\n self.account_names_list = {}\n self.server_database = server_database\n super().__init__()\n\n def socket(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.bind((self.address, self.port))\n self.sock.settimeout(0.5)\n self.sock.listen(MAX_CONNECTIONS)\n\n def run(self):\n self.socket()\n\n while True:\n try:\n client, client_address = self.sock.accept()\n except socket.error:\n pass\n else:\n logger.info(f'Установлено соедение с клиентом {client_address}')\n self.clients.append(client)\n\n get_message_list = []\n send_message_list = []\n # self.errors_list = []\n\n try:\n if self.clients:\n get_message_list, send_message_list, errors_list = select.select(self.clients, self.clients, [], 0)\n except OSError:\n pass\n\n if get_message_list:\n info = 'good client' # ЗАГЛУШКА ДЛЯ ТЕСТА ПЕРЕДАЧИ ДОП ПАРАМЕТРА В БАЗУ\n for client_with_message in get_message_list:\n try:\n self.process_client_message(get_message(client_with_message),\n self.messages, client_with_message,\n self.clients, self.account_names_list, info)\n except Exception as ex:\n print(ex)\n logger.info(f'Потеряно соединение с клиентом {client_with_message.getpeername()}.')\n self.clients.remove(client_with_message)\n\n for msg in self.messages:\n try:\n self.prc_message(msg, self.account_names_list, send_message_list)\n except Exception:\n logger.info(f'Потеряно соединение с клиентом {msg[TO][ACCOUNT_NAME]}.')\n self.clients.remove(self.account_names_list[msg[TO][ACCOUNT_NAME]])\n del self.account_names_list[msg[TO][ACCOUNT_NAME]]\n self.messages.clear()\n\n # обработка сообщения\n @log\n def prc_message(self, msg, account_names_list, send_message_list):\n if msg[FROM][ACCOUNT_NAME] in account_names_list and \\\n account_names_list[msg[TO][ACCOUNT_NAME]] in send_message_list:\n send_message(account_names_list[msg[TO][ACCOUNT_NAME]], msg)\n\n logger.info(f'Cообщение отправлено пользователю {msg[TO][ACCOUNT_NAME]} '\n f'от пользователя {msg[FROM][ACCOUNT_NAME]}.')\n elif msg[TO][ACCOUNT_NAME] in account_names_list and \\\n account_names_list[msg[TO][ACCOUNT_NAME]] not in send_message_list:\n raise ConnectionError\n else:\n logger.error(\n f'Пользователь {msg[TO][ACCOUNT_NAME]} не существует, отправка сообщения невозможна.')\n\n # пришем сообщения от пользователя\n @log\n def process_client_message(self, message, list_of_messages, client_with_message, clients_list, account_names_list,\n info):\n global new_connection\n logger.debug(f'Разбор сообщения от клиента {client_with_message}')\n\n if ACTION in message and message[ACTION] == PRESENCE and TIME in message \\\n and USER in message:\n if message[USER][ACCOUNT_NAME] not in account_names_list.keys():\n self.account_names_list[message[USER][ACCOUNT_NAME]] = client_with_message\n client_ip_address, client_port = client_with_message.getpeername()\n info = message[USER][INFO]\n # print(client_ip_address, client_port, info)\n self.server_database.user_login(message[USER][ACCOUNT_NAME], info, client_ip_address, client_port)\n answer = send_message(client_with_message, {RESPONSE: 200})\n logger.info(answer)\n with connection_lock:\n new_connection = True\n else:\n response = {RESPONSE: 400, ERROR: 'Пользователь с таким именем уже существует.'}\n send_message(client_with_message, response)\n clients_list.remove(client_with_message)\n client_with_message.close()\n return\n elif ACTION in message and message[ACTION] == MESSAGE and \\\n TIME in message and MESSAGE_CLIENT in message and \\\n FROM in message and TO in message:\n # print(message[FROM][ACCOUNT_NAME], message[TO][ACCOUNT_NAME])\n return list_of_messages.append(message)\n\n elif ACTION in message and message[ACTION] == GET_CONTACTS and \\\n TIME in message and USER in message and \\\n self.account_names_list[message[USER][ACCOUNT_NAME]] == client_with_message:\n response = {RESPONSE: 202, 'contacts_list': None}\n response['contacts_list'] = self.server_database.contacts_list(message[USER][ACCOUNT_NAME])\n send_message(client_with_message, response)\n\n elif ACTION in message and message[ACTION] == ADD_CONTACT and \\\n TIME in message and USER in message and CONTACT in message and \\\n self.account_names_list[message[USER][ACCOUNT_NAME]] == client_with_message:\n self.server_database.add_contact(message[USER][ACCOUNT_NAME], message[CONTACT][ACCOUNT_NAME])\n response = {RESPONSE: 200}\n # print(message)\n # print(message[USER][ACCOUNT_NAME], message[CONTACT][ACCOUNT_NAME])\n # print(response)\n send_message(client_with_message, response)\n\n elif ACTION in message and message[ACTION] == REMOVE_CONTACT and \\\n TIME in message and USER in message and CONTACT in message and \\\n self.account_names_list[message[USER][ACCOUNT_NAME]] == client_with_message:\n self.server_database.remove_contact(message[USER][ACCOUNT_NAME], message[CONTACT][ACCOUNT_NAME])\n response = {RESPONSE: 200}\n send_message(client_with_message, response)\n\n elif ACTION in message and message[ACTION] == USERS_LIST and USER in message \\\n and self.account_names_list[message[USER][ACCOUNT_NAME]] == client_with_message:\n response = {RESPONSE: 202, 'users_list': [user[0] for user in self.server_database.select_users()]}\n send_message(client_with_message, response)\n\n elif ACTION in message and message[ACTION] == 'exit' and ACCOUNT_NAME in message:\n clients_list.remove(account_names_list[message[ACCOUNT_NAME]])\n self.server_database.user_logout(message[ACCOUNT_NAME])\n clients_list[message[ACCOUNT_NAME]].close()\n del clients_list[message[ACCOUNT_NAME]]\n with connection_lock:\n new_connection = True\n return\n\n else:\n error = send_message(client_with_message, {\n RESPONSE: 400,\n ERROR: 'Bad Request'\n })\n logger.info(error)\n return error\n\n\n@log\ndef load_params(default_port, default_address):\n # валидация и загрузка порта\n try:\n if '-p' in sys.argv:\n listen_port = int(sys.argv[sys.argv.index('-p') + 1])\n else:\n listen_port = default_port\n except IndexError:\n logger.error('После параметра -\\'p\\' необходимо указать номер порта.')\n sys.exit(1)\n\n # валидация и загрузка адреса\n try:\n if '-address' in sys.argv:\n listen_address = sys.argv[sys.argv.index('-address') + 1]\n else:\n listen_address = default_address\n\n except IndexError:\n logger.error('После параметра -\\'address\\'- необходимо указать адрес, который будет слушать сервер.')\n sys.exit(1)\n return listen_address, listen_port\n\n\ndef make_sock_get_msg_send_answer():\n config = configparser.ConfigParser()\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n config.read(f\"{dir_path}/{'server_config.ini'}\")\n\n # Загрузка параметров командной строки, если нет параметров, то задаём\n # значения по умоланию.\n listen_address, listen_port = load_params(\n int(config['SETTINGS']['default_port']), config['SETTINGS']['listen_address'])\n\n # Инициализация базы данных\n server_database = ServerStorage(\n os.path.join(\n config['SETTINGS']['database_path'],\n config['SETTINGS']['database_file']))\n\n # -p 8081 -address 192.168.1.109 (при проверке: работает как через терминал, так и через PyCharm)\n # listen_address, listen_port = load_params()\n # server_database = ServerStorage()\n\n server = Server(listen_address, listen_port, server_database)\n server.daemon = True\n server.start()\n\n # Добавим команды для получения результатов из базы (работает пока не запущен хотя бы один клиент)\n while True:\n cmd = input('Введите комманду: ')\n if cmd == 'users':\n for usr in sorted(server_database.select_users()):\n print(f'Пользователь с логином {usr[0]}, дата создания - {usr[1]}, последний вход - {usr[1]}')\n elif cmd == 'active_users':\n for usr in sorted(server_database.select_active_users()):\n print(f'Активный пользователь {usr[0]}, ip - {usr[1]}, port - {usr[2]}, дата и время входа - {usr[3]}')\n elif cmd == 'history':\n usr = input('Введите username/login пользователя: ')\n for hist in sorted(server_database.login_history_user(usr)):\n print(f'Юзер - {hist[0]}, дата входа - {hist[1]}, ip - {hist[2]}, port - {hist[3]}')\n elif cmd == 'contacts':\n usr = input('Введите username/login пользователя: ')\n for contact in sorted(server_database.contacts_list(usr)):\n print(f'Контакт - {contact}')\n elif cmd == 'add_contact':\n owner = input('Кому добавить новый контакт: ')\n new_contact = input('Введите username нового контакта: ')\n server_database.add_contact(owner, new_contact)\n elif cmd == 'exit':\n print('Завершение работы')\n break\n elif cmd == 'help':\n print('users - список юзеров,\\n'\n 'active_users - список активных юзеров,\\n'\n 'history - история посещений юзера\\n'\n 'contacts - cписок контактов юзера\\n'\n 'add_contact - добавить контакт\\n' \n 'exit - выход')\n else:\n print('Неверная команда, ведите help для получения списка команд')\n\n # создание графического интерфейса\n server_app = QApplication(sys.argv)\n main_window = MainWindow()\n main_window.statusBar().showMessage('Server working')\n main_window.active_users_table.setModel(gui_create_model(server_database))\n main_window.active_users_table.resizeColumnsToContents()\n main_window.active_users_table.resizeRowsToContents()\n\n # функция для обновления списка активных юзеров в зависимости от флага (новый коннекшн или нет)\n def list_update():\n global new_connection\n if new_connection:\n main_window.active_users_table.setModel(\n gui_create_model(server_database))\n main_window.active_users_table.resizeColumnsToContents()\n main_window.active_users_table.resizeRowsToContents()\n with connection_lock:\n new_connection = False\n\n # функция, создающяя окно со статистикой клиентов\n def show_statistics():\n global stat_window\n stat_window = HistoryWindow()\n stat_window.login_history_table.setModel(create_stat_model(server_database))\n stat_window.login_history_table.resizeColumnsToContents()\n stat_window.login_history_table.resizeRowsToContents()\n stat_window.show()\n\n # Функция сохранения настроек сервера\n def save_server_config():\n global config_window\n message = QMessageBox()\n config['SETTINGS']['database_path'] = config_window.db_path.text()\n config['SETTINGS']['database_file'] = config_window.db_file.text()\n try:\n port = int(config_window.port.text())\n except ValueError:\n message.warning(config_window, 'Ошибка', 'Порт должен быть числом')\n else:\n config['SETTINGS']['listen_address'] = config_window.ip.text()\n if 1023 < port < 65536:\n config['SETTINGS']['default_port'] = str(port)\n print(port)\n with open('server/server_config.ini', 'w') as conf:\n config.write(conf)\n message.information(\n config_window, 'OK', 'Настройки успешно сохранены!')\n else:\n message.warning(\n config_window,\n 'Ошибка', 'Порт должен быть от 1024 до 65535')\n\n # Функция создающяя окно с настройками сервера\n def server_config():\n global config_window\n config_window = ConfigWindow()\n config_window.db_path.insert(config['SETTINGS']['database_path'])\n config_window.db_file.insert(config['SETTINGS']['database_file'])\n config_window.port.insert(config['SETTINGS']['default_port'])\n config_window.ip.insert(config['SETTINGS']['listen_address'])\n config_window.save_button.clicked.connect(save_server_config)\n\n # таймер для обновления списка раз в секунду\n timer = QTimer()\n timer.timeout.connect(list_update)\n timer.start(1000)\n\n # Связь кнопок с процедурами\n main_window.refresh_button.triggered.connect(list_update)\n main_window.show_history_button.triggered.connect(show_statistics)\n main_window.config_button.triggered.connect(server_config)\n\n # Запуск GUI\n server_app.exec_()\n\n\nif __name__ == '__main__':\n make_sock_get_msg_send_answer()\n","sub_path":"homework/hw05/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":17267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166289016","text":"# Copyright 2017 IBM Corporation\n# Copyright 2017 The Johns Hopkins University\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\nfrom setuptools import setup, find_packages\nfrom os import path\nfrom codecs import open\nfrom objectfs import __version__\n\nROOT = path.abspath(path.dirname(__file__))\n\n# read the requirements file\nwith open(path.join(ROOT, 'setup', 'requirements.txt'), encoding='utf-8') as file_handle:\n install_requires = file_handle.read().split('\\n')\n\n# read the long description readme file\nwith open(path.join(ROOT, 'README.md'), encoding='utf-8') as file_handle:\n long_description = file_handle.read()\n\n# run setup\nsetup(\n name = 'objectfs',\n version = __version__,\n description = 'A file system with the power of an object store',\n long_description = long_description,\n url = 'https://github.com/objectfs/objectfs',\n author = 'Kunal Lillaney',\n author_email = 'lillaney@jhu.edu',\n maintainer = 'Kunal Lillaney',\n maintainer_email = 'lillaney@jhu.edu',\n license = 'Apache 2.0',\n scripts = ['objectfs/objectfs_cli'],\n data_files = [\n ('/etc/', ['objectfs/settings.ini'])\n ],\n packages = find_packages(exclude=['docs', 'tests', 'benchmark', 'util']),\n include_package_data = True,\n install_requires = install_requires\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488056805","text":"class Solution(object):\n def shortestDistance(self, words, word1, word2):\n \"\"\"\n :type words: List[str]\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n p1 = p2 = -1\n ans = (1 << 31) - 1\n for i in xrange(len(words)):\n if words[i] == word1:\n p1 = i\n if words[i] == word2:\n p2 = i\n if p1 != -1 and p2 != -1:\n ans = min(ans, abs(p1 - p2))\n return ans","sub_path":"src/main/java/com/practice/python/shortest_word_distance.py","file_name":"shortest_word_distance.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338979346","text":"\"\"\"empty message\n\nRevision ID: 6252e3daa359\nRevises: 0594699df53c\nCreate Date: 2017-03-11 20:25:25.499733\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6252e3daa359'\ndown_revision = '0594699df53c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_unique_constraint(None, 'user_profile', ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user_profile', type_='unique')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/6252e3daa359_.py","file_name":"6252e3daa359_.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39946942","text":"\"\"\"\nCreated on: 27/04/2018\nAuthor: Alejandro Alvarez Ayllon\n\"\"\"\nimport numpy as np\n\nfrom nnpz import NnpzFlag\nfrom nnpz.utils import Logging\n\nlog = Logging.getLogger(__name__)\n\n\ndef _apply_weight_calculator(fcalculator, target_i_list, ref_obj, target_data, result_flags):\n target_obj = target_data[target_i_list]\n target_flags = [result_flags[i] for i in target_i_list]\n nan_masks = [np.logical_not(np.isnan(target_obj_i[:, 0])) for target_obj_i in target_obj]\n return [fcalculator(ref_obj_i[mask_i, :], target_obj_i[mask_i, :], flag) for\n ref_obj_i, target_obj_i, mask_i, flag in\n zip(ref_obj, target_obj, nan_masks, target_flags)]\n\n\nclass ReferenceSampleWeightCalculator(object):\n\n def __init__(self, weight_phot_provider, weight_calculator, weight_calculator_alt):\n \"\"\"\n Constructor\n Args:\n weight_phot_provider: An object implementing WeightPhotometryProvider\n weight_calculator: An object implementing WeightCalculatorInterface\n \"\"\"\n self._weight_phot_provider = weight_phot_provider\n self._weight_calculator = weight_calculator\n self._weight_calculator_alt = weight_calculator_alt\n\n def computeWeights(self, affected, target_data, result_flags, progress_listener):\n \"\"\"\n Args:\n affected: The output of AffectedSourcesFinder.findAffected\n target_data: Target catalog data\n result_flags: A list of NnpzFlag, one per entry on the target catalog\n progress_listener: An object implementing ProgressListener\n\n Returns:\n A map where the keys are the indices of the reference sample objects\n and values are lists of the computed weight of the reference sample object per each\n object in the target catalog\n \"\"\"\n # Note that we iterate the affected map in increasing order of the reference\n # sample indices. This is done to use as much the cache of the disk, by accessing\n # the SEDs sequentially.\n weights = {}\n\n # All weights of a target object are 0 if their sum is 0\n weight_sum_per_target = np.zeros(target_data.shape[0], dtype=np.float32)\n\n # A map where the key is a tuple (ref index, target_index), and the value\n # an alternative weight precomputed if the preferred one was 0\n alt_weights = {}\n\n # A map to keep track of the references that are a neighbor of a given target\n alt_neighbors = {}\n\n filters_shape = target_data.shape[1:]\n for progress, ref_i in enumerate(sorted(affected)):\n progress_listener(progress)\n\n # Affected targets\n target_i_list = affected[ref_i]\n\n # Get the reference sample object photometry to use for the weight calculation\n ref_obj = np.ndarray((len(target_i_list),) + filters_shape, dtype=np.float32)\n for i, target_i in enumerate(target_i_list):\n flag = result_flags[target_i]\n ref_obj[i, :, :] = self._weight_phot_provider(ref_i, target_i, flag)\n\n weights[ref_i] = _apply_weight_calculator(\n self._weight_calculator, target_i_list, ref_obj, target_data, result_flags\n )\n\n for target_i, w in zip(target_i_list, weights[ref_i]):\n weight_sum_per_target[target_i] += w\n\n # Since we have the photometry calculated here already, and\n # computing it is expensive, for weights that are 0 with the preferred method\n # we apply an alternative method, and keep it for later, in case all weights\n # for a given target are 0\n if self._weight_calculator_alt:\n target_i_zero_weights = [\n target_i for target_i, ref_w in zip(target_i_list, weights[ref_i]) if ref_w == 0\n ]\n ref_obj_zero_weights = [\n ref_obj for ref_obj, ref_w in zip(ref_obj, weights[ref_i]) if ref_w == 0\n ]\n new_weights = _apply_weight_calculator(\n self._weight_calculator_alt, target_i_zero_weights, ref_obj_zero_weights, target_data, result_flags\n )\n for target_i, w in zip(target_i_zero_weights, new_weights):\n alt_weights[(ref_i, target_i)] = w\n if target_i not in alt_neighbors:\n alt_neighbors[target_i] = list()\n alt_neighbors[target_i].append(ref_i)\n\n # For target objects with *all* their weights being 0, override with the alternative\n all_zero_mask = (weight_sum_per_target == 0)\n all_zero_i = np.arange(len(weight_sum_per_target))[all_zero_mask]\n\n if len(all_zero_i) > 0:\n log.debug('{} objects with all weights set to 0, using alternative weight'.format(len(all_zero_i)))\n log.debug(all_zero_i)\n\n for target_i in all_zero_i:\n # Some target entries may not even have any neighbor\n for ref_i in alt_neighbors.get(target_i, []):\n offset = affected[ref_i].index(target_i)\n weights[ref_i][offset] = alt_weights[(ref_i, target_i)]\n result_flags[target_i] |= NnpzFlag.AlternativeWeightFlag\n\n return weights\n","sub_path":"nnpz/framework/ReferenceSampleWeightCalculator.py","file_name":"ReferenceSampleWeightCalculator.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"74656231","text":"def in_array(array1, array2):\n result = []\n for a1 in array1:\n for a2 in array2:\n if a2.count(a1): \n result.append(a1)\n break\n return result\n\na1 = [\"tarp\", \"mice\", \"bull\"]\na2 = [\"lively\", \"alive\", \"harp\", \"sharp\", \"armstrong\"]\nprint(in_array(a1, a2))","sub_path":"Codewars/sorter.py","file_name":"sorter.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17889854","text":"from typing import Iterable\n\nimport numpy as np\nfrom bnk.tensor import HSpace, QTensor, zero, one\n\n\nclass ReducedHSpace(HSpace):\n def __init__(self, org_eigenstates, name=None, key=None):\n super().__init__(len(org_eigenstates), name, key)\n \n org_eigenstates = tuple(org_eigenstates)\n \n transform = zero\n for i, org_eigenstate in enumerate(org_eigenstates):\n transform += self.eigenstate(i) @ org_eigenstate.ct\n \n self.org_eigenstates = org_eigenstates\n self.transform = transform\n \n @staticmethod\n def from_seed(psis: Iterable[QTensor], operators: Iterable[QTensor], name=None, key=None):\n def tobi(t: QTensor):\n return QTensor(t.dims, t.values != 0)\n \n all_psi = zero\n for psi in psis:\n all_psi += tobi(psi)\n all_psi = tobi(all_psi)\n \n all_op = zero\n for op in operators:\n all_op += tobi(op)\n all_op = tobi(all_op)\n \n while True:\n new_psi = all_op @ all_psi\n new_psi += all_psi\n new_psi = tobi(new_psi)\n if new_psi == all_psi:\n break\n all_psi = new_psi\n \n indices = np.transpose(np.where(all_psi.values))\n eigenstates = []\n for index in indices:\n eigenstate = one\n for i, dim in zip(index, all_psi.dims):\n eigenstate @= dim.space.eigenstate(i)\n eigenstates.append(eigenstate)\n \n return ReducedHSpace(eigenstates, name, key)\n \n def org_eigenstate(self, index):\n return self.org_eigenstates[index]\n \n def reduce(self, tensor: QTensor):\n has_ket = False\n has_bra = False\n for dim in tensor.dims:\n if dim.is_ket:\n has_ket = True\n elif dim.is_bra:\n has_bra = True\n if has_ket:\n tensor = self.transform @ tensor\n if has_bra:\n tensor = tensor @ self.transform.ct\n return tensor\n \n def inflate(self, tensor: QTensor):\n has_ket = False\n has_bra = False\n for dim in tensor.dims:\n if dim.is_ket:\n has_ket = True\n elif dim.is_bra:\n has_bra = True\n if has_ket:\n tensor = self.transform.ct @ tensor\n if has_bra:\n tensor = tensor @ self.transform\n return tensor\n","sub_path":"bnk/reduce.py","file_name":"reduce.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131630382","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 09 17:46:48 2017\r\n\r\n@author: rrambhia\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\n \r\ndf = pd.read_csv(\"../data/dailyFruitVeggie_drop_NaN.csv\")\r\n\r\ndf = df[df._AGEG5YR < 14]\r\n\r\ndf.isnull().sum()\r\n\r\n#df = df[df.SMOKDAY2 > 0]\r\ndf = df[df._RFCHOL > 0]\r\ndf = df[df.EXERANY2 > 0]\r\n\r\ndf.shape\r\n\r\n\r\ndf['single'] = np.where(df.MARITAL==1,0,np.where(df.MARITAL==6,0,1))\r\ndf['diabetic'] = np.where(df.DIABETE3==1,1,np.where(df.DIABETE3==2,1,0))\r\ndf['male'] = np.where(df.SEX == 1,1,0)\r\ndf['hicholestrol'] = np.where(df._RFCHOL == 2, 1, 0)\r\ndf['ow_obese'] = np.where(df._RFBMI5 == 2, 1, 0)\r\ndf['exercise'] = np.where(df.EXERANY2 == 1, 1, 0)\r\ndf['senior'] = np.where(df._AGEG5YR >= 10, 1, 0)\r\n\r\n\r\n#df['dailySmoker'] = np.where(df.SMOKDAY2 == 1, 1, 0)\r\n#df['nonSmoker'] = np.where(df.SMOKDAY2 == 3, 1, 0)\r\ndf.single.value_counts()\r\ndf.diabetic.value_counts()\r\ndf.male.value_counts()\r\n\r\ndf.diabetic.describe()\r\n\r\n\r\ndf = df[df.senior==1]\r\n\r\nsns.heatmap(df.corr())\r\n\r\ndf.HD.value_counts()\r\n\r\ndf.shape\r\ndf.boxplot(column=\"dailyVeggie\", by=\"HD\")\r\ndf.boxplot(column=\"dailyFruit\", by=\"HD\")\r\n\r\n\r\ndf_a.to_csv(\"../data/dailyFruitVeggie_drop_NaN_non_diabetic.csv\",index=False)\r\n\r\ndf.to_csv(\"../data/dailyFruitVeggie_drop_NaN_with_dummies.csv\",index=False)","sub_path":"project/code/21_Fruit_Veggie_nonDiabetic.py","file_name":"21_Fruit_Veggie_nonDiabetic.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281552233","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\nfrom datetime import datetime, timedelta\nfrom unittest.mock import MagicMock, patch\n\nimport pytest\nfrom source_nasa.source import NasaApod, SourceNasa\n\ndate_format = \"%Y-%m-%d\"\nmin_date = datetime.strptime(\"1995-06-16\", date_format)\ntomorrow = SourceNasa().max_date\nafter_tomorrow_str = (tomorrow + timedelta(days=1)).strftime(date_format)\nvalid_date_str = (min_date + timedelta(days=10)).strftime(date_format)\n\n\n@pytest.mark.parametrize(\n (\"config\", \"expected_return\"),\n [\n ({\"api_key\": \"foobar\"}, (True, None)),\n ({\"api_key\": \"foobar\", \"start_date\": valid_date_str}, (True, None)),\n (\n {\"api_key\": \"foobar\", \"start_date\": valid_date_str, \"count\": 5},\n (False, \"Invalid parameter combination. Cannot use start_date and count together.\"),\n ),\n (\n {\"api_key\": \"foobar\", \"end_date\": valid_date_str, \"count\": 5},\n (False, \"Invalid parameter combination. Cannot use end_date and count together.\"),\n ),\n ({\"api_key\": \"foobar\", \"end_date\": valid_date_str}, (False, \"Cannot use end_date without specifying start_date.\")),\n (\n {\"api_key\": \"foobar\", \"start_date\": valid_date_str, \"end_date\": min_date.strftime(date_format)},\n (\n False,\n f\"Invalid values. start_date ({datetime.strptime(valid_date_str, date_format)}) needs to be lower than or equal to end_date ({min_date}).\",\n ),\n ),\n ({\"api_key\": \"foobar\", \"start_date\": min_date.strftime(date_format), \"end_date\": valid_date_str}, (True, None)),\n ({\"api_key\": \"foobar\", \"count\": 0}, (False, \"Invalid count value: 0. The value should be in the range [1,101).\")),\n ({\"api_key\": \"foobar\", \"count\": 101}, (False, \"Invalid count value: 101. The value should be in the range [1,101).\")),\n ({\"api_key\": \"foobar\", \"count\": 1}, (True, None)),\n ],\n)\ndef test_check_connection(mocker, config, expected_return):\n with patch.object(NasaApod, \"read_records\") as mock_http_request:\n mock_http_request.return_value = iter([None])\n source = SourceNasa()\n logger_mock = MagicMock()\n assert source.check_connection(logger_mock, config) == expected_return\n\n\ndef test_streams(mocker):\n source = SourceNasa()\n config_mock = MagicMock()\n streams = source.streams(config_mock)\n expected_streams_number = 1\n assert len(streams) == expected_streams_number\n","sub_path":"dts/airbyte/airbyte-integrations/connectors/source-nasa/unit_tests/test_source.py","file_name":"test_source.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168439876","text":"import datetime\n\nimport dash\nfrom dash.dependencies import Input, Output, State\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport cv2\nfrom io import BytesIO\nimport base64\nimport numpy as np\n\napp = dash.Dash(__name__)\napplication = app.server\napp.title='Blur Detector'\n\napp.layout = html.Div([\n html.Div([\n html.H2('Blur Detector'),\n html.Strong('This application measures the blur of an image using Laplacian Variance'),\n ]),\n\n dcc.Upload(\n id='upload-image',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select Files')\n ]),\n style={\n 'width': '100%',\n 'height': '100px',\n 'lineHeight': '100px',\n 'borderWidth': '1px',\n 'borderStyle': 'dashed',\n 'borderRadius': '5px',\n 'textAlign': 'center',\n 'margin': '10px'\n },\n # Allow multiple files to be uploaded\n multiple=True\n ),\n\n html.Div(id='output-image-upload'),\n])\n\n\ndef parse_contents(contents, filename, date):\n #convert uploaded image file in Pillow image file\n encoded_image = contents.split(\",\")[1]\n decoded_image = base64.b64decode(encoded_image)\n bytes_image = BytesIO(decoded_image)\n #image = Image.open(bytes_image).convert('RGB')\n image = cv2.imdecode(np.frombuffer(decoded_image, np.uint8), 1)\n\n blur_measure = cv2.Laplacian(image, cv2.CV_64F).var()\n if blur_measure < 100:\n blur_message = f\"This image is too blurry. The blur measure for this image is {blur_measure}\"\n else:\n blur_message = f\"This image is clear. The blur measure for this image is {blur_measure}\"\n\n\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n brightness_mean = hsv[...,2].mean()\n \n lab = cv2.cvtColor(image,cv2.COLOR_BGR2LAB)\n L,A,B=cv2.split(lab)\n # compute minimum and maximum in 5x5 region using erode and dilate\n kernel = np.ones((5,5),np.uint8)\n min = cv2.erode(L,kernel,iterations = 1)\n max = cv2.dilate(L,kernel,iterations = 1)\n\n # convert min and max to floats\n min = min.astype(np.float64)\n max = max.astype(np.float64)\n\n # compute local contrast\n contrast = (max-min)/(max+min)\n\n # get average across whole image\n average_contrast = 100*np.mean(contrast)\n \n return html.Div([\n # HTML images accept base64 encoded strings in the same format\n # that is supplied by the upload\n html.Strong(blur_message),\n html.Br(),\n html.Strong(f\"The contrast of this image is {average_contrast}%\"),\n html.Br(),\n html.Strong(f\"The brightness of this image is {brightness_mean}\"),\n html.Br(),\n html.Img(src=contents),\n html.Hr(),\n ])\n\n\n@app.callback(Output('output-image-upload', 'children'),\n Input('upload-image', 'contents'),\n State('upload-image', 'filename'),\n State('upload-image', 'last_modified'))\ndef update_output(list_of_contents, list_of_names, list_of_dates):\n if list_of_contents is not None:\n children = [\n parse_contents(c, n, d) for c, n, d in\n zip(list_of_contents, list_of_names, list_of_dates)]\n return children\n\n\nif __name__ == '__main__':\n app.run_server(port=8080)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145396501","text":"import os, uuid, sys\nfrom azure.storage.filedatalake import DataLakeFileClient\nfrom io import BytesIO\nimport pandas as pd\n\nclass QueryDatalake:\n \n def __init__(self, connection_string: str, file_system_name: str, file_path: str):\n \n # coonect to datalake storage...\n self.file = DataLakeFileClient.from_connection_string(connection_string, \n file_system_name = file_system_name, file_path = file_path)\n \n # downlaod the contents of the file from storage\n self.download = self.file.download_file()\n # readall the contents to data variable...\n self.data = self.download.readall()\n \n \n\n\n def query_datalake(self, empid: int, query: str):\n # loading the bytes data into pandas dataframe...\n df = pd.read_csv(BytesIO(self.data))\n # df = pd.read_csv(\"C:\\\\Users\\\\rmaganti\\\\Downloads\\\\export.csv\")\n query_output = \"\"\n df = df[df['job_tos_is1'] == 1]\n # query = int(query)\n if empid not in list(df['prsnel_id']):\n return \"Sorry!!!. Employee ID not found. Please check and Re-enter.\"\n\n if query == \"Current status\":\n if df[df['prsnel_id'] == empid]['emplmt_status_desc'].values[0] in ('Terminated', 'Retired'):\n query_output = \"The employee is {0} on {1}\".format(df[df['prsnel_id'] == empid]['emplmt_status_desc'].values[0],\n df[df['prsnel_id'] == empid]['event_end_dt'].values[0])\n else:\n query_output = \"The employee status is {0}\".format(df[df['prsnel_id'] == empid]['emplmt_status_desc'].values[0])\n\n elif query == \"Location of Employee\":\n query_output = \"The employee location is {0}\".format(df[df['prsnel_id'] == empid]['location_group_desc'].values[0])\n\n elif query == \"Department\":\n query_output = \"The employee department is {0}\".format(df[df['prsnel_id'] == empid]['department_unit_desc'].values[0])\n \n \"\"\"\n for i in range(len(df[df['prsnel_id']== query])):\n \n if df[df['prsnel_id']== query]['emplmt_status_desc'].values[i] == 'Active':\n query_output += \"The employee is {0} from {1} to {2}.\".format(df[df['prsnel_id']== query]['emplmt_status_desc'].values[i],\n df[df['prsnel_id']== query]['event_start_dt'].values[i],\n df[df['prsnel_id']== query]['event_end_dt'].values[i])\n \n else:\n query_output += \"The employee is {0} on {1}.\".format(df[df['prsnel_id']== query]['emplmt_status_desc'].values[i], \n df[df['prsnel_id']== query]['event_end_dt'].values[i])\n \"\"\"\n\n\n \n # return df.iloc[int(query)].to_string()\n return query_output\n\n\n \n\n\n","sub_path":"05.multi-turn-prompt - Copy1/querydatalake.py","file_name":"querydatalake.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543251208","text":"\"\"\" DigitalICS: mobile data collection tool to complete surveys with integrated multimedia\r\n\r\n Copyright (C) 2009. Yael Schwartzman \r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see \r\n \r\n Contact information: Yael Schwartzman - yaelsf@gmail.com\r\n \"\"\"\r\nimport os.path as path\r\nimport cerealizer.cerealizer as cerealizer\r\nfrom api.fexplorer import FExplorer\r\n\r\nclass Pickler:\r\n \r\n def __init__(self,pc = False):\r\n self.fexplorer = FExplorer(pc = pc)\r\n self.pickle_file = self.fexplorer.get_organization_pickle_file()\r\n if not path.exists(self.pickle_file):\r\n self.create_pickle_file()\r\n self.pickle_obj = self.load()\r\n \r\n def create_pickle_file(self):\r\n organization_file = open(self.fexplorer.get_organization_data_file(),'r')\r\n cd_contents = organization_file.read()\r\n cd_contents = cd_contents.replace(\"\\n\",\"\")\r\n cd_list = cd_contents.split(\"%%\")\r\n organization_file.close()\r\n #cols\r\n CLAVE_ORG = 0\r\n RECOMMENDATION = 1\r\n COMMUNITY = 2\r\n NAME = 3\r\n c_dict = {}\r\n for line in cd_list:\r\n items = line.split(';')\r\n if len(items) == 4:\r\n #if not c_dict.has_key(items[COMMUNITY]):\r\n # c_dict[items[COMMUNITY]] = {}\r\n #community_dict = c_dict[items[COMMUNITY]]\r\n if not c_dict.has_key(items[CLAVE_ORG]):\r\n c_dict[items[CLAVE_ORG]] = {'name': items[NAME],\r\n 'recommendations': items[RECOMMENDATION]}\r\n \r\n self.dump(c_dict)\r\n \r\n def dump(self,obj):\r\n p_file = open(self.pickle_file,'wb')\r\n cerealizer.dump(obj,p_file)\r\n p_file.close()\r\n \r\n def load(self):\r\n p_file = open(self.pickle_file,'rb')\r\n obj = cerealizer.load(p_file)\r\n p_file.close()\r\n \r\n return obj \r\n\r\n #def get_communities(self):\r\n # return self.pickle_obj.keys()\r\n \r\n def get_producer_codes(self):\r\n return self.pickle_obj.keys()\r\n \r\n def get_producer_id(self,prod_path):\r\n parts =[]\r\n length = [3,4,3,3]\r\n length_count = 0\r\n for i in range(len(length)):\r\n prod_path,item = path.split(prod_path)\r\n zeros = length[i] - len(item)\r\n for j in range(zeros):\r\n item = \"0\" + item\r\n parts.insert(0,item)\r\n \r\n\r\n id = \"E\" + \"\".join(parts)\r\n return id\r\n\r\n def get_recommendation(self,community=None,municipio = None, localidad = None, producer= None):\r\n \r\n code = self.get_producer_id(\"%s/%s/%s/%s\" % (community,municipio,localidad,producer))\r\n if self.pickle_obj.has_key(code):\r\n return \"%s: %s\" % (self.pickle_obj[code]['name'],self.pickle_obj[code]['recommendations'])\r\n else:\r\n return \"\"\r\n# comm = self.pickle_obj[community]\r\n# for k,v in comm.iteritems():\r\n# if v['name'] == producer:\r\n# return comm[k]['recommendations']\r\n \r\n def get_producer_names(self,community):\r\n comm = self.pickle_obj[community]\r\n return [comm[code]['name'] for code in comm.keys()]\r\n \r\n def get_producer_code(self,community,producer_name):\r\n comm = self.pickle_obj[community]\r\n for k,v in comm.iteritems():\r\n if v['name'] == producer_name:\r\n return k\r\n \r\nif __name__==\"__main__\": \r\n p = Pickler()\r\n d = p.load()\r\n \r\n\r\n producers = p.get_producer_codes()\r\n for prod in producers:\r\n rec = p.get_recommendation(prod)\r\n","sub_path":"digitalics/src/api/pickler.py","file_name":"pickler.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"622381587","text":"# coding: utf-8\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport json\nimport hashlib\nimport pandas as pd\nfrom args import msvd_csv_path, msvd_anno_json_path, msvd_video_name2id_map\n\n\n# 关闭屏幕输出\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\n\n# 恢复屏幕输出\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\n\nclass CocoAnnotations:\n\n def __init__(self):\n self.images = []\n self.annotations = []\n self.img_dict = {}\n info = {\n \"year\": 2017,\n \"version\": '1',\n \"description\": 'Video CaptionEval',\n \"contributor\": 'Subhashini Venugopalan, Yangyu Chen',\n \"url\": 'https://github.com/vsubhashini/, https://github.com/Yugnaynehc/',\n \"date_created\": '',\n }\n licenses = [{\"id\": 1, \"name\": \"test\", \"url\": \"test\"}]\n self.res = {\"info\": info,\n \"type\": 'captions',\n \"images\": self.images,\n \"annotations\": self.annotations,\n \"licenses\": licenses,\n }\n\n def read_multiple_files(self, filelist):\n for filename in filelist:\n print('In file %s\\n' % filename)\n self.read_file(filename)\n\n def get_image_dict(self, img_name):\n code = img_name.encode('utf8')\n image_hash = int(int(hashlib.sha256(code).hexdigest(), 16) % sys.maxsize)\n if image_hash in self.img_dict:\n assert self.img_dict[image_hash] == img_name, 'hash colision: {0}: {1}'.format(\n image_hash, img_name)\n else:\n self.img_dict[image_hash] = img_name\n image_dict = {\"id\": image_hash,\n \"width\": 0,\n \"height\": 0,\n \"file_name\": img_name,\n \"license\": '',\n \"url\": img_name,\n \"date_captured\": '',\n }\n return image_dict, image_hash\n\n def read_file(self, filename):\n count = 0\n with open(filename, 'r') as opfd:\n for line in opfd:\n count += 1\n id_sent = line.strip().split('\\t')\n try:\n assert len(id_sent) == 2\n sent = id_sent[1]\n except Exception as e:\n # print(line)\n continue\n image_dict, image_hash = self.get_image_dict(id_sent[0])\n self.images.append(image_dict)\n\n self.annotations.append({\n \"id\": len(self.annotations) + 1,\n \"image_id\": image_hash,\n \"caption\": sent,\n })\n\n def dump_json(self, outfile):\n self.res[\"images\"] = self.images\n self.res[\"annotations\"] = self.annotations\n with open(outfile, 'w') as fd:\n json.dump(self.res, fd, ensure_ascii=False, sort_keys=True,\n indent=2, separators=(',', ': '))\n\n\ndef create_reference_json(reference_txt_path):\n output_file = '{0}.json'.format(reference_txt_path)\n crf = CocoAnnotations()\n crf.read_file(reference_txt_path)\n crf.dump_json(output_file)\n print('Created json references in %s' % output_file)\n\n\nclass CocoResFormat:\n\n def __init__(self):\n self.res = []\n self.caption_dict = {}\n\n def read_multiple_files(self, filelist, hash_img_name):\n for filename in filelist:\n print('In file %s\\n' % filename)\n self.read_file(filename, hash_img_name)\n\n def read_file(self, filename, hash_img_name):\n count = 0\n with open(filename, 'r') as opfd:\n for line in opfd:\n count += 1\n id_sent = line.strip().split('\\t')\n if len(id_sent) > 2:\n id_sent = id_sent[-2:]\n assert len(id_sent) == 2\n sent = id_sent[1]\n\n if hash_img_name:\n img_id = int(int(hashlib.sha256(id_sent[0].encode('utf8')).hexdigest(),\n 16) % sys.maxsize)\n else:\n img = id_sent[0].split('_')[-1].split('.')[0]\n img_id = int(img)\n imgid_sent = {}\n\n if img_id in self.caption_dict:\n assert self.caption_dict[img_id] == sent\n else:\n self.caption_dict[img_id] = sent\n imgid_sent['image_id'] = img_id\n imgid_sent['caption'] = sent\n self.res.append(imgid_sent)\n\n def dump_json(self, outfile):\n with open(outfile, 'w') as fd:\n json.dump(self.res, fd, ensure_ascii=False, sort_keys=True,\n indent=2, separators=(',', ': '))\n\n\ndef build_msvd_annotation():\n '''\n 仿照MSR-VTT数据集的格式,为MSVD数据集生成一个包含video信息和caption标注的json文件\n 之所以要和MSR-VTT的格式相似,是因为所有的数据集要共用一套prepare_captions的代码\n '''\n # 首先根据MSVD数据集官方提供的CSV文件确定每段视频的名字\n video_data = pd.read_csv(msvd_csv_path, sep=',', encoding='utf8')\n video_data = video_data[video_data['Language'] == 'English']\n # 只使用clean的描述\n # 不行,有的视频没有clean的描述\n # video_data = video_data[video_data['Source'] == 'clean']\n video_data['VideoName'] = video_data.apply(lambda row: row['VideoID'] + '_' +\n str(row['Start']) + '_' +\n str(row['End']), axis=1)\n # 然后根据youtubeclips整理者提供的视频名字到视频id的映射构建一个词典\n video_name2id = {}\n with open(msvd_video_name2id_map, 'r') as f:\n lines = f.readlines()\n for line in lines:\n name, vid = line.strip().split()\n # 提取出视频的数字id\n # 减1是因为id是从1开始的,但是之后处理的时候我们默认是0开始的\n # 因为实际上我们关系的是顺序,所以减1并不影响什么\n vid = int(vid[3:]) - 1\n # 再把vid变成video+数字id的形式\n # 不要问我为什么这么做<摊手>,因为MSR-VTT是这样的,好蠢啊...\n vid = 'video%d' % vid\n video_name2id[name] = vid\n\n # 开始准备按照MSR-VTT的结构构造json文件\n sents_anno = []\n not_use_video = []\n for name, desc in zip(video_data['VideoName'], video_data['Description']):\n if name not in video_name2id:\n if name not in not_use_video:\n print('No use: %s' % name)\n not_use_video.append(name)\n not_use_video.append(name)\n continue\n # 有个坑,SKhmFSV-XB0这个视频里面有一个caption的内容是NaN\n if type(desc) == float:\n print('Error annotation: %s\\t%s' % (name, desc))\n continue\n d = {}\n # 放大招了! 过滤掉所有非ascii字符!\n desc = desc.encode('ascii', 'ignore').decode('ascii')\n # 还有很多新的坑! 有的句子带有一大堆\\n或者带有\\r\\n\n desc = desc.replace('\\n', '')\n desc = desc.replace('\\r', '')\n # 有的句子有句号结尾,有的没有,甚至有的有多句.把句号以及多于一句的内容去掉\n # MSR-VTT数据集是没有句号结尾的\n desc = desc.split('.')[0]\n\n d['caption'] = desc\n d['video_id'] = video_name2id[name]\n sents_anno.append(d)\n\n anno = {'sentences': sents_anno}\n with open(msvd_anno_json_path, 'w') as f:\n json.dump(anno, f)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492732202","text":"from django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse, HttpResponseRedirect\r\nfrom .models import *\r\nfrom .forms import *\r\nfrom accounts.models import Donor_reg, Donor_details\r\nfrom django.contrib import messages\r\nfrom accounts.models import veremail\r\nfrom accounts.views import confirm_register, dropindb, sendmail, em_verify\r\nfrom random import randint as rand\r\n# Create your views here.\r\n\r\n\r\ndef home(request):\r\n return render(request, 'home.html')\r\n\r\ndef donor(request):\r\n saved = False\r\n if request.method == 'POST':\r\n if request.session.has_key('sess_id_donor'):\r\n un = str(request.session['sess_id_donor']).split('_')[2]\r\n user = Donor_reg.objects.get(username = un)\r\n print('working')\r\n if user.email_verified: \r\n form = Donor_Form(request.POST)\r\n form1 = Disease_form(request.POST)\r\n if form.is_valid() and form1.is_valid():\r\n don_or_sell = form.cleaned_data['don_or_sell']\r\n last_donate_date = form.cleaned_data['last_donate_date']\r\n no1w=timezone.now()\r\n diff=no1w-last_donate_date\r\n if(int(diff.total_seconds())<4838400):\r\n reason=\" You have not crossed the optimum time period that one has to wait before full blood donation. We request you to try again after you have done so.\"\r\n context={'reason':reason}\r\n return render(request, 'payments/cant_donate.html', context)\r\n else:\r\n ob=Donor_DataBase.objects.create(user_name=user, don_or_sell=don_or_sell, last_donate_date=last_donate_date)\r\n Asthma, Cancer, Cardiac_Disease, Diabetes, Hypertension, Kidney_Disease, Epilepsy, HIV = form1.cleaned_data['Asthma'], form1.cleaned_data['Cancer'], form1.cleaned_data['Cardiac_Disease'], form1.cleaned_data['Diabetes'], form1.cleaned_data['Hypertension'], form1.cleaned_data['Kidney_Disease'], form1.cleaned_data['Epilepsy'], form1.cleaned_data['HIV']\r\n ob1=Diseases(donor=ob,Asthma=Asthma, Cancer=Cancer, Cardiac_Disease=Cardiac_Disease, Diabetes=Diabetes, Hypertension=Hypertension, Kidney_Disease=Kidney_Disease, Epilepsy=Epilepsy, HIV=HIV)\r\n if Cancer == 'Yes' or Diabetes=='Yes' or Kidney_Disease=='Yes' or HIV=='Yes':\r\n reason=\"You have been diagnosed with diseases that are not suitable for donating blood\"\r\n context={'reason':reason}\r\n ob.delete()\r\n return render(request, 'payments/cant_donate.html', context)\r\n\r\n\r\n messages.success(request, f'Your request has been processed. You will soon be notified via E-mail')\r\n return redirect('processed')\r\n else:\r\n dropindb(veremail,un)\r\n code = rand(100000,999999)\r\n ef = veremail.objects.create(ab=int(code), uname=un)\r\n print(code)\r\n em_verify(user.email, code)\r\n context = {'uname':un, 'catg': 'donor'}\r\n print(context)\r\n return render(request,'confirm_register.html',context)\r\n\r\n else:\r\n return HttpResponseRedirect('/accounts/login')\r\n else:\r\n donor_form = Donor_Form()\r\n disease_form = Disease_form()\r\n context = {\r\n 'form':donor_form,\r\n 'form1':disease_form,\r\n }\r\n return render(request, 'donor.html', context)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"bbms/donor_portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638175935","text":"import lda\nfrom sklearn.feature_extraction.text import CountVectorizer as CV\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import RegexpTokenizer\n\n\nclass LemmaTokenizer(object):\n def __init__(self):\n self.wnl = WordNetLemmatizer()\n\n def __call__(self, doc):\n tokenizer = RegexpTokenizer(r'[a-zA-Z\\-]{3,}')\n return [self.wnl.lemmatize(t) for t in tokenizer.tokenize(doc)]\n\n\nn_topics = 10\nvectorizer = CV(tokenizer=LemmaTokenizer(), strip_accents='unicode', stop_words='english',\n lowercase=True, max_df=0.7, min_df=10)\n\n\ndef read_txt_data(filename):\n with open(filename, 'r') as f:\n lines = [row.strip('\\n') for row in f]\n return lines\n\n\ndef print_topics(model, vector, top_n=n_topics):\n for i, topic in enumerate(model.topic_word_):\n print(\"Topic-{}:\".format(i+1))\n print([(vector.get_feature_names()[i], topic[i]) for i in topic.argsort()[:-top_n - 1:-1]])\n\n\nmovie_file = 'data/MovieCorpus.txt'\nmovie_data = read_txt_data(filename=movie_file)\n\ntwitter_file = 'data/TwitterCorpus.txt'\ntwitter_data = read_txt_data(filename=twitter_file)\n\nbnc_file = 'data/BNCSplitWordsCorpus.txt'\nbnc_data = read_txt_data(filename=bnc_file)\n\nX = movie_data + twitter_data + bnc_data\nvectorized_data = vectorizer.fit_transform(bnc_data)\n\n\nmodel = lda.LDA(n_topics=10, n_iter=500, random_state=1)\nmodel.fit_transform(vectorized_data) # model.fit_transform(X) is also available\nprint_topics(model, vectorizer)","sub_path":"lda-LDA.py","file_name":"lda-LDA.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353349635","text":"import json\nfrom test.test_const import CONST_BASE_URL, CONST_PORT, CONST_SSL\nfrom unittest import TestCase\nfrom requests.exceptions import HTTPError\n\nfrom pygrocydm import GrocyAPI\nfrom pygrocydm.recipes import RECIPES_ENDPOINT, Recipe\nfrom pygrocydm.grocy_api_client import GrocyApiClient\n\n\nclass TestRecipe(TestCase):\n\n def setUp(self):\n self.grocy_api = GrocyAPI(CONST_BASE_URL, \"demo_mode\", verify_ssl = CONST_SSL, port = CONST_PORT)\n self.api_client = GrocyApiClient(CONST_BASE_URL, \"demo_mode\", verify_ssl=CONST_SSL, port=CONST_PORT)\n self.endpoint = f\"{RECIPES_ENDPOINT}/1/fulfillment\"\n\n def test_recipe_data_diff_valid(self):\n recipe = self.api_client.do_request(\"GET\", self.endpoint)\n recipe_keys = recipe.keys()\n moked_recipe_json = \"\"\"{\n \"id\": \"1\",\n \"recipe_id\": \"1\",\n \"need_fulfilled\": \"0\",\n \"need_fulfilled_with_shopping_list\": \"0\",\n \"missing_products_count\": \"4\",\n \"costs\": \"24.25\",\n \"calories\": \"492.0\"\n }\"\"\"\n moked_keys = json.loads(moked_recipe_json).keys()\n self.assertCountEqual(list(recipe_keys), list(moked_keys))\n\n def test_parse_json(self):\n recipe = Recipe(self.api_client, self.api_client.do_request(\"GET\", self.endpoint))\n assert isinstance(recipe.id, int)\n assert isinstance(recipe.recipe_id, int)\n assert isinstance(recipe.need_fulfilled, bool)\n assert isinstance(recipe.need_fulfilled_with_shopping_list, bool)\n assert isinstance(recipe.missing_products_count, int)\n assert isinstance(recipe.costs, float)\n assert isinstance(recipe.calories, float)\n\n def test_add_product(self):\n recipes = self.grocy_api.recipes().fullfilment_list\n for recipe in recipes:\n if recipe.recipe_id == 2:\n recipe.add_not_fulfilled_products_to_shoppinglist()\n break\n\n def test_add_product_exclude(self):\n recipes = self.grocy_api.recipes().fullfilment_list\n for recipe in recipes:\n if recipe.recipe_id == 2:\n recipe.add_not_fulfilled_products_to_shoppinglist([17])\n break\n\n def test_consume_valid(self):\n recipes = self.grocy_api.recipes().fullfilment_list\n for recipe in recipes:\n if recipe.recipe_id == 3:\n recipe.consume()\n break\n\n def test_consume_error(self):\n recipes = self.grocy_api.recipes().fullfilment_list\n for recipe in recipes:\n if recipe.recipe_id == 0:\n self.assertRaises(HTTPError, recipe.consume)\n","sub_path":"test/test_recipes.py","file_name":"test_recipes.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371063896","text":"# Weather Assignment\n# Date, MaxTemperature, MinTemperature, AvgTemperature,\n# AvgTemperature, HDD, CDD, Precipitation, Snowfall, Snowdepth\n\nimport statistics\ndate = []\nmaxTemp = []\nminTemp = []\n\nf = open('weather.txt', 'r')\nfor line in f:\n d, maxt, mint, n1, n2, n3, n4, n5, n6, n7 = line.split(\",\")\n date.append(d)\n maxTemp.append(int(maxt))\n minTemp.append(int(mint))\n print(d, maxt, mint)\nf.close()\n\n# Sum up Arrays\nsumHigh = sum(maxTemp)\nsumLow = sum(minTemp)\n\n# Get length of arrays\nlengthHigh = len(maxTemp)\nlengthLow = len(minTemp)\n\n# Get the average of our arrays\naveMaxTemp = float(sumHigh) / lengthHigh\naveMinTemp = float(sumLow) / lengthHigh\n\n# Sort our arrays\nmaxTemp.sort()\nminTemp.sort()\n\n# Find the median of our arrays\nmedMaxTemp = statistics.median(maxTemp)\nmedMinTemp = statistics.median(minTemp)\n\n#print(\"Sum = \", sumHigh, \"Number of values = \", lengthHigh,\n# \"Average High Temp = \", aveMaxTemp, \" Median maxTemp = \", medMaxTemp)\n\n# Print out assignment\nprint(\"1. Highest High Temp = \", max(maxTemp), \" Lowest High Tempurature = \", min(maxTemp))\nprint(\"2. Highest Low Temp = \", max(minTemp), \" Lowest Low Tempurature = \", min(minTemp))\nprint(\"3. Low Tempurature Ramge = \", (max(minTemp) - min(minTemp)))\nprint(\"4. High Tempurature Ramge = \", (max(maxTemp) - min(maxTemp)))\nprint('{0}{1:.2f}{2}{3:.2f}'.format(\"5. Average High Temp = \", aveMaxTemp, \" Average Low Temp = \", aveMinTemp))\nprint(\"6. Median Max Temp = \", medMaxTemp, \" Median Min Temp = \", medMinTemp)\n","sub_path":"Python/weatherAssignment.py","file_name":"weatherAssignment.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503468695","text":"from copy import deepcopy\nfrom math import floor\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.db.models import Avg, Count, ExpressionWrapper, F, Max, Min\n\nfrom allianceauth.authentication.models import CharacterOwnership\nfrom allianceauth.eveonline.models import EveCharacter\nfrom allianceauth.services.hooks import get_extension_logger\nfrom app_utils.caching import ObjectCacheMixin\nfrom app_utils.logging import LoggerAddTag\n\nfrom .. import __title__\n\nlogger = LoggerAddTag(get_extension_logger(__name__), __title__)\n\n\nclass CharacterQuerySet(models.QuerySet):\n def eve_character_ids(self) -> set:\n return set(\n self.values_list(\"character_ownership__character__character_id\", flat=True)\n )\n\n\nclass CharacterManagerBase(ObjectCacheMixin, models.Manager):\n def unregistered_characters_of_user_count(self, user: User) -> int:\n return CharacterOwnership.objects.filter(\n user=user, memberaudit_character__isnull=True\n ).count()\n\n def user_has_access(self, user: User) -> models.QuerySet:\n \"\"\"Returns list of characters the given user has permission\n to access via character viewer\n \"\"\"\n if user.has_perm(\"memberaudit.view_everything\") and user.has_perm(\n \"memberaudit.characters_access\"\n ):\n qs = self.all()\n else:\n qs = self.filter(character_ownership__user=user)\n if (\n user.has_perm(\"memberaudit.characters_access\")\n and user.has_perm(\"memberaudit.view_same_alliance\")\n and user.profile.main_character.alliance_id\n ):\n user_alliance_ids = set(\n EveCharacter.objects.filter(\n character_ownership__user=user\n ).values_list(\"alliance_id\", flat=True)\n )\n qs = qs | self.filter(\n character_ownership__user__profile__main_character__alliance_id__in=(\n user_alliance_ids\n )\n )\n elif user.has_perm(\"memberaudit.characters_access\") and user.has_perm(\n \"memberaudit.view_same_corporation\"\n ):\n user_corporation_ids = set(\n EveCharacter.objects.filter(\n character_ownership__user=user\n ).values_list(\"corporation_id\", flat=True)\n )\n qs = qs | self.filter(\n character_ownership__user__profile__main_character__corporation_id__in=user_corporation_ids\n )\n\n if user.has_perm(\"memberaudit.view_shared_characters\"):\n qs = qs | self.filter(is_shared=True)\n\n return qs\n\n\nCharacterManager = CharacterManagerBase.from_queryset(CharacterQuerySet)\n\n\nclass CharacterUpdateStatusManager(models.Manager):\n def statistics(self) -> dict:\n \"\"\"returns detailed statistics about the last update run and the app\"\"\"\n from django.conf import settings as auth_settings\n\n from .. import app_settings\n from ..models import (\n Character,\n CharacterAsset,\n CharacterContact,\n CharacterContract,\n CharacterMail,\n SkillSet,\n SkillSetGroup,\n )\n\n def root_task_id_or_none(obj):\n try:\n return obj.root_task_id\n except AttributeError:\n return None\n\n all_characters_count = Character.objects.count()\n\n settings = {\n name: value\n for name, value in vars(app_settings).items()\n if name.startswith(\"MEMBERAUDIT_\")\n }\n schedule = deepcopy(auth_settings.CELERYBEAT_SCHEDULE)\n for name, details in schedule.items():\n for k, v in details.items():\n if k == \"schedule\":\n schedule[name][k] = str(v)\n\n settings[\"CELERYBEAT_SCHEDULE\"] = schedule\n\n qs_base = self.filter(\n is_success=True,\n started_at__isnull=False,\n finished_at__isnull=False,\n ).exclude(root_task_id=\"\", parent_task_id=\"\")\n root_task_ids = {\n ring: root_task_id_or_none(\n qs_base.filter(section__in=Character.sections_in_ring(ring))\n .order_by(\"-finished_at\")\n .first()\n )\n for ring in range(1, 4)\n }\n duration_expression = ExpressionWrapper(\n F(\"finished_at\") - F(\"started_at\"),\n output_field=models.fields.DurationField(),\n )\n qs_base = qs_base.filter(root_task_id__in=root_task_ids.values()).annotate(\n duration=duration_expression\n )\n update_stats = dict()\n if self.count() > 0:\n # per ring\n for ring in range(1, 4):\n sections = Character.sections_in_ring(ring)\n\n # calc totals\n qs = qs_base.filter(section__in=sections)\n try:\n first = qs.order_by(\"started_at\").first()\n last = qs.order_by(\"finished_at\").last()\n started_at = first.started_at\n finshed_at = last.finished_at\n duration = round((finshed_at - started_at).total_seconds(), 1)\n except (KeyError, AttributeError):\n first = None\n last = None\n duration = None\n started_at = None\n finshed_at = None\n\n available_time = (\n settings[f\"MEMBERAUDIT_UPDATE_STALE_RING_{ring}\"]\n - settings[\"MEMBERAUDIT_UPDATE_STALE_OFFSET\"]\n ) * 60\n throughput = (\n floor(all_characters_count / duration * 3600) if duration else None\n )\n within_boundaries = duration < available_time if duration else None\n update_stats[f\"ring_{ring}\"] = {\n \"total\": {\n \"duration\": duration,\n \"started_at\": started_at,\n \"finshed_at\": finshed_at,\n \"root_task_id\": root_task_ids.get(ring),\n \"throughput_est\": throughput,\n \"available_time\": available_time,\n \"within_available_time\": within_boundaries,\n },\n \"max\": {},\n \"sections\": {},\n }\n\n # add longest running section w/ character\n obj = qs.order_by(\"-duration\").first()\n update_stats[f\"ring_{ring}\"][\"max\"] = self._info_from_obj(obj)\n\n # add first and last section\n update_stats[f\"ring_{ring}\"][\"first\"] = self._info_from_obj(first)\n update_stats[f\"ring_{ring}\"][\"last\"] = self._info_from_obj(last)\n\n # calc section stats\n for section in sections:\n try:\n section_max = round(\n qs_base.filter(section=section)\n .aggregate(Max(\"duration\"))[\"duration__max\"]\n .total_seconds(),\n 1,\n )\n section_avg = round(\n qs_base.filter(section=section)\n .aggregate(Avg(\"duration\"))[\"duration__avg\"]\n .total_seconds(),\n 1,\n )\n section_min = round(\n qs_base.filter(section=section)\n .aggregate(Min(\"duration\"))[\"duration__min\"]\n .total_seconds(),\n 1,\n )\n except (KeyError, AttributeError):\n section_max = (None,)\n section_avg = None\n section_min = None\n\n update_stats[f\"ring_{ring}\"][\"sections\"].update(\n {\n str(section): {\n \"max\": section_max,\n \"avg\": section_avg,\n \"min\": section_min,\n }\n }\n )\n\n ring_characters_count = (\n Character.objects.filter(update_status_set__in=qs)\n .annotate(num_sections=Count(\"update_status_set__section\"))\n .filter(num_sections=len(sections))\n .count()\n )\n update_stats[f\"ring_{ring}\"][\"total\"][\n \"characters_count\"\n ] = ring_characters_count\n update_stats[f\"ring_{ring}\"][\"total\"][\"completed\"] = (\n ring_characters_count == all_characters_count\n )\n\n return {\n \"app_totals\": {\n \"users_count\": User.objects.filter(\n character_ownerships__memberaudit_character__isnull=False\n )\n .distinct()\n .count(),\n \"all_characters_count\": all_characters_count,\n \"skill_set_groups_count\": SkillSetGroup.objects.count(),\n \"skill_sets_count\": SkillSet.objects.count(),\n \"assets_count\": CharacterAsset.objects.count(),\n \"mails_count\": CharacterMail.objects.count(),\n \"contacts_count\": CharacterContact.objects.count(),\n \"contracts_count\": CharacterContract.objects.count(),\n },\n \"settings\": settings,\n \"update_statistics\": update_stats,\n }\n\n @staticmethod\n def _info_from_obj(obj) -> dict:\n try:\n section_name = str(obj.section)\n character_name = str(obj.character)\n duration = round(obj.duration.total_seconds(), 1)\n except (KeyError, AttributeError):\n section_name = None\n character_name = None\n duration = None\n\n return {\n \"section\": section_name,\n \"character\": character_name,\n \"duration\": duration,\n }\n","sub_path":"memberaudit/managers/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":10411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"184101962","text":"import DatabaseConnection\n\n__author__ = \"Eduardo Carrasco Jr.\"\n__email__ = \"eduardo.carrasco.jr@outlook.com\"\n__version__ = \"1.0\"\n\n\ndb = DatabaseConnection.DatabaseConnection(productionDatabase=True)\n\n\nclass PatientClass(object):\n def __init__(self, id):\n self.id = id\n\n def get_patient_id(self):\n return self.id\n\n def get_patient_number(self):\n query_input = \"\"\"\n select pat.patient_number from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_year_of_birth(self):\n query_input = \"\"\"\n select pat.year_of_birth from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_sex(self):\n query_input = \"\"\"\n select pat.sex from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_date_of_diagnosis(self):\n query_input = \"\"\"\n select pat.date_of_diagnosis from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_date_of_death(self):\n query_input = \"\"\"\n select pat.date_of_death from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_summary(self):\n query_input = \"\"\"\n select pat.summary from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_instition_id(self):\n query_input = \"\"\"\n select pat.institution_id from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_race_id(self):\n query_input = \"\"\"\n select pat.race_id from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n\n def get_tumor_location(self):\n query_input = \"\"\"\n select pat.tumor_location from patients pat\n where pat.id = %s \"\"\"\n return db.query_one(query_input % self.get_patient_id())\n","sub_path":"Patient.py","file_name":"Patient.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"423861313","text":"from datetime import datetime\nimport os\nimport math\n\nimport tensorflow as tf\n\nimport dataset\nfrom utils import add_summaries\nfrom utils import align_image\nfrom utils import convert_rgb_to_y\nfrom utils import convert_rgb_to_ycbcr\nfrom utils import convert_y_and_cbcr_to_rgb\nfrom utils import resize_image\nfrom utils import save_image\nfrom utils import load_image\nfrom utils import calc_psnr_and_ssim\nfrom utils import get_validation_files\n\n\nclass Dcscn:\n def __init__(self, with_restore=False):\n # Scale factor for Super Resolution (should be 2 or more)\n self.scale = 2\n\n # Number of feature extraction layers\n self.layers = 12\n\n # Number of image channels used. Now it should be 1. using only Y from YCbCr.\n self.input_channel = 1\n self.output_channel = 1\n\n # Number of filters of first feature-extraction CNNs\n self.filters = 196\n\n # Number of filters of last feature-extraction CNNs\n self.min_filters = 48\n\n # Number of CNN filters are decayed\n # from [filters] to [min_filters] by this gamma\n self.filters_decay_gamma = 1.5\n\n # Initial weight stddev (won't be used when you use he or xavier initializer)\n self.weight_dev = 0.01\n\n # Output nodes should be kept by this probability. If 1, don't use dropout.\n self.dropout_rate = 0.8\n\n # Use batch normalization after each CNNs\n self.batch_norm = False\n\n # Norm for gradient clipping. If it's <= 0 we don't use gradient clipping.\n self.clipping_norm = 5\n\n # L2 decay\n self.l2_decay = 0.00003\n\n # Number of mini-batch images for training\n self.batch_size = 5\n\n self.initial_learning_rate = 0.0002\n\n self.H = []\n self.Weights = []\n self.Biases = []\n\n # Restore model path\n self.is_use_restore = False\n\n if with_restore:\n self.is_use_restore = True\n self.restore_model_path = with_restore\n\n # Build graph\n x, y, x2, learning_rate, dropout, is_training = self.placeholders(\n input_channel=self.input_channel, output_channel=self.output_channel\n )\n self.x = x\n self.x2 = x2\n self.y = y\n self.learning_rate = learning_rate\n self.dropout = dropout\n self.is_training = is_training\n self.y_hat = self.forward(self.x, self.x2, self.dropout)\n\n def _he_initializer(self, shape):\n n = shape[0] * shape[1] * shape[2]\n stddev = math.sqrt(2.0 / n)\n return tf.truncated_normal(shape=shape, stddev=stddev)\n\n def _weight(self, shape, name=\"weight\"):\n initial = self._he_initializer(shape)\n return tf.Variable(initial, name=name)\n\n def _bias(self, shape, initial_value=0.0, name=\"bias\"):\n initial = tf.constant(initial_value, shape=shape)\n return tf.Variable(initial, name=name)\n\n def _conv2d(self, input, w, stride, bias=None, use_batch_norm=False, name=\"\"):\n output = tf.nn.conv2d(\n input,\n w,\n strides=[1, stride, stride, 1],\n padding=\"SAME\",\n name=name + \"_conv\",\n )\n\n if bias is not None:\n output = tf.add(output, bias, name=name + \"_add\")\n\n if use_batch_norm:\n output = tf.layers.batch_normalization(\n output, training=self.is_training, name=\"BN\"\n )\n\n return output\n\n def _prelu(self, input, features, name=\"\"):\n with tf.variable_scope(\"prelu\"):\n alphas = tf.Variable(\n tf.constant(0.1, shape=[features]), name=name + \"_prelu\"\n )\n\n output = tf.nn.relu(input) + tf.multiply(alphas, (input - tf.abs(input))) * 0.5\n return output\n\n def _convolutional_block(\n self,\n name,\n input,\n kernel_size,\n input_feature_num,\n output_feature_num,\n use_batch_norm=False,\n dropout_rate=1.0,\n dropout=None,\n ):\n with tf.variable_scope(name):\n shape_of_weight = [\n kernel_size,\n kernel_size,\n input_feature_num,\n output_feature_num,\n ]\n w = self._weight(shape=shape_of_weight, name=\"conv_W\")\n\n shape_of_bias = [output_feature_num]\n b = self._bias(shape=shape_of_bias, name=\"conv_B\")\n\n z = self._conv2d(\n input, w, stride=1, bias=b, use_batch_norm=use_batch_norm, name=name\n )\n\n a = self._prelu(z, output_feature_num, name=name)\n\n if dropout_rate < 1.0:\n a = tf.nn.dropout(a, dropout, name=\"dropout\")\n\n self.H.append(a)\n\n add_summaries(\"weight\", name, w, save_stddev=True, save_mean=True)\n add_summaries(\"output\", name, a, save_stddev=True, save_mean=True)\n add_summaries(\"bias\", name, b, save_stddev=True, save_mean=True)\n\n # # Save image\n # shapes = w.get_shape().as_list()\n # weights = tf.reshape(w, [shapes[0], shapes[1], shapes[2] * shapes[3]])\n # weights_transposed = tf.transpose(weights, [2, 0, 1])\n # weights_transposed = tf.reshape(\n # weights_transposed, [shapes[2] * shapes[3], shapes[0], shapes[1], 1]\n # )\n # tf.summary.image(\"weights\", weights_transposed, max_outputs=6)\n\n self.Weights.append(w)\n self.Biases.append(b)\n\n return a\n\n def _pixel_shuffler(\n self, name, input, kernel_size, scale, input_feature_num, output_feature_num\n ):\n with tf.variable_scope(name):\n self._convolutional_block(\n name + \"_CNN\",\n input,\n kernel_size,\n input_feature_num=input_feature_num,\n output_feature_num=scale * scale * output_feature_num,\n use_batch_norm=False,\n )\n\n self.H.append(tf.depth_to_space(self.H[-1], scale))\n\n def placeholders(self, input_channel, output_channel):\n x = tf.placeholder(\n tf.float32, shape=[None, None, None, input_channel], name=\"x\"\n )\n y = tf.placeholder(\n tf.float32, shape=[None, None, None, output_channel], name=\"y\"\n )\n x2 = tf.placeholder(\n tf.float32, shape=[None, None, None, output_channel], name=\"x2\"\n )\n learning_rate = tf.placeholder(tf.float32, shape=[], name=\"LearningRate\")\n dropout = tf.placeholder(tf.float32, shape=[], name=\"dropout_keep_rate\")\n is_training = tf.placeholder(tf.bool, name=\"is_training\")\n\n return x, y, x2, learning_rate, dropout, is_training\n\n def _calc_filters(self, first, last, layers, decay):\n return [\n int((first - last) * (1 - pow(i / float(layers - 1), 1.0 / decay)) + last)\n for i in range(layers)\n ]\n\n def forward(self, input, x2, dropout):\n # building feature extraction layers\n total_output_feature_num = 0\n\n with tf.name_scope(\"X_\"):\n mean_var = tf.reduce_mean(input)\n stddev_var = tf.sqrt(tf.reduce_mean(tf.square(input - mean_var)))\n tf.summary.scalar(\"output/mean\", mean_var)\n tf.summary.scalar(\"output/stddev\", stddev_var)\n\n filters = self._calc_filters(\n self.filters, self.min_filters, self.layers, self.filters_decay_gamma\n )\n\n input_filter = self.input_channel\n for i, filter in enumerate(filters):\n self._convolutional_block(\n \"CNN%d\" % (i + 1),\n input,\n kernel_size=3,\n input_feature_num=input_filter,\n output_feature_num=filter,\n use_batch_norm=self.batch_norm,\n dropout_rate=self.dropout_rate,\n dropout=dropout,\n )\n input_filter = filter\n input = self.H[-1]\n total_output_feature_num += filter\n\n with tf.variable_scope(\"Concat\"):\n self.H_concat = tf.concat(self.H, 3, name=\"H_concat\")\n\n # building reconstruction layers\n self._convolutional_block(\n \"A1\",\n self.H_concat,\n kernel_size=1,\n input_feature_num=total_output_feature_num,\n output_feature_num=64,\n dropout_rate=self.dropout_rate,\n dropout=dropout,\n )\n\n self._convolutional_block(\n \"B1\",\n self.H_concat,\n kernel_size=1,\n input_feature_num=total_output_feature_num,\n output_feature_num=32,\n dropout_rate=self.dropout_rate,\n dropout=dropout,\n )\n self._convolutional_block(\n \"B2\",\n self.H[-1],\n kernel_size=3,\n input_feature_num=32,\n output_feature_num=32,\n dropout_rate=self.dropout_rate,\n dropout=dropout,\n )\n self.H.append(tf.concat([self.H[-1], self.H[-3]], 3, name=\"Concat2\"))\n\n # building upsampling layer\n pixel_shuffler_channel = 64 + 32\n self._pixel_shuffler(\n \"Up-PS\",\n self.H[-1],\n kernel_size=3,\n scale=self.scale,\n input_feature_num=pixel_shuffler_channel,\n output_feature_num=pixel_shuffler_channel,\n )\n\n self._convolutional_block(\n \"R-CNN0\",\n self.H[-1],\n kernel_size=3,\n input_feature_num=pixel_shuffler_channel,\n output_feature_num=self.output_channel,\n )\n\n y_hat = tf.add(self.H[-1], x2, name=\"output\")\n\n with tf.name_scope(\"Y_\"):\n mean = tf.reduce_mean(y_hat)\n stddev = tf.sqrt(tf.reduce_mean(tf.square(y_hat - mean)))\n tf.summary.scalar(\"output/mean\", mean)\n tf.summary.scalar(\"output/stddev\", stddev)\n tf.summary.histogram(\"output\", y_hat)\n\n return y_hat\n\n def loss(self, y_hat, y):\n diff = tf.subtract(y_hat, y, \"diff\")\n\n mse = tf.reduce_mean(tf.square(diff, name=\"diff_square\"), name=\"mse\")\n image_loss = tf.identity(mse, name=\"image_loss\")\n\n l2_norm_losses = [tf.nn.l2_loss(w) for w in self.Weights]\n l2_norm_loss = self.l2_decay + tf.add_n(l2_norm_losses)\n loss = image_loss + l2_norm_loss\n\n tf.summary.scalar(\"Loss\", loss)\n tf.summary.scalar(\"L2WeightDecayLoss\", l2_norm_loss)\n\n return loss, image_loss, mse\n\n def optimizer(self, loss, learning_rate):\n beta1 = 0.9\n beta2 = 0.999\n if self.batch_norm:\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n optimizer = tf.train.AdamOptimizer(\n learning_rate, beta1=beta1, beta2=beta2, epsilon=1e-8\n )\n else:\n optimizer = tf.train.AdamOptimizer(\n learning_rate, beta1=beta1, beta2=beta2, epsilon=1e-8\n )\n\n trainables = tf.trainable_variables()\n grads = tf.gradients(loss, trainables)\n\n if self.clipping_norm > 0:\n clipped_grads, _ = tf.clip_by_global_norm(\n grads, clip_norm=self.clipping_norm\n )\n grad_var_pairs = zip(clipped_grads, trainables)\n training_optimizer = optimizer.apply_gradients(grad_var_pairs)\n else:\n training_optimizer = optimizer.minimize(loss)\n\n # Save weights\n # for i in range(len(grads)):\n # var = grads[i]\n # mean_var = tf.reduce_mean(var)\n # stddev_var = tf.sqrt(tf.reduce_mean(tf.square(var - mean_var)))\n\n # # tf.summary.scalar(\"{}/mean\".format(var.name), var)\n # # tf.summary.scalar(\"{}/stddev\".format(grads[i].name), stddev_var)\n # # tf.summary.histogram(grads[i].name, var)\n\n return training_optimizer\n\n def train(self, output_path, validation_dataset=None):\n loss, image_loss, mse = self.loss(self.y_hat, self.y)\n\n training = self.optimizer(loss, self.learning_rate)\n\n loader = dataset.Loader(\n \"bsd200\", scale=self.scale, image_size=48, batch_size=self.batch_size\n )\n\n summary = tf.summary.merge_all()\n\n with tf.Session() as sess:\n log_dir = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n writer = tf.summary.FileWriter(\"logs/{}\".format(log_dir), graph=sess.graph)\n\n sess.run(tf.global_variables_initializer())\n\n for i in range(8000 * 100):\n input_images, upscaled_images, original_images = loader.feed()\n\n feed_dict = {\n self.x: input_images,\n self.x2: upscaled_images,\n self.y: original_images,\n self.learning_rate: self.initial_learning_rate,\n self.dropout: self.dropout_rate,\n self.is_training: 1,\n }\n\n _, s_loss, s_mse = sess.run([training, loss, mse], feed_dict=feed_dict)\n print(\"Step: {}, loss: {}, mse: {}\".format(i, s_loss, s_mse))\n\n if i % 100 == 0:\n summarized, _ = sess.run([summary, loss], feed_dict=feed_dict)\n writer.add_summary(summarized, i)\n\n # Learning rate\n lr_summary = tf.Summary(\n value=[\n tf.Summary.Value(\n tag=\"LR\", simple_value=self.initial_learning_rate\n )\n ]\n )\n writer.add_summary(lr_summary, i)\n\n if i % 8000 == 0:\n # Metrics\n if validation_dataset is not None:\n validation_files = get_validation_files(validation_dataset)\n psnr, ssim = self.calc_metrics(validation_files)\n print(\"PSNR: {}, SSSIM: {}\".format(psnr, ssim))\n psnr_summary = tf.Summary(\n value=[tf.Summary.Value(tag=\"PSNR\", simple_value=psnr)]\n )\n ssim_summary = tf.Summary(\n value=[tf.Summary.Value(tag=\"SSIM\", simple_value=ssim)]\n )\n writer.add_summary(psnr_summary, i)\n writer.add_summary(ssim_summary, i)\n\n writer.close()\n\n # Save model\n output_dir = os.path.dirname(os.path.join(os.getcwd(), output_path))\n os.makedirs(output_dir, exist_ok=True)\n self.save(sess, output_path)\n\n def run(self, input_image, input_bicubic_image):\n h, w = input_image.shape[:2]\n ch = input_image.shape[2] if len(input_image.shape) > 2 else 1\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n # Restore model\n if self.is_use_restore:\n restore_path = os.path.join(\n os.getcwd(), self.restore_model_path + \".ckpt\"\n )\n saver = tf.train.Saver()\n saver.restore(sess, restore_path)\n\n feed_dict = {\n self.x: input_image.reshape(1, h, w, ch),\n self.x2: input_bicubic_image.reshape(\n 1,\n self.scale * input_image.shape[0],\n self.scale * input_image.shape[1],\n ch,\n ),\n self.learning_rate: self.initial_learning_rate,\n self.dropout: 1.0,\n self.is_training: 0,\n }\n y_hat = sess.run([self.y_hat], feed_dict=feed_dict)\n output = y_hat[0][0]\n\n return output\n\n def inference(self, input_image, output_dir, save_images=False):\n # Create scaled image\n scaled_image = resize_image(input_image, 2)\n\n # Create y and scaled y image\n input_y_image = convert_rgb_to_y(input_image)\n scaled_y_image = resize_image(input_y_image, self.scale)\n\n output_y_image = self.run(input_y_image, scaled_y_image)\n\n # Create result image\n scaled_ycbcr_image = convert_rgb_to_ycbcr(scaled_image)\n result_image = convert_y_and_cbcr_to_rgb(\n output_y_image, scaled_ycbcr_image[:, :, 1:3]\n )\n\n if save_images:\n save_image(input_image, \"{}/original.jpg\".format(output_dir))\n save_image(scaled_image, \"{}/bicubic.jpg\".format(output_dir))\n save_image(\n scaled_y_image, \"{}/bicubic_y.jpg\".format(output_dir), is_rgb=False\n )\n save_image(\n output_y_image, \"{}/result_y.jpg\".format(output_dir), is_rgb=False\n )\n save_image(result_image, \"{}/result.jpg\".format(output_dir))\n\n return result_image\n\n def evaluate(self, filepath):\n input_image = align_image(load_image(filepath), self.scale)\n input_y_image = resize_image(convert_rgb_to_y(input_image), 1 / self.scale)\n input_scaled_y_image = resize_image(input_y_image, self.scale)\n\n output_y_image = self.run(input_y_image, input_scaled_y_image)\n ground_truth_y_image = convert_rgb_to_y(input_image)\n\n return calc_psnr_and_ssim(\n ground_truth_y_image, output_y_image, border=self.scale\n )\n\n def save(self, sess, name=\"\"):\n filename = \"{}.ckpt\".format(name)\n saver = tf.train.Saver(max_to_keep=None)\n saver.save(sess, filename)\n\n def calc_metrics(self, files):\n psnrs = 0\n ssims = 0\n\n for file in files:\n psnr, ssim = self.evaluate(file)\n psnrs += psnr\n ssims += ssim\n\n psnr /= len(files)\n ssim = ssims / len(files)\n\n return psnr, ssim\n\n \n def metrics(self, output, labels):\n output_transposed = output if self.data_format == 'NHWC' else tf.transpose(output, perm=[0, 2, 3, 1])\n\n output = tf.Print(output, [tf.shape(output)], message=\"shape of output:\", summarize=1000)\n output = tf.Print(output, [output], message=\"value of output:\", summarize=1000)\n # labels = tf.Print(labels, [labels])\n # labels = tf.Print(labels)\n\n # labels = tf.image.rgb_to_yuv(labels)\n\n results = {}\n updates = []\n with tf.name_scope('metrics_cals'):\n mean_squared_error, mean_squared_error_update = tf.metrics.mean_squared_error(\n labels,\n output_transposed,\n )\n results[\"mean_squared_error\"] = mean_squared_error\n updates.append(mean_squared_error_update)\n\n psnr_array = tf.image.psnr(labels, output, max_val=1.0)\n psnr, psnr_update = tf.metrics.mean(psnr_array)\n results[\"psnr\"] = psnr\n updates.append(psnr_update)\n\n ssim_array = tf.image.ssim(labels, output, max_val=1.0)\n ssim, ssim_update = tf.metrics.mean(ssim_array)\n results[\"ssim\"] = ssim\n updates.append(ssim_update)\n\n # merge all updates\n updates_op = tf.group(*updates)\n\n return results, updates_op\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":19273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612533746","text":"# Copyright (c) 2020 LightOn, All Rights Reserved.\n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\nimport sys\nfrom builtins import object, TypeError\nfrom contextlib import contextmanager, ExitStack\nfrom enum import Enum\nfrom typing import Union, Tuple, List\nimport numpy as np\n\nfrom lightonml.internal.pidfile import PidFile, ProcessRunningException\nfrom lightonml.internal.types import OutputRoiStrategy, Roi, Tuple2D\n\n# Default values for hardware parameters\ndefault_frametime_us = 500\ndefault_exposure_us = 400\ndefault_gain_dB = 0.\n\n# for constant. checked for truth when hardware is opened\n_input1_shape = (912, 1140)\n_output1_shape_max = (1920, 1080)\n_output2_shape_max = (2040, 1088)\n_output3_shape_max = (2048, 1088)\n\n\nclass OpuAlreadyUsedException(Exception):\n \"\"\"Exception raised when hardware resources for an OPU are already taken\"\"\"\n pass\n\n\nclass AcqState(Enum):\n \"\"\"Acquisition state (see common/include/opu_types.hpp)\"\"\"\n stopped = 1\n batch = 2\n online = 3\n\n\n# noinspection PyPep8Naming\nclass OpuDevice(object):\n \"\"\"\n Class for hardware interface with a LightOn OPU.\n\n Implements a context manager interface for acquiring access to the OPU,\n but most properties are gettable and settable even though the OPU isn't active.\n\n \"\"\"\n\n # noinspection PyUnresolvedReferences\n def __init__(self, opu_type: str, frametime_us: int,\n exposure_us: int, sequence_nb_prelim=0,\n output_roi: Roi = None, verbose=0, name=\"opu\"):\n\n if opu_type == \"type1\":\n from lightonopu import opu1_pybind\n self.__opu = opu1_pybind.OPU()\n self._output_shape_max = _output1_shape_max\n # With Model1 we just get the ROI in the middle\n self._output_roi_strategy = OutputRoiStrategy.mid_square\n self._output_roi_increment = 8\n elif opu_type == \"type2\":\n from lightonopu import opu2_pybind\n self.__opu = opu2_pybind.OPU()\n self._output_shape_max = _output2_shape_max\n # With Model2 we get max width in the middle\n self._output_roi_strategy = OutputRoiStrategy.mid_width\n self._output_roi_increment = 1\n elif opu_type == \"type3\":\n from lightonopu import opu3_pybind\n self.__opu = opu3_pybind.OPU()\n self._output_shape_max = _output3_shape_max\n # With Model2 we get max width in the middle\n self._output_roi_strategy = OutputRoiStrategy.mid_width\n self._output_roi_increment = 1\n else:\n raise TypeError(\"Don't know this OPU type: \" + opu_type)\n\n # context for pid file\n self.pidfile = ExitStack()\n self.opu_type = opu_type\n # \"off\" fields allow to know what to send at resource acquisition\n # force to int if input is e.g. a float\n self._frametime_us_off = int(frametime_us)\n self._exposure_us_off = int(exposure_us)\n self._gain_dB_off = default_gain_dB\n self._output_roi_off = output_roi\n self._reserved_off = 0\n self._sequence_nb_prelim = sequence_nb_prelim\n self.name = name\n\n self.verbose = verbose\n from lightonml import get_trace_fn, get_debug_fn\n self._trace = get_trace_fn()\n self._debug = get_debug_fn()\n\n # forward opu interface to class\n self.transform1 = self.__opu.transform1\n self.transform2 = self.__opu.transform2\n self.transform_single = self.__opu.transform_single\n self.transform_online = self.__opu.transform_online\n if hasattr(self.__opu, \"transform_online_test\"):\n self.transform_online_test = self.__opu.transform_online_test\n\n def open(self):\n \"\"\"\n Acquires hardware resource.\n\n Do nothing if the resource is already acquired in the current object.\n If the resource isn't available, do 4 retries until it is available,\n or raise a OPUUsedByOther exception\n\n Equivalent is to use context manager interface::\n\n with opu:\n outs = opu.transform(ins)\n\n Raises\n ------\n self.OPUUsedByOther\n if hardware has already been acquired in another process or object\n \"\"\"\n # Just return if it's already active\n if self.__opu.active:\n return\n # A PID file allows to check whether an OPU of this name already runs on the system,\n # and provide the user with a helpful message\n try:\n log = sys.stdout if self.verbose >= 2 else None\n warn = sys.stderr if self.verbose >= 2 else None\n self.pidfile.enter_context(PidFile(\"/tmp/lighton/lighton-{}.pid\"\n .format(self.name), log, warn))\n except ProcessRunningException:\n # \"from None\" to disable exception chaining, not useful here\n raise OpuAlreadyUsedException(_already_used_text) from None\n\n if self.verbose:\n print(\"Opening OPU... \", end='', flush=True)\n\n # noinspection PyPep8\n try:\n self.__opu.open(self._frametime_us_off, self._exposure_us_off,\n self._sequence_nb_prelim, self.verbose)\n\n # check that input&output constants is conform to what the hardware tells\n if self.input_shape != tuple(self.__opu.input_shape):\n raise Exception(\"Incorrect values for internal input shape\")\n if self.output_shape_max != tuple(self.__opu.output_shape_max):\n raise Exception(\"Incorrect values for internal max output shape\")\n if self.input_size != self.__opu.input_size:\n raise Exception(\"Incorrect values for internal input size\")\n if default_gain_dB != self.__opu.gain_dB:\n raise Exception(\"Incorrect defaults for output gain\")\n\n # sets hardware parameter back\n self.gain_dB = self._gain_dB_off\n if self._output_roi_off is not None:\n self.output_roi = self._output_roi_off\n if self._reserved_off != 0:\n self.reserve(self._reserved_off)\n if self.verbose:\n print(\"OK\")\n except:\n # Cleanup if an exception was thrown\n try:\n self.__opu.close()\n finally:\n self.pidfile.close()\n raise\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, *args):\n self.close()\n\n def close(self):\n # grab hardware values before closing\n try:\n if self.active:\n self._frametime_us_off = self.__opu.frametime_us\n self._exposure_us_off = self.__opu.exposure_us\n self._gain_dB_off = self.__opu.gain_dB\n self._output_roi_off = to_roi(self.__opu.output_roi)\n\n self.__opu.close()\n self._debug(\"OPU device closed\")\n finally:\n # In the end make sure the pidfile is released\n self.pidfile.close()\n\n @contextmanager\n def acquiring(self, triggered=True, online=False, n_images=0):\n try:\n if n_images:\n self.reserve(n_images)\n if online:\n self.__opu.start_online_acq(triggered)\n self._trace(\"Online acq started\")\n else:\n self.__opu.start_acq(triggered)\n self._trace(\"Normal acq started\")\n yield\n finally:\n self.__opu.stop_acq()\n self._trace(\"Acquisition stopped\")\n\n @property\n def active(self):\n \"\"\"bool, whether the hardware resources have been acquired\"\"\"\n return self.__opu.active\n\n @property\n def input_shape(self) -> Tuple2D:\n \"\"\"tuple(int), Shape of the input, in elements and cartesian coordinates\n \"\"\"\n return _input1_shape\n\n @property\n def output_shape_max(self) -> Tuple2D:\n \"\"\"tuple(int): Shape of the whole output (no ROI),\n in elements and cartesian coordinates\"\"\"\n return self._output_shape_max\n\n @property\n def output_roi_strategy(self) -> OutputRoiStrategy:\n return self._output_roi_strategy\n\n @property\n def output_roi_increment(self) -> int:\n return self._output_roi_increment\n\n @property\n def nb_features(self) -> int:\n \"\"\"int: Total number of features supported by the OPU\"\"\"\n return self.input_shape[0] * self.input_shape[1]\n\n @property\n def input_size(self) -> int:\n \"\"\"int: Input size, in bytes\"\"\"\n return self.nb_features // 8\n\n @property\n def exposure_us(self) -> int:\n \"\"\"int: exposure for output, in microseconds\"\"\"\n return self.__opu.exposure_us if self.active else self._exposure_us_off\n\n @property\n def output_readout_us(self) -> int:\n \"\"\"int: time given for readout, in microseconds\"\"\"\n if not self.active:\n raise RuntimeError(\"The Opu must be active to get this value\")\n return self.__opu.output_readout_us\n\n @property\n def frametime_us(self) -> int:\n \"\"\"int: time for which each input display, in microseconds\"\"\"\n return self.__opu.frametime_us if self.active else self._frametime_us_off\n\n @frametime_us.setter\n def frametime_us(self, value):\n if self.active:\n self.__opu.frametime_us = int(value)\n else:\n self._frametime_us_off = int(value)\n\n @exposure_us.setter\n def exposure_us(self, value):\n if self.active:\n self.__opu.exposure_us = int(value)\n else:\n self._exposure_us_off = int(value)\n\n def reserve(self, n_images):\n \"\"\"Does internal allocation of a number of images, necessary for transform2 calls\"\"\"\n if self.active:\n self.__opu.reserve(int(n_images))\n else:\n self._reserved_off = int(n_images)\n\n @property\n def output_shape(self) -> Tuple2D:\n \"\"\"\n list(int): Shape of the current output ROI, in elements\n and cartesian coordinates\n \"\"\"\n return self.output_roi[1]\n\n @property\n def acq_state(self) -> Union[AcqState, None]:\n return AcqState(self.__opu.acq_state) if self.active else None\n\n @property\n def output_dtype(self):\n return np.uint8\n\n @property\n def output_roi(self) -> Roi:\n \"\"\" tuple(list(int)): offset and size of the current output ROI\"\"\"\n return to_roi(self.__opu.output_roi) if self.active else self._output_roi_off\n\n @output_roi.setter\n def output_roi(self, value: Roi):\n if self.active:\n # Binding accepts tuple(list(int), list(inst))\n self.__opu.output_roi = (list(value[0]), list(value[1]))\n else:\n self._output_roi_off = value\n\n @property\n def gain_dB(self) -> float:\n \"\"\" Gain of the output (not implemented in every device)\"\"\"\n return self.__opu.gain_dB if self.active else self._gain_dB_off\n\n @gain_dB.setter\n def gain_dB(self, value):\n if self.active:\n self.__opu.gain_dB = value\n else:\n self._gain_dB_off = value\n\n def versions(self):\n \"\"\"Returns multi-line string with device and libraries versions\"\"\"\n version = []\n # device version needs an active OPU\n if self.active:\n version.append(self.__opu.device_versions())\n # this is static so works even if non active\n version.append(self.__opu.library_versions())\n return '\\n'.join(version)\n\n def __deepcopy__(self, memo):\n \"\"\"\n Deep copy of an object\n\n Can't make a deep copy of an OPU that represents a hardware\n resource, However sklearn needs to clone it as an estimator\n \"\"\"\n return self\n\n def __getstate__(self):\n \"\"\"Closes and return current state\"\"\"\n state = {\"active\": self.active,\n \"opu_type\": self.opu_type,\n \"frametime_us\": self.frametime_us,\n \"exposure_us\": self.exposure_us,\n \"gain_dB\": self.gain_dB,\n \"output_ROI\": self.output_roi,\n \"reserved\": self._reserved_off,\n \"sequence_nb_prelim\": self._sequence_nb_prelim,\n \"verbose\": self.verbose,\n \"name\": self.name}\n self.close()\n return state\n\n def __setstate__(self, state):\n \"\"\"Restore object with given state\"\"\"\n self.__init__(state[\"opu_type\"], state[\"frametime_us\"], state[\"exposure_us\"],\n state[\"sequence_nb_prelim\"], state[\"output_ROI\"], state[\"verbose\"],\n state[\"name\"])\n self.gain_dB = state[\"gain_dB\"]\n self._reserved_off = state[\"reserved\"]\n # If state was active then open OPU\n if state[\"active\"]:\n self.open()\n\n def __str__(self):\n active = \"Active\" if self.active else \"Inactive\"\n return '{} OPU, frametime {} μs, exposure {} μs, output ROI {}'.format(\n active, self.frametime_us, self.exposure_us, self.output_roi)\n\n\n_already_used_text = \"\"\"\nThe OPU hardware resources have already been reserved by another OPU or OPUMap object.\nThe options to recover from this are:\n * shutdown the kernel if it's in a notebook;\n * call close() on the object when you don't need it anymore, or use the Python \"with\" statement.\n\"\"\"\n\n\ndef to_roi(roi: Tuple[List[int], List[int]]) -> Roi:\n # Binding returns tuple(list, list), we want tuple(tuple, tuple)\n # noinspection PyTypeChecker\n return tuple(roi[0]), tuple(roi[1])\n","sub_path":"lightonml/internal/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":13670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"41496702","text":"import sys\nimport unittest\n\nsys.path.append('../')\nfrom Cms_base import CMS\n\n\nclass MyTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.cms = CMS()\n cls.cms.login()\n\n def test_01(self):\n ti = self.cms.driver.title\n title = 'CRM客户关系管理系统'\n self.assertEqual(title, ti)\n\n def test_02(self):\n url = 'http://ztwxwh.eatuo.com:8070/index'\n ul = self.cms.driver.current_url\n self.assertEqual(url, ul)\n\n @classmethod\n def tearDownClass(cls):\n cls.cms.cms_close()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"case/test_cms_login.py","file_name":"test_cms_login.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175940822","text":"# -*- coding: utf-8 -*-\n# extract topic page/question to json-structered information\n\nfrom bs4 import BeautifulSoup\nimport re\nimport os, sys\nimport pprint\nimport json\n\npp = pprint.PrettyPrinter(indent=4)\n\n\ndef content_norm(str):\n tmp = str.strip().lower()\n tmp1 = re.sub(r'\\s+',' ', tmp)\n return re.sub(r'\\n+',' ', tmp1)\n\ndef extract_topic_page(file):\n res = None\n with open(file, 'r') as fd:\n res = {}\n page = BeautifulSoup(fd, 'lxml')\n res['topic_name'] = content_norm(page.select('h1[class=\"topic-name\"]')[0].get_text())\n res['latin_name'] = content_norm(page.select('em[class=\"topic-description\"]')[0].get_text())\n infos = page.select('p[class=\"info-description\"]')\n num = len(infos)\n res['desc'] = content_norm(infos[0].get_text())\n res['use'] = content_norm(infos[1].get_text())\n res['propagation'] = content_norm(infos[2].get_text())\n res['diseases'] = []\n diseases = page.select('div.disease')\n for d in diseases:\n dobj = {}\n title_sec = d.select('h3[class=\"disease-title\"]')[0]\n dobj['label'] = content_norm(title_sec.select('span.label')[0].get_text())\n for span_tmp in title_sec.select('span'):\n span_tmp.extract()\n dobj['title'] = content_norm(title_sec.get_text())\n disease_secs = d.select('p')\n disease_sec_num = len(disease_secs)\n if disease_sec_num > 0:\n dobj['symptoms'] = content_norm(disease_secs[0].get_text())\n if disease_sec_num > 1:\n dobj['comments'] = content_norm(disease_secs[1].get_text())\n if disease_sec_num > 2:\n dobj['management'] = content_norm(disease_secs[2].get_text())\n res['diseases'].append(dobj)\n return res\ndef extract_question_page(file):\n res = None\n with open(file, 'r') as fd:\n res = []\n p = json.load(fd)\n for post in p['posts']:\n post_obj = {}\n post_obj['title'] = content_norm(post['title'])\n post_obj['text'] = content_norm(post['text'])\n if len(post['post_images']) > 0:\n post_obj['images'] = []\n for post_image in post['post_images']:\n post_obj['images'].append(post_image['url'])\n res.append(post_obj)\n return res\n\n\ndef main():\n directory = sys.argv[1]\n topics_summary = \"plant-village-topics-summary\"\n topics = {}\n questions_summary = \"plant-village-questions-summary\"\n questions = {}\n if len(sys.argv) > 2:\n topic_summary = sys.argv[2]\n if len(sys.argv) > 3:\n question_summary = sys.argv[3]\n for subdir in os.listdir(directory):\n topic= os.path.split(subdir)[1]\n topic_dir = os.path.join(directory, subdir)\n topic_page = os.path.join(topic_dir, \"diseases_and_pests_description_uses_propagation\")\n question_page = os.path.join(topic_dir, \"questions\")\n if os.path.exists(topic_page):\n topics[topic] = extract_topic_page(topic_page)\n if os.path.exists(question_page):\n pp.pprint(question_page)\n questions[topic] = extract_question_page(question_page)\n pp.pprint(questions[topic])\n\n with open(topics_summary, 'w') as topics_summary_fd:\n topics_summary_fd.write(json.dumps(topics, indent=2).encode('utf-8'))\n \n with open(questions_summary, 'w') as questions_summary_fd:\n questions_summary_fd.write(json.dumps(questions, indent=2).encode('utf-8'))\nif __name__ == '__main__':\n main()\n","sub_path":"content/plantvillage/extracter.py","file_name":"extracter.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"130395216","text":"import random\nfrom random import randint\nfrom camisas.models import Camisa, Pantalon, Zapato, Vestimenta\nfrom faker import Faker\nfrom random_words import RandomWords\n\nfaker = Faker()\nrw = RandomWords()\n\nfor i in range(5):\n\tcamisa = Camisa.objects.create(\n\t\ttalla=randint(1,100),\n\t\tcolor=rw.random_word(),\n\t\ttipo_camisa=random.choice(['chemmis', 'guarda_camisa', 'guayabera'])\n\t)\nprint(\"Camisas creadas exitosamente\")\n\nfor i in range(5):\n\tpantalon = Pantalon.objects.create(\n\t\ttalla=randint(1,100),\n\t\tcolor=rw.random_word(),\n\t\ttipo_pantalon=random.choice(['corto', 'largo', 'blue yean'])\n\t)\nprint(\"Pantalones Creados exitosamente\")\n\nfor i in range(5):\n\tzapato = Zapato.objects.create(\n\t\ttalla=randint(1,100),\n\t\tcolor=rw.random_word(),\n\t\ttipo_zapato=random.choice(['de vestir', 'botas', 'tenis'])\n\t)\nprint(\"Zapatos Creados exitosamente\")","sub_path":"camisas/seeds/CamisaSeeder.py","file_name":"CamisaSeeder.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"157519905","text":"#!/usr/bin/env python\n\n# stdlib imports\nimport os.path\n\n# local imports\nfrom amptools.io.cosmos.core import read_cosmos\nfrom amptools.io.cwb.core import read_cwb\nfrom amptools.io.dmg.core import read_dmg\nfrom amptools.io.geonet.core import read_geonet\nfrom amptools.io.knet.core import read_knet\nfrom amptools.io.obspy.core import read_obspy\nfrom amptools.io.smc.core import read_smc\n\nREQUIRED = ['horizontal_orientation',\n 'instrument_period',\n 'instrument_damping',\n 'process_time',\n 'process_level',\n 'station_name',\n 'sensor_serial_number',\n 'instrument',\n 'comments',\n 'structure_type',\n 'corner_frequency',\n 'units',\n 'source',\n 'source_format']\n\n\ndef test_smc():\n homedir = os.path.dirname(os.path.abspath(\n __file__)) # where is this script?\n datadir = os.path.join(homedir, '..', '..', 'data')\n\n files = {'cosmos': (read_cosmos, 'Cosmos12TimeSeriesTest.v1'),\n 'cwb': (read_cwb, '1-EAS.dat'),\n 'dmg': (read_dmg, 'CE89146.V2'),\n 'geonet': (read_geonet, '20161113_110259_WTMC_20.V1A'),\n 'knet': (read_knet, 'AOM0011801241951.EW'),\n 'obspy': (read_obspy, '51PJW_H1.mseed'),\n 'smc': (read_smc, '0111a.smc')}\n\n for ftype, ftuple in files.items():\n print(ftype)\n filename = os.path.join(datadir, ftype, ftuple[1])\n stream = ftuple[0](filename)\n std_dict = stream[0].stats.standard\n for key in REQUIRED:\n print('\\t%s' % key)\n assert key in std_dict\n print(ftype, std_dict['source_format'])\n\n\nif __name__ == '__main__':\n test_smc()\n","sub_path":"tests/amptools/io/standard_test.py","file_name":"standard_test.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127546631","text":"def task1(timestamp, bus):\n nextBus = bus - (timestamp%bus) #minutes until next bus\n return nextBus\n\n#==============================================================================\ninputFile = open(\"input.txt\", 'r')\ntimestamp = int(inputFile.readline())\nbuses = inputFile.readline().split(',')\ninputFile.close()\n\nfor i in range(buses.count('x')):\n buses.remove('x')\n\nfor i in range(len(buses)):\n buses[i] = int(buses[i])\n\ntimes = dict()\nfor bus in buses:\n times[bus] = task1(timestamp, bus)\nkeyMin = min(times.keys(), key=(lambda k: times[k]))\nprint(keyMin*times[keyMin])","sub_path":"day13/day13.1.py","file_name":"day13.1.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232090058","text":"import datetime\nimport glob\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport time\nfrom functools import partial\n\nimport peewee\n\nimport objects\n\nlogger = logging.getLogger(__name__)\n\n# TAGGER_PID = None\nARTICLES_DB = objects.DATABASE_LOCATION\nTIME_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\"\n\nFILE_PATH = os.path.dirname(os.path.realpath(__file__))\n\n\nclass Stopwatch:\n \"\"\"\n Stopwatch. Times and prints code run time in seconds.\n Start the stopwatch with initializiation:\n s = Stopwatch()\n Time the laps using\n s.lap(\"String to print\")\n \"\"\"\n\n def __init__(self):\n self.time_last = time.time()\n\n def lap(self, string_to_print):\n time_now = time.time()\n time_dif = time_now - self.time_last\n self.time_last = time_now\n print(string_to_print, time_dif)\n\n\ndef async_getter(function_pointer=None, input_list=None, pass_data=None, processes=4, timeout=5):\n logger.info(function_pointer)\n \"\"\"\n Function that is used to provide easier functionality of asynchronous processes.\n You can use it in applications with a single list of items that need to be processed\n and that need to be put into a single list of output items.\n\n Example:\n def async_process():\n m = multiprocessing.Manager()\n results = m.list()\n async_getter(\n function_pointer=function,\n input_list=[1,2,3],\n pass_data={\"results\": results}\n )\n return results\n\n def function(list_item, pass_data=None):\n results = pass_data[\"results\"]\n a = 1+list_item\n results.append(a)\n\n\n :param function_pointer: Function that async getter asynchronously starts.\n :param input_list: List of items that should be fed to function.\n :param pass_data: Additional data that should be fed to function (e.g. combined output).\n :param processes: Number of spawned asynchronous processes.\n :param progress_bar: Enables progress bar (which works only with Pool function - not ThreadPool).\n :param bar_format: Overrides progress bar look.\n :param timeout: Maximum allowed time to finish single async process in seconds.\n :return: TODO: define return\n \"\"\"\n\n function_pointer = partial(function_pointer, pass_data=pass_data)\n p = multiprocessing.pool.ThreadPool(processes)\n p.map(partial(abortable_worker, function_pointer, timeout=timeout), input_list)\n p.terminate()\n\n\ndef abortable_worker(func, *args, **kwargs):\n logger.info(func)\n \"\"\"\n Helper function of async_getter that enables easier timeout handling.\n :param func: Function that operates asynchronously.\n :param args: Function arguments.\n :param kwargs: Function keyword arguments.\n :return: Returns apply_async().get() .\n \"\"\"\n timeout = kwargs.get('timeout', None)\n p = multiprocessing.pool.ThreadPool(1)\n res = p.apply_async(func, args=args)\n try:\n out = res.get(timeout) # Wait timeout seconds for func to complete.\n return out\n except multiprocessing.TimeoutError:\n p.terminate()\n\n\ndef create_articles_database():\n logger.info('')\n \"\"\"\n Creates an article database if it does not exist.\n \"\"\"\n db = peewee.SqliteDatabase(objects.DATABASE_LOCATION)\n db.connect()\n if not objects.ArticleObject.table_exists():\n db.create_tables([objects.ArticleObject])\n db.close()\n\n\ndef write_to_articles_database(list_of_article_dicts):\n logger.info('')\n \"\"\"\n Inserts a list of articles into the article database.\n Use with large lists.\n :param list_of_article_dicts: Self-explanatory.\n :return:\n \"\"\"\n db = peewee.SqliteDatabase(ARTICLES_DB)\n db.connect()\n\n articles = [(j[\"url\"], json.dumps(j)) for j in list_of_article_dicts]\n articles_to_write = []\n\n for a in articles:\n url = a[0]\n jsn = a[1]\n if not article_in_database(url):\n articles_to_write.append({\"url\": url, \"json\": jsn})\n\n with db.atomic():\n for idx in range(0, len(articles_to_write), 100):\n objects.ArticleObject.insert_many(articles_to_write[idx:idx + 100]).execute()\n db.close()\n\n\ndef get_article_from_database(url):\n logger.info('')\n \"\"\"\n Gets single article from database.\n :param url: Unique article url.\n :return: Returns article object.\n \"\"\"\n db = peewee.SqliteDatabase(ARTICLES_DB)\n db.connect()\n article = objects.ArticleObject.get(objects.ArticleObject.url == url)\n db.close()\n return article\n\n\ndef article_in_database(article_url):\n logger.debug('')\n \"\"\"\n Returns true if article_url is in database, else false.\n :param article_url: Unique article url.\n :return: Boolean.\n \"\"\"\n db = peewee.SqliteDatabase(ARTICLES_DB)\n db.connect()\n query = objects.ArticleObject.select().where(objects.ArticleObject.url == article_url)\n db.close()\n if query.exists():\n return True\n else:\n return False\n\n\ndef string_to_date(string):\n logger.debug('')\n \"\"\"\n Converts string to datetime object.\n :param string: Date string.\n :return: datetime object.\n \"\"\"\n return datetime.datetime.strptime(string, TIME_FORMAT)\n\n\ndef date_to_string(date, time_format=TIME_FORMAT):\n logger.debug('')\n \"\"\"\n Converts string to datetime object.\n :param date: date object\n :return: String object.\n \"\"\"\n return datetime.datetime.strftime(date, time_format)\n\n\ndef clean_datetime_string(string):\n logger.info('')\n \"\"\"\n Cleans and formats date strings.\n :param string: Date string\n :return: Formatted date string.\n \"\"\"\n if \"+\" in string:\n string = string.split(\"+\")[0]\n if \".\" in string:\n string = string.split(\".\")[0]\n if \"Z\" not in string:\n string = string + \"Z\"\n return string\n\n\ndef get_article_daterange(date_from, date_to):\n logger.info('')\n \"\"\"\n Gets article list for articles ranging from (not including) date_from\n to (not including) date to.\n :param date_from: date_object\n :param date_to: date_object\n :return: list of article dictionaries.\n \"\"\"\n out = []\n for a in objects.ArticleObject.select():\n a_json = json.loads(a.json)\n published_at = a_json['publishedAt']\n published_at_date = string_to_date(published_at)\n\n if date_from < published_at_date < date_to:\n out.append(json.loads(a.json))\n return out\n\n\ndef clean_date_strings():\n logger.info('')\n \"\"\"\n Cleanes database of incorrectly formatted dates.\n \"\"\"\n articles_in_db = objects.ArticleObject.select()\n num_articles = len(articles_in_db)\n print(\"cleaning\", num_articles, \"articles\")\n i = 0\n for a in articles_in_db:\n i += 1\n a_json = json.loads(a.json)\n if \"publishedAt\" in a_json:\n published_at = a_json['publishedAt']\n published_clean = clean_datetime_string(published_at)\n if published_clean != published_at:\n a_json['publishedAt'] = published_clean\n to_write_json = json.dumps(a_json)\n a.json = to_write_json\n a.save()\n else:\n print(a.json)\n a.delete_instance()\n\n\ndef get_next_midnight(timedelta=0):\n logger.info('')\n \"\"\"\n Returns next midnight (as datetime object) + timedelta (in days).\n :param timedelta: Integer : number of days.\n :return: datetime object.\n \"\"\"\n # Defaults to today at midnight\n date_now = datetime.datetime.now()\n date_today_midnight = date_now.replace(hour=0, minute=0, second=0, microsecond=0)\n date_from = date_today_midnight + datetime.timedelta(days=timedelta)\n return date_from\n\n\ndef parse_date_str(date_str=None, default_timedelta=0):\n logger.info('')\n \"\"\"\n Parses date string and tries to return datetime object.\n If input string equals None, it returns get_next_midnight(default_timedelta).\n TODO: Check if that is correct behaviour.\n :param date_str: String : formatted date.\n :param default_timedelta: Integer : number of days to add.\n :return: datetime object.\n \"\"\"\n if not date_str:\n date = get_next_midnight(default_timedelta)\n else:\n date = string_to_date(date_str)\n return date\n\n\ndef clean_string(string):\n logger.debug('')\n \"\"\"\n Cleans string.\n Removes non-alphanumeric characters. Strips extra whitespace.\n :param string: Input string.\n :return: Output string.\n \"\"\"\n string = \"\".join([c if c.isalnum() or c == \" \" else \"\" for c in string])\n string = string.strip()\n string = ' '.join(string.split())\n return string\n\n\ndef delete_location_logs():\n logger.info('')\n list_of_files = glob.glob(os.path.join(\n FILE_PATH, \"logs\", \"locations\", \"*.log\"))\n files_to_delete = sorted(list_of_files, key=os.path.getctime, reverse=True)[1:]\n i = 0\n for f in files_to_delete:\n os.remove(f)\n i += 1\n\n if i > 0:\n print(\"Deleted\", i, \"old location logs!\")\n return\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514852606","text":"#!/usr/bin/env python3\n# Example from:\n# https://www.askpython.com/python-modules/tkinter/tkinter-treeview-widget\n# Tkinter TreeView Widget\n\nimport tkinter as tk\nimport tkinter.ttk as ttk\n \nclass Application(tk.Frame):\n def __init__(self, root):\n self.root = root\n self.initialize_user_interface()\n \n def initialize_user_interface(self):\n # Configure the root object for the Application\n self.root.title(\"Application\")\n self.root.grid_rowconfigure(0, weight=1)\n self.root.grid_columnconfigure(0, weight=1)\n self.root.config(background=\"green\")\n \n # Define the different GUI widgets\n self.name_label = tk.Label(self.root, text=\"Name:\")\n self.name_entry = tk.Entry(self.root)\n self.name_label.grid(row=0, column=0, sticky=tk.W)\n self.name_entry.grid(row=0, column=1)\n \n self.idnumber_label = tk.Label(self.root, text=\"ID\")\n self.idnumber_entry = tk.Entry(self.root)\n self.idnumber_label.grid(row=1, column=0, sticky=tk.W)\n self.idnumber_entry.grid(row=1, column=1)\n \n self.submit_button = tk.Button(self.root, text=\"Insert\", command=self.insert_data)\n self.submit_button.grid(row=2, column=1, sticky=tk.W)\n \n self.exit_button = tk.Button(self.root, text=\"Exit\", command=self.root.quit)\n self.exit_button.grid(row=0, column=3)\n \n # Set the treeview\n self.tree = ttk.Treeview(self.root, columns=('Name', 'ID'))\n \n # Set the heading (Attribute Names)\n self.tree.heading('#0', text='Item')\n self.tree.heading('#1', text='Name')\n self.tree.heading('#2', text='ID')\n \n # Specify attributes of the columns (We want to stretch it!)\n self.tree.column('#0', stretch=tk.YES)\n self.tree.column('#1', stretch=tk.YES)\n self.tree.column('#2', stretch=tk.YES)\n \n self.tree.grid(row=4, columnspan=4, sticky='nsew')\n self.treeview = self.tree\n \n self.id = 0\n self.iid = 0\n \n def insert_data(self):\n self.treeview.insert('', 'end', iid=self.iid, text=\"Item_\" + str(self.id),\n values=(\"Name: \" + self.name_entry.get(),\n self.idnumber_entry.get()))\n self.iid = self.iid + 1\n self.id = self.id + 1\n \napp = Application(tk.Tk())\napp.root.mainloop()\n","sub_path":"Programming/python/tkinter/tree.001.tk.py","file_name":"tree.001.tk.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152806795","text":"\r\nimport numpy as np\r\n\r\n\r\nm = 3\r\nx0_data = np.ones((m, 1))\r\nx1_data = np.float32(np.random.rand(2, m)).reshape(m,2) \r\nx_data = np.hstack((x0_data, x1_data))\r\n\r\ny_data = np.dot(x_data, [0.300, 0.100, 0.200])\r\n\r\n'''\r\ny_data1 = np.dot(x_data,[0,100,0.200]) + 0.300 \r\nY = W * X + b\r\nW=[0.100,0.200]\r\nb=0.300\r\n\r\ntheta =[0.300,0.100,0.200]\r\nY = theta * X\r\n\r\n'''\r\n\r\n'''\r\n Training Set:\r\n Y X\r\n y_data, x_data\r\n \r\n Hypothesis:\r\n Y = theta * X\r\n \r\n slove :\r\n theta\r\n'''\r\n\r\n'''\r\nLoss or Cost function\r\nX_data.shape=(m,3)\r\ntheta.shape =(3,)\r\nY_data.shape=(m,)\r\n'''\r\ndef loss_function(theta, X_data, Y_data):\r\n '''Cost function J definition.'''\r\n diff = np.dot(X_data, theta) - Y_data\r\n num = np.size(Y_data)\r\n return (1./2*num) * np.dot(np.transpose(diff), diff)\r\n\r\n\r\n'''gradient function\r\n'''\r\ndef gradient_function(theta, X_data, Y_data):\r\n '''Gradient of the function J definition.'''\r\n diff = np.dot(X_data,theta) - Y_data\r\n num = np.size(Y_data)\r\n return (1./num) * np.dot(np.transpose(X_data), diff)\r\n\r\n\r\n'''get min point\r\n'''\r\ndef gradient_descent(X_data, Y_data, optimizer,theta):\r\n '''Perform gradient descent.'''\r\n gradient = gradient_function(theta, X_data, Y_data)\r\n while not np.all(np.absolute(gradient) <= 1e-5):\r\n theta = theta - optimizer * gradient\r\n gradient = gradient_function(theta, X_data, Y_data)\r\n return theta \r\n\r\n\r\ndef train(X_data,Y_data,optimizer,theta):\r\n gradient = gradient_function(theta, X_data, Y_data)\r\n theta = theta - optimizer * gradient\r\n return theta\r\n\r\n\r\noptimizer = 0.5\r\ntheta = np.array([1, 1, 1]).reshape(3,) #init thera\r\n\r\nprint(x_data)\r\nprint(y_data)\r\ntheta = gradient_descent(x_data, y_data, optimizer,theta)\r\nprint(theta)\r\n\r\n#for step in xrange(0, 501):\r\n# theta = train(x_data, y_data, optimizer,theta)\r\n# if step % 20 == 0:\r\n# print(step, theta)\r\n\r\n","sub_path":"algorithm/linear_algebra/np_tf_demo.py","file_name":"np_tf_demo.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"147119375","text":"from pprint import pprint\n\nfrom fabric.api import env, task, run, sudo, settings\n\nfrom .decorators import require_environment\n\n\n@task\n@require_environment\ndef deploy():\n with settings(\n host_string=env.rush_env['default_server'],\n port=env.rush_env.get('ssh_port', 22),\n user=env.rush_env.get('default_user', env.user),\n ):\n cmd = env.rush_env['deployment_command']\n sudo(cmd)\n","sub_path":"rushcoil/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29143063","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n# 後端連接\nimport datetime\nimport pymongo\n\n\n# 資料庫連線\ndef connectDB():\n try:\n client = pymongo.MongoClient(\n \"mongodb+srv://dbUser1:test123@dbtest.ojwhb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority\"\n )\n db = client.restaurant\n print('restaurant db connect succeed')\n return db\n except Exception as e:\n print(e)\n\n\n# 讀取db collection中全部資料,並集合成list回傳\ndef findAllOrder():\n db = connectDB()\n mycol = db.order\n data ={}\n print(mycol.count_documents({})) # db['mycol']內有多少筆資料\n doc: object\n for num,doc in enumerate(mycol.find({})):\n print(\"doc {}: {}\".format(num, doc))\n data[str(num)] = doc\n print(data)\n return data\n\n# 測試功能example 修改\ndef example_update():\n db = connectDB()\n mycol = db.order\n myquery = {\"_id\": \"20210425001\"}\n newvalues = {\"$set\": {\"telephone\": \"(11)11111111\"}}\n mycol.update_one(myquery, newvalues)\n print(\"modified\")\n\n\n# 測試功能example 刪除\ndef example_del():\n db = connectDB()\n mycol = db.order\n myquery = {\"_id\": \"20210425001\"}\n mycol.delete_one(myquery)\n print(\"deleted\")\n\n\n# 測試功能example 新增\ndef example_insert():\n db = connectDB()\n posts = db.order\n today = datetime.datetime.now() # 當日日期 2021-04-25 ...\n datestr = str(today).split(' ')[0].replace('-', '') # 當日日期字串處理 20210425\n post = {\n \"_id\": \"20210516001\",\n \" Customer_name\": \"王小明\",\n \"telephone\": \"0923547813\",\n \"VIP\": False,\n \"Meals\": {\n \"pre-meal\": [\"salad\", \"chowder\"],\n \"Main_meal\": \"pasta\",\n \"dessert\": \" cheese cake\",\n \"drink\": \"Americano\"\n },\n \"Table_number\": \"01\"\n }\n post_id = posts.insert_one(post)\n print(post_id + \" inserted\")\n\n\n# 主程式測試\nif __name__ == '__main__':\n connectDB()\n findAllOrder()\n","sub_path":"myMongoDB.py","file_name":"myMongoDB.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"117216061","text":"import yaml\nfrom sceptre.cli.helpers import CfnYamlLoader\n\ndef sceptre_handler(sceptre_user_data) ->str:\n with open(\"templates/ec2.yaml\") as ec2_yaml:\n template_obj=yaml.load(ec2_yaml,Loader=CfnYamlLoader)\n \n BlockDeviceMappings = sceptre_user_data.get(\"BlockDeviceMappings\")\n UserData=sceptre_user_data.get(\"UserData\")\n AvailabilityZone=sceptre_user_data.get(\"AvailabilityZone\")\n NeedsLoadBalancerDomain = sceptre_user_data.get(\"NeedsLoadBalancerDomain\",False)\n\n if BlockDeviceMappings:\n template_obj[\"Resources\"][\"EC2Instance\"][\"Properties\"][\"BlockDeviceMappings\"] = BlockDeviceMappings\n\n if NeedsLoadBalancerDomain:\n template_obj[\"Parameters\"][\"LoadBalacerDomain\"] = {\n \"Description\": \"Domain of Load Balancer\",\n \"Type\": \"String\"\n }\n \n if UserData:\n template_obj[\"Resources\"][\"EC2Instance\"][\"Properties\"][\"UserData\"]=UserData\n if AvailabilityZone:\n template_obj[\"Resources\"][\"EC2Instance\"][\"Properties\"][\"AvailabilityZone\"]=AvailabilityZone\n\n return str(yaml.dump(template_obj))","sub_path":"sceptre-project/cloud-nokku-project/templates/resources/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565088040","text":"from Node import *\nimport DTNgeneral\nimport datetime as dt\n\nclass ThreeRNode(Node):\n\n ## Constructor function\n def __init__(self, myid, bufferSize, dump_policy, datestart):\n self.myid = myid\n self.dump_policy = dump_policy\n self.buffer = 0\n self.datestart = datestart\n self.bufferSize = bufferSize \n self.pac = []\n self.receivedPac = []\n self.lastupdatetime={}\n self.conthis = {} #[index, time of contacts]\n\n def update_history(self, node2, time, constime, conetime):\n #print(\"update history\")\n is_weekday = True\n curdt = self.datestart+dt.timedelta(seconds=time)\n if(curdt.date().weekday() > 4):\n is_weekday = False\n index = curdt.hour\n id2 = node2.myid\n if(not self.conthis.__contains__(id2)):\n temp = [[0]*24, [0]*24]\n self.conthis.update({id2:temp})\n temp = self.conthis[id2]\n times = self.cal_uptime(constime, conetime, time-DTNgeneral.dur, time)\n \n if(times ==0):\n times=1\n \n if(is_weekday):\n temp[0][index] +=times\n else:\n temp[1][index]+=times\n self.conthis.update({id2:temp})\n #print(self.conthis)\n self.lastupdatetime.update({id2:conetime})\n\n def remove_conthis(self, curtime):\n remove = []\n for i in self.lastupdatetime:\n if(not remove.__contains__(i)):\n if (curtime - self.lastupdatetime[i]>2592000):\n remove.append(i)\n for i in remove:\n del self.lastupdatetime[i]\n del self.conthis[i]\n \n \n def cal_uptime(self, cst, cet, inttimes, inttimee):\n if(cet<=inttimee):\n if(cst>= inttimes):\n return int((cet-cst)/60)\n elif(cst< inttimes):\n return int((cet-inttimes)/60)\n elif(cet>inttimee):\n if(cst>= inttimes):\n return int((inttimee - cst)/60)\n elif(cst< inttimes):\n return int((inttimee - inttimes)/60)\n\n\n def cal_prob(self, id2, pacborn, pacdeadline):\n \n count = 0\n is_weekday = True\n checklength = int((pacdeadline - pacborn)/3600)+1\n problist = []\n packetborn = self.datestart + dt.timedelta(seconds= pacborn)\n j = packetborn.hour\n if(packetborn.date().weekday()>4):\n is_weekday= False\n\n while(count <= checklength):\n total = 0\n id2times = 0\n \n for i in self.conthis:\n if(is_weekday == True):\n if(i == id2):\n id2times+= self.conthis[i][0][j]\n total += self.conthis[i][0][j]\n else:\n if(i == id2):\n id2times+= self.conthis[i][1][j]\n total += self.conthis[i][1][j] \n j+=1\n count+=1\n if(j>23):\n j=0\n if((packetborn + dt.timedelta(hours= count)).date().weekday()>4):\n is_weekday = False\n else:\n is_weekday = True\n if(total !=0):\n prob = id2times/total\n problist.append(prob)\n if(problist != []):\n \n p=1\n for i in range(len(problist)):\n p *=(1-problist[i])\n p = 1-p\n \n return p\n return 0\n \n","sub_path":"ThreeRNode.py","file_name":"ThreeRNode.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24201998","text":"__appname__ = 'shop'\n__version__ = '0.0.0'\n\n# Configuration variables\napi_key = None\napi_version = 1\napi_base = 'http://127.0.0.1:54095'\n\nfrom shop import http_client\nfrom shop.resource import (\n Product\n)\n","sub_path":"shop/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483426983","text":"#!/usr/bin/python\nimport numpy as np\nimport hoomd\nfrom hoomd import md, deprecated, data, group, init\nimport gsd.hoomd\nimport sys\nimport random\n\nhoomd.context.initialize()\n\ns = hoomd.init.read_gsd(\"../Sim_dump_frame/init_strip.gsd\")\n\nfor p in s.particles:\n\tif p.type == 'A':\n\t\tx, y, z = p.position\n\t\tz += random.uniform(-0.10,0.10)\n\t\tp.position = (x,y,z)\n\nharmonic = md.bond.harmonic()\ndih = md.dihedral.harmonic()\n\n#walls.add_plane(origin=(50.5, 50.4, 0),normal=(-1,-1,0),inside=True)\n\n#dih.dihedral_coeff.set('B', k=5.000, d=1, n=1)\n#harmonic.bond_coeff.set('B', k=800.000, r0=1.0)\n\nwalls = md.wall.group()\nwalls.add_plane(origin=(-1,-1,0),normal=(1,1,0),inside=True)\nprint(walls)\n\ndih.dihedral_coeff.set('A', k=10.000, d=1, n=1)\nharmonic.bond_coeff.set('A', k=800.000, r0=1.0)\n\nlj=md.wall.lj(walls, r_cut=75.0)\nlj.force_coeff.set('B', sigma=1.0,epsilon=10.0, r_cut=75.0)\nlj.force_coeff.set('A', sigma=1.0,epsilon=0.0, r_cut=25.0)\nlj.force_coeff.set('C', sigma=1.0,epsilon=0.0, r_cut=25.0)\nlj.force_coeff.set('D', sigma=1.0,epsilon=0.0, r_cut=25.0)\n\n\nhoomd.analyze.log(filename=\"../Sim_dump_frame/observable4.log\", quantities=[\"temperature\", \"potential_energy\",\"bond_harmonic_energy\",\"kinetic_energy\",\"dihedral_harmonic_energy\"], period=5000, header_prefix=\"#\", overwrite=True)\n\nmd.integrate.mode_standard(dt=0.0010)\n\ngroup1 = hoomd.group.type(name='group1', type='A')\ngroup2 = hoomd.group.type(name='group2', type='B')\ngroup12 = hoomd.group.union(name='group12',a=group1,b=group2)\ngroup3 = hoomd.group.type(name='group1', type='D')\ngroup4 = hoomd.group.union(name='group12',a=group12,b=group3)\n\nmd.constrain.oneD(group=group2, constraint_vector=[1,1,0])\n\nhoomd.dump.gsd(filename=\"../Sim_dump_frame/trajectory4.gsd\", group=group.all(), period=5000, overwrite=True,static=[])\n\n#print(s.particles[2899])\n\n#all = group.all()\nmd.integrate.nvt(group=group12,kT=1.0, tau=0.2)\n\n#print(s.particles[5])\n\nhoomd.run(1e7)\n\n#print(s.particles[5])\n\n#hoomd.run(10)\n#print(s.particles[5])\n#print(s.bonds[5])\n","sub_path":"HOOMD_python/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470429598","text":"# -*- coding: utf-8 -*\n#rid 3 STP\nimport xlsxwriter\nfrom io import BytesIO\nimport datetime\nfrom .. import stp_config\n\ndef form_url(params):\n\tbase_url = str(stp_config.CONST.API_URL_PREFIX) + 'stp_contract_detail/'\n\tbase_url += str(params[\"year\"])\n\treturn base_url\n\n\n#Species Summary\ndef render(res, params):\n\n\trid = params[\"rid\"]\n\tyear = params[\"year\"]\n\tcon_num = params[\"con_num\"]\n\tassign_num = params[\"assign_num\"]\n\n\toutput = BytesIO()\n\tworkbook = xlsxwriter.Workbook(output, {'in_memory': True})\n\tworksheet = workbook.add_worksheet()\n\tdata = res\n\ttitle = 'Contract Preparation - Species Summary'\n\t\n\t\n\t#MAIN DATA FORMATING\n\tformat_text = workbook.add_format(stp_config.CONST.FORMAT_TEXT)\n\tformat_num = workbook.add_format(stp_config.CONST.FORMAT_NUM)\n\titem_header_format = workbook.add_format(stp_config.CONST.ITEM_HEADER_FORMAT)\t\n\n\ttitle_format = workbook.add_format(stp_config.CONST.TITLE_FORMAT)\n\titem_format_money = workbook.add_format(stp_config.CONST.ITEM_FORMAT_MONEY)\n\tsubtitle_format = workbook.add_format(stp_config.CONST.SUBTITLE_FORMAT)\n\tsubtitle_format2 = workbook.add_format(stp_config.CONST.SUBTITLE_FORMAT2)\n\tsubtotal_format = workbook.add_format(stp_config.CONST.SUBTOTAL_FORMAT)\n\tsubtotal_format_text = workbook.add_format(stp_config.CONST.SUBTOTAL_FORMAT_TEXT)\n\tsubtotal_format_money = workbook.add_format(stp_config.CONST.SUBTOTAL_FORMAT_MONEY)\n\n\t#Set column and rows\n\tworksheet.set_column('A:B', 60)\n\tworksheet.set_row(0,36)\n\tworksheet.set_row(1,36)\n\n\t#HEADER\n\t#write general header and format\n\trightmost_idx = 'B'\n\tstp_config.const.write_gen_title(title, workbook, worksheet, rightmost_idx, year, con_num)\n\n\t#additional header image\n\tworksheet.insert_image('B1', stp_config.CONST.ENV_LOGO,{'x_offset':180,'y_offset':18, 'x_scale':0.5,'y_scale':0.5, 'positioning':2})\n\n\t#MAIN DATA\n\titem_fields = ['Species', 'Quantity']\n\n\tspecies = {}\n\tcr = 7\n\t#print(data[\"items\"])\n\tfor idx, val in enumerate(data[\"items\"]):\n\t\tif \"species\" in data[\"items\"][idx]:\n\t\t\tif not data[\"items\"][idx][\"species\"] in species:\n\t\t\t\tspecies[data[\"items\"][idx][\"species\"]] = data[\"items\"][idx][\"quantity\"]\n\t\t\telse:\n\t\t\t\tspecies[data[\"items\"][idx][\"species\"]] += data[\"items\"][idx][\"quantity\"]\n\n\tworksheet.write_row('A' + str(cr), item_fields, item_header_format)\n\tcr += 1\n\n\tstart = cr\n\tfor sid, spec in enumerate(species):\n\t\t#worksheet.write('A' + str(cr), [spec, species[spec]], format_text)\n\t\tworksheet.write('A' + str(cr), spec, format_text)\n\t\tworksheet.write('B' + str(cr), species[spec], format_num)\n\n\t\tcr += 1\n\n\tworksheet.write('A{}'.format(cr), 'Total: ', subtotal_format_text)\n\tworksheet.write_formula('B{}'.format(cr), '=sum(B{}:B{})'.format(start, cr - 1), subtotal_format)\n\n\tworkbook.close()\n\t\n\txlsx_data = output.getvalue()\n\treturn xlsx_data","sub_path":"stp/report_classes/stp_ss.py","file_name":"stp_ss.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"121049386","text":"from django.urls import path\nfrom django.conf.urls import url\n\nfrom hackernews_app import views\n\n# SET THE NAMESPACE!\napp_name = 'news'\n\nurlpatterns=[\n path('register/',views.register,name='register'),\n path('user_login/',views.user_login,name='user_login'),\n path('mark_as_read//', views.mark_as_read, name='mark_as_read'),\n path('delete//', views.delete, name='delete'),\n path('my_articles/', views.user_articles, name='user_articles')\n]","sub_path":"hackernews_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436303116","text":"\"\"\"\nContains our GUI elements used to create simple menus and user interaction.\n\"\"\"\nimport sys\nimport string\nimport pygame\nfrom pygame.locals import *\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nDARKGRAY = ( 64, 64, 64)\nGRAY = (128, 128, 128)\nLIGHTGRAY = (212, 208, 200)\nACCEPTED = string.ascii_letters\n\n\nclass _Widget(object):\n def update(self, *args):\n pass #This class is meant to be overwritten\n\nclass Button(_Widget):\n def __init__(self, text = \"\", rect=None, bgcolour=(0, 0, 0), fgcolour=(0, 0, 0), normal=None, down = None, hover=None, font = None):\n self.hovering = False\n self.bDown = False\n self._visible = True\n self.imageSurface = False\n self._text = text\n self._bgcolour = bgcolour\n self._fgcolour = fgcolour\n self.customSurfaces = False\n self.lastDown = False\n \n if font is None:\n self._font = pygame.font.Font('freesansbold.ttf', 14)\n else:\n self._font = font\n \n if rect is None:\n self._rect = pygame.Rect(50,50,100,100)\n else:\n self._rect = pygame.Rect(rect)\n\n if normal is None:\n self.surfaceNormal = pygame.Surface(self._rect.size)\n self.surfaceDown = pygame.Surface(self._rect.size)\n self.surfaceHover = pygame.Surface(self._rect.size)\n self.update()\n else:\n self.surfaces(normal, down, hover)\n \n def getEvent(self, event):\n if event.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN):\n return []\n\n returnvalues = []\n exited = False\n\n if not self.hovering and self._rect.collidepoint(event.pos):\n #if mouse has entered the button:\n self.hovering = True\n returnvalues.append('enter')\n elif self.hovering and not self._rect.collidepoint(event.pos):\n #if mouse has exited the button:\n self.hovering = False\n exited = True\n\n if self._rect.collidepoint(event.pos):\n # if mouse event happened over the button:\n if event.type == MOUSEMOTION:\n returnvalues.append('move')\n elif event.type == MOUSEBUTTONDOWN:\n self.bDown = True\n self.lastDown = True\n returnvalues.append('down')\n else:\n if event.type in (MOUSEBUTTONUP, MOUSEBUTTONDOWN):\n # if an up/down happens off the button, then the next up won't cause mouseClick()\n self.lastDown = False\n\n # mouse up is handled whether or not it was over the button\n mouseClick = False\n if event.type == MOUSEBUTTONUP:\n if self.lastDown:\n mouseClick = True\n self.lastDown = False\n\n if self.bDown:\n self.bDown = False\n returnvalues.append('up')\n\n if mouseClick:\n self.bDown = False\n returnvalues.append('click')\n\n if exited:\n returnvalues.append('exit')\n\n return returnvalues\n \n def draw(self, surface):\n if self._visible:\n if self.bDown:\n surface.blit(self.surfaceDown, self._rect)\n elif self.hovering:\n surface.blit(self.surfaceHover, self._rect)\n else:\n surface.blit(self.surfaceNormal, self._rect)\n \n def hover(self):\n pass\n\n def pressed(self):\n pass\n\n def unpressed(self):\n pass\n\n def surfaces(self, normal=None, down=None, hover=None):\n if down is None:\n down = normal\n if hover is None:\n hover = normal\n\n if type(normal) == str:\n self.originalNormal = pygame.image.load(normal)\n if type(down) == str:\n self.originalDown = pygame.image.load(down)\n if type(hover) == str:\n self.originalHover = pygame.image.load(hover)\n\n if self.originalNormal.get_size() != self.originalDown.get_size() != self.originalHover.get_size():\n raise Exception('foo')\n\n self.surfaceNormal = self.originalNormal\n self.surfaceDown = self.originalDown\n self.surfaceHover = self.originalHover\n self.customSurfaces = True\n self.imageSurface = True\n if self.imageSurface:\n self.surfaceNormal = pygame.transform.smoothscale(self.originalNormal, self._rect.size)\n self.surfaceDown = pygame.transform.smoothscale(self.originalDown, self._rect.size)\n self.surfaceHover = pygame.transform.smoothscale(self.originalHover, self._rect.size) \n self._rect = pygame.Rect((self._rect.left, self._rect.top, self.surfaceNormal.get_width(), self.surfaceNormal.get_height()))\n\n def update(self):\n if self.imageSurface:\n self.surfaceNormal = pygame.transform.smoothscale(self.originalNormal, self._rect.size)\n self.surfaceDown = pygame.transform.smoothscale(self.originalDown, self._rect.size)\n self.surfaceHover = pygame.transform.smoothscale(self.originalHover, self._rect.size)\n\n width = self._rect.width\n height = self._rect.height\n\n self.surfaceNormal.fill(self._bgcolour)\n self.surfaceDown.fill(self._bgcolour)\n self.surfaceHover.fill(self._bgcolour)\n\nclass Textbox(_Widget):\n def __init__(self, rect, **kwargs):\n self.rectangle = pygame.Rect(rect)\n self.charQueue = []\n self.blink = True\n self.blink_timer = 0.0\n self.final = None\n self.rendered = None\n self.render_rect = None\n self.render_area = None\n self.process_kwargs(kwargs)\n\n def process_kwargs(self,kwargs):\n defaults = {\"id\": None,\n \"command\": None,\n \"active\": True,\n \"color\": pygame.Color(\"white\"),\n \"font_color\": pygame.Color(\"black\"),\n \"outline_color\": pygame.Color(\"black\"),\n \"outline_width\": 2,\n \"active_color\": pygame.Color(\"black\"),\n \"font\" : pygame.font.Font(None, self.rectangle.height+4),\n \"clear_on_enter\": False,\n \"inactive_on_enter\": True}\n for kwarg in kwargs:\n if kwarg in defaults:\n defaults[kwarg] = kwargs[kwarg]\n else:\n raise KeyError(\"InputBox accepts no keyword {}.\".format(kwarg))\n self.__dict__.update(defaults)\n\n def getEvent(self, event):\n if event.type == pygame.KEYDOWN and self.active:\n if event.key in (pygame.K_RETURN,pygame.K_KP_ENTER) and self.charQueue != []:\n pInput = self.charQueue\n self.execute()\n return pInput\n elif event.key == pygame.K_BACKSPACE:\n if self.charQueue:\n self.charQueue.pop()\n elif event.unicode in ACCEPTED and len(self.charQueue) < 7:\n self.charQueue.append(event.unicode)\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n self.active = self.rectangle.collidepoint(event.pos)\n\n def update(self):\n new = \"\".join(self.charQueue)\n if new != self.final:\n self.final = new\n self.rendered = self.font.render(self.final, True, self.font_color)\n self.render_rect = self.rendered.get_rect(x=self.rectangle.x+2,centery=self.rectangle.centery)\n\n if self.render_rect.width > self.rectangle.width-6:\n offset = self.render_rect.width-(self.rectangle.width-6)\n self.render_area = pygame.Rect(offset,0,self.rectangle.width-6,self.render_rect.height)\n else:\n self.render_area = self.rendered.get_rect(topleft=(0,0))\n if pygame.time.get_ticks()-self.blink_timer > 200:\n self.blink = not self.blink\n self.blink_timer = pygame.time.get_ticks()\n\n def draw(self,surface):\n outline_color = self.active_color if self.active else self.outline_color\n outline = self.rectangle.inflate(self.outline_width*2,self.outline_width*2)\n surface.fill(outline_color,outline)\n surface.fill(self.color,self.rectangle)\n if self.rendered:\n surface.blit(self.rendered,self.render_rect,self.render_area)\n if self.blink and self.active:\n curse = self.render_area.copy()\n curse.topleft = self.render_rect.topleft\n surface.fill(self.font_color,(curse.right+1,curse.y,2,curse.h))\n\n def execute(self):\n if self.command:\n self.command(self.id,self.final)\n self.active = not self.inactive_on_enter\n if self.clear_on_enter:\n self.charQueue = []","sub_path":"GUI/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467463411","text":"from socket import *\n#创建套接字\nsockfd = socket()\n\n#连接\nsockfd.connect(('127.0.0.1',4016))\n\n#收发消息\nwhile True:\n send_message = input(\"msg>>\")\n if not send_message:\n break\n sockfd.send(send_message.encode())\n data = sockfd.recv(1024)\n print(\"server:\",data.decode())\n\n#关闭\nsockfd.close()\n\n","sub_path":"SecondStage/IO/TCP_Content/TCP_client.py","file_name":"TCP_client.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"118520346","text":"import numpy\n\nfrom django.contrib.gis.geos import Polygon\nfrom django.test.utils import override_settings\nfrom raster.const import WEB_MERCATOR_SRID\nfrom raster.valuecount import RasterAggregationException, aggregator\n\nfrom .raster_testcase import RasterTestCase\n\n\n@override_settings(RASTER_TILE_CACHE_TIMEOUT=0)\nclass RasterValueCountTests(RasterTestCase):\n\n def test_value_count_no_geom(self):\n self.assertEqual(\n self.rasterlayer.value_count(),\n {str(k): v for k, v in self.expected_totals.items()}\n )\n\n def test_value_count_with_geom_covering_all(self):\n # Set extent covering all tiles\n extent = (\n -10036039.001754418, 1028700.0747658457,\n -3016471.122513413, 5548267.9540068507,\n )\n\n # Create polygon from extent\n bbox = Polygon.from_bbox(extent)\n bbox.srid = WEB_MERCATOR_SRID\n\n # Confirm global count\n self.assertEqual(\n self.rasterlayer.value_count(bbox),\n {str(key): val for key, val in self.expected_totals.items()}\n )\n # Drop nodata value from expected data\n self.assertEqual(\n self.rasterlayer.db_value_count(bbox),\n self.expected_totals\n )\n\n def test_value_count_with_geom_covering_single_tile(self):\n # Get extent from single tile\n tile = self.rasterlayer.rastertile_set.get(tilez=11, tilex=552, tiley=858)\n extent = tile.rast.extent\n\n # Create polygon from extent, transform into different projection\n bbox = Polygon.from_bbox(extent)\n bbox.srid = WEB_MERCATOR_SRID\n bbox.transform(3086)\n\n # Compute expected counts for this tile\n expected = {}\n val, counts = numpy.unique(tile.rast.bands[0].data(), return_counts=True)\n for pair in zip(val, counts):\n if pair[0] in expected:\n expected[pair[0]] += pair[1]\n else:\n expected[pair[0]] = pair[1]\n # Drop nodata value (aggregation uses masked arrays)\n expected.pop(255)\n\n # Confirm clipped count\n self.assertEqual(\n self.rasterlayer.value_count(bbox),\n {str(k): v for k, v in expected.items()}\n )\n # For db based counts, remove nodata\n self.assertEqual(\n self.rasterlayer.db_value_count(bbox),\n expected\n )\n\n def test_area_calculation_with_geom_covering_single_tile(self):\n # Get extent from single tile\n tile = self.rasterlayer.rastertile_set.get(tilez=11, tilex=552, tiley=858)\n extent = tile.rast.extent\n\n # Create polygon from extent in default projection\n bbox = Polygon.from_bbox(extent)\n bbox.srid = WEB_MERCATOR_SRID\n bbox.transform(3086)\n\n expected = {}\n val, counts = numpy.unique(tile.rast.bands[0].data(), return_counts=True)\n for pair in zip(val, counts):\n pair = (str(pair[0]), pair[1])\n if pair[0] in expected:\n expected[pair[0]] += pair[1] * 1.44374266645\n else:\n expected[pair[0]] = pair[1] * 1.44374266645\n # Drop nodata value (aggregation uses masked arrays)\n expected.pop('255')\n\n # Confirm clipped count\n result = self.rasterlayer.value_count(bbox, area=True)\n for k, v in result.items():\n self.assertAlmostEqual(v, expected[k], 5)\n\n def test_value_count_at_lower_zoom(self):\n # Precompute expected totals from value count\n expected = {}\n for tile in self.rasterlayer.rastertile_set.filter(tilez=9):\n val, counts = numpy.unique(tile.rast.bands[0].data(), return_counts=True)\n for pair in zip(val, counts):\n if pair[0] in expected:\n expected[pair[0]] += pair[1]\n else:\n expected[pair[0]] = pair[1]\n\n # Drop nodata value (aggregation uses masked arrays)\n expected.pop(255)\n\n self.assertEqual(\n self.rasterlayer.value_count(zoom=9),\n {str(k): v for k, v in expected.items()}\n )\n self.assertEqual(\n self.rasterlayer.db_value_count(zoom=9),\n expected\n )\n\n def test_value_count_for_continuous_raster(self):\n self.rasterlayer.datatype = 'co'\n self.rasterlayer.save()\n self.assertEqual(\n self.rasterlayer.value_count(),\n self.continuous_expected_histogram\n )\n\n\nclass RasterAggregatorTests(RasterTestCase):\n\n def test_layer_with_no_tiles(self):\n result = aggregator(\n layer_dict={'a': self.rasterlayer.id, 'b': self.empty_rasterlayer.id},\n formula='a*b'\n )\n self.assertDictEqual(result, {})\n\n def test_layer_discrete_grouping(self):\n result = aggregator(\n layer_dict={'a': self.rasterlayer.id},\n formula='a',\n grouping='discrete'\n )\n self.assertDictEqual(\n result,\n {str(k): v for k, v in self.expected_totals.items()}\n )\n\n def test_layer_continuous_grouping(self):\n result = aggregator(\n layer_dict={'a': self.rasterlayer.id},\n formula='a',\n grouping='continuous'\n )\n self.assertDictEqual(\n result,\n self.continuous_expected_histogram\n )\n\n def test_layer_with_legend_grouping(self):\n # Use a legend with simple int expression\n result = aggregator(\n layer_dict={'a': self.rasterlayer.id},\n formula='a',\n grouping=self.legend.id\n )\n self.assertDictEqual(\n result,\n {'2': self.expected_totals[2]}\n )\n # Use a legend with formula expression\n result = aggregator(\n layer_dict={'a': self.rasterlayer.id},\n formula='a',\n grouping=self.legend_with_expression.id\n )\n self.assertDictEqual(\n result,\n {'(x >= 2) & (x < 5)': self.expected_totals[2] + self.expected_totals[3] + self.expected_totals[4]}\n )\n\n def test_valuecount_exception(self):\n with self.assertRaises(RasterAggregationException):\n aggregator(\n layer_dict={'a': self.rasterlayer.id},\n formula='a',\n grouping='unknown'\n )\n","sub_path":"tests/test_valuecount.py","file_name":"test_valuecount.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437042978","text":"\"\"\"\nDistributed under the terms of the BSD 3-Clause License.\n\nThe full license is in the file LICENSE, distributed with this software.\n\nAuthor: Ebad Kamil and Jun Zhu \nCopyright (C) European X-Ray Free-Electron Laser Facility GmbH.\nAll rights reserved.\n\"\"\"\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (\n QCheckBox, QFileDialog, QGridLayout, QHBoxLayout, QGroupBox, QListWidget,\n QListWidgetItem, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget\n)\n\nfrom zmq.error import ZMQError\n\nfrom .base_window import _AbstractSatelliteWindow\nfrom ..ctrl_widgets.smart_widgets import SmartLineEdit\nfrom ...logger import logger\nfrom ...database import Metadata as mt\nfrom ...database import MetaProxy\nfrom ...offline import gather_sources, FileServer\n\n\nclass _FileStreamCtrlWidget(QWidget):\n\n def __init__(self, *, parent=None):\n super().__init__(parent=parent)\n\n self._load_run_btn = QPushButton(\"Load Run Folder\")\n\n self._data_folder_le = SmartLineEdit()\n\n self._serve_start_btn = QPushButton(\"Stream files\")\n self._serve_terminate_btn = QPushButton(\"Terminate\")\n self._serve_terminate_btn.setEnabled(False)\n\n self._stream_files_once_cb = QCheckBox(\"Repeat Stream\")\n self._stream_files_once_cb.setChecked(False)\n self._slow_source_list_widget = QListWidget()\n self._run_info_te = QPlainTextEdit()\n self._run_info_te.setReadOnly(True)\n\n self._slow_source_list_widget.setMinimumHeight(60)\n self.initCtrlUI()\n\n def initCtrlUI(self):\n \"\"\"Override.\"\"\"\n GROUP_BOX_STYLE_SHEET = 'QGroupBox:title {'\\\n 'color: #8B008B;' \\\n 'border: 1px;' \\\n 'subcontrol-origin: margin;' \\\n 'subcontrol-position: top left;' \\\n 'padding-left: 10px;' \\\n 'padding-top: 10px;' \\\n 'margin-top: 0.0em;}'\n layout = QVBoxLayout()\n\n load_stream_layout = QGridLayout()\n load_stream_gb = QGroupBox(\"Load and Stream\")\n load_stream_gb.setStyleSheet(GROUP_BOX_STYLE_SHEET)\n\n load_stream_layout.addWidget(self._load_run_btn, 0, 0)\n load_stream_layout.addWidget(self._data_folder_le, 0, 1, 1, 2)\n\n load_stream_layout.addWidget(self._stream_files_once_cb, 1, 0)\n load_stream_layout.addWidget(self._serve_start_btn, 1, 1)\n load_stream_layout.addWidget(self._serve_terminate_btn, 1, 2)\n\n load_stream_gb.setLayout(load_stream_layout)\n\n run_info_gb = QGroupBox(\"Data Sources and Run Info\")\n run_info_gb.setStyleSheet(GROUP_BOX_STYLE_SHEET)\n\n run_info_layout = QHBoxLayout()\n run_info_layout.addWidget(self._slow_source_list_widget)\n run_info_layout.addWidget(self._run_info_te)\n\n run_info_gb.setLayout(run_info_layout)\n\n layout.addWidget(load_stream_gb)\n layout.addWidget(run_info_gb)\n self.setLayout(layout)\n\n def initConnections(self):\n self._data_folder_le.returnPressed.connect(\n lambda: self.populateSources(\n self._data_folder_le.text()))\n\n self._data_folder_le.returnPressed.emit()\n\n self._serve_start_btn.clicked.connect(\n self.onFileServerStarted)\n self._serve_terminate_btn.clicked.connect(\n self.onFileServerStopped)\n\n self._load_run_btn.clicked.connect(self.onRunFolderLoad)\n\n def onRunFolderLoad(self):\n folder_name = QFileDialog.getExistingDirectory(\n options=QFileDialog.ShowDirsOnly)\n if folder_name:\n self._slow_source_list_widget.clear()\n self._data_folder_le.setText(folder_name)\n\n def populateSources(self, path):\n self._slow_source_list_widget.clear()\n self._run_info_te.clear()\n if path:\n sources, info = gather_sources(path)\n for src in sources:\n item = QListWidgetItem()\n item.setCheckState(Qt.Unchecked)\n item.setText(src)\n self._slow_source_list_widget.addItem(item)\n\n self._slow_source_list_widget.sortItems()\n self._run_info_te.appendPlainText(info)\n\n def onFileServerStarted(self):\n logger.info(\"File server started\")\n self._serve_start_btn.setEnabled(False)\n self._serve_terminate_btn.setEnabled(True)\n self._data_folder_le.setEnabled(False)\n self._slow_source_list_widget.setEnabled(False)\n self._load_run_btn.setEnabled(False)\n self._stream_files_once_cb.setEnabled(False)\n\n def onFileServerStopped(self):\n self._serve_start_btn.setEnabled(True)\n self._serve_terminate_btn.setEnabled(False)\n self._data_folder_le.setEnabled(True)\n self._slow_source_list_widget.setEnabled(True)\n self._load_run_btn.setEnabled(True)\n self._stream_files_once_cb.setEnabled(True)\n\n\nclass FileStreamControllerWindow(_AbstractSatelliteWindow):\n\n _title = \"File Streamer\"\n\n def __init__(self, *args, detector=None, port=None, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._detector = detector\n self._port = port\n self._data_folder = None\n self._file_server = None\n self._repeat_stream = False\n self._slow_devices = set()\n\n self._meta = MetaProxy()\n\n self._cw = QWidget()\n self._file_stream_ctrl_widget = _FileStreamCtrlWidget(parent=self)\n self._widget = self._file_stream_ctrl_widget\n\n self.initUI()\n self.setMinimumSize(800, 500)\n self.setCentralWidget(self._cw)\n\n self.initConnections()\n\n self.show()\n\n def initUI(self):\n layout = QVBoxLayout()\n layout.addWidget(self._widget)\n self._cw.setLayout(layout)\n\n def initConnections(self):\n \"\"\"Override\"\"\"\n self._widget._data_folder_le.returnPressed.connect(\n lambda: self.onFileServerDataFolderChange(\n self._widget._data_folder_le.text()))\n\n self._widget._serve_start_btn.clicked.connect(\n self.startFileServer)\n self._widget._serve_terminate_btn.clicked.connect(\n self.stopFileServer)\n\n self._widget._slow_source_list_widget.itemClicked.connect(\n lambda x: self.onSlowDeviceChange(\n x.checkState(), x.text()))\n\n self._widget._stream_files_once_cb.toggled.connect(\n self.onRepeatStreamChange)\n\n self._widget.initConnections()\n\n def onFileServerDataFolderChange(self, path):\n self._slow_devices.clear()\n self._data_folder = path if path else None\n\n def startFileServer(self):\n folder = self._data_folder\n\n if folder is None:\n logger.error(\"No run folder specified\")\n return\n\n if self._port is not None:\n port = self._port\n else:\n cfg = self._meta.hget_all(mt.CONNECTION)\n try:\n port = list(cfg.keys())[0].split(':')[-1]\n except KeyError as e:\n logger.error(repr(e))\n return\n\n slow_devices = list(self._slow_devices)\n repeat_stream = self._repeat_stream\n # process can only be start once\n self._file_server = FileServer(folder, port,\n detector=self._detector,\n slow_devices=slow_devices,\n repeat_stream=repeat_stream)\n try:\n self._file_server.start()\n\n logger.info(\"Serving file in the folder {} through port {}\"\n .format(folder, port))\n except FileNotFoundError:\n logger.info(\"{} does not exist!\".format(folder))\n except ZMQError:\n logger.info(\"Port {} is already in use!\".format(port))\n\n def stopFileServer(self):\n if self._file_server is not None and self._file_server.is_alive():\n # a file_server does not have any shared object\n logger.info(\"Shutting down File server\")\n self._file_server.terminate()\n\n if self._file_server is not None:\n # this join may be redundant\n self._file_server.join()\n\n def onSlowDeviceChange(self, state, source):\n self._slow_devices.add((source, '*')) if state \\\n else self._slow_devices.discard((source, '*'))\n\n def onRepeatStreamChange(self, state):\n self._repeat_stream = state\n\n def closeEvent(self, QCloseEvent):\n \"\"\"Override\"\"\"\n self.stopFileServer()\n super().closeEvent(QCloseEvent)\n","sub_path":"extra_foam/gui/windows/file_stream_controller_w.py","file_name":"file_stream_controller_w.py","file_ext":"py","file_size_in_byte":8672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329774190","text":"# Create your views here.\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.core.paginator import Paginator, InvalidPage, EmptyPage\nfrom django.db import connection, transaction\n\nfrom buildbotweb.buildbot.models import Tests, TestRuns, UnitTestResults, TestSuites, TestSuiteRuns, TestResults\n\ndef testrunsindex(request, testsuite_id=None):\n if testsuite_id:\n testrun_list = TestRuns.objects.all().filter(testsuiterun__testsuite__id = testsuite_id).order_by('testtime').reverse()\n testsuite = TestSuites.objects.get(id=testsuite_id).testsuite\n else:\n testrun_list = TestRuns.objects.all().order_by('testtime').reverse()\n testsuite = 'All'\n #testrun_list = TestRuns.objects.all().order_by('testtime')\n\n testruns = paginate(request, testrun_list)\n return render_to_response('testruns/index.html', {'testruns': testruns, 'testsuite':testsuite})\n\ndef testrunsdetail(request, testrun_id):\n #r = get_object_or_404(TestRuns, pk=testrun_id)\n testrun = TestRuns.objects.get(id=testrun_id)\n test = testrun.test\n results = [{'results':'N/A'}]\n if testrun.test.testtype_id == 2:\n vals = testrun.unittestresults_set.all().values()\n if vals:\n results = vals\n elif testrun.test.testtype_id == 1:\n vals = testrun.mailtestresults_set.all().values()\n if vals:\n results = vals\n else:\n results = testrun.testresults_set.all().values('result_name','result_value')\n #if vals:\n # results = {}\n # for val in vals:\n # results[val.result_name] = val.result_value\n # results = [results]\n #if vals:\n # results = [dict(map(lambda x: map(lambda y: x.get(y), x.keys()), vals)).items()]\n\n #tests = Tests.objects.filter(testsuitetests__testsuite = tsr.testsuite.id)\n #test = Tests.obje\n return render_to_response('testruns/details.html', {'testrun': testrun, 'test':test, 'results':results})\n\ndef resultsindex(request):\n testsuite_list = TestSuites.objects.all().order_by('id')\n return render_to_response('results/index.html', {'testsuites': testsuite_list})\n\ndef results(request, suiteid = None):\n results = UnitTestResults.objects.all().order_by('testrun')\n cursor = connection.cursor()\n\n sqlstr = \"\"\"\n SELECT DISTINCT\n a.id,\n svnrev, \n numtests as alltests,\n numtests - numerrors as runnabletests,\n numtests - numerrors - numfailures as passingtests,\n statements,\n statements_executed,\n (statements_executed * 1.0 / statements * 1.0) * 100.0 as pct_coverage\n FROM buildbot_unittestresults a \n INNER JOIN buildbot_testruns b \n INNER JOIN buildbot_testsuiteruns c\n ON \n a.testrun_id = b.id \n AND b.testsuiterun_id = c.id\n \"\"\"\n if suiteid:\n sqlstr = \"%s\\n%s\" % (\n sqlstr,\n \"WHERE c.testsuite_id = %s\" % suiteid\n )\n\n cursor.execute(sqlstr)\n utest_rows = cursor.fetchall()\n counter = range(len(utest_rows))\n\n\n return render_to_response('results/resultgraph.html', {'counter': counter, 'results': results, 'utest_results': utest_rows})\n\ndef allresults(request):\n return results(request, None)\n\ndef testsuiteindex(request):\n test_suites_all = TestSuites.objects.all().order_by('id').reverse()\n\n test_suites = paginate(request, test_suites_all)\n return render_to_response('testsuites/index.html', {'testsuites': test_suites})\n\ndef testsuitedetails(request, testsuite_id):\n testsuite = TestSuites.objects.all().filter(id=testsuite_id)[0]\n tests = Tests.objects.filter(testsuitetests__testsuite = testsuite.id)\n return render_to_response(\n 'testsuites/detail.html', \n {'testsuite': testsuite, 'tests': tests}\n )\n\n# Nice example of using default detail view\ndef __testsuitedetails(request, testsuite_id):\n testsuite = TestSuites.objects.all().filter(id=testsuite_id)\n return render_to_response('detail.html', {'data': testsuite.values(), 'title':'Test Suite Detail'})\n\ndef testresultsindex(request):\n test_results_all = TestResults.objects.all().order_by('id').reverse().values()\n return genericindex(request, test_results_all, 'Test Results Index')\n\n testresults = paginate(request, test_results_all)\n return render_to_response('testresults/index.html', {'testresults': testresults})\n\ndef testsindex(request):\n tests = Tests.objects.all().values()\n return genericindex(request, tests, 'Tests Index') \n\ndef paginate(request, data_all):\n paginator = Paginator(data_all, 25)\n\n try:\n page = int(request.GET.get('page', '1'))\n except ValueError:\n page = 1\n\n try:\n data = paginator.page(page)\n except (EmptyPage, InvalidPage):\n data = paginator.page(paginator.num_pages)\n\n return data\n\ndef genericindex(request, data_all, title=''):\n data = paginate(request, data_all)\n return render_to_response('index.html', {'data': data, 'title':title})\n\ndef testresults(request, testid = None, testsuiteid = None):\n test = Tests.objects.get(id = testid)\n if testid and testsuiteid:\n testruns = TestRuns.objects.filter(test__id=testid, testsuiterun__testsuite__id=testsuiteid)\n elif testid:\n testruns = TestRuns.objects.filter(test__id=testid)\n elif testsuiteid:\n testruns = TestRuns.objects.filter(testsuiterun__testsuite__id=testsuiteif)\n else:\n return testresultsindex(request)\n\n keys = []\n results = []\n count = 0\n for testrun in testruns:\n data = testrun.testresults_set.values('result_name', 'result_value')\n #data.sort()\n\n if data:\n result = {}\n result['svnrev'] = testrun.testsuiterun.svnrev\n result['data'] = data\n result['count'] = count\n if not keys:\n keycount = 2\n for datum in data:\n t_result = datum.get('result_name')\n # For some reason string.translate will not work. Odd.\n t_result = t_result.replace(\".\", \"_\")\n t_result = t_result.replace(\"_\", \"_\")\n t_result = t_result.replace(\"/\", \"_\")\n t_result = t_result.replace(\"-\", \"_\")\n keys.append({'name':t_result,'id':keycount})\n keycount+=1\n results.append(result)\n count += 1\n\n #testrun_ids = testrun.testresults_set.values('testrun').distinct()\n\n #for testrun_id in testrun_ids:\n # id = testrun_id.get('testrun')\n # data = TestResults.objects.filter(testrun=id)\n # trets = []\n # for datum in data:\n # trets.append((datum.result_name, datum.result_value))\n # trets.sort()\n # results.append(trets)\n\n return render_to_response('testresults/testresults.html', {'results':results, 'keys':keys, 'test':test})\n\ndef main(request, site_url=\"\"):\n try:\n tsr = TestSuiteRuns.objects.latest('testtime')\n # Probably should check for DoesNotExist error explicitly\n except:\n tsr = {}\n return render_to_response('main/index.html', {'tsr':tsr,'site_url':site_url})\n\ndef running_testsuites(request):\n testrun_list = TestSuiteRuns.objects.all().order_by('testtime').reverse()\n #testrun_list = TestRuns.objects.all().order_by('testtime')\n\n testsuiteruns = paginate(request, testrun_list)\n return render_to_response('testsuiteruns/index.html', {'testsuiteruns': testsuiteruns})\n\ndef testsuiterun_details(request, tsr_id):\n tsr = TestSuiteRuns.objects.get(id=tsr_id)\n \n tests = Tests.objects.filter(testsuitetests__testsuite = tsr.testsuite.id)\n testsuite = TestSuites.objects.get(id=tsr.testsuite.id)\n testruns = TestRuns.objects.filter(testsuiterun = tsr)\n\n surf = {\n 'next':tsr.id + 1,\n 'prev':tsr.id - 1\n }\n\n return render_to_response(\n 'testsuiteruns/details.html', \n {'tests': tests, 'testsuite': testsuite, 'tsr':tsr, 'testruns':testruns, 'surf':surf}\n )\n\n","sub_path":"buildbotweb/buildbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568529968","text":"from flask import Blueprint, jsonify, request, g\nfrom models.user import UserSchema, User\nfrom lib.secure_route import secure_route\n\napi = Blueprint('auth', __name__)\nuser_schema = UserSchema()\n\n@api.route('/register', methods=['POST'])\ndef register():\n\n user, errors = user_schema.load(request.get_json())\n\n if errors:\n return jsonify(errors), 422\n\n user.save()\n\n return jsonify({'message': 'Registration successful'}), 201\n\n\n@api.route('/login', methods=['POST'])\ndef login():\n\n data = request.get_json()\n user = User.query.filter_by(email=data.get('email')).first()\n\n if not user or not user.validate_password(data.get('password', '')):\n return jsonify({'message': 'Unauthorized'}), 401\n\n return jsonify({\n 'message': 'Welcome back {}!'.format(user.email),\n 'token': user.generate_token()\n })\n\n\n@api.route('/me', methods=['GET'])\n@secure_route\ndef me():\n\n return user_schema.jsonify(g.current_user)\n","sub_path":"controllers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297414118","text":"import os\nimport logging\nfrom flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_oidc import OpenIDConnect\n\n\n################### Logging information #######################\n\nlogger = logging.getLogger('api')\nlogger.setLevel(logging.DEBUG)\nfh = logging.FileHandler('api.log')\nfh.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\n '%(asctime)s - [%(name)s/%(funcName)s] - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(ch)\n\n##############################################################\n\napp = Flask(__name__)\n\nCORS(app)\n\napp.config.from_object('config')\n\n\napp.config.update({\n 'SECRET_KEY': os.getenv('SECRET_KEY'),\n 'OIDC_CLIENT_SECRETS': 'client_secrets.json',\n 'OIDC_ID_TOKEN_COOKIE_SECURE': False,\n 'OIDC_REQUIRE_VERIFIED_EMAIL': False,\n 'OIDC_USER_INFO_ENABLED': True,\n 'OIDC_OPENID_REALM': 'api',\n 'OIDC_SCOPES': ['openid', 'email', 'profile'],\n 'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post',\n 'OIDC_VALID_ISSUERS': [os.getenv('VALID_ISSUER')]\n})\n\noidc = OpenIDConnect(app)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQL_URI')\n# silence the deprecation warning\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n\nfrom src.crud.controller import ap\nfrom src.auth.controller import auth\n\napp.register_blueprint(ap)\napp.register_blueprint(auth)\n\n@app.errorhandler(404)\ndef not_found(e):\n return error(\"No exite la ruta para la url deseada en esta api\"), 404\n\n\n@app.errorhandler(405)\ndef doesnt_exist(e):\n return error(\"No exite la ruta para la url deseada en esta api\"), 405\n\n\ndef error(message):\n return jsonify({\n 'success': False,\n 'message': message\n })\n","sub_path":"src/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"544470286","text":"#random.choice() random.int()\n\nimport random\n\na=[\"the\",\"a\"]\ns=[\"cat\",\"dog\",\"woman\",\"man\"]\ng=[\"sang\",\"ran\",\"jumped\",]\nn=[\"loudly\",\"quietly\",\"well\",\"badly\"]\nP=[a,s,g,n]\n\n\ncount=0\nparam=5\n\ntry:\n x=int(input(\"введите количество строк >>> \"))\n if x!=None:\n param=x\nexcept ValueError as err:\n None\n\nprint()\n\nwhile count 0:\n payload = Raw(RandString(size=remaining_size))\n pkt = pkt / payload\n\n return pkt\n\ndef modify_packet(pkt):\n pkt = add_payload(pkt)\n pkt = add_eth_hdr(pkt)\n\n return pkt\n\ndef parse_file_and_append(file_name, write_file, task_idx):\n global total_tasks\n\n local_pkt_dict = dict()\n\n command = f'capinfos {file_name} | grep \"Number of packets\" | tr -d \" \" | grep -oP \"Numberofpackets=\\K\\d+\"'\n output = subprocess.check_output(command, shell=True, universal_newlines=True)\n maxentries = int(output.strip())\n tot_pbar = maxentries\n\n multiplier = (task_idx - 1) * MAX_FILE_SIZE\n with PcapNgReader(file_name) as pcap_reader:\n for j in atpbar(range(tot_pbar), name=f\"Task {task_idx}/{total_tasks}\"):\n if j < maxentries:\n pkt = pcap_reader.read_packet()\n pkt = modify_packet(pkt)\n if pkt is not None:\n local_pkt_dict[int(multiplier + j)] = (pkt.time, pkt)\n\n with PcapNgWriter(write_file) as writer:\n for _, buf in local_pkt_dict.values():\n writer.write(buf)\n\n return write_file\n\n\ndef modify_and_write_pcap(input_file, output_file):\n global total_tasks\n \n final_list = []\n file_list = []\n\n tmp_dir = tempfile.TemporaryDirectory(dir = \"/tmp\")\n ret = subprocess.call(f\"editcap -c {MAX_FILE_SIZE} {input_file} {tmp_dir.name}/trace.pcap\", shell=True)\n for file in os.listdir(tmp_dir.name):\n if file.endswith(\".pcap\"):\n write_file = os.path.splitext(file)[0] + \"_write.pcap\"\n file_list.append((file, write_file))\n\n file_list.sort(key=lambda x: x[0])\n\n prepend_str = tmp_dir.name + \"/\"\n file_list = [(prepend_str + a, prepend_str + b) for a, b in file_list]\n\n total_tasks = len(file_list)\n print(f\"Total number of tasks will be {total_tasks}\")\n\n task_order_list = list()\n task_idx = 0\n task_order_list.append(task_idx)\n\n reporter = find_reporter()\n future_to_file = dict()\n with concurrent.futures.ProcessPoolExecutor(max_workers=max(os.cpu_count(), 8), initializer=register_reporter, initargs=[reporter]) as executor:\n for file, write_file in file_list:\n task_idx += 1\n future_to_file[executor.submit(parse_file_and_append, copy.deepcopy(file), copy.deepcopy(write_file), copy.deepcopy(task_idx))] = file\n flush()\n print(\"Waiting for tasks to complete...\")\n print(f\"Total tasks: {len(future_to_file)}\")\n for future in concurrent.futures.as_completed(future_to_file):\n file = future_to_file[future]\n try:\n file_written = future.result()\n final_list.append(file_written)\n except Exception as exc:\n print('%r generated an exception: %s' % (file, exc))\n\n print(f\"Created {len(final_list)} pcap files\") \n\n final_list.sort()\n\n print(\"Let's concatenate all the files\")\n\n # create a single string with elements separated by a space\n files_to_write = ' '.join(final_list)\n\n print(f\"The files to write are {files_to_write}\")\n\n ret = subprocess.call(f\"mergecap -a {files_to_write} -w {output_file}\", shell=True)\n if ret != 0:\n print(f\"Error merging files into {output_file}\")\n return -1\n \n print(f\"Finished merging all files into {output_file}\")\n tmp_dir.cleanup()\n\n return 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Program used to convert a PCAP into a numpy data structure (easier to work with)')\n parser.add_argument(\"-i\", \"--input-file\", required=True, type=str, help=\"Filename for input PCAP\")\n parser.add_argument(\"-o\", \"--output-file\", required=True, type=str, help=\"Filename for output parsed numpy file (for efficient loading)\")\n parser.add_argument(\"-c\", \"--count\", metavar=\"count\", type=int, default=-1, help=\"Number of packets to read before stopping. Default is -1 (no limit).\")\n parser.add_argument(\"-v\",\"--verbose\", action=\"store_true\", help=\"Show additional debug info.\")\n parser.add_argument(\"-j\", \"--json\", action=\"store_true\", help=\"Output JSON instead of numpy array\")\n\n args = parser.parse_args()\n\n input_file_path = args.input_file\n output_file_path = args.output_file\n\n # check if mergecap is installed\n if not shutil.which(\"mergecap\"):\n print(\"mergecap not found. Please install wireshark.\")\n sys.exit(1)\n \n # check if editcap is installed\n if not shutil.which(\"editcap\"):\n print(\"editcap not found. Please install wireshark.\")\n sys.exit(1)\n\n # check if capinfos is installed\n if not shutil.which(\"capinfos\"):\n print(\"capinfos not found. Please install wireshark.\")\n sys.exit(1)\n\n try:\n os.remove(output_file_path)\n except OSError:\n pass\n\n modify_and_write_pcap(input_file_path, output_file_path)\n\n print(f\"Output file created: {output_file_path}\")\n","sub_path":"pcap-tools/pcap-rewrite-scapy.py","file_name":"pcap-rewrite-scapy.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631102965","text":"import json\nimport CustomNeuronClassSet as CS\nimport createPlots as CP\nimport plotBuilder as PB\nimport plotly.graph_objs as go\nimport colour\nfrom collections import defaultdict\nimport plotly.plotly as py\nimport numpy as np\n\n'''\nNeurons present in buildSet:\nVPN = [284703, 292771, 1143611, 6107965]\nOtherVisual = [7741106, 3734117]\nVisualInterneuron = [867713, 2977775, 864634, 2438338]\nJO = [7664963, 8255422, 8576699, 8578056, 9594272]\nMechanoInter = [3785330, 1200640, 4140263, 4223727]\nNonVisInter = [2416268, 2260024]\nAscending = [3483710, 2799979]\nDescending = [3410595, 7164401]\nGF = 4947529\nGF2 = 291870\n'''\n\ndef multimodalCheck(mySet):\n modals = ['Visual_Interneuron', 'Non-Visual_Interneuron', 'Mechanosensory Interneuron']\n multiModal = []\n for neuron in mySet:\n results = {}\n annos = neuron.annotations\n for mode in modals:\n results[mode] = annos.count(mode)\n if sum(results.values()) > 1:\n multiModal.append(neuron)\n for i in multiModal:\n if \"JONeuron\" in i.annotations:\n multiModal.remove(i)\n if \"Visual\" in i.annotations:\n multiModal.remove(i)\n if \"Descending Neuron\" in i.annotations:\n multiModal.remove(i)\n if \"Ascending Neuron\" in i.annotations:\n multiModal.remove(i)\n mmLen = len(multiModal)\n taggedModal = []\n for i in mySet:\n if \"Multi-Modal\" in i.annotations:\n taggedModal.append(i)\n tmLen = len(taggedModal)\n twoTag = []\n for i in mySet:\n if \"Visual_Interneuron\" in i.annotations and \"Mechanosensory Interneuron\" in i.annotations and \"Descending Neuron\" not in i.annotations and \"Ascending Neuron\" not in i.annotations:\n twoTag.append(i)\n ttLen = len(twoTag)\n diff_list = []\n # print(ttLen)\n # print(tmLen)\n # print(mmLen)\n if mmLen == tmLen == ttLen:\n return\n elif mmLen == tmLen != ttLen:\n mmNames = []\n ttNames= []\n for i in multiModal:\n mmNames.append(i.neuronName)\n for i in twoTag:\n ttNames.append(i.neuronName)\n diff_list = np.setdiff1d(mmNames, ttNames)\n print(diff_list)\n raise Exception(\"Two Tag not the same\")\n elif mmLen != tmLen == ttLen:\n mmNames = []\n ttNames = []\n for i in multiModal:\n mmNames.append(i.neuronName)\n for i in twoTag:\n ttNames.append(i.neuronName)\n diff_list = np.setdiff1d(mmNames, ttNames)\n print(diff_list)\n raise Exception(\"Multi-Modal not the same\")\n elif mmLen == ttLen != tmLen:\n mmNames = []\n tMNames = []\n for i in multiModal:\n mmNames.append(i.neuronName)\n for i in taggedModal:\n tMNames.append(i.neuronName)\n diff_list = np.setdiff1d(mmNames, tMNames)\n print(diff_list)\n raise Exception(\"Tagged Modal not the same\")\n else:\n raise Exception(\"Unknown Error\")\n return\n\ndef getPosterModalities(mySet):\n multimodalCheck(mySet)\n for i in mySet:\n if \"Multi-Modal\" in i.annotations:\n i.modality = 'Multi-Modal'\n elif \"Visual_Interneuron\" in i.annotations:\n i.modality = \"Visual Interneuron\"\n elif \"Non-Visual_Interneuron\" in i.annotations:\n i.modality = \"Non-Visual Interneuron\"\n elif \"Mechanosensory Interneuron\" in i.annotations:\n i.modality = \"Mechanosensory Interneuron\"\n if \"Neuron Fragment\" in i.annotations:\n i.modality = \"Unknown\"\n if \"Descending Neuron\" in i.annotations:\n i.modality = \"Descending Neuron\"\n if \"Ascending Neuron\" in i.annotations:\n i.modality = \"Ascending Neuron\"\n if \"Visual\" in i.annotations:\n i.modality = \"VPN\"\n if \"JONeuron\" in i.annotations:\n i.modality = \"JONeuron\"\n if \"Other Visual\" in i.annotations:\n i.modality = \"VPN\"\n return\n\n'''def buildModalitySet():\n allIDs = [3410595, 7164401, 3483710, 2799979, 2416268, 2260024, 3785330, 1200640, 4140263, 4223727, 7664963,\n 8255422, 8576699, 8578056, 9594272, 867713, 2977775, 864634, 2438338, 7741106, 3734117, 284703, 292771,\n 1143611, 6107965]\n modalitySet = CS.buildFromSkidList(allIDs)\n modalitySet.findModality()\n return modalitySet'''\n\ndef buildPosterModalitySet():\n allIDs = [3410595, 7164401, 3483710, 2799979, 2416268, 2260024, 3785330, 1200640, 4140263, 4223727, 7664963,\n 8255422, 8576699, 8578056, 9594272, 867713, 2977775, 864634, 2438338, 7741106, 3734117, 292771,\n 1143611, 874409, 3658067]\n modalitySet = CS.buildFromSkidList(allIDs)\n getPosterModalities(modalitySet)\n return modalitySet\n\ndef createJSON(inputSet):\n aListOfNeurons = []\n for item in inputSet:\n mySKID = item.skeletonID\n color = item.curColor\n aNeuron = {\n \"skeleton_id\": mySKID,\n \"color\": color,\n \"opacity\": 1\n }\n aListOfNeurons.append(aNeuron)\n GF1 = {\n \"skeleton_id\": 4947529,\n \"color\": \"rgb(135, 135, 135)\",\n \"opacity\": 1\n }\n GF2 = {\n \"skeleton_id\": 291870,\n \"color\": \"rgb(135, 135, 135)\",\n \"opacity\": 1\n }\n aListOfNeurons.append(GF1)\n aListOfNeurons.append(GF2)\n myJSON = json.dumps(aListOfNeurons, separators=(', \\n', ': '))\n return myJSON\n\ndef modalityImage():\n modalitySet = buildPosterModalitySet()\n for i in modalitySet:\n if i.modality == \"JONeuron\":\n i.curColor = \"rgb(255, 242, 0)\"\n elif i.modality == \"VPN\":\n i.curColor = \"rgb(197, 108, 240)\"\n elif i.modality == \"Multi-Modal\":\n i.curColor = \"rgb(6, 82, 221)\"\n elif i.modality == \"Visual Interneuron\":\n i.curColor = \"rgb(255, 56, 56)\"\n elif i.modality == \"Mechanosensory Interneuron\":\n i.curColor = \"rgb(255, 159, 26)\"\n elif i.modality == \"Non-Visual Interneuron\":\n i.curColor = \"rgb(58, 227, 116)\"\n elif i.modality == \"Ascending Neuron\":\n i.curColor = \"rgb(23, 192, 235)\"\n elif i.modality == \"Descending Neuron\":\n i.curColor = \"rgb(0,0,0)\"\n myJSON = createJSON(modalitySet)\n c = open(\"ModalityImage.json\", 'w')\n c.write(myJSON)\n c.close()\n return\n\n'''\nusing the color website: https://flatuicolors.com/\nscheme 1 = dutch top, scheme 2 = dutch bottom\nscheme 3 = turkish, scheme 4 = german\na few colors may be switched out in schemes\n'''\n\ndef colorSchemeJSON(modalitySet):\n for i in modalitySet:\n i.curColor = None\n getPosterModalities(modalitySet)\n for i in modalitySet:\n if i.modality == \"JONeuron\":\n i.curColor = \"rgb(255, 242, 0)\"\n elif i.modality == \"VPN\":\n i.curColor = \"rgb(197, 108, 240)\"\n elif i.modality == \"Multi-Modal\":\n i.curColor = \"rgb(6, 82, 221)\"\n elif i.modality == \"Visual Interneuron\":\n i.curColor = \"rgb(255, 56, 56)\"\n elif i.modality == \"Mechanosensory Interneuron\":\n i.curColor = \"rgb(255, 159, 26)\"\n elif i.modality == \"Non-Visual Interneuron\":\n i.curColor = \"rgb(58, 227, 116)\"\n elif i.modality == \"Ascending Neuron\":\n i.curColor = \"rgb(23, 192, 235)\"\n elif i.modality == \"Descending Neuron\":\n i.curColor = \"rgb(0,0,0)\"\n myJSON = createJSON(modalitySet)\n c = open(\"PosterColorScheme.json\", 'w')\n c.write(myJSON)\n c.close()\n return\n\n\n\"\"\"\nLC4s = [310806, 873664, 873720, 874359, 1060221, 1060322, 1077585, 1108155, 1325578]\n\"\"\"\n\"\"\"\nLPLC2s = [1143465, 5996597, 1143611, 1316553, 1316678, 1316994, 1317004, 3755062, 3815708]\n\"\"\"\n\"\"\"\nGCI = [295022, 308072, 2369058]\n\"\"\"\n\"\"\"\nJO = [7460597, 7426399, 7237462, 7196379, 6864302, 6544974, 6538032, 5296246, 3786320]\n\"\"\"\n\"\"\"\nDNp06 = [3158872]\n\"\"\"\n\"\"\"\ntypes = LC4, LPLC2, DNp06, GCI, JO\n\"\"\"\ndef knownTypesJSON(type):\n LC4s = [310806, 873664, 873720, 874359, 1060221, 1060322, 1077585, 1108155, 1325578]\n LPLC2s = [1143465, 5996597, 1143611, 1316553, 1316678, 1316994, 1317004, 3755062, 3815708]\n GCI = [295022, 308072, 2369058]\n JO = [7460597, 7426399, 7237462, 7196379, 6864302, 6544974, 6538032, 5296246, 3786320]\n DNp06 = [3158872]\n\n if type == \"LC4\":\n LC4Set = CS.buildFromSkidList(LC4s)\n for i in LC4Set:\n i.curColor = \"rgb(197, 108, 240)\"\n myJSON = createJSON(LC4Set)\n elif type == \"LPLC2\":\n LPLC2Set = CS.buildFromSkidList(LPLC2s)\n for i in LPLC2Set:\n i.curColor = \"rgb(197, 108, 240)\"\n myJSON = createJSON(LPLC2Set)\n elif type == \"GCI\":\n GCISet = CS.buildFromSkidList(GCI)\n for i in GCISet:\n i.curColor = \"rgb(255, 56, 56)\"\n myJSON = createJSON(GCISet)\n elif type == \"JO\":\n JOSet = CS.buildFromSkidList(JO)\n for i in JOSet:\n i.curColor = \"rgb(255, 242, 0)\"\n myJSON = createJSON(JOSet)\n elif type == \"DNp06\":\n DNp06Set = CS.buildFromSkidList(DNp06)\n for i in DNp06Set:\n i.curColor = \"rgb(0,0,0)\"\n myJSON = createJSON(DNp06Set)\n\n c = open(\"Known\" + str(type) + \"colored.json\", 'w')\n c.write(myJSON)\n c.close()\n return\n\n\n\n#---------------------------------------------------------------------------------------------------\n\n#histogram by type\ndef gfClassHistogram(mySet, filename='Poster/HistogramByType_Synapse'):\n mySet = CS.sortBySynH2L(mySet)\n classes = []\n GF1Syn = []\n mySetCopy = CP.shortenClassNames(mySet)\n\n classif = defaultdict(list)\n for neuron in mySetCopy:\n classes.append(neuron.classification)\n GF1Syn.append(neuron.GF1synapseCount)\n classif[neuron.classification].append(neuron.GF1synapseCount)\n\n countsList = []\n for v in classif.values():\n countsList.append(len(v))\n keys = list(classif.keys())\n values = []\n for k, v in classif.items():\n sum = 0\n for syn in v:\n sum = sum + syn\n values.append(sum)\n\n values, keys, countsList = zip(*sorted(zip(values, keys, countsList),reverse=True))\n countsList = list(countsList)\n\n trace1 = go.Bar(\n x= keys,\n y=values,\n text=countsList,\n textposition='outside'\n )\n data = [trace1]\n layout = go.Layout(\n bargap=0.2,\n margin=go.layout.Margin(\n b=300,\n r=200\n ),\n title=\"Class Synapse Count\",\n yaxis=dict(title='Synapse Count'),\n )\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n#histogram by type\ndef gfClassHistogram2(mySet, filename='Poster/HistogramByType_Neuron'):\n mySet = CS.sortBySynH2L(mySet)\n classes = []\n GF1Syn = []\n mySetCopy = CP.shortenClassNames(mySet)\n\n classif = defaultdict(list)\n for neuron in mySetCopy:\n classes.append(neuron.classification)\n GF1Syn.append(neuron.GF1synapseCount)\n classif[neuron.classification].append(neuron.GF1synapseCount)\n\n countsList = []\n for v in classif.values():\n countsList.append(len(v))\n keys = list(classif.keys())\n values = []\n lengths = []\n for k, v in classif.items():\n sum = 0\n lengths.append(len(v))\n for syn in v:\n sum = sum + syn\n values.append(sum)\n\n\n lengths, keys, countsList = zip(*sorted(zip(lengths, keys, countsList),reverse=True))\n countsList = list(countsList)\n\n trace1 = go.Bar(\n x=keys,\n y=lengths,\n textposition='outside'\n )\n data = [trace1]\n layout = go.Layout(\n bargap=0.2,\n margin=go.layout.Margin(\n b=300,\n r=200\n ),\n title=\"Class Synapse Count\",\n yaxis=dict(title='Synapse Count'),\n )\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\n\ndef makePosterModalityBars(mySet, filename='Poster/ModalityBars'):\n mySetCopy = CP.shortenClassNames(mySet)\n #removed other visual\n keys = ['VPN', 'Non-Visual Interneuron', 'JONeuron', 'Mechanosensory Interneuron',\n 'Visual Interneuron', 'Multi-Modal', 'Descending Neuron',\n 'Ascending Neuron', 'Unknown']\n modalities = {k: [] for k in keys}\n for neuron in mySetCopy:\n modalities[neuron.modality].append(neuron)\n modalities.pop('Unknown')\n keys = list(modalities.keys())\n values = []\n for k, v in modalities.items():\n values.append(len(v))\n # H -> L : VPN, NVI, JO, MI, VI, MM, DN, AN\n colors = ['rgb(197, 108, 240)', \"rgb(58, 227, 116)\",\n 'rgb(255, 242, 0)', 'rgb(255, 159, 26)', \"rgb(255, 56, 56)\",\n \"rgb(6, 82, 221)\", 'rgb(0,0,0)', \"rgb(23, 192, 235)\"]\n Modalities = go.Bar(\n name='Modalities',\n x=keys,\n y=values,\n # text=values,\n textposition='auto',\n marker=dict(color=colorbis)\n\n )\n layout = go.Layout(autosize=False,\n showlegend=False,\n margin=dict(b=200),\n bargap=0\n # title='Modality Bars by Neuron Count',\n # xaxis=dict(\n # tickfont=dict(size=20),\n # range=[-0.5, 10]\n # ),\n # yaxis=dict(title='Neuron Count'),\n # legend=dict(\n # font=dict(\n # size=30\n # )\n # )\n )\n data = [Modalities]\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\ndef makePosterModalityBarsBySynapse(mySet, filename='Poster/ModalityBarsSynapse'):\n mySetCopy = CP.shortenClassNames(mySet)\n #removed other visual\n getPosterModalities(mySetCopy)\n keys = ['VPN', 'Multi-Modal','Mechanosensory Interneuron', \"JONeuron\",\n 'Non-Visual Interneuron', 'Visual Interneuron', 'Descending Neuron',\n 'Ascending Neuron', 'Unknown']\n modalities = {k: [] for k in keys}\n for neuron in mySetCopy:\n modalities[neuron.modality].append(neuron)\n modalities.pop('Unknown')\n keys = list(modalities.keys())\n values = defaultdict(int)\n GFSyns = 0\n for k, v in modalities.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.GF1synapseCount\n values[k] = GFSyns\n GFSyns = 0\n # H -> L : VPN, MM, MI, JO, NVI, VI, DN, AN\n colors = ['rgb(197, 108, 240)', \"rgb(6, 82, 221)\",\n \"rgb(255, 159, 26)\", \"rgb(255, 242, 0)\", \"rgb(58, 227, 116)\",\n \"rgb(255, 56, 56)\", 'rgb(0,0,0)', \"rgb(23, 192, 235)\"]\n values2 = list(values.values())\n Modalities = go.Bar(\n name='Modalities',\n x=keys,\n y=values2,\n # text=values,\n textposition='auto',\n marker=dict(color=colors)\n\n )\n layout = go.Layout(autosize=False,\n showlegend=False,\n margin=dict(b=200),\n bargap=0\n # title='Modality Bars by Neuron Count',\n # xaxis=dict(\n # tickfont=dict(size=20),\n # range=[-0.5, 10]\n # ),\n # yaxis=dict(title='Neuron Count'),\n # legend=dict(\n # font=dict(\n # size=30\n # )\n # )\n )\n data = [Modalities]\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\n\ndef makePosterTopInputtingPlotAll(mySet, filename='Poster/Top10'):\n mySetCopy = CP.shortenClassNames(mySet)\n summedDict = CP.synapseDict(mySetCopy)\n\n top10 = {k: summedDict[k] for k in list(summedDict)[:10]}\n\n #colors = ['rgb(197, 108, 240)', 'rgb(255, 242, 0)', 'rgb(197, 108, 240)',\n # 'rgb(240,0,172)', 'rgb(240,0,172)', 'rgb(240,0,172)',\n # 'rgb(240,0,172)', 'rgb(240,0,172)', 'rgb(240,0,172)',\n # 'rgb(240,0,172)']\n#VPN, JO, VPN, MI, MM, MM, MI, MM, DESC, NVI\n colors = ['rgb(197, 108, 240)', 'rgb(255, 242, 0)', 'rgb(197, 108, 240)',\n \"rgb(255, 56, 56)\", \"rgb(6, 82, 221)\", \"rgb(6, 82, 221)\",\n \"rgb(255, 159, 26)\", \"rgb(6, 82, 221)\", \"rgb(0,0,0)\", \"rgb(58, 227, 116)\"]\n keys = list(top10.keys())\n keys = ['LC4', 'JO', 'LPLC2', 'Type 25', 'Type 10', 'Type 8', 'Type 30*', 'Type 31*', 'Type 3', 'Type 2a*']\n values = list(top10.values())\n trace1 = go.Bar(\n x = keys,\n y=values,\n marker=dict(color=list(colors)),\n text=None,\n #width=[0.3, 0.3, 0.3, 0.3, 0.3,0.3, 0.3, 0.3, 0.3, 0.3]\n )\n data = [trace1]\n layout = go.Layout(\n margin=go.layout.Margin(\n b=300,\n r=200\n ),\n xaxis=None,\n bargap = 0\n )\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\ndef makePosterTopTenNeurons(mySet, filename='Poster/Top10Neurons'):\n mySet = CS.sortBySynH2L(mySet)\n top10 = mySet[0:10]\n getPosterModalities(mySet)\n colors = []\n for i in top10:\n if i.modality == \"JONeuron\":\n i.curColor = \"rgb(255, 242, 0)\"\n elif i.modality == \"VPN\":\n i.curColor = \"rgb(197, 108, 240)\"\n elif i.modality == \"Multi-Modal\":\n i.curColor = \"rgb(6, 82, 221)\"\n elif i.modality == \"Visual Interneuron\":\n i.curColor = \"rgb(255, 56, 56)\"\n elif i.modality == \"Mechanosensory Interneuron\":\n i.curColor = \"rgb(255, 159, 26)\"\n elif i.modality == \"Non-Visual Interneuron\":\n i.curColor = \"rgb(58, 227, 116)\"\n elif i.modality == \"Ascending Neuron\":\n i.curColor = \"rgb(23, 192, 235)\"\n elif i.modality == \"Descending Neuron\":\n i.curColor = \"rgb(0,0,0)\"\n neuronNames = []\n GFSYN = []\n for i in top10:\n colors.append(i.curColor)\n\n for neuron in top10:\n GFSYN.append(neuron.GF1synapseCount)\n neuronNames.append(neuron.neuronName)\n\n aListOfNeurons = []\n for item in top10:\n mySKID = item.skeletonID\n aNeuron = {\n \"skeleton_id\": mySKID,\n \"color\": item.curColor,\n \"opacity\": 1\n }\n aListOfNeurons.append(aNeuron)\n myJSON = json.dumps(aListOfNeurons, separators=(', \\n', ': '))\n c = open('top10Neurons.json', 'w')\n c.write(myJSON)\n c.close()\n trace1 = go.Bar(\n y=GFSYN,\n x=neuronNames,\n marker=dict(color=list(colors))\n )\n data = [trace1]\n layout = go.Layout(\n margin=go.layout.Margin(\n b=300,\n r=200\n )\n )\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\ndef makePosterSynapseBars(mySet, filename='Poster/Synapse Count Bars'):\n mySet = CS.sortBySynH2L(mySet)\n GFSYN = []\n neuronNames = []\n for neuron in mySet:\n GFSYN.append(neuron.GF1synapseCount)\n neuronNames.append(neuron.neuronName)\n colors = []\n color = str()\n getPosterModalities(mySet)\n for i in mySet:\n if i.modality == \"JONeuron\":\n i.curColor = \"rgb(255, 242, 0)\"\n elif i.modality == \"VPN\":\n i.curColor = \"rgb(197, 108, 240)\"\n elif i.modality == \"Multi-Modal\":\n i.curColor = \"rgb(6, 82, 221)\"\n elif i.modality == \"Visual Interneuron\":\n i.curColor = \"rgb(255, 56, 56)\"\n elif i.modality == \"Mechanosensory Interneuron\":\n i.curColor = \"rgb(255, 159, 26)\"\n elif i.modality == \"Non-Visual Interneuron\":\n i.curColor = \"rgb(58, 227, 116)\"\n elif i.modality == \"Ascending Neuron\":\n i.curColor = \"rgb(23, 192, 235)\"\n elif i.modality == \"Descending Neuron\":\n i.curColor = \"rgb(0,0,0)\"\n else:\n i.curColor = \"rgb(192,192,192)\"\n colors.append(i.curColor)\n trace1 = go.Bar(\n y=GFSYN,\n marker=dict(color=colors)\n )\n data = [trace1]\n layout = go.Layout(\n bargap=0.2,\n margin=go.layout.Margin(\n b=300,\n r=200\n ),\n # title=\"Individual Neuron Synapse Count\"\n )\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\n\n\ndef makePosterStackedModalityByNeuron(mySet, filename='Poster/Stacked Modalities By Neuron Count'):\n mySetCopy = CP.shortenClassNames(mySet)\n branches = defaultdict(list)\n for neuron in mySetCopy:\n if \"Input to GF1 anterior\" in neuron.annotations:\n branches[\"Anterior\"].append(neuron)\n if \"Input to GF1 lateral\" in neuron.annotations:\n branches[\"Lateral\"].append(neuron)\n if \"Input to GF1 medial\" in neuron.annotations:\n branches[\"Medial\"].append(neuron)\n if \"Input to GF1 descending tract\" in neuron.annotations:\n branches[\"Descending Tract\"].append(neuron)\n if \"Input to GF1 soma tract\" in neuron.annotations:\n branches[\"Soma Tract\"].append(neuron)\n\n AnteriorModes = defaultdict(list)\n LateralModes = defaultdict(list)\n MedialModes = defaultdict(list)\n DescendingModes = defaultdict(list)\n SomaModes = defaultdict(list)\n\n for neuron in branches['Anterior']:\n AnteriorModes[neuron.modality].append(neuron)\n for neuron in branches['Lateral']:\n LateralModes[neuron.modality].append(neuron)\n for neuron in branches['Medial']:\n MedialModes[neuron.modality].append(neuron)\n for neuron in branches['Descending Tract']:\n DescendingModes[neuron.modality].append(neuron)\n for neuron in branches['Soma Tract']:\n SomaModes[neuron.modality].append(neuron)\n\n AnteriorModesSummed = defaultdict(int)\n for k, v in AnteriorModes.items():\n AnteriorModesSummed[k] = len(v)\n # AnteriorModesSummed.pop('default_factory')\n\n LateralModesSummed = defaultdict(int)\n for k, v in LateralModes.items():\n LateralModesSummed[k] = (len(v))\n # LateralModesSummed.pop('default_factory')\n MedialModesSummed = defaultdict(int)\n for k, v in MedialModes.items():\n MedialModesSummed[k] = (len(v))\n # MedialModesSummed.pop('default_factory')\n DescendingModesSummed = defaultdict(int)\n for k, v in DescendingModes.items():\n DescendingModesSummed[k] = (len(v))\n # DescendingModesSummed.pop('default_factory')\n SomaModesSummed = defaultdict(int)\n for k, v in SomaModes.items():\n SomaModesSummed[k] = (len(v))\n # SomaModesSummed.pop('default_factory')\n\n VPN = []\n VI = []\n MM = []\n NVI = []\n JO = []\n MI = []\n DN = []\n AN = []\n\n branches = [\"Anterior\", \"Lateral\", \"Medial\", \"Descending Tract\", \"Soma Tract\"]\n allBranchesSummed = [AnteriorModesSummed, LateralModesSummed,\n MedialModesSummed, DescendingModesSummed,\n SomaModesSummed]\n for branch in allBranchesSummed:\n if 'Visual Interneuron' in branch:\n VI.append(branch['Visual Interneuron'])\n else:\n VI.append(0)\n if 'VPN' in branch:\n VPN.append(branch['VPN'])\n else:\n VPN.append(0)\n if 'Multi-Modal' in branch:\n MM.append(branch['Multi-Modal'])\n else:\n MM.append(0)\n if 'Non-Visual Interneuron' in branch:\n NVI.append(branch['Non-Visual Interneuron'])\n else:\n NVI.append(0)\n if 'JONeuron' in branch:\n JO.append(branch['JONeuron'])\n else:\n JO.append(0)\n if 'Mechanosensory Interneuron' in branch:\n MI.append(branch['Mechanosensory Interneuron'])\n else:\n MI.append(0)\n if 'Descending Neuron' in branch:\n DN.append((branch['Descending Neuron']))\n else:\n DN.append(0)\n if 'Ascending Neuron' in branch:\n AN.append(branch['Ascending Neuron'])\n else:\n AN.append(0)\n\n sumAnt = sum(AnteriorModesSummed.values())\n sumLat = sum(LateralModesSummed.values())\n sumMed = sum(MedialModesSummed.values())\n sumDesc = sum(DescendingModesSummed.values())\n sumSoma = sum(SomaModesSummed.values())\n\n trace1 = go.Bar(\n y=branches,\n x=VPN,\n # text=VPN,\n # textposition='auto',\n name='VPN',\n marker=dict(color='rgb(197, 108, 240)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace2 = go.Bar(\n y=branches,\n x=MM,\n # text=OV,\n # textposition='auto',\n name='Multi-Modal',\n marker=dict(color='rgb(6, 82, 221)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace3 = go.Bar(\n y=branches,\n x=VI,\n # text=VI,\n # textposition='auto',\n name='Visual Interneuron',\n marker=dict(color='rgb(255, 56, 56)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace4 = go.Bar(\n y=branches,\n x=JO,\n # text=JO,\n # textposition='auto',\n name='JONeuron',\n marker=dict(color='rgb(255, 242, 0)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace5 = go.Bar(\n y=branches,\n x=MI,\n # text=MI,\n # textposition='auto',\n name='Mechanosensory Interneuron',\n marker=dict(color='rgb(255, 159, 26)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace6 = go.Bar(\n y=branches,\n x=NVI,\n # text=NVI,\n # textposition='auto',\n name='Non-Visual Interneuron',\n marker=dict(color='rgb(58, 227, 116)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace7 = go.Bar(\n y=branches,\n x=AN,\n # text=AN,\n # textposition='auto',\n name='Ascending Neuron',\n marker=dict(color='rgb(23, 192, 235)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace8 = go.Bar(\n y=branches,\n x=DN,\n # text=DN,\n # textposition='auto',\n name='Descending Neuron',\n marker=dict(color='rgb(0,0,0)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n layout = go.Layout(\n barmode='stack',\n autosize=False,\n # title=\"Modality by Branch by Neuron Count\",\n barnorm='percent',\n # xaxis=dict(title='Neuron Count'),\n # yaxis=dict(\n # tickfont=dict(size=10)\n # )\n )\n data = [trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8]\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\ndef makePosterStackedModalityBySynapse(mySet, filename='Poster/Stacked Modalities by Synapse'):\n mySetCopy = CP.shortenClassNames(mySet)\n branches = defaultdict(list)\n for neuron in mySetCopy:\n if \"Input to GF1 anterior\" in neuron.annotations:\n branches[\"Anterior\"].append(neuron)\n if \"Input to GF1 lateral\" in neuron.annotations:\n branches[\"Lateral\"].append(neuron)\n if \"Input to GF1 medial\" in neuron.annotations:\n branches[\"Medial\"].append(neuron)\n if \"Input to GF1 descending tract\" in neuron.annotations:\n branches[\"Descending Tract\"].append(neuron)\n if \"Input to GF1 soma tract\" in neuron.annotations:\n branches[\"Soma Tract\"].append(neuron)\n\n AnteriorModes = defaultdict(list)\n LateralModes = defaultdict(list)\n MedialModes = defaultdict(list)\n DescendingModes = defaultdict(list)\n SomaModes = defaultdict(list)\n\n for neuron in branches['Anterior']:\n AnteriorModes[neuron.modality].append(neuron)\n for neuron in branches['Lateral']:\n LateralModes[neuron.modality].append(neuron)\n for neuron in branches['Medial']:\n MedialModes[neuron.modality].append(neuron)\n for neuron in branches['Descending Tract']:\n DescendingModes[neuron.modality].append(neuron)\n for neuron in branches['Soma Tract']:\n SomaModes[neuron.modality].append(neuron)\n\n GFSyns = 0\n AnteriorModesSummed = defaultdict(int)\n for k, v in AnteriorModes.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.synapsesByBranch['anterior']\n AnteriorModesSummed[k] = GFSyns\n GFSyns = 0\n\n LateralModesSummed = defaultdict(int)\n for k, v in LateralModes.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.synapsesByBranch['lateral']\n LateralModesSummed[k] = GFSyns\n GFSyns = 0\n\n MedialModesSummed = defaultdict(int)\n for k, v in MedialModes.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.synapsesByBranch['medial']\n MedialModesSummed[k] = GFSyns\n GFSyns = 0\n\n DescendingModesSummed = defaultdict(int)\n for k, v in DescendingModes.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.synapsesByBranch['descending tract']\n DescendingModesSummed[k] = GFSyns\n GFSyns = 0\n\n SomaModesSummed = defaultdict(int)\n for k, v in SomaModes.items():\n for neuron in v:\n GFSyns = GFSyns + neuron.synapsesByBranch['soma tract']\n SomaModesSummed[k] = GFSyns\n GFSyns = 0\n\n VPN = []\n VI = []\n MM = []\n NVI = []\n JO = []\n MI = []\n DN = []\n AN = []\n\n branches = [\"Anterior\", \"Lateral\", \"Medial\", \"Descending Tract\", \"Soma Tract\"]\n allBranchesSummed = [AnteriorModesSummed, LateralModesSummed,\n MedialModesSummed, DescendingModesSummed,\n SomaModesSummed]\n for branch in allBranchesSummed:\n if 'Visual Interneuron' in branch:\n VI.append(branch['Visual Interneuron'])\n else:\n VI.append(0)\n if 'VPN' in branch:\n VPN.append(branch['VPN'])\n else:\n VPN.append(0)\n if 'Multi-Modal' in branch:\n MM.append(branch['Multi-Modal'])\n else:\n MM.append(0)\n if 'Non-Visual Interneuron' in branch:\n NVI.append(branch['Non-Visual Interneuron'])\n else:\n NVI.append(0)\n if 'JONeuron' in branch:\n JO.append(branch['JONeuron'])\n else:\n JO.append(0)\n if 'Mechanosensory Interneuron' in branch:\n MI.append(branch['Mechanosensory Interneuron'])\n else:\n MI.append(0)\n if 'Descending Neuron' in branch:\n DN.append((branch['Descending Neuron']))\n else:\n DN.append(0)\n if 'Ascending Neuron' in branch:\n AN.append(branch['Ascending Neuron'])\n else:\n AN.append(0)\n\n trace1 = go.Bar(\n y=branches,\n x=VPN,\n # text=VPN,\n # textposition='auto',\n name='VPN',\n marker=dict(color='rgb(197, 108, 240)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace2 = go.Bar(\n y=branches,\n x=MM,\n # text=OV,\n # textposition='auto',\n name='Multi-Modal',\n marker=dict(color='rgb(6, 82, 221)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace3 = go.Bar(\n y=branches,\n x=VI,\n # text=VI,\n # textposition='auto',\n name='Visual Interneuron',\n marker=dict(color='rgb(255, 56, 56)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace4 = go.Bar(\n y=branches,\n x=JO,\n # text=JO,\n # textposition='auto',\n name='JONeuron',\n marker=dict(color='rgb(255, 242, 0)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace5 = go.Bar(\n y=branches,\n x=MI,\n # text=MI,\n # textposition='auto',\n name='Mechanosensory Interneuron',\n marker=dict(color='rgb(255, 159, 26)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace6 = go.Bar(\n y=branches,\n x=NVI,\n # text=NVI,\n # textposition='auto',\n name='Non-Visual Interneuron',\n marker=dict(color='rgb(58, 227, 116)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace7 = go.Bar(\n y=branches,\n x=AN,\n # text=AN,\n # textposition='auto',\n name='Ascending Neuron',\n marker=dict(color='rgb(23, 192, 235)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n trace8 = go.Bar(\n y=branches,\n x=DN,\n # text=DN,\n # textposition='auto',\n name='Descending Neuron',\n marker=dict(color='rgb(0,0,0)'),\n # width=[0.3, 0.3, 0.3, 0.3, 0.3],\n orientation='h'\n )\n layout = go.Layout(\n barmode='stack',\n autosize=False,\n # title=\"Modality by Branch by Synapse Count\",\n barnorm='percent',\n # xaxis=dict(title='Synapse Count'),\n # yaxis=dict(\n # tickfont=dict(size=10)\n # )\n )\n data = [trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8]\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename=filename)\n return\n\n\n\n# returns list of neurons in mySet that have the modality given.\ndef modalityList(mySet, modality):\n modalityOnly = []\n for i in mySet:\n if i.modality == modality:\n modalityOnly.append(i)\n\n return modalityOnly\n\ndef modalitySkid(mySet, modality):\n modalSkid = []\n modalOnly = modalityList(mySet, modality)\n for item in modalOnly:\n modalSkid.append(item.skeletonID)\n\n return modalSkid\n# returns tuple of connectorID, {cID, x, y, z, conf, partners)\n# includes ALL partners of connector ID\n# MUST use another formula to retrieve relevant skeletons\n# Can be used for XYZ coordinates\n# params: mySet - gf set, allInfo - returned list from 'getSynInfo', modality - string\ndef modalitySynapses(mySet, allInfo, modality):\n\n modal_Skid = modalitySkid(mySet, modality)\n\n modal_Syn = []\n for item in allInfo.items():\n for partner in item[1]['partners']:\n if partner['relation_name'] == 'presynaptic_to':\n if partner['skeleton_id'] in modal_Skid:\n modal_Syn.append(item)\n\n return modal_Syn\n\ndef getModalityTrace(mySet, allInfo, modality, rgb):\n x_vals = []\n y_vals = []\n z_vals = []\n synapses = modalitySynapses(mySet, allInfo, modality)\n for item in synapses:\n x_vals.append(item[1]['x'])\n y_vals.append(item[1]['y'])\n z_vals.append(item[1]['z'])\n modalTrace = go.Scatter3d(\n x=x_vals,\n y=y_vals,\n z=z_vals,\n mode='markers',\n marker=dict(\n size=5,\n color=rgb),\n name=modality)\n return modalTrace\n\ndef createModalityScatterPlot(mySet, allInfo):\n Structure = CP.createStructure()\n VPN = getModalityTrace(mySet, allInfo, \"VPN\", 'rgb(197, 108, 240)')\n JONeuron = getModalityTrace(mySet, allInfo, \"JONeuron\", 'rgb(255, 242, 0)')\n MultiModal = getModalityTrace(mySet, allInfo, \"Multi-Modal\", 'rgb(6, 82, 221)')\n VisualInterneuron = getModalityTrace(mySet, allInfo, \"Visual Interneuron\", 'rgb(255, 56, 56)')\n MechanoInterneuron = getModalityTrace(mySet, allInfo, \"Mechanosensory Interneuron\", 'rgb(255, 159, 26)')\n NonVisInterneuron = getModalityTrace(mySet, allInfo, \"Non-Visual Interneuron\", 'rgb(58, 227, 116)')\n Ascending = getModalityTrace(mySet, allInfo, \"Ascending Neuron\", 'rgb(23, 192, 235)')\n Descending = getModalityTrace(mySet, allInfo, \"Descending Neuron\", 'rgb(0, 0, 0)')\n\n allData = [Structure, VPN, JONeuron, MultiModal, VisualInterneuron, MechanoInterneuron, NonVisInterneuron,\n\n Ascending, Descending]\n\n PB.createPlotlyPlot(allData, \"Poster/All Modality Synapse Scatter\")\n return\n","sub_path":"poster.py","file_name":"poster.py","file_ext":"py","file_size_in_byte":36016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365270411","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\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 proto # type: ignore\n\nfrom google.cloud.iot_v1.types import resources\nfrom google.protobuf import field_mask_pb2 # type: ignore\n\n\n__protobuf__ = proto.module(\n package='google.cloud.iot.v1',\n manifest={\n 'CreateDeviceRegistryRequest',\n 'GetDeviceRegistryRequest',\n 'DeleteDeviceRegistryRequest',\n 'UpdateDeviceRegistryRequest',\n 'ListDeviceRegistriesRequest',\n 'ListDeviceRegistriesResponse',\n 'CreateDeviceRequest',\n 'GetDeviceRequest',\n 'UpdateDeviceRequest',\n 'DeleteDeviceRequest',\n 'ListDevicesRequest',\n 'GatewayListOptions',\n 'ListDevicesResponse',\n 'ModifyCloudToDeviceConfigRequest',\n 'ListDeviceConfigVersionsRequest',\n 'ListDeviceConfigVersionsResponse',\n 'ListDeviceStatesRequest',\n 'ListDeviceStatesResponse',\n 'SendCommandToDeviceRequest',\n 'SendCommandToDeviceResponse',\n 'BindDeviceToGatewayRequest',\n 'BindDeviceToGatewayResponse',\n 'UnbindDeviceFromGatewayRequest',\n 'UnbindDeviceFromGatewayResponse',\n },\n)\n\n\nclass CreateDeviceRegistryRequest(proto.Message):\n r\"\"\"Request for ``CreateDeviceRegistry``.\n Attributes:\n parent (str):\n Required. The project and cloud region where this device\n registry must be created. For example,\n ``projects/example-project/locations/us-central1``.\n device_registry (google.cloud.iot_v1.types.DeviceRegistry):\n Required. The device registry. The field ``name`` must be\n empty. The server will generate that field from the device\n registry ``id`` provided and the ``parent`` field.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n device_registry = proto.Field(\n proto.MESSAGE,\n number=2,\n message=resources.DeviceRegistry,\n )\n\n\nclass GetDeviceRegistryRequest(proto.Message):\n r\"\"\"Request for ``GetDeviceRegistry``.\n Attributes:\n name (str):\n Required. The name of the device registry. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass DeleteDeviceRegistryRequest(proto.Message):\n r\"\"\"Request for ``DeleteDeviceRegistry``.\n Attributes:\n name (str):\n Required. The name of the device registry. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass UpdateDeviceRegistryRequest(proto.Message):\n r\"\"\"Request for ``UpdateDeviceRegistry``.\n Attributes:\n device_registry (google.cloud.iot_v1.types.DeviceRegistry):\n Required. The new values for the device registry. The ``id``\n field must be empty, and the ``name`` field must indicate\n the path of the resource. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Required. Only updates the ``device_registry`` fields\n indicated by this mask. The field mask must not be empty,\n and it must not contain fields that are immutable or only\n set by the server. Mutable top-level fields:\n ``event_notification_config``, ``http_config``,\n ``mqtt_config``, and ``state_notification_config``.\n \"\"\"\n\n device_registry = proto.Field(\n proto.MESSAGE,\n number=1,\n message=resources.DeviceRegistry,\n )\n update_mask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass ListDeviceRegistriesRequest(proto.Message):\n r\"\"\"Request for ``ListDeviceRegistries``.\n Attributes:\n parent (str):\n Required. The project and cloud region path. For example,\n ``projects/example-project/locations/us-central1``.\n page_size (int):\n The maximum number of registries to return in the response.\n If this value is zero, the service will select a default\n size. A call may return fewer objects than requested. A\n non-empty ``next_page_token`` in the response indicates that\n more data is available.\n page_token (str):\n The value returned by the last\n ``ListDeviceRegistriesResponse``; indicates that this is a\n continuation of a prior ``ListDeviceRegistries`` call and\n the system should return the next page of data.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n page_size = proto.Field(\n proto.INT32,\n number=2,\n )\n page_token = proto.Field(\n proto.STRING,\n number=3,\n )\n\n\nclass ListDeviceRegistriesResponse(proto.Message):\n r\"\"\"Response for ``ListDeviceRegistries``.\n Attributes:\n device_registries (Sequence[google.cloud.iot_v1.types.DeviceRegistry]):\n The registries that matched the query.\n next_page_token (str):\n If not empty, indicates that there may be more registries\n that match the request; this value should be passed in a new\n ``ListDeviceRegistriesRequest``.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n device_registries = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=resources.DeviceRegistry,\n )\n next_page_token = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass CreateDeviceRequest(proto.Message):\n r\"\"\"Request for ``CreateDevice``.\n Attributes:\n parent (str):\n Required. The name of the device registry where this device\n should be created. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n device (google.cloud.iot_v1.types.Device):\n Required. The device registration details. The field\n ``name`` must be empty. The server generates ``name`` from\n the device registry ``id`` and the ``parent`` field.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n device = proto.Field(\n proto.MESSAGE,\n number=2,\n message=resources.Device,\n )\n\n\nclass GetDeviceRequest(proto.Message):\n r\"\"\"Request for ``GetDevice``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n field_mask (google.protobuf.field_mask_pb2.FieldMask):\n The fields of the ``Device`` resource to be returned in the\n response. If the field mask is unset or empty, all fields\n are returned. Fields have to be provided in snake_case\n format, for example: ``last_heartbeat_time``.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n field_mask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass UpdateDeviceRequest(proto.Message):\n r\"\"\"Request for ``UpdateDevice``.\n Attributes:\n device (google.cloud.iot_v1.types.Device):\n Required. The new values for the device. The ``id`` and\n ``num_id`` fields must be empty, and the field ``name`` must\n specify the name path. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\\ or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Required. Only updates the ``device`` fields indicated by\n this mask. The field mask must not be empty, and it must not\n contain fields that are immutable or only set by the server.\n Mutable top-level fields: ``credentials``, ``blocked``, and\n ``metadata``\n \"\"\"\n\n device = proto.Field(\n proto.MESSAGE,\n number=2,\n message=resources.Device,\n )\n update_mask = proto.Field(\n proto.MESSAGE,\n number=3,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass DeleteDeviceRequest(proto.Message):\n r\"\"\"Request for ``DeleteDevice``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ListDevicesRequest(proto.Message):\n r\"\"\"Request for ``ListDevices``.\n Attributes:\n parent (str):\n Required. The device registry path. Required. For example,\n ``projects/my-project/locations/us-central1/registries/my-registry``.\n device_num_ids (Sequence[int]):\n A list of device numeric IDs. If empty, this\n field is ignored. Maximum IDs: 10,000.\n device_ids (Sequence[str]):\n A list of device string IDs. For example,\n ``['device0', 'device12']``. If empty, this field is\n ignored. Maximum IDs: 10,000\n field_mask (google.protobuf.field_mask_pb2.FieldMask):\n The fields of the ``Device`` resource to be returned in the\n response. The fields ``id`` and ``num_id`` are always\n returned, along with any other fields specified in\n snake_case format, for example: ``last_heartbeat_time``.\n gateway_list_options (google.cloud.iot_v1.types.GatewayListOptions):\n Options related to gateways.\n page_size (int):\n The maximum number of devices to return in the response. If\n this value is zero, the service will select a default size.\n A call may return fewer objects than requested. A non-empty\n ``next_page_token`` in the response indicates that more data\n is available.\n page_token (str):\n The value returned by the last ``ListDevicesResponse``;\n indicates that this is a continuation of a prior\n ``ListDevices`` call and the system should return the next\n page of data.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n device_num_ids = proto.RepeatedField(\n proto.UINT64,\n number=2,\n )\n device_ids = proto.RepeatedField(\n proto.STRING,\n number=3,\n )\n field_mask = proto.Field(\n proto.MESSAGE,\n number=4,\n message=field_mask_pb2.FieldMask,\n )\n gateway_list_options = proto.Field(\n proto.MESSAGE,\n number=6,\n message='GatewayListOptions',\n )\n page_size = proto.Field(\n proto.INT32,\n number=100,\n )\n page_token = proto.Field(\n proto.STRING,\n number=101,\n )\n\n\nclass GatewayListOptions(proto.Message):\n r\"\"\"Options for limiting the list based on gateway type and\n associations.\n\n Attributes:\n gateway_type (google.cloud.iot_v1.types.GatewayType):\n If ``GATEWAY`` is specified, only gateways are returned. If\n ``NON_GATEWAY`` is specified, only non-gateway devices are\n returned. If ``GATEWAY_TYPE_UNSPECIFIED`` is specified, all\n devices are returned.\n associations_gateway_id (str):\n If set, only devices associated with the specified gateway\n are returned. The gateway ID can be numeric (``num_id``) or\n the user-defined string (``id``). For example, if ``123`` is\n specified, only devices bound to the gateway with ``num_id``\n 123 are returned.\n associations_device_id (str):\n If set, returns only the gateways with which the specified\n device is associated. The device ID can be numeric\n (``num_id``) or the user-defined string (``id``). For\n example, if ``456`` is specified, returns only the gateways\n to which the device with ``num_id`` 456 is bound.\n \"\"\"\n\n gateway_type = proto.Field(\n proto.ENUM,\n number=1,\n oneof='filter',\n enum=resources.GatewayType,\n )\n associations_gateway_id = proto.Field(\n proto.STRING,\n number=2,\n oneof='filter',\n )\n associations_device_id = proto.Field(\n proto.STRING,\n number=3,\n oneof='filter',\n )\n\n\nclass ListDevicesResponse(proto.Message):\n r\"\"\"Response for ``ListDevices``.\n Attributes:\n devices (Sequence[google.cloud.iot_v1.types.Device]):\n The devices that match the request.\n next_page_token (str):\n If not empty, indicates that there may be more devices that\n match the request; this value should be passed in a new\n ``ListDevicesRequest``.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n devices = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=resources.Device,\n )\n next_page_token = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass ModifyCloudToDeviceConfigRequest(proto.Message):\n r\"\"\"Request for ``ModifyCloudToDeviceConfig``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n version_to_update (int):\n The version number to update. If this value\n is zero, it will not check the version number of\n the server and will always update the current\n version; otherwise, this update will fail if the\n version number found on the server does not\n match this version number. This is used to\n support multiple simultaneous updates without\n losing data.\n binary_data (bytes):\n Required. The configuration data for the\n device.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n version_to_update = proto.Field(\n proto.INT64,\n number=2,\n )\n binary_data = proto.Field(\n proto.BYTES,\n number=3,\n )\n\n\nclass ListDeviceConfigVersionsRequest(proto.Message):\n r\"\"\"Request for ``ListDeviceConfigVersions``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n num_versions (int):\n The number of versions to list. Versions are\n listed in decreasing order of the version\n number. The maximum number of versions retained\n is 10. If this value is zero, it will return all\n the versions available.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n num_versions = proto.Field(\n proto.INT32,\n number=2,\n )\n\n\nclass ListDeviceConfigVersionsResponse(proto.Message):\n r\"\"\"Response for ``ListDeviceConfigVersions``.\n Attributes:\n device_configs (Sequence[google.cloud.iot_v1.types.DeviceConfig]):\n The device configuration for the last few\n versions. Versions are listed in decreasing\n order, starting from the most recent one.\n \"\"\"\n\n device_configs = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=resources.DeviceConfig,\n )\n\n\nclass ListDeviceStatesRequest(proto.Message):\n r\"\"\"Request for ``ListDeviceStates``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n num_states (int):\n The number of states to list. States are\n listed in descending order of update time. The\n maximum number of states retained is 10. If this\n value is zero, it will return all the states\n available.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n num_states = proto.Field(\n proto.INT32,\n number=2,\n )\n\n\nclass ListDeviceStatesResponse(proto.Message):\n r\"\"\"Response for ``ListDeviceStates``.\n Attributes:\n device_states (Sequence[google.cloud.iot_v1.types.DeviceState]):\n The last few device states. States are listed\n in descending order of server update time,\n starting from the most recent one.\n \"\"\"\n\n device_states = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=resources.DeviceState,\n )\n\n\nclass SendCommandToDeviceRequest(proto.Message):\n r\"\"\"Request for ``SendCommandToDevice``.\n Attributes:\n name (str):\n Required. The name of the device. For example,\n ``projects/p0/locations/us-central1/registries/registry0/devices/device0``\n or\n ``projects/p0/locations/us-central1/registries/registry0/devices/{num_id}``.\n binary_data (bytes):\n Required. The command data to send to the\n device.\n subfolder (str):\n Optional subfolder for the command. If empty,\n the command will be delivered to the\n /devices/{device-id}/commands topic, otherwise\n it will be delivered to the /devices/{device-\n id}/commands/{subfolder} topic. Multi-level\n subfolders are allowed. This field must not have\n more than 256 characters, and must not contain\n any MQTT wildcards (\"+\" or \"#\") or null\n characters.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n binary_data = proto.Field(\n proto.BYTES,\n number=2,\n )\n subfolder = proto.Field(\n proto.STRING,\n number=3,\n )\n\n\nclass SendCommandToDeviceResponse(proto.Message):\n r\"\"\"Response for ``SendCommandToDevice``. \"\"\"\n\n\nclass BindDeviceToGatewayRequest(proto.Message):\n r\"\"\"Request for ``BindDeviceToGateway``.\n Attributes:\n parent (str):\n Required. The name of the registry. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n gateway_id (str):\n Required. The value of ``gateway_id`` can be either the\n device numeric ID or the user-defined device identifier.\n device_id (str):\n Required. The device to associate with the specified\n gateway. The value of ``device_id`` can be either the device\n numeric ID or the user-defined device identifier.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n gateway_id = proto.Field(\n proto.STRING,\n number=2,\n )\n device_id = proto.Field(\n proto.STRING,\n number=3,\n )\n\n\nclass BindDeviceToGatewayResponse(proto.Message):\n r\"\"\"Response for ``BindDeviceToGateway``. \"\"\"\n\n\nclass UnbindDeviceFromGatewayRequest(proto.Message):\n r\"\"\"Request for ``UnbindDeviceFromGateway``.\n Attributes:\n parent (str):\n Required. The name of the registry. For example,\n ``projects/example-project/locations/us-central1/registries/my-registry``.\n gateway_id (str):\n Required. The value of ``gateway_id`` can be either the\n device numeric ID or the user-defined device identifier.\n device_id (str):\n Required. The device to disassociate from the specified\n gateway. The value of ``device_id`` can be either the device\n numeric ID or the user-defined device identifier.\n \"\"\"\n\n parent = proto.Field(\n proto.STRING,\n number=1,\n )\n gateway_id = proto.Field(\n proto.STRING,\n number=2,\n )\n device_id = proto.Field(\n proto.STRING,\n number=3,\n )\n\n\nclass UnbindDeviceFromGatewayResponse(proto.Message):\n r\"\"\"Response for ``UnbindDeviceFromGateway``. \"\"\"\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/iot/v1/iot-v1-py/google/cloud/iot_v1/types/device_manager.py","file_name":"device_manager.py","file_ext":"py","file_size_in_byte":21272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459018776","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 9 10:05:24 2019\r\n\r\n@author: PRASHANT\r\n\"\"\"\r\n\r\n#GRADING \r\nx=float(input(\"Enter marks out of 100: \")) #prompt user for marks\r\n\r\nif(x<=100.0 and x>=0.0): #check for valid marks\r\n if(x>90.0): \r\n grade='A'\r\n elif(x<=90.0 and x>80.0):\r\n grade='B'\r\n elif(x<=80.0 and x>70.0):\r\n grade='C'\r\n elif(x<=70.0 and x>60.0):\r\n grade='D'\r\n elif(x<=60.0):\r\n grade='FAIL'\r\n \r\n print(\"GRADE AWARDED IS:\",grade) #show grade\r\nelse:\r\n print(\"ENTER VALID MARKS!!!\") \r\n\r\n\r\n\r\n \r\n ","sub_path":"GRADING.py","file_name":"GRADING.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168909779","text":"from scipy import *\nimport scipy.io\nimport scipy.ndimage\nimport numpy as np\nimport scipy.optimize as spoptim\nimport numpy.random\nimport matplotlib\n#matplotlib.use('Agg') # When running on cluster, plots cannot be shown and this must be used\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nplt.rc('image', cmap='viridis')\nfrom scipy import optimize\nnumpy.random.seed(13)\nfrom multiprocessing import Pool\nfrom sklearn.decomposition import PCA\n\n################################################\n# Parameters for inference, not for generating #\n################################################\nT = 2000 #2000 # Max time 85504\n\nN = 51 #73 #16 # Total of 73 neurons\n # Time offset 70400: cutoff_spike_number 10:19 50:16 100:16 200:14\n # Time offset 0: downsample 2: cutoff_spike_number 30-50:16 100:15\n # downsample 1: cutoff_spike_number 30:16 50:15\nprint(\"N =\", N, \"but take care that it must be changed manually if neuron screening settings are changed\")\n\nN_iterations = 0\nglobal_initial_sigma_n = 2.5\nsigma_n = np.copy(global_initial_sigma_n) # Assumed variance of observations for the GP that is fitted. 10e-5\nlr = 0.99 # Learning rate by which we multiply sigma_n at every iteration\n\n# Parameters for data loading #\ndownsampling_factor = 1 #supreme: 2\noffset = 0 # 0 is good and wraps around a lot #64460 (not so good) #68170 (getting stuck lower in middle) # 70400 (supreme)\n\nKEEP_PATH_BETWEEN_ZERO_AND_TWO_PI = True\nINFER_F_POSTERIORS = True\nGRADIENT_FLAG = True # Set True to use analytic gradient\nUSE_OFFSET_AND_SCALING_AT_EVERY_ITERATION = False\nUSE_OFFSET_AND_SCALING_AFTER_CONVERGENCE = True\nUSE_ONLY_OFFSET_AFTER_CONVERGENCE = False\nTOLERANCE = 1e-5\nX_initialization = \"pca\" #\"true\" \"ones\" \"pca\" \"randomrandom\" \"flatrandom\" \"randomprior\" \"linspace\" \"supreme\"\nsmoothingwindow_for_PCA = 4\nPCA_TYPE = \"angle\" #\"angle\" \"1d\"\nUSE_ENTIRE_DATA_LENGTH_FOR_PCA_INITIALIZATION = False\nLET_INDUCING_POINTS_CHANGE_PLACE_WITH_X_ESTIMATE = False # If False, they stay at (min_inducing_point, max_inducing_point)\nFLIP_AFTER_SOME_ITERATION = False\nFLIP_AFTER_HOW_MANY = 1\nNOISE_REGULARIZATION = False\nSMOOTHING_REGULARIZATION = False\nGIVEN_TRUE_F = False\nSPEEDCHECK = False\nOPTIMIZE_HYPERPARAMETERS = False\nPLOTTING = True\nLIKELIHOOD_MODEL = \"poisson\" # \"bernoulli\" \"poisson\"\nCOVARIANCE_KERNEL_KX = \"periodic\" # \"periodic\" \"nonperiodic\"\nPLOT_GRADIENT_CHECK = False\nN_inducing_points = 30 # Number of inducing points. Wu uses 25 in 1D and 10 per dim in 2D\nN_plotgridpoints = 30 # Number of grid points for plotting f posterior only \nsigma_f_fit = 8 # Variance for the tuning curve GP that is fitted. 8\ndelta_f_fit = 0.5 # Scale for the tuning curve GP that is fitted. 0.3\nmin_inducing_point = 0\nmax_inducing_point = 2*np.pi\n# For inference:\nsigma_x = 5 # Variance of X for K_t\ndelta_x = 50 # Scale of X for K_t\njitter_term = 1e-5\ncutoff_spike_number = 30 # How many spikes a neuron must produce in chosen time interval for us to include it\n\nprint(\"-- using Peyrache parameter file --\")","sub_path":"goodplotcodes/pre-03-07-peyrache-param-file-possibly-for-overview.py","file_name":"pre-03-07-peyrache-param-file-possibly-for-overview.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226798008","text":"#!/usr/bin/env python\n\nimport re\n\nparsed_table = []\n\nwith open('slr_table.txt', 'r') as f:\n table = f.readlines()\n\n for line in table:\n line = re.sub(' +',',', line)\n if line[-1] == '\\n':\n line = line[:-1]\n if line[0] == ',':\n line = line[1:]\n parsed_table.append(line)\n\nwith open('slr_table.csv', 'w') as f:\n for line in parsed_table:\n f.write(line + '\\n')\n","sub_path":"Trabalho3/src/to_csv.py","file_name":"to_csv.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643908899","text":"import numpy as np \nimport pandas as pd \nfrom sklearn.feature_extraction.text import CountVectorizer\n\ndata = pd.read_excel('attitudes_all.xlsx',encoding = 'ansi')\n\ncount_vectorizer = CountVectorizer(ngram_range=(1, 2),stop_words = 'english')\n\ndf = data.copy()\nX_text = df['tweet']\ncount_vectorizer.fit(X_text)\nX = count_vectorizer.transform(X_text)\nwords = count_vectorizer.get_feature_names()\nprint(type(words))\nprint(type(X.toarray()))\nwords_df = pd.DataFrame(X.toarray())\nwords_df.columns = words\nwords_df = words_df.T\nwords_df['row_sum'] = words_df.apply(lambda x: x.sum(), axis = 1)\nprint(words_df['row_sum'])\nwords_df['row_sum'].to_csv('word_frequency_only.csv')\nprint('finish')","sub_path":"FINAL/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165873058","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import #zmiana strategii ladowanie modulow w py2 z relative na absolute jak w py3\nfrom Components.config import config\nfrom Components.Converter.Converter import Converter\nfrom Components.Element import cached\nfrom Components.Converter.Poll import Poll\n\ntry: #obejscie dla VTI 11, ktore nie ma konwertera genre\n from Components.Converter.genre import getGenreStringSub\nexcept Exception:\n def getGenreStringSub(hn = None, ln = None):\n return ''\n\nDBG = False\ntry:\n if DBG: from Components.j00zekComponents import j00zekDEBUG\nexcept Exception:\n DBG = False\n\nclass j00zekModEventName(Poll, Converter, object):\n NAME = 0\n SHORT_DESCRIPTION = 1\n EXTENDED_DESCRIPTION = 2\n FULL_DESCRIPTION = 3\n ID = 4\n NAME_NOW = 5\n NAME_NEXT = 6\n GENRE = 7\n RATING = 8\n SRATING = 9\n PDC = 10\n PDCTIME = 11\n PDCTIMESHORT = 12\n ISRUNNINGSTATUS = 13\n EPGPIC = 14\n\n def __init__(self, type):\n Converter.__init__(self, type)\n Poll.__init__(self)\n self.picFileName = ''\n self.poll_interval = 100\n self.WaitForEvent = True\n \n if type == \"Description\":\n self.type = self.SHORT_DESCRIPTION\n elif type == \"ExtendedDescription\":\n self.type = self.EXTENDED_DESCRIPTION\n elif type == \"FullDescription\":\n self.type = self.FULL_DESCRIPTION\n elif type == \"ID\":\n self.type = self.ID\n elif type == \"NameNow\":\n self.type = self.NAME_NOW\n elif type == \"NameNext\":\n self.type = self.NAME_NEXT\n elif type == \"Genre\":\n self.type = self.GENRE\n elif type == \"Rating\":\n self.type = self.RATING\n elif type == \"SmallRating\":\n self.type = self.SRATING\n elif type == \"Pdc\":\n self.type = self.PDC\n elif type == \"PdcTime\":\n self.type = self.PDCTIME\n elif type == \"PdcTimeShort\":\n self.type = self.PDCTIMESHORT\n elif type == \"IsRunningStatus\":\n self.type = self.ISRUNNINGSTATUS\n elif type.startswith('isEPGpic:'):\n self.type = self.EPGPIC\n self.picFileName = type.split(':')[1]\n else:\n self.type = self.NAME\n\n @cached\n def getBoolean(self):\n event = self.source.event\n if event is None:\n return False\n if self.type == self.PDC:\n if event.getPdcPil():\n return True\n return False\n\n boolean = property(getBoolean)\n\n @cached\n def getText(self):\n event = self.source.event\n if event is None:\n if self.WaitForEvent == True:\n if DBG: j00zekDEBUG(\"[j00zekModEventName:getText] event is None, wating 100ms\")\n self.poll_enabled = True\n self.WaitForEvent = False\n else:\n self.poll_enabled = False\n if DBG: j00zekDEBUG(\"[j00zekModEventName:getText] event is None\")\n return \"\"\n else:\n if DBG: j00zekDEBUG(\"[j00zekModEventName:getText] event data found\")\n self.WaitForEvent = True #for next event\n self.poll_enabled = False\n \n if self.type == self.NAME:\n return event.getEventName()\n elif self.type == self.SRATING:\n rating = event.getParentalData()\n if rating is None:\n return \"\"\n else:\n country = rating.getCountryCode()\n age = rating.getRating()\n if age == 0:\n return _(\"All ages\")\n elif age > 15:\n return _(\"bc%s\") % age\n else:\n age += 3\n return \" %d+\" % age\n elif self.type == self.RATING:\n rating = event.getParentalData()\n if rating is None:\n return \"\"\n else:\n country = rating.getCountryCode()\n age = rating.getRating()\n if age == 0:\n return _(\"Rating undefined\")\n elif age > 15:\n return _(\"Rating defined by broadcaster - %d\") % age\n else:\n age += 3\n return _(\"Minimum age %d years\") % age\n elif self.type == self.GENRE:\n genre = event.getGenreData()\n if genre is None:\n return \"\"\n else:\n return getGenreStringSub(genre.getLevel1(), genre.getLevel2())\n elif self.type == self.EPGPIC:\n if DBG: j00zekDEBUG(\"[j00zekModEventName:getText] self.type == self.EPGPIC, returning '%s'\" % self.picFileName)\n return self.picFileName\n elif self.type == self.NAME_NOW:\n return pgettext(\"now/next: 'now' event label\", \"Now\") + \": \" + event.getEventName()\n elif self.type == self.NAME_NEXT:\n return pgettext(\"now/next: 'next' event label\", \"Next\") + \": \" + event.getEventName()\n elif self.type == self.ID:\n return str(event.getEventId())\n elif self.type == self.PDC:\n if event.getPdcPil():\n return _(\"PDC\")\n return \"\"\n elif self.type in (self.PDCTIME, self.PDCTIMESHORT):\n pil = event.getPdcPil()\n if pil:\n if self.type == self.PDCTIMESHORT:\n return _(\"%02d:%02d\") % ((pil & 0x7C0) >> 6, (pil & 0x3F))\n return _(\"%d.%02d. %02d:%02d\") % ((pil & 0xF8000) >> 15, (pil & 0x7800) >> 11, (pil & 0x7C0) >> 6, (pil & 0x3F))\n return \"\"\n elif self.type == self.ISRUNNINGSTATUS:\n if event.getPdcPil():\n running_status = event.getRunningStatus()\n if running_status == 1:\n return _(\"not running\")\n if running_status == 2:\n return _(\"starts in a few seconds\")\n if running_status == 3:\n return _(\"pausing\")\n if running_status == 4:\n return _(\"running\")\n if running_status == 5:\n return _(\"service off-air\")\n if running_status in (6,7):\n return _(\"reserved for future use\")\n return _(\"undefined\")\n return \"\"\n elif self.type in (self.SHORT_DESCRIPTION , self.EXTENDED_DESCRIPTION, self.FULL_DESCRIPTION):\n description = event.getShortDescription()\n extended = event.getExtendedDescription()\n if config.plugins.j00zekCC.enTMDBratingFirst.value:\n tmdbRating = 'TBC'\n else:\n tmdbRating = ''\n if config.plugins.j00zekCC.enDescrType.value == '1' or self.type == self.SHORT_DESCRIPTION:\n return tmdbRating + description.strip()\n elif config.plugins.j00zekCC.enDescrType.value == '2' or self.type == self.EXTENDED_DESCRIPTION:\n return extended or description\n elif config.plugins.j00zekCC.enDescrType.value == '3' or self.type == self.FULL_DESCRIPTION:\n if description and extended:\n if description.replace('\\n','') == extended.replace('\\n',''):\n return extended\n description += '\\n'\n return tmdbRating + description + extended\n elif config.plugins.j00zekCC.enDescrType.value == '4':\n if description and extended: \n extendedCut = extended[:len(description) + 10].replace('\\n',' ').strip().replace(' ',' ').split(' ')\n descrWords = description.replace('\\n',' ').strip().replace(' ',' ').split(' ')\n if len(descrWords) > 0:\n wordCount = 0\n for word in descrWords:\n if word in extendedCut:\n wordCount += 1\n if wordCount >= len(descrWords) * 0.75:\n return tmdbRating + extended\n return tmdbRating + description + extended\n \n\n text = property(getText) ","sub_path":"e2components/Components/Converter/j00zekModEventName.py","file_name":"j00zekModEventName.py","file_ext":"py","file_size_in_byte":8239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61462256","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('goodshare.accounts.views',\n # Examples:\n # url(r'^$', 'goodshare.views.home', name='home'),\n # url(r'^goodshare/', include('goodshare.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^login', 'login_account'),\n url(r'^logout', 'logout_account'),\n url(r'^register', 'register'),\n url(r'^p(?P\\d+)/$', 'profile'),\n)\n","sub_path":"goodshare/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519304085","text":"import numpy as np\nfrom pandas import DataFrame, read_excel\nfrom numpy.linalg import matrix_power\nfrom random import randint\n\n#import transition matrix\ndf = read_excel(\"master.xls\", sheet_name=\"m-tr2\", header=None)\ntr = df.to_numpy()\n\n#choices for initial pc set\nv0n = randint(1, 4)\n\nif v0n == 1:\n v0 = [1, 0, 0, 0, 0, 0, 0, 0]\nelif v0n == 2:\n v0 = [0, 1, 0, 0, 0, 0, 0, 0]\nelif v0n == 3:\n v0 = [0, 0, 1, 0, 0, 0, 0, 0]\nelif v0n == 4:\n v0 = [0, 0, 0, 1, 0, 0, 0, 0]\n\nprint(v0n)\n\n#choices for pitch-class set\npcset = np.arange(1, 9)\n\nfor i in range(1, 15):\n out = np.random.choice(pcset, 1, p=np.dot(matrix_power(tr, i), v0))\n print(out)\n","sub_path":"m-tr2.py","file_name":"m-tr2.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338601170","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4 import QtCore, QtGui\nimport sys\nimport os\nimport os.path\nimport shapefile\nimport shapefile as shp\nimport math\nimport processing\n#Import de QGIS\nfrom qgis import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n# chargement du fichier d'interface graphique créé \nfrom Ui_gpx_shp import Ui_gpx_shp\n\ndx=0\ndy=0\n\n# avoir path plugins\npath_absolute = os.path.dirname(os.path.realpath(__file__))\n\nclass gpx_shpDialog(QDialog):\n\tdef __init__(self): #On récupère le dictionnaire des communes\n\t\tQDialog.__init__(self) \n\t\t# Set up the user interface from Designer. \n\t\tself.ui = Ui_gpx_shp ()\n\t\tself.ui.setupUi(self)\n\t\t\n\n\t\t#IMPORTANT :\n\t\t#Recupetation dans self.iface des proprietes d'acces à l'interface ! (self.iface)\n\t\t# self.iface = classe_iface_parent.iface\n\t\t# et aussi le QgsMapCanvas\n\t\t# self.canvas = self.iface.mapCanvas()\n\t\t\n\t\t# SIGNAL SLOT\n\t\tself.connect(self.ui.btn_RepgpxOuvrir,SIGNAL(\"clicked()\"), self.repGpxOuvrir)\n\t\tself.connect(self.ui.btn_RepshpSave,SIGNAL(\"clicked()\"), self.RepShpSave)\n\t\tself.connect(self.ui.btn_Executer,SIGNAL(\"clicked()\"), self.Executer)\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t\t\t\n\t# pour choisir le fichier dans DialogBox standard\t\t\t\n\tdef repGpxOuvrir(self):\n\t\tglobal path_absolute\n\t\tself.ui.cbxLayer.clear()\n\t\tdialog = QtGui.QFileDialog.getOpenFileName(self, \"Ouvrir Fichier Vecteur...\", None,\n\t\t\"Shape (*.shp)\")\n\t\tif dialog:\n\t\t\tself.ui.cbxLayer.addItem(dialog)\n\t\t\tshpEtoTmp = self.ui.cbxLayer.currentText()\n\t\t\t#rep_shpLaborde='C:/Users/rbienvenue/.qgis2/python/plugins/gridLaborde/tmp_shp/shpLaborde.shp'\n\t\t\trep_shpLaborde=os.path.join(path_absolute, 'tmp_shp/shpLaborde.shp')\n\t\t\trep_shpLaborde=rep_shpLaborde.replace('\\\\','/')\n\t\t\t\n\t\t\t\"\"\"\n\t\t\t#Supprimer si déjà existé mais ils sont attaché par le programme qgis\n\t\t\trep_shp_dbf=os.path.join(path_absolute, 'tmp_shp/shpLaborde.dbf')\n\t\t\trep_shp_shx=os.path.join(path_absolute, 'tmp_shp/shpLaborde.shx')\n\t\t\trep_shp_prj=os.path.join(path_absolute, 'tmp_shp/shpLaborde.prj')\n\t\t\trep_shp_qpj=os.path.join(path_absolute, 'tmp_shp/shpLaborde.qpj')\n\t\t\t\n\t\t\trep_shp_dbf=rep_shp_dbf.replace('\\\\','/')\n\t\t\trep_shp_shx=rep_shp_shx.replace('\\\\','/')\n\t\t\trep_shp_prj=rep_shp_prj.replace('\\\\','/')\n\t\t\trep_shp_qpj=rep_shp_qpj.replace('\\\\','/')\n\t\t\t\n\t\t\tif os.path.exists(rep_shpLaborde)==True and os.path.exists(rep_shp_dbf)==True and os.path.exists(rep_shp_shx)==True:\n\t\t\t\tos.remove(rep_shpLaborde)\n\t\t\t\tos.remove(rep_shp_dbf)\n\t\t\t\tos.remove(rep_shp_shx)\n\t\t\tif os.path.exists(rep_shp_prj)==True and os.path.exists(rep_shp_qpj)==True:\n\t\t\t\tos.remove(rep_shpLaborde)\n\t\t\t\tos.remove(rep_shp_dbf)\n\t\t\t\tos.remove(rep_shp_shx)\n\t\t\t\"\"\"\t\n\t\t\t\n\t\t\t# verifie sa projection\n\t\t\tlayer = QgsVectorLayer(shpEtoTmp , 'shpWGS84', \"ogr\")\n\t\t\tcrs_eto=layer.crs().authid()\n\t\t\tnom_crs=str(crs_eto)\n\t\t\t# si WGS84\n\t\t\t# if nom_crs=='EPSG:4326':\n\t\t\tif crs_eto=='EPSG:4326':\n\t\t\t\t# pour afficher extent initial\n\t\t\t\tshpEto = self.ui.cbxLayer.currentText()\n\t\t\t\tsf_Init = shapefile.Reader(shpEto)\n\t\t\t\tshapes = sf_Init.shapes()\n\t\t\t\t# XMin YMin XMax Ymax\n\t\t\t\tbbox = shapes[0].bbox\n\t\t\t\tself.ui.x_min.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max.setText(str(Maxbbox[1]))\n\t\t\t\t\n\t\t\t\t# transforme en fichier Laborde pour calculer en metric\n\t\t\t\tprocessing.runalg(\"qgis:reprojectlayer\", shpEtoTmp, \"epsg:29702\", rep_shpLaborde)\n\t\t\t\tlayer2 = QgsVectorLayer(rep_shpLaborde , 'shpLaborde', \"ogr\")\n\t\t\t\tbox_laborde = layer2.extent().toString()\n\t\t\t\t# crs_eto2=layer2.crs().authid()\n\t\t\t\t# XMin, YMin : XMax, Ymax\n\t\t\t\tbbox =box_laborde.split(\":\")\n\t\t\t\tMinbbox=bbox[0].split(\",\")\n\t\t\t\tMaxbbox=bbox[1].split(\",\")\n\t\t\t\t# pour calculer en laborde\n\t\t\t\tself.ui.x_min_2.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min_2.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max_2.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max_2.setText(str(Maxbbox[1]))\t\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tshpEto = self.ui.cbxLayer.currentText()\n\t\t\t\tsf = shapefile.Reader(shpEto)\n\t\t\t\tshapes = sf.shapes()\n\t\t\t\t# XMin YMin XMax Ymax\n\t\t\t\tbbox = shapes[0].bbox \n\t\t\t\tself.ui.x_min.setText(str(bbox[0]))\n\t\t\t\tself.ui.y_min.setText(str(bbox[1]))\n\t\t\t\tself.ui.x_max.setText(str(bbox[2]))\n\t\t\t\tself.ui.y_max.setText(str(bbox[3]))\n\t\t\t\t# pour calculer en laborde\n\t\t\t\tself.ui.x_min_2.setText(str(bbox[0]))\n\t\t\t\tself.ui.y_min_2.setText(str(bbox[1]))\n\t\t\t\tself.ui.x_max_2.setText(str(bbox[2]))\n\t\t\t\tself.ui.y_max_2.setText(str(bbox[3]))\n\t\treturn\t\t\n\n\tdef RepShpSave(self):\n\t\tfilecsv = QFileDialog.getSaveFileName(self, \"Selectionner fichier de sortie (shapefile) \",\"\", '*.shp')\n\t\tif filecsv:\n\t\t\tself.ui.rep_shpSave.setText(filecsv)\n\t\treturn\n\t\n\tdef chargerCoucheExist(self):\n\t\tself.ui.cbxLayer.clear()\n\t\tif self.ui.chbxLayer.isChecked() == True:\n\t\t\t#names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]\n\t\t\t# for layer in QgsMapLayerRegistry.instance().mapLayers().values():\n\t\t\tlayer_list = []\n\t\t\tlayers = QgsMapLayerRegistry.instance().mapLayers().values()\n\t\t\tfor layer in layers:\n\t\t\t\t# pour verifier si vecteur\n\t\t\t\t# if layer.type() == QgsMapLayer.VectorLayer or QgsMapLayer.rasterLayer:\n\t\t\t\tif layer.type() == QgsMapLayer.VectorLayer:\n\t\t\t\t\t# layers = self.iface.activeLayer()\n\t\t\t\t\t# if layer > 0:\n\t\t\t\t\tlayer_list.append(layer.name())\n\t\t\tself.ui.cbxLayer.addItems(layer_list)\n\t\n\tdef trouver_coor(self):\n\t\tif self.ui.chbxLayer.isChecked() == True:\n\t\t\tglobal path_absolute\n\t\t\t# on cherche par layer en cours\n\t\t\ts_LayerIndex = self.ui.cbxLayer.currentIndex\n\t\t\tn_layer = str(self.ui.cbxLayer.currentText())\n\t\t\t# rep_shpLaborde=rep_shpLaborde='C:/Users/rbienvenue/.qgis2/python/plugins/gridLaborde/tmp_shp/shpLaborde.shp'\n\t\t\trep_shpLaborde=os.path.join(path_absolute, 'tmp_shp/shpLaborde.shp')\n\t\t\trep_shpLaborde=rep_shpLaborde.replace('\\\\','/')\n\t\t\tvl = QgsMapLayerRegistry.instance().mapLayersByName(n_layer)[0]\n\t\t\t# verifie sa projection\n\t\t\tcrs_eto=vl.crs().authid()\n\t\t\tnom_crs=str(crs_eto)\n\t\t\t# si WGS84\n\t\t\t#if nom_crs=='EPSG:4326':\n\t\t\tif crs_eto=='EPSG:4326':\n\t\t\t\t# pour afficher extent initial\n\t\t\t\tbox_Init = vl.extent().toString()\n\t\t\t\t# XMin, YMin : XMax, Ymax\n\t\t\t\tbbox =box_Init.split(\":\")\n\t\t\t\tMinbbox=bbox[0].split(\",\")\n\t\t\t\tMaxbbox=bbox[1].split(\",\")\n\t\t\t\tself.ui.x_min.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max.setText(str(Maxbbox[1]))\n\t\t\t\t\n\t\t\t\t# transforme en fichier Laborde pour calculer en metric\n\t\t\t\tprocessing.runalg(\"qgis:reprojectlayer\", vl, \"epsg:29702\", rep_shpLaborde)\n\t\t\t\tlayer2 = QgsVectorLayer(rep_shpLaborde , 'shpLaborde', \"ogr\")\n\t\t\t\t# crs_eto2=layer2.crs().authid()\n\t\t\t\tbox_laborde = layer2.extent().toString()\n\t\t\t\t# XMin, YMin : XMax, Ymax\n\t\t\t\tbbox =box_laborde.split(\":\")\n\t\t\t\tMinbbox=bbox[0].split(\",\")\n\t\t\t\tMaxbbox=bbox[1].split(\",\")\n\t\t\t\t# pour calculer en laborde\n\t\t\t\tself.ui.x_min_2.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min_2.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max_2.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max_2.setText(str(Maxbbox[1]))\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tbox = vl.extent().toString()\n\t\t\t\t# XMin, YMin : XMax, Ymax\n\t\t\t\tbbox =box.split(\":\")\n\t\t\t\tMinbbox=bbox[0].split(\",\")\n\t\t\t\tMaxbbox=bbox[1].split(\",\")\n\t\t\t\tself.ui.x_min.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max.setText(str(Maxbbox[1]))\n\t\t\t\t# pour calculer en laborde\n\t\t\t\tself.ui.x_min_2.setText(str(Minbbox[0]))\n\t\t\t\tself.ui.y_min_2.setText(str(Minbbox[1]))\n\t\t\t\tself.ui.x_max_2.setText(str(Maxbbox[0]))\n\t\t\t\tself.ui.y_max_2.setText(str(Maxbbox[1]))\n\t\t\t\t\n\t\t\t\t\n\n\tdef trouver_grille(self):\n\t\t\"\"\"\n\t\t1cm carte donne 50 000 cm ou 50m ou 0.05 km sur terrain\n\t\tdonc trouver par orientation et format, echelle\n\t\t\"\"\"\n\t\tglobal dx\n\t\tglobal dy\n\t\t# minx,maxx,miny,maxy = float(self.ui.x_min.toPlainText()), float(self.ui.x_max.toPlainText()),float(self.ui.y_min.toPlainText()), float(self.ui.y_max.toPlainText())\n\t\tminx,maxx,miny,maxy = float(self.ui.x_min_2.toPlainText()), float(self.ui.x_max_2.toPlainText()),float(self.ui.y_min_2.toPlainText()), float(self.ui.y_max_2.toPlainText())\n\t\t# trouver dimension grille par format et orientation\n\t\tif self.ui.cbxFormat.currentText() =='A4':\n\t\t\tif self.ui.cbxOrientation.currentText() =='Portrait':\n\t\t\t\tdx = 0.21 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.297 * int(self.ui.cbxEchelle.currentText())\n\t\t\tif self.ui.cbxOrientation.currentText() =='Paysage':\n\t\t\t\tdx = 0.297 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.21 * int(self.ui.cbxEchelle.currentText())\n\t\telif self.ui.cbxFormat.currentText() =='A3':\n\t\t\tif self.ui.cbxOrientation.currentText() =='Portrait':\n\t\t\t\tdx = 0.297 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.42 * int(self.ui.cbxEchelle.currentText())\n\t\t\tif self.ui.cbxOrientation.currentText() =='Paysage':\n\t\t\t\tdx = 0.42 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.297 * int(self.ui.cbxEchelle.currentText())\n\t\telif self.ui.cbxFormat.currentText() =='A2':\n\t\t\tif self.ui.cbxOrientation.currentText() =='Portrait':\n\t\t\t\tdx = 0.42 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.594 * int(self.ui.cbxEchelle.currentText())\n\t\t\tif self.ui.cbxOrientation.currentText() =='Paysage':\n\t\t\t\tdx = 0.594 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.42 * int(self.ui.cbxEchelle.currentText())\n\t\telse:\n\t\t\tif self.ui.cbxOrientation.currentText() =='Portrait':\n\t\t\t\tdx = 0.594 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 1.188 * int(self.ui.cbxEchelle.currentText())\n\t\t\tif self.ui.cbxOrientation.currentText() =='Paysage':\n\t\t\t\tdx = 10.188 * int(self.ui.cbxEchelle.currentText())\n\t\t\t\tdy = 0.594 * int(self.ui.cbxEchelle.currentText())\n\t\t\n\t\t# trouver nombre grille\n\t\tnbrx = int(math.ceil(abs(maxx - minx)/dx))\n\t\tnbry = int(math.ceil(abs(maxy - miny)/dy))\n\t\t# afficher pour informations\n\t\ttotGrid=nbrx*nbry\n\t\tself.ui.lbl_Gridxy.setText(str(dx) + \" x \" + str(dy))\n\t\tself.ui.lbl_Nbregrid.setText(\"Total: \" + str(totGrid) + \" dont :\" + str(nbrx) + \" x \" + str(nbry))\n\t\n\tdef Executer(self):\n\t\trepEto = self.ui.rep_shpSave.toPlainText()\n\t\tif repEto != '':\n\t\t\t# recuperer le nom de fichier\n\t\t\tinfos_shp = QFileInfo(repEto)\n\t\t\tNomfile = infos_shp.baseName()\n\t\t\t#Creer grid\n\t\t\t# minx,maxx,miny,maxy = float(self.ui.x_min.toPlainText()), float(self.ui.x_max.toPlainText()),float(self.ui.y_min.toPlainText()), float(self.ui.y_max.toPlainText())\n\t\t\tminx,maxx,miny,maxy = float(self.ui.x_min_2.toPlainText()), float(self.ui.x_max_2.toPlainText()),float(self.ui.y_min_2.toPlainText()), float(self.ui.y_max_2.toPlainText())\n\t\t\tnx = int(math.ceil(abs(maxx - minx)/dx))\n\t\t\tny = int(math.ceil(abs(maxy - miny)/dy))\n\t\t\t# Ajouter marge pour la dernière case si avec marge\n\t\t\tif self.ui.chbxMarge.isChecked() == True:\n\t\t\t\tif self.ui.xMarge.toPlainText() !='' and self.ui.yMarge.toPlainText() !='':\n\t\t\t\t\tif self.ui.xMarge.toPlainText().isnumeric()==True and self.ui.yMarge.toPlainText().isnumeric() ==True:\n\t\t\t\t\t\tplus_y=(int(self.ui.yMarge.toPlainText())*ny)*3\n\t\t\t\t\t\tplus_x=(int(self.ui.xMarge.toPlainText())*nx)*2\n\t\t\t\t\t\tminx,maxx,miny,maxy =minx,maxx+plus_x,miny-plus_y,maxy #+plus_y\n\t\t\t\t\t\t\n\t\t\t\n\t\t\t# Definir le polygone\n\t\t\tw = shp.Writer(shp.POLYGON)\n\t\t\tw.autoBalance = 1\n\t\t\tw.field(\"ID\")\n\t\t\tw.field(\"Ech\")\n\t\t\tw.field(\"Sens\")\n\t\t\tw.field(\"Format\")\n\t\t\tw.field(\"nom_grid\")\n\t\t\tw.field(\"nom_row\")\n\t\t\tw.field(\"nom_col\")\n\t\t\tw.field(\"marge_row\")\n\t\t\tw.field(\"marge_col\")\n\t\t\tw.field(\"unite\")\n\t\t\tid=0\n\t\t\t# verifier si avec marge\n\t\t\tif self.ui.chbxMarge.isChecked() == True:\n\t\t\t\tif self.ui.xMarge.toPlainText() =='' or self.ui.yMarge.toPlainText() =='':\n\t\t\t\t\tQtGui.QMessageBox.information(self,'Message',\"Valeur incorrecte pour les champs\")\n\t\t\t\t\tif self.ui.xMarge.toPlainText() =='':\n\t\t\t\t\t\tself.ui.xMarge.setFocus()\n\t\t\t\t\tif self.ui.yMarge.toPlainText() =='':\n\t\t\t\t\t\tself.ui.yMarge.setFocus()\n\t\t\t\t\t# sortie de la function\n\t\t\t\t\treturn None\n\t\t\t\tif self.ui.xMarge.toPlainText().isnumeric()==False or self.ui.yMarge.toPlainText().isnumeric() ==False:\n\t\t\t\t\tQtGui.QMessageBox.information(self,'Message',\"Valeur incorrecte pour les champs\")\n\t\t\t\t\treturn None\n\t\t\t\t# charger marge dans le champs\n\t\t\t\tval_xMarge =self.ui.xMarge.toPlainText()\n\t\t\t\tval_xMarge =self.ui.yMarge.toPlainText()\n\t\t\t\tval_unite='metre'\n\t\t\telse:\n\t\t\t\tval_xMarge =''\n\t\t\t\tval_xMarge =''\n\t\t\t\tval_unite =''\n\t\t\t\n\n\t\t\t\n\t\t\t\t\n\t\t\t# charger les shapes\t\t\n\t\t\tfor i in range(ny):\n\t\t\t\tfor j in range(nx):\n\t\t\t\t\tid+=1\n\t\t\t\t\tvertices = []\n\t\t\t\t\tparts = []\n\t\t\t\t\tif self.ui.xMarge.toPlainText() !='' and self.ui.yMarge.toPlainText() != '':\n\t\t\t\t\t\t# x =j, y = i\n\t\t\t\t\t\tif j==0 and i==0:\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*i,miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*i,miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif j ==0 and i>0:\n\t\t\t\t\t\t\t# dymarge=2*i\n\t\t\t\t\t\t\tdymarge=int(self.ui.yMarge.toPlainText())*i\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*i,miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*i,miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*(i+1),miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*(i+1),miny)+dymarge])\n\t\t\t\t\t \n\t\t\t\t\t\tif j>0 and i==0:\n\t\t\t\t\t\t\t# dxmarge=2*j\n\t\t\t\t\t\t\tdxmarge=int(self.ui.xMarge.toPlainText())*j\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx)-dxmarge,max(maxy-dy*i,miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx)-dxmarge,max(maxy-dy*i,miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx)-dxmarge,max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx)-dxmarge,max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif j>0 and i>0:\n\t\t\t\t\t\t\t# dxmarge=2*j\n\t\t\t\t\t\t\t# dymarge=2*i\n\t\t\t\t\t\t\tdymarge=int(self.ui.yMarge.toPlainText())*i\n\t\t\t\t\t\t\tdxmarge=int(self.ui.xMarge.toPlainText())*j\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx)-dxmarge,max(maxy-dy*i,miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx)-dxmarge,max(maxy-dy*i,miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx)-dxmarge,max(maxy-dy*(i+1),miny)+dymarge])\n\t\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx)-dxmarge,max(maxy-dy*(i+1),miny)+dymarge])\n\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*i,miny)])\n\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*i,miny)])\n\t\t\t\t\t\tvertices.append([min(minx+dx*(j+1),maxx),max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\tvertices.append([min(minx+dx*j,maxx),max(maxy-dy*(i+1),miny)])\n\t\t\t\t\t\t\n\t\t\t\t\t# charger shapefile\n\t\t\t\t\tparts.append(vertices)\n\t\t\t\t\tw.poly(parts)\n\t\t\t\t\tw.record(id, \n\t\t\t\t\tstr(self.ui.cbxEchelle.currentText()),\n\t\t\t\t\tstr(self.ui.cbxOrientation.currentText()),\n\t\t\t\t\tstr(self.ui.cbxFormat.currentText()),\n\t\t\t\t\tstr(i) +\"_\" + str(j), i, j, val_xMarge, val_xMarge, val_unite)\n\t\t\t# sauvegarder shapefile\n\t\t\tw.save(repEto)\n\t\t\t\n\t\t\t# charger dans qgis avec SCR laborde 29702\n\t\t\tif self.ui.chbxCanvas.isChecked() == True:\n\t\t\t\tlayer = QgsVectorLayer(repEto, Nomfile, \"ogr\")\n\t\t\t\tif not layer.isValid():\n\t\t\t\t\tQtGui.QMessageBox.information(self,'Message',\"Impossible de charger le fichier\")\n\t\t\t\telse:\n\t\t\t\t\tlayer.setCrs( QgsCoordinateReferenceSystem(29702, QgsCoordinateReferenceSystem.EpsgCrsId) )\n\t\t\t\t\tQgsMapLayerRegistry.instance().addMapLayer(layer)\n\t\t\t# vider tous les champs\n\t\t\tself.ui.chbxLayer.setChecked(False)\n\t\t\tself.ui.cbxLayer.clear()\n\t\t\tself.ui.chbxMarge.setChecked(False)\n\t\t\tself.ui.grb_Marge.setEnabled(False)\n\t\t\tself.ui.xMarge.setText('')\n\t\t\tself.ui.yMarge.setText('')\n\t\t\tself.ui.x_min.setText('')\n\t\t\tself.ui.y_min.setText('')\n\t\t\tself.ui.x_max.setText('')\n\t\t\tself.ui.y_max.setText('')\n\t\t\t# pour calculer en laborde\n\t\t\tself.ui.x_min_2.setText('')\n\t\t\tself.ui.y_min_2.setText('')\n\t\t\tself.ui.x_max_2.setText('')\n\t\t\tself.ui.y_max_2.setText('')\n\t\t\tself.ui.rep_shpSave.setText('')\n\t\t\t\n\t\telse:\n\t\t\tQtGui.QMessageBox.information(self,'Message',\"Veuillez selectionner le Repertoire pour le shapefile\")\n\t\t\n","sub_path":"tmp_dos/gpx_shp_dialog_stock_code.py","file_name":"gpx_shp_dialog_stock_code.py","file_ext":"py","file_size_in_byte":15778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474480593","text":"import hashlib\n\n\ndef hash_func(input_str):\n hash_hex = hashlib.md5(input_str.encode('utf-8')).hexdigest()\n return int(hash_hex[:15], 16)\n\n# Alias\nspoiler_hash_func = hash_func\n\ndef choose_color_assignment(user_id):\n key = \"{}|color\".format(user_id)\n\n slot = spoiler_hash_func(key) % 20\n \n if slot < 10:\n return 'red'\n else:\n return 'blue'","sub_path":"pycon2017-experiment-assignment-on-the-web/utils/spoilers.py","file_name":"spoilers.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279312109","text":"import json\nimport logging\nimport datetime\nfrom tasks.monitor import CheckStatus\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_service_status():\n services = None\n # Attempt to load current statistics, backtracking until stats are available:\n for mins in range(0,60):\n try:\n status_date = datetime.datetime.today() - datetime.timedelta(minutes=mins)\n json_file = CheckStatus(date=status_date).output().path\n logger.info(\"Looking for... %s\" % json_file)\n #json_file = \"../state/monitor/checkstatus.2016-11-22T1110\"\n services = load_services(json_file)\n services['status_date'] = status_date.isoformat()\n services['status_date_delta'] = mins\n if( mins > 2 ):\n services['status_date_warning'] = \"Status data is %s minutes old!\" % mins\n except Exception as e:\n logger.info(\"Could not load %i mins ago... %s\" % (mins, e))\n #app.logger.exception(e)\n\n if services is not None:\n break\n\n if services is None:\n logger.error(\"Could not find any status file.\")\n raise Exception(\"Could not load a recent service status file!\")\n\n return services\n\n\ndef load_services(json_file):\n logger.info(\"Attempting to load %s\" % json_file)\n with open(json_file, 'r') as reader:\n services = json.load(reader)\n return services\n\n","sub_path":"ukwa-mon/webapp/monitor/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"613707012","text":"from node import *\nimport math\nfrom constants import *\n\nclass Env:\n def __init__(self):\n # 系统设备状况\n self.transmitStore=TransmitStore()\n self.mobileNum=MOBILE_NUM\n self.mecNum=MEC_NUM\n self.mobiles=list()\n self.mecs=list()\n for i in range(self.mobileNum):\n self.mobiles.append(Mobile(\"mobile\"+str(i),\"1.1.1.\"+str(i),{\"mem\":4}))\n for i in range(self.mecNum):\n self.mecs.append(MEC(\"mec\"+str(i),\"1.1.2.\"+str(i), {\"mem\":16}))\n # 时隙设定\n self.interval=0.1\n self.timeSlots=10\n self.currentTime=0\n # 信道带宽-MHz,信噪比-db\n self.bandwidth=50\n self.SNR=10\n\n def reset(self):\n self.currentTime=0\n for mobile in self.mobiles:\n mobile.processQueue.clear()\n mobile.resourceAvil[\"mem\"]=4\n for mec in self.mecs:\n mec.processQueue.clear()\n mec.resourceAvil[\"mem\"]=16\n self.transmitStore.storeQueue.clear()\n\n def createTasks(self):\n tasks=list()\n for i in range(self.mobileNum):\n tasks.append(self.mobiles[i].createTask(self.currentTime))\n return tasks\n\n def createAllTasks(self):\n allTasks=list()\n for i in range(self.timeSlots):\n tasks=list()\n for j in range(self.mobileNum):\n tasks.append(self.mobiles[j].createTask(i))\n allTasks.append(tasks)\n return allTasks\n\n def step(self,tasks):\n transmitSpeed=self.getTransmitSpeed()\n for task in tasks:\n if task.offloadAction==0:\n self.mobiles[int(task.nodeFrom[-1])].updateByTime(task,self.currentTime,self.interval,self.transmitStore.storeQueue,transmitSpeed)\n else:\n self.mobiles[int(task.nodeFrom[-1])].updateByTime(task,self.currentTime,self.interval,self.transmitStore.storeQueue,transmitSpeed)\n self.mecs[task.offloadAction-1].updateByTime(self.currentTime, self.interval,self.transmitStore.storeQueue)\n\n def end(self):\n if self.timeSlots= 1\n lvl = lvl_fmt[:1]\n fmt = lvl_fmt[1:]\n s = { 'i': '%', 'e': '?', 'E': '!?'}[lvl]\n s += self.type.value[0] # the printable message\n if len(fmt) == 1:\n s += ': ' + IEMsg.fmt_arg(fmt[0], self.data)\n else:\n sep = ': '\n for fmt_char, data in zip(fmt, self.data):\n s += IEMsg.fmt_arg(fmt_char, data)\n sep = ', '\n return s\n\n @classmethod\n def find(cls, msg_type, msgs):\n for msg in msgs:\n if msg.type == msg_type:\n return msg.data\n else:\n return None\n\n\nclass IETagType(IntEnum):\n AUTO = 1 # if not found, auto-add |\n # flag tag as auto-added\n BASED = 2 # if not found, put | in the imported tags\n # flag item as tag-needs-edit\n UNBASED = 3 # if not found, put in the imported tags\n # flag item as tag-needs-edit\n WORD = 4 # multiple words may need to be concatenated to get a tag\n # flag item as tags-are-words\n NOTE = 5 # auto-add a 'Facebook Event' note to the item, with url = \n\n def __repr__(self):\n return '+-?WN'[self.value]\n\n @classmethod\n def from_code(self, code):\n if code == '+': return IETagType.AUTO\n if code == '-': return IETagType.BASED\n if code == '?': return IETagType.UNBASED\n if code == 'W': return IETagType.WORD\n if code == 'N': return IETagType.NOTE\n raise ValueError\n\n\nclass IETag:\n\n def __init__(self, type, text=None, bases=None, url=None):\n self.type = type\n self.text = text\n self.bases = bases\n self.url = url\n\n def pname(self):\n s = self.type.name\n if self.bases is not None:\n s += '(' + self.bases + ')'\n if self.text is not None:\n s += \" '\" + self.text + \"'\"\n if self.url is not None:\n s += ' @' + self.url\n return s\n\n def diff_tup(self):\n # (n|w|t, state, bases)\n if self.type == IETagType.NOTE:\n type = 'n'\n text = self.text\n elif self.type == IETagType.WORD:\n type = 'w'\n text = self.text\n else: # IETagType.TAG\n type = 't'\n text = self.text.replace('/', '|')\n # 'meta/misc/cool' => 'meta|misc|cool'\n # FIXME: this fix is specific to Corbett image tags,\n # so it should be done in ie_fs.py\n return type, text, self.bases\n\n def __repr__(self):\n return '' % self.pname()\n\n def is_tag(self):\n return self.type in {IETagType.AUTO, IETagType.BASED,\n IETagType.UNBASED}\n\n\nclass IEFolder(object):\n\n def __init__(self, fs_path, db_date, db_name, mod_datetime):\n self.fs_path = fs_path # filesystem absolute db_name\n\n # DbFolder date and db_name suggested by import code\n self.db_date = db_date # folder date, e.g. 10/07/2017, may be None\n self.db_name = db_name # the db_name, e.g. 'virginia'\n\n self.mod_datetime = mod_datetime\n self.images = {} # IEImage.name -> IEImage\n self.image_insts = {} # map: IEImageInst.fs_path -> IEImageInst\n self.msgs = [] # list of IEMsg\n self.tags = [] # list of IETag\n\n def add_image(self, ie_image):\n self.images[ie_image.name] = ie_image\n\n def add_tag(self, ie_tag):\n self.tags.append(ie_tag)\n\n def pname(self):\n return '%s %s' % (\n str(self.db_date) if self.db_date is not None else '-',\n self.db_name)\n\n def __repr__(self):\n return '' % self.pname()\n\n\nthumbnail_exts = [ '.jpg', '.jpg-hi' ] # TODO: silly PIL doesn't do TIFFs\n\n\nexif_exts = [ '.tif', '.psd', '.jpg', '.jpg-hi' ]\n\n\nclass IEImage(object):\n\n def __init__(self, ie_folder, name):\n\n self.ie_folder = ie_folder\n self.name = name # [] (copied to Fs/DbImage)\n self.msgs = [] # list of IEMsg\n self.insts = {} # extension -> list of IEImageInst\n\n self.newest_inst_with_thumbnail = None # updated by IEImageInst init\n self.thumbnail = None # set by bg_proc_ie_work_item() > get_ie_image_thumbnails()\n self.tags = [] # list of IETag\n self.exif = exif.Exif() # EXIF attributes, set by set_attrs_from_exiftool_json()\n\n def add_tag(self, ie_tag):\n self.tags.append(ie_tag)\n\n def pname(self):\n return '%s|%s' % (self.ie_folder.pname(), self.name)\n\n def __repr__(self):\n return '' % self.pname()\n\n def set_attrs_from_exiftool_json(self, item):\n for xa in exif.attrs:\n try:\n if len(xa) > 1 and xa[0] in item:\n val = item[xa[0]]\n if len(xa) > 2:\n val = xa[2](val)\n setattr(self.exif, xa[1], val)\n self.exif.any_set = True\n except Exception as ed:\n print('bb')\n if 'Subject' in item:\n for tag in item['Subject']:\n self.add_tag(\n IETag(IETagType.UNBASED, text=tag, bases='band,person'))\n\n\nclass IEImageInst(object):\n\n def __init__(self, ie_image, fs_path, ext, mod_datetime):\n\n self.ie_image = ie_image\n self.fs_path = fs_path # filesystem full pathname, key in ie_folder.image_insts\n self.ext = ext # key in ie_image.insts, e.g '.jpg', '.jpg-hi'\n self.mod_datetime = mod_datetime\n self.msgs = [] # list of IEMsg\n\n # add to the IEFolder's pathname => IEImageInst map\n ie_image.ie_folder.image_insts[fs_path] = self\n\n if (ext in thumbnail_exts\n and (\n ie_image.newest_inst_with_thumbnail is None\n or mod_datetime > ie_image.newest_inst_with_thumbnail.mod_datetime\n )):\n ie_image.newest_inst_with_thumbnail = self\n\n def pname(self):\n return '%s|%s' % (self.ie_image.pname(), self.ext)\n\n def __repr__(self):\n return '' % self.pname()\n\n def get_thumbnail(self):\n try:\n pimage = Image.open(self.fs_path)\n pimage.thumbnail((200, 200))\n byte_array = io.BytesIO()\n pimage.save(byte_array, format='JPEG')\n bytes = byte_array.getvalue()\n return bytes\n except:\n return None\n\n\n_exiftool_command_args = ['exiftool', '-S', '-j', '-q']\n\n\n_exiftool_attr_args = ['-%s' % attr[0] for attr in exif.attrs]\n\n\ndef _get_exiftool_json(argv):\n \"\"\" Run exiftool on and return a list of dictionariess. \"\"\"\n try:\n outb = subprocess.check_output(argv)\n #FIXME: diagnostic if no exiftool\n except Exception as ed:\n pass\n outs = str(outb)[2:-5]\\\n .replace(r'\\n', '').replace(r'\\r', '').replace(r\"\\'\", \"'\")\n try:\n exiftool_json = json.loads(outs)\n except:\n pass\n return exiftool_json\n\nie_image_set0 = None\n\ndef get_ie_image_exifs(ie_image_set, pub):\n \"\"\" Get exif event for all the images in .\n\n deletes images from the set as their exifs are processed\n \"\"\"\n\n def proc_exiftool_json(ie_image_set, ext_paths, exiftool_json):\n try:\n for item in exiftool_json:\n fs_path = item['SourceFile']\n if fs_path in ext_paths:\n ie_image_inst = ext_paths[fs_path]\n ie_image = ie_image_inst.ie_image\n if ie_image in ie_image_set:\n ie_image_inst.ie_image.set_attrs_from_exiftool_json(item)\n ie_image_set.remove(ie_image_inst.ie_image)\n except Exception as ed:\n print('aaa')\n\n # attempt in the order of exif_exts\n global ie_image_set0\n ie_image_set0 = ie_image_set.copy()\n for ext in exif_exts:\n if len(ie_image_set) == 0:\n break\n # collect IEImageInsts and their directories\n dir_insts = {} # map: directory pathname => list of IEImageInst\n ext_paths = {} # map: fs_path => image_inst for images w/ this extension\n for ie_image in ie_image_set:\n if ext in ie_image.insts:\n for ie_image_inst in ie_image.insts[ext]:\n inst_path = (os.path.abspath(ie_image_inst.fs_path)\n .replace('\\\\', '/'))\n inst_path = os.path.splitdrive(inst_path)[1]\n ext_paths[inst_path] = ie_image_inst\n dir_path = os.path.dirname(inst_path)\n if dir_path in dir_insts:\n dir_insts[dir_path].append(ie_image_inst)\n else:\n dir_insts[dir_path] = [ie_image_inst]\n if len(dir_insts) == 0:\n continue # no image files with this extenstion\n fs_ext = ext[0:-3] if ext.endswith('-hi') else ext # .jpg-hi => .jpg\n for dir_path, worklist in dir_insts.items():\n num_dir_files = len(os.listdir(dir_path))\n if len(worklist) > num_dir_files / 2:\n # run exiftools on

/*.\n len0 = len(ie_image_set)\n argv = list(_exiftool_command_args)\n argv.append(os.path.join(dir_path, '*' + fs_ext))\n argv.extend(_exiftool_attr_args)\n exiftool_json = _get_exiftool_json(argv)\n proc_exiftool_json(ie_image_set, ext_paths, exiftool_json)\n pub('ie.sts imported tags', data = len0 - len(ie_image_set))\n else:\n # run exiftools on ...\n while len(worklist) > 0:\n n = min(len(worklist), 30) # up to 30 files per run\n sublist, worklist = worklist[:n], worklist[n:]\n len0 = len(ie_image_set)\n argv = list(_exiftool_command_args)\n for ie_image_inst in sublist:\n argv.append(ie_image_inst.fs_path)\n argv.extend(_exiftool_attr_args)\n exiftool_json = _get_exiftool_json(argv)\n proc_exiftool_json(ie_image_set, ext_paths, exiftool_json)\n pub('ie.sts imported tags', data = len0 - len(ie_image_set))\n\ndef get_ie_image_thumbnails(ie_image_set, pub):\n \"\"\" extract thumbnails for the images in \n deletes images from the set as their thumbnails are proecesed\n \"\"\"\n pub('ie.sts.import thumbnails', data=len(ie_image_set))\n for ie_image in ie_image_set:\n ie_image_inst = ie_image.newest_inst_with_thumbnail\n assert ie_image_inst is not None\n ie_image.thumbnail = ie_image_inst.get_thumbnail()\n pub('ie.sts imported thumbnails', data=1)\n # clear(ie_image_set) FIXME: why does this fail?\n\n# a std_dirname has the form 'yymmdd db_name'\nleading_date_space = re.compile(r'^\\d{6,6} ')\nleading_date_underscore = re.compile(r'^\\d{6,6}_')\nleading_date = re.compile(r'^\\d{6,6}')\n\ndef is_std_dirname(dirname):\n \"\"\" return whether dirname is a \"standard\" directory of image files \"\"\"\n return True\n # TODO: return leading_date_space.match(dirname) is not None\n\ndef proc_std_dirname(dir_pathname, dir_name):\n match = leading_date.match(dir_name)\n if match is None:\n db_date = None\n db_name = dir_name\n else:\n yymmdd = match.group()\n db_date = util.date_from_yymmdd(yymmdd)\n db_name = dir_name[match.end():].lstrip(' ')\n stat_mtime = os.path.getmtime(dir_pathname)\n mtime = datetime.datetime.fromtimestamp(stat_mtime)\n folder = IEFolder(dir_pathname, db_date, db_name, mtime)\n if db_date is None:\n folder.msgs.append(IEMsg(IEMsgType.NO_DATE, dir_pathname))\n return folder\n\ndef scan_dir_set(dir_set_pathname, test, proc):\n \"\"\" return a list of IEFolders representing each directory satisfying test\n the list is sorted by folder fs_name\n test(dir_name) checks whether the directory should be processed\n proc(dir_pathname, dir_name) returns an IEFolder for the directory\n \"\"\"\n folders = []\n for dir in os.listdir(dir_set_pathname):\n dir_path = os.path.join(dir_set_pathname, dir)\n if os.path.isdir(dir_path) and test(dir):\n folder = proc(dir_path, dir)\n if folder is not None:\n folders.append(folder)\n folders.sort(key=lambda folder: folder.fs_path)\n return folders\n\ndef scan_dir_sel(dir_pathname_list, proc):\n \"\"\" return a list of IEFolders representing each directory satisfying test\n the list is sorted by fs_name\n proc(dir_pathname, dir_name) returns an IEFolder for the directory\n \"\"\"\n\n folders = []\n for dir_path in dir_pathname_list:\n if os.path.isdir(dir_path):\n folder = proc(dir_path, os.path.basename(dir_path))\n if folder is not None:\n folders.append(folder)\n folders.sort(key=lambda folder: folder.fs_path)\n return folders\n\n# recognized image file extensions\nimg_extensions = [ '.nef', '.tif', '.psd', '.jpg' ]\nraw_prefixes = [ 'img_', 'dsc_' ]\nignored_extensions = [ '.zip' ]\nignored_subdirectories = [ 'del' ]\n# 'New Text Document.txt'(!) is recognized as a source of folder tags\n\ndef add_ie_folder_image_inst(ie_folder, file_path, file_name, high_res, mtime):\n base_name, ext = os.path.splitext(file_name)\n base_name = base_name.lower()\n ext = ext.lower()\n if ext in img_extensions:\n if high_res:\n ext += '-hi'\n if base_name.find('-') != -1:\n seq = base_name.split('-')[1]\n elif any(base_name.startswith(pfx) for pfx in raw_prefixes):\n # FIXME: prefixes w/ length other than 4\n seq = base_name[4:]\n else:\n # e.g. simple named files, as in 'my format/ayers/dks.psd\n base = ''\n seq = base_name\n if seq in ie_folder.images:\n ie_image = ie_folder.images[seq]\n else:\n ie_image = IEImage(ie_folder, seq)\n ie_folder.images[seq] = ie_image\n ie_image_inst = IEImageInst(ie_image, file_path, ext, mtime)\n if ext not in ie_image.insts:\n ie_image.insts[ext] = [ie_image_inst]\n else:\n ie_image.msgs.append(IEMsg(IEMsgType.EXTRA_INSTS, file_path))\n ie_image.insts[ext].append(ie_image_inst)\n else:\n ie_folder.msgs.append(IEMsg(IEMsgType.UNEXPECTED_FILE, 'file_path'))\n\ndef add_ie_folder_name_word_tags(ie_folder, bases):\n \"\"\" add tags based on th ewords of the folder's db_name \"\"\"\n for word in ie_folder.db_name.split(' '):\n ie_folder.add_tag(\n IETag(IETagType.WORD, text=word, bases=bases))\n\ndef add_ie_folder_name_tag(ie_folder, bases):\n \"\"\" add a tag based on the folder's db_name \"\"\"\n ie_folder.add_tag(IETag(\n IETagType.BASED, text=ie_folder.db_name, bases=bases))\n\ndef scan_std_dir_files(ie_folder):\n\n def acquire_file(file_path, file_name, high_res):\n got_folder_tags = False\n if file_name == 'New Text Document.txt':\n got_folder_tags = True\n tag_lines = open(file_path, 'r').readlines()\n for tag_line in tag_lines:\n tags = [l.strip(' \\n\\r') for l in tag_line.split(',')]\n for tag in tags:\n ie_folder.add_tag(IETag(\n IETagType.BASED, text=tag, bases='band'))\n elif os.path.isfile(file_path):\n stat_mtime = os.path.getmtime(file_path)\n mtime = datetime.datetime.fromtimestamp(stat_mtime)\n add_ie_folder_image_inst(\n ie_folder, file_path, file_name, high_res, mtime)\n else:\n # special file -- ignore\n pass\n return got_folder_tags\n\n def acquire_dir(pathname, high_res):\n # TODO: detect high_res from exif dimensions\n logging.debug('scan_std_dir_images(%s)', pathname)\n got_folder_tags = False\n file_name_list = os.listdir(pathname)\n for file_name in file_name_list:\n file_path = os.path.join(pathname, file_name)\n if os.path.isdir(file_path):\n if file_name not in ignored_subdirectories:\n acquire_dir(file_path, file_name == 'hi')\n else:\n got_folder_tags |= acquire_file(file_path, file_name, high_res)\n return got_folder_tags\n\n assert ie_folder is not None\n got_folder_tags = acquire_dir(ie_folder.fs_path, high_res=False)\n if got_folder_tags:\n # the standard case, where there's a state file with band names\n # and the folder db_name is the venue\n add_ie_folder_name_tag(ie_folder, 'venue')\n else:\n # who knows?\n add_ie_folder_name_word_tags(ie_folder, 'band, venue, place, event')\n ie_folder.msgs.append(\n IEMsg(IEMsgType.NAME_NEEDS_EDIT, ie_folder.db_name))\n # TODO: adjust seq numbers for Nikon 9999 rollover:\n # 0001, 9999 => 10001, 09999\n\ncorbett_date = re.compile(r'[0-9]{2,2}_[0-9]{2,2}(&[0-9]{2,2})?_[0-9]{2,2}')\ncorbett_trailing_date = re.compile(\n r'[0-9]{2,2}_[0-9]{2,2}(&[0-9]{2,2})?_[0-9]{2,2}$')\namper_date = re.compile(r'&[0-9]+')\n\ndef proc_corbett_filename(file_pathname, file_name, folders):\n base_name, ext = os.path.splitext(file_name)\n\n base_name = base_name.lower()\n base, seq = base_name.split('-')\n stat_mtime = os.path.getmtime(file_pathname)\n mtime = datetime.datetime.fromtimestamp(stat_mtime)\n\n if (len(folders) == 0 or\n base != os.path.basename(folders[-1].fs_path).split('-')[0].lower()\n ):\n # start a new IEFolder\n match = corbett_date.search(base)\n tmatch = corbett_trailing_date.search(base)\n if match is None and tmatch is None:\n db_date = None\n db_name = base.replace('_', ' ')\n else:\n if tmatch is not None:\n date_str = tmatch.group()\n name_str = base[0:tmatch.start()]\n else:\n date_str = match.group()\n s, e = match.start(), match.end()\n if s != 0:\n pass # does this case happen?\n name_str = base[0:s] + base[e:]\n date_str = amper_date.sub('', date_str)\n month_str, day_str, year_str = date_str.split('_')\n year = int(year_str)\n year += 1900 if year >= 70 else 2000\n month = int(month_str)\n day = int(day_str)\n try:\n db_date = datetime.date(year, month, day)\n except:\n db_date = datetime.date(1941, 12, 7)\n pass\n db_name_words = name_str.split('_')\n db_name = ' '.join(db_name_words).strip(' ')\n ie_folder = IEFolder(file_pathname, db_date, db_name, mtime)\n add_ie_folder_name_word_tags(ie_folder, 'venue, band')\n ie_folder.msgs.append(IEMsg(IEMsgType.TAGS_ARE_WORDS, file_pathname))\n ie_folder.msgs.append(IEMsg(IEMsgType.NAME_NEEDS_EDIT, db_name))\n if db_date is None:\n ie_folder.msgs.append(IEMsg(IEMsgType.NO_DATE, file_pathname))\n folders.append(ie_folder)\n else:\n ie_folder = folders[-1]\n if mtime > ie_folder.mod_datetime:\n # folder.mod_datetime is the newest instance's\n ie_folder.mod_datetime = mtime\n if seq in ie_folder.images:\n ie_image = ie_folder.images[seq]\n else:\n ie_image = IEImage(ie_folder, seq)\n ie_folder.images[seq] = ie_image\n ie_image_inst = IEImageInst(ie_image, file_pathname, ext, mtime)\n ie_image.insts[ext] = [ie_image_inst]\n folders[-1].images[seq] = ie_image\n return ie_image_inst\n\ndef scan_file_set(file_set_pathname, test, proc):\n \"\"\" Return a list of IEFolders (each containing IEImages).\n\n the IEFolders/Images represent the folders and images\n found in file_set_pathname\n the list is sorted by folder.fs_path\n test(file_name)\n checks whether the directory should be processed\n proc(file_pathname, file_name, folders)\n returns an IEImage for the file, and,\n if the filename has a new prefix, adds a new IEFolder to folders\n \"\"\"\n folders = []\n try:\n os.listdir(file_set_pathname)\n except:\n pass\n for file in os.listdir(file_set_pathname):\n file_path = os.path.join(file_set_pathname, file)\n if os.path.isfile(file_path) and test(file):\n proc(file_path, file, folders)\n folders.sort(key=lambda folder: folder.fs_path)\n\n return folders\n\ndef scan_file_sel(file_pathname_list, proc):\n \"\"\" return a list of IEFolders (each containing IEImages)\n representing the folders and images found in file_pathname_list\n the list is sorted by folder fs_path\n test(file_name)\n checks whether the directory should be processed\n proc(file_pathname, file_name, folders)\n returns an IEImage for the file, and,\n if the filename has a new prefix, adds a new IEFolder to folders\n \"\"\"\n folders = []\n for file_path in file_pathname_list:\n if os.path.isfile(file_path):\n proc(file_path, os.path.basename(file_path), folders)\n folders.sort(key=lambda folder: folder.fs_path)\n return folders\n","sub_path":"ie_fs.py","file_name":"ie_fs.py","file_ext":"py","file_size_in_byte":23610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232810196","text":"from Descriptive_Statistics.Mean import Mean\nfrom numpy import absolute\nclass Mean_Absolute_Deviation:\n\n @staticmethod\n def meanDev(list):\n sum = 0\n\n listmean = Mean.Mean_Calculator(list)\n for i in range(len(list)):\n dev = absolute(list[i] - listmean)\n sum += dev\n\n return sum/len(list)","sub_path":"Descriptive_Statistics/Mean_Absolute_Deviation.py","file_name":"Mean_Absolute_Deviation.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419540677","text":"import tkinter\n\nroot = tkinter.Tk()\n\nroot.title('Rozmowa')\nroot.geometry('800x600')\n\nlabel1 = tkinter.Label(master=root, text='Jak masz na imię?', fg='black', font=('Arial', 24, 'bold'))\nlabel1.pack()\n\npoleTekstowe = tkinter.Entry(root, font=('Consolas', 24), bg='white')\npoleTekstowe.pack()\n\ndef akcja():\n imie = poleTekstowe.get()\n label2.configure(text=f'Witaj {imie}!')\n\nbutton1 = tkinter.Button(master=root, text='OK', font=('Arial', 24, 'bold'), command=akcja)\nbutton1.pack()\n\nlabel2 = tkinter.Label(master=root, text='', fg='blue', font=('Arial', 24, 'bold'))\nlabel2.pack()\n\nroot.mainloop()\n\n# odczytanie aktualnej wartości pola: poleTekstowe.get()\n# ustawienie nowej wartości w label-u : label2.configure(text='nowy tekst')\n\n","sub_path":"python3days/p18_okienka/rozmowa1.py","file_name":"rozmowa1.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"320847795","text":"import os\ndef fsize(filename):\n finfo=os.stat(filename)\n print(\"the size of the file in bytes :\",finfo.st_size)\ndef fstats(filename):\n f=open(filename,'r')\n l=f.readlines()\n print(\"NO OF LINES IN THE FILE :\",len(l))\n word_count=0\n letter_count=0\n for line in l:\n word_list=line.split()\n word_count=word_count+len(word_list)\n for word in word_list:\n letter_count=letter_count+len(word)\n print(\"the no of word in the file :\",word_count)\n print(\"the no of letters in the file :\",letter_count)\nfname=input(\"enter the file name\")\nfsize(fname)\nfstats(fname)\n\n","sub_path":"filestats.py","file_name":"filestats.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84074077","text":"#!/usr/bin/python3\nimport cv2\nimport speech_recognition as sr\n\n\nimg1=cv2.imread('index1.jpg')\nimg2=cv2.imread('index2.jpg')\n\nr=sr.Recognizer()\n\nwith sr.Microphone() as source:\n\tr.adjust_for_ambient_noise(source)\n\tprint(\"say percentage\")\n\taudio=r.listen(source)\n\n\ntry:\n\ttext=r.recognize_google(audio)\n\tprint(\"you said \" +text)\n\tnewimg=cv2.addWeighted(img1,text,img2,0.7,0)\n\ta=os.system(cv2.imshow('w1',newimg))\n\tprint(a)\n\t\n\t\t\nexcept Exception as e:\n\tprint (e)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"imgusrvoc.py","file_name":"imgusrvoc.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569393546","text":"#!/usr/bin/env python3\n# __@@__ Coding:utf-8\n\n\"\"\"\n@Version: ??\n@Author: luxutao\n@Licence: Apache Licence\n@Contact: xutao.lu.cn@gmail.com\n@Site: http://www.123m.me\n@Filename: AiohttpwebServer.py\n@Projectname: PycharmProjects\n@Time: 2016/9/8 10:54\n@Platform: Windows 7 Ultimate\n\"\"\"\n\nimport asyncio\nfrom aiohttp import web\n\nasync def index(request):\n await asyncio.sleep(0.5)\n return web.Response(body=b'

Index

')\n\n\nasync def hello(request):\n await asyncio.sleep(0.5)\n text = '

hello,%s!

' % request.match_info['name']\n return web.Response(body=text.encode()) #web应答\n\n\nasync def init(fuck):\n app = web.Application(loop=fuck) #loop参数用事件循环处理http的请求\n app.router.add_route('GET','/',index) #请求的方法,路径,处理程序\n app.router.add_route('GET','/hello/{name}',hello)\n srv = await fuck.create_server(app.make_handler(),'127.0.0.1',8000) #创建一个服务器,第一个参数\n #是创建HTTP协议的工厂来处理请求\n print('Server started at http://127.0.0.1:8000')\n return srv\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(init(loop))\nloop.run_forever()","sub_path":"aiohttpwebServer.py","file_name":"aiohttpwebServer.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300426569","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.db import connection\nfrom rest_framework.renderers import JSONRenderer\nimport sqlalchemy as sql\nfrom sqlalchemy.dialects import postgresql\nimport psycopg2.sql\nimport json\nfrom operator import itemgetter\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nclass JsonResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super().__init__(content, **kwargs)\n\n\ndef sql_text(text):\n assert (connection.vendor == \"postgresql\")\n statement = sql.text(text)\n result = str(statement.compile(dialect=postgresql.dialect()))\n return result\n\n\ndef fetchall_as_dict(cursor):\n columns = [col[0] for col in cursor.description]\n return [\n dict(zip(columns, row))\n for row in cursor.fetchall()\n ]\n\n\ndef ping(request):\n return render(request, 'api/PingTemplate.html')\n\n\ndef get_random_link(request):\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n SELECT * FROM api_link\n ORDER BY RANDOM()\n LIMIT 1\n '''))\n result = fetchall_as_dict(cursor)\n return JsonResponse(result)\n\n\ndef get_all_links(request):\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''SELECT * FROM api_link'''))\n result = fetchall_as_dict(cursor)\n return JsonResponse(result)\n\n\ndef get_keywords(request):\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n SELECT DISTINCT UNNEST(keywords) AS keyword\n FROM api_link\n '''))\n result = fetchall_as_dict(cursor)\n return JsonResponse(sorted(map(lambda obj: obj['keyword'], result)))\n\n\ndef get_link(request, link_id):\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n SELECT *\n FROM api_link\n WHERE id = :link_id\n '''), {\n 'link_id': link_id\n })\n result = fetchall_as_dict(cursor)\n return JsonResponse(result[0])\n\n\ndef search(request):\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n SELECT * \n FROM links\n WHERE (title LIKE '%' || :query || '%' OR notes LIKE '%' || :query || '%')\n '''), {\n 'query': request.GET.get('q', '')\n })\n result = fetchall_as_dict(cursor)\n return JsonResponse(result)\n\n\n@csrf_exempt\ndef add_link(request):\n body = json.loads(request.body)\n notes, title, url, keywords = itemgetter('notes', 'title', 'url', 'keywords')(body)\n\n keywords = [] if '' else keywords.split(',')\n\n if request.method == 'POST':\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n INSERT INTO links (notes, title, url, keywords, last_accessed)\n VALUES (:notes, :title, :url, :keywords, NOW())\n RETURNING id\n '''), {\n 'notes': notes,\n 'title': title,\n 'url': url,\n 'keywords': keywords,\n })\n result = fetchall_as_dict(cursor)\n return JsonResponse(result[0])\n\n\n@csrf_exempt\ndef delete_link(request):\n body = json.loads(request.body)\n link_id = body['id']\n if request.method == 'POST':\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n DELETE FROM links\n WHERE id = :id\n '''), {\n 'id': link_id\n })\n result = fetchall_as_dict(cursor)\n return JsonResponse(result[0])\n\n\n@csrf_exempt\ndef update_link(request):\n body = json.loads(request.body)\n link_id, notes, title, url, keywords = itemgetter('id', 'notes', 'title', 'url', 'keywords')(body)\n\n keywords = [] if '' else keywords.split(',')\n\n if request.method == 'POST':\n with connection.cursor() as cursor:\n cursor.execute(sql_text('''\n UPDATE links\n SET keywords = :keywords, title = :title, url = :url, notes = :notes, last_accessed = NOW()\n WHERE id = :id\n '''), {\n 'id': link_id,\n 'notes': notes,\n 'title': title,\n 'url': url,\n 'keywords': keywords,\n })\n result = fetchall_as_dict(cursor)\n return JsonResponse({'status': \"success\", id: id, 'message': \"Link updated\"})\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"536367992","text":"from bot import SlackBot\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.http import require_POST\nfrom slack.models import SlackUser\nimport cleverbot\nimport json\nimport re\n\n\n@require_POST\ndef command_webhook(request):\n \"\"\"\n Handle data from a webhook\n \"\"\"\n info_url = \"https://www.changetip.com/tip-online/slack\"\n get_started = \"To send your first tip, login with your slack account on ChangeTip: %s\" % info_url\n print(json.dumps(request.POST.copy(), indent=2))\n # Do we have this user?\n user_name = request.POST.get(\"user_name\")\n slack_sender, created = SlackUser.objects.get_or_create(\n name=user_name,\n team_id=request.POST.get(\"team_id\"),\n user_id=request.POST.get(\"user_id\"),\n )\n if created:\n return JsonResponse({\"text\": \"Nice to meet you, %s! %s\" % (user_name, get_started)})\n\n text = request.POST.get(\"text\", \"\")\n\n # Check for mention in the format of <@$userid>\n mention_match = re.search('<@(U[A-Z0-9]+)>', text)\n if not mention_match:\n # Say something clever\n cb = cleverbot.Cleverbot()\n response = cb.ask(text.replace('changetip', ''))\n return JsonResponse({\"text\": response})\n\n slack_receiver = SlackUser.objects.filter(team_id = slack_sender.team_id, user_id=mention_match.group(1)).first()\n if not slack_receiver:\n return JsonResponse({\"text\": \"%s, I don't know who that person is yet. They should say hi to me before I give them money.\" % user_name})\n\n # Substitute the @username back in\n text = text.replace(mention_match.group(0), '@%s' % slack_receiver.name)\n\n # Submit the tip\n bot = SlackBot()\n team_domain = request.POST.get(\"team_domain\")\n tip_data = {\n \"sender\": \"%s@%s\" % (slack_sender.name, team_domain),\n \"receiver\": \"%s@%s\" % (slack_receiver.name, team_domain),\n \"message\": text,\n \"context_uid\": bot.unique_id(request.POST.copy()),\n \"meta\": {}\n }\n for meta_field in [\"token\", \"team_id\", \"channel_id\", \"channel_name\", \"user_id\", \"user_name\", \"command\"]:\n tip_data[\"meta\"][meta_field] = request.POST.get(meta_field)\n\n if request.POST.get(\"noop\"):\n return JsonResponse({\"text\": \"Hi!\"})\n\n response = bot.send_tip(**tip_data)\n out = \"\"\n if response.get(\"error_code\") == \"invalid_sender\":\n out = get_started\n elif response.get(\"error_code\") == \"duplicate_context_uid\":\n out = \"That looks like a duplicate tip.\"\n elif response.get(\"error_message\"):\n out = response.get(\"error_message\")\n elif response.get(\"state\") in [\"ok\", \"accepted\"]:\n tip = response[\"tip\"]\n if tip[\"status\"] == \"out for delivery\":\n out += \"The tip for %s is out for delivery. %s needs to collect by connecting their ChangeTip account to slack at %s\" % (tip[\"amount_display\"], tip[\"receiver\"], info_url)\n elif tip[\"status\"] == \"finished\":\n out += \"The tip has been delivered, %s has been added to %s's ChangeTip wallet.\" % (tip[\"amount_display\"], tip[\"receiver\"])\n\n if \"+debug\" in text:\n out += \"\\n```\\n%s\\n```\" % json.dumps(response, indent=2)\n\n return JsonResponse({\"text\": out})\n\n\ndef home(request):\n return HttpResponse(\"OK\")\n","sub_path":"slack/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"41005013","text":"from django.urls import path\nfrom .views import (\n DepartamentoList,\n DepartamentoNovo,\n DepartamentoUpdate,\n DepartamentoDelete,\n)\n\nurlpatterns = [\n path('list', DepartamentoList.as_view(), name='list_departamentos'),\n path('novo', DepartamentoNovo.as_view(), name='create_departamento'),\n path('update//', DepartamentoUpdate.as_view(), name='update_departamento'),\n path('delete//', DepartamentoDelete.as_view(), name='delete_departamento'),\n]","sub_path":"apps/departamentos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300199423","text":"#! python\nimport threading\nimport time\nimport os\nimport Tkinter as tk\nprint(\"Welcome to Inc, Incorporated! Here you can buy items to sell, all of which are related to ink!\")\nkeepAlive = True\n\n\n\nmoney = 0\nuserInput = \"\"\ndef beg():\n global money\n money += 1\n print(\"Begged: +1 Money\")\nclass item:\n def __init__(self):\n self.name = \"item\"\n self.cost = 0\n self.count = 0\n self.wages = 0\n self.oCost = 0\n \n def buy(self):\n global money\n if money >= self.cost:\n money -= self.cost\n self.count += 1\n print(self.name + \" Purchased! Money: \"+ str(money))\n self.inflate()\n print(self.getMPS())\n else:\n print(\"Insufficient money for purchase. Need: \" + str(self.cost - money))\n print(\"Cost: \" + str(self.cost))\n def inflate(self):\n self.cost += (self.oCost / 10)\n \n def getCount(self):\n return self.name + \"s: \" + self.count\n \n def getMPS(self):\n return int(self.wages * self.count)\n\n def makeBtn(self):\n self.btn = tk.Button(win, text = \"Buy \" + self.name, command = self.buy)\n self.btn.pack()\nclass pen(item):\n def __init__(self):\n self.name = \"Pen\"\n self.cost = 100\n self.wages = 1\n self.count = 16\n self.oCost = 100\n\nclass printer(item):\n def __init__(self):\n self.name = \"Printer\"\n self.cost = 200\n self.wages = 4\n self.count = 0\n self.oCost = 200\n \nclass squidfarm(item):\n def __init__(self):\n self.name = \"Squid Farm\"\n self.cost = 400\n self.wages = 16\n self.count = 0\n self.oCost = 400\n \nclass mntblnk(item):\n def __init__(self):\n self.name = \"Mont Blanc\"\n self.cost = 800\n self.wages = 64\n self.count = 0\n self.oCost = 800\n\nclass earth(item):\n def __init__(self):\n self.name = \"Earth\"\n self.cost = 1600\n self.wages = 256\n self.count = 0\n self.oCost = 1600\n \nclass inkplanet(item):\n def __init__(self):\n self.name = \"Ink Planet\"\n self.cost = 3200\n self.wages = 1025\n self.count = 0\n self.oCost = 3200\n \nclass upgrade:\n def __init__(self):\n self.boost = 0\n self.name = ''\n\nclass game:\n def makeWin(self):\n self.win = tk.Tk()\n self.win.title(\"Status\")\n self.bBeg = tk.Button(self.win, text = \"Beg\", command = beg)\n self.bPen = tk.Button(self.win, text = \"Buy Pen\", command = Pen.buy)\n self.bPrinter = tk.Button(self.win, text = \"Buy Printer\", command = Printer.buy)\n self.bFarm = tk.Button(self.win, text = \"Buy Squid Farm\", command = Squidfarm.buy)\n self.bMntblnk = tk.Button(self.win, text = \"Buy Mont Blanc\", command = Mntblnk.buy)\n self.bEarth = tk.Button(self.win, text = \"Buy Earth!\", command = Earth.buy)\n self.bInkplanet = tk.Button(self.win, text = \"Buy Ink Planet\", command = Inkplanet.buy)\n self.bMPS = tk.Button(self.win, text = \"MPS\", command = g.mps)\n self.bStatus = tk.Button(self.win, text = \"Money\", command = status)\n self.bItems = tk.Button(self.win, text = \"Items\", command = g.items)\n self.bEnd = tk.Button(self.win, text = \"Quit\", command = g.end)\n \n self.bBeg.pack()\n self.bPen.pack()\n self.bPrinter.pack()\n self.bFarm.pack()\n self.bMntblnk.pack()\n self.bEarth.pack()\n self.bInkplanet.pack()\n self.bMPS.pack()\n self.bStatus.pack()\n self.bItems.pack()\n self.bEnd.pack()\n \n self.win.mainloop()\n\n\n def items(self):\n print(\"Pens: \" + str(Pen.count) + \"\\nPrinters: \" + str(Printer.count) + \"\\nSquid Farms: \" + str(Squidfarm.count) + \"\\nMont Blancs: \" + str(Mntblnk.count) + \"\\nEarths: \" + str(Earth.count) + \"\\nInk Planets: \" + str(Inkplanet.count))\n\n def mps(self):\n print(\"Money per second: \" + str((Pen.getMPS() + Printer.getMPS() + Squidfarm.getMPS() + Mntblnk.getMPS() + Earth.getMPS() + Inkplanet.getMPS()) / d))\n def end(self):\n keepAlive = False \n exit()\n \n\nPen = pen()\nPrinter = printer()\nSquidfarm = squidfarm()\nMntblnk = mntblnk()\nEarth = earth()\nInkplanet = inkplanet()\ng = game()\nd = 2\ndef profit():\n global money\n \n while keepAlive:\n \n \n time.sleep(1)\n \n money += ((Pen.count * Pen.wages + Printer.count * Printer.wages + Squidfarm.count * Squidfarm.wages + Mntblnk.wages * Mntblnk.count + Earth.count * Earth.wages ) / d)\n if keepAlive != True:\n break\n\n\n\ndef status():\n print(\"Current Money: \" + str(money))\np = threading.Thread(name='profit', target=profit)\nw = threading.Thread(name=\"UI\", target = g.makeWin)\np.start()\nw.start()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140252028","text":"import logging\r\nimport unittest\r\nimport os\r\nimport time\r\nimport threading\r\nimport logging\r\n\r\nlog = logging.getLogger('tftpy')\r\nlog.setLevel(logging.INFO)\r\n\r\n# console handler\r\nhandler = logging.StreamHandler()\r\nhandler.setLevel(logging.DEBUG)\r\ndefault_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nhandler.setFormatter(default_formatter)\r\nlog.addHandler(handler)\r\n\r\nimport tftpy\r\nfrom tftpy.exceptions import TftpTimeout\r\n\r\n# FIXME: Tests are not suppported on Windows/Cygwin\r\n# os.fork()\r\n# signal - alarms are only supported on Unix\r\n\r\nclass TestTftpyServer(unittest.TestCase):\r\n def test_server_download_stop_now(self, output='/tmp/out'):\r\n print('TEST - test_server_download_stop_now')\r\n root = os.path.dirname(os.path.abspath(__file__))\r\n server = tftpy.TftpServer(root,listenip='localhost',listenport=20001)\r\n client = tftpy.TftpClient('localhost',\r\n 20001,\r\n {})\r\n # Fork a server and run the client in this process.\r\n child_pid = os.fork()\r\n if child_pid:\r\n with self.assertRaises(TftpTimeout):\r\n time.sleep(1)\r\n def delay_hook(pkt):\r\n time.sleep(0.005) # 5ms\r\n client.download('640KBFILE', output, delay_hook)\r\n\r\n os.kill(child_pid, 15)\r\n os.waitpid(child_pid, 0)\r\n\r\n else:\r\n import signal\r\n def handlealarm(signum, frame):\r\n server.stop(now=True)\r\n signal.signal(signal.SIGALRM, handlealarm)\r\n signal.alarm(2)\r\n server.listen()\r\n\r\n # Wait until parent kills us\r\n while True:\r\n time.sleep(1)\r\n\r\n def test_server_download_stop(self, output='/tmp/out'):\r\n print('TEST - test_server_download_stop')\r\n root = os.path.dirname(os.path.abspath(__file__))\r\n server = tftpy.TftpServer(root, 'localhost', 20001)\r\n client = tftpy.TftpClient('localhost',\r\n 20001,\r\n {})\r\n # Fork a server and run the client in this process.\r\n child_pid = os.fork()\r\n if child_pid:\r\n time.sleep(1)\r\n def delay_hook(pkt):\r\n time.sleep(0.005) # 5ms\r\n client.download('640KBFILE', output, delay_hook)\r\n\r\n os.kill(child_pid, 15)\r\n os.waitpid(child_pid, 0)\r\n\r\n else:\r\n import signal\r\n def handlealarm(signum, frame):\r\n server.stop(now=False)\r\n signal.signal(signal.SIGALRM, handlealarm)\r\n signal.alarm(2)\r\n server.listen()\r\n # Wait until parent kills us\r\n while True:\r\n time.sleep(1)\r\n\r\n def test_server_download_dynamic_port(self, output='/tmp/out'):\r\n print('TEST - test_server_download_dynamic_port')\r\n\r\n root = os.path.dirname(os.path.abspath(__file__))\r\n\r\n server = tftpy.TftpServer(root, 'localhost', 0)\r\n print(server.listen)\r\n server_thread = threading.Thread(target=server.listen)\r\n server_thread.start()\r\n\r\n try:\r\n server.is_running.wait()\r\n client = tftpy.TftpClient('localhost', server.listenport, {})\r\n time.sleep(1)\r\n client.download('640KBFILE',\r\n output)\r\n finally:\r\n server.stop(now=False)\r\n server_thread.join()","sub_path":"tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"492789703","text":"import pandas as pd\n\ndef check(fname, target):\n\tdata = pd.read_csv(fname, encoding = \"utf8\")\n\t#numNULL = data.isnull().sum()\n\t#print(numNULL)\n\tch = data[data[\"url\"] == target[2]]\n\n\tif(ch.shape[0] == 0):\n\t\tprint('NOT FOUND [{0}]'.format(target))\n\t\tnew = pd.Series(target, index = data.columns, name = data.shape[0])\n\t\tdata = data.append(new)\n\t\tprint(\"\")\n\t\tprint(data.tail())\n\t\tdata.to_csv('data.csv', encoding='utf-8', index = False)\n\t\treturn 1, new\n\n\telse:\n\t\tprint('FOUND')\n\t\tprint(ch)\n\t\tempty = pd.Series(['None','None','None'], index = data.columns, name = data.shape[0])\n\t\treturn 0, empty\n\nif __name__ == '__main__':\n\tname = \"data.csv\"\n\ttitle = \"hello\"\n\timage = \"hello\"\n\turl = \"http://sukai9682.jp/fn_image/ff_2940496_full.jpg\"\n\t#url = \"http://sukai9682.jp/fn_image/ff_2795221_full.jpg\"\n\tcheckData = [title, image, url]\n\tisChecked, info = check(name, checkData)\n\tprint(\"isChecked = {0}\".format(isChecked))\n\tprint(info)\n","sub_path":"src_otherwise/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60501720","text":"import numpy as np\nfrom . import maze\nfrom . import maze2d_single_goal\nfrom .. import env_base\n\n\nONE_ROOM_MAZE = maze.Maze(maze.SquareRoomFactory(size=15))\nONE_ROOM_GOAL_POS = np.array([15, 15])\nTWO_ROOM_MAZE = maze.Maze(maze.TwoRoomsFactory(size=15))\nTWO_ROOM_GOAL_POS = np.array([9, 15])\nHARD_MAZE = maze.Maze(maze.MazeFactoryBase(maze_str=maze.HARD_MAZE))\nHARD_MAZE_GOAL_POS = np.array([10, 10])\n\n\nclass OneRoomEnv(env_base.Environment):\n def __init__(self):\n task = maze2d_single_goal.Maze2DSingleGoal(\n maze=ONE_ROOM_MAZE,\n episode_len=50,\n start_pos='random',\n use_stay_action=True,\n reward_type='neg',\n goal_pos=ONE_ROOM_GOAL_POS,\n end_at_goal=False)\n super().__init__(task)\n\n\nclass TwoRoomEnv(env_base.Environment):\n def __init__(self):\n task = maze2d_single_goal.Maze2DSingleGoal(\n maze=TWO_ROOM_MAZE,\n episode_len=50,\n start_pos='random',\n use_stay_action=True,\n reward_type='neg',\n goal_pos=TWO_ROOM_GOAL_POS,\n end_at_goal=False)\n super().__init__(task)\n\n\nclass HardMazeEnv(env_base.Environment):\n def __init__(self):\n task = maze2d_single_goal.Maze2DSingleGoal(\n maze=HARD_MAZE,\n episode_len=50,\n start_pos='random',\n use_stay_action=True,\n reward_type='neg',\n goal_pos=HARD_MAZE_GOAL_POS,\n end_at_goal=False)\n super().__init__(task)\n\n\n\nENV_CLSS = {\n 'OneRoom': OneRoomEnv,\n 'TwoRoom': TwoRoomEnv,\n 'HardMaze': HardMazeEnv,\n}\n\n\ndef make(env_id):\n return ENV_CLSS[env_id]()\n\n","sub_path":"rl_lap/envs/gridworld/gridworld_envs.py","file_name":"gridworld_envs.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416648939","text":"import torch\r\nimport torch.nn.functional as F\r\n\r\nfrom PIL import Image\r\n\r\nimport os\r\nimport json\r\nimport numpy as np\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\nimport torchvision\r\nfrom torchvision import datasets, models, transforms\r\n\r\nfrom captum.attr import IntegratedGradients\r\n\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n#name of the network that will be used in interpretation\r\nmodel = torch.load('resnet_network_rgb')\r\nmodel.to(device)\r\nmodel.eval()\r\n\r\n#normalize validation images\r\ntransform = transforms.Compose([\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n\r\nclass ImageFolderWithPaths(datasets.ImageFolder):\r\n # override the __getitem__ method. this is the method that dataloader calls\r\n def __getitem__(self, index):\r\n # this is what ImageFolder normally returns \r\n original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)\r\n # the image file path\r\n path = self.imgs[index][0]\r\n # make a new tuple that includes original and the path\r\n tuple_with_path = (original_tuple + (path,))\r\n return tuple_with_path\r\n\r\n#location of validation data \r\ndata_dir = 'rgb/val/'\r\n\r\nimage_dataset = ImageFolderWithPaths(root=data_dir, transform=transform)\r\ntestloader = torch.utils.data.DataLoader(image_dataset,batch_size=198,shuffle=False, num_workers=0)\r\n\r\nfor inputs,labels, paths in testloader:\r\n inputs=inputs.to(device)\r\n labels=labels.to(device)\r\n print(labels, paths)\r\n\r\nclasses = ('high','low')\r\n\r\nprint('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(198)))\r\n\r\noutputs = model(inputs)\r\n\r\n_, predicted = torch.max(outputs, 1)\r\n\r\nprint('Predicted: ', ' '.join('%5s' % classes[predicted[j]]\r\n for j in range(198)))\r\n\r\nind = 0\r\nfor ind in range(0,198):\r\n \r\n input = inputs[ind].unsqueeze(0).to(device)\r\n input.requires_grad = True\r\n \r\n def attribute_image_features(algorithm, input, **kwargs):\r\n model.zero_grad()\r\n tensor_attributions = algorithm.attribute(input,\r\n target=labels[ind],\r\n **kwargs\r\n )\r\n return tensor_attributions\r\n \r\n ig = IntegratedGradients(model)\r\n attr_ig, delta = attribute_image_features(ig, input, baselines=input * 0, return_convergence_delta=True)\r\n attr_ig = np.transpose(attr_ig.squeeze().cpu().detach().numpy(), (1, 2, 0))\r\n print('Approximation delta: ', abs(delta))\r\n\r\n print('Original Image')\r\n print('Predicted:', classes[predicted[ind]], \r\n ' Probability:', torch.max(F.softmax(outputs, 1)).item())\r\n \r\n original_image = np.transpose((inputs[ind].cpu().detach().numpy() / 2) + 0.5, (1, 2, 0))\r\n \r\n _ = viz.visualize_image_attr(attr_ig, original_image, method=\"blended_heat_map\",sign=\"all\",show_colorbar=True, title=\"Overlayed Integrated Gradients\")\r\n \r\n plt.savefig('Figures_rgb/fig'+str(ind)+'.png',bbox_inches='tight',pad_inches=0)\r\n \r\n ind = ind +1\r\n","sub_path":"deep learning interpretation.py","file_name":"deep learning interpretation.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"588730779","text":"import config\nimport csv\nimport time\nimport itertools\nimport dateutil.relativedelta\nfrom itertools import cycle, islice, dropwhile\nimport datetime\nimport os\nimport pandas as pd\ndb = config.db\ncount = 0\ns= 20090000 #for Mongo Query\ne= 20161231\nstarting = 2008 #argument for starting year\nending = 2016 #argument for ending year\nending_for_range = ending + 1\ntimestr = time.strftime(\" %Y%m%d-%H%M%S\")\nfilename = \"splitFYFQ\" + \".csv\"\nfieldnames = ['entityId','companyName','stockSymbol','cik','count_of_NULL']\nwith open(filename, 'w') as csvfile:\n for n in range(starting, ending_for_range):\n fieldnames.extend([str(n) + 'Q1', str(n) + 'Q2', str(n) + 'Q3', str(n) + \"FY\"])\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', lineterminator='\\n')\n writer.writeheader()\n company =[] #stores stockSymbols of all companies in entityReferences\n eref= db.EntityReferences.find()\n for stocksymbol in eref:\n company.append(stocksymbol[\"stockSymbol\"])\n ss= [ 'ahgp','pson','aapl','fb'] #test list\n for symbol in company: #replace company by ss to run test list of stockSymbols\n filing = db.SECFilings.find({\"stockSymbol\": symbol,'filingPeriod': {'$lte': e, '$gte': s}}).sort(\"filingDate\",1)\n datarow ={} #intializing datarow dictionary to store all data from SECFilings\n for document in filing:\n try:\n filingperiod = str(document[\"filingPeriod\"])\n monthday = (filingperiod[4:])\n yearpart = int((filingperiod[:4]))\n fiscalyearend = str(document[\"fiscalYearEnd\"])\n months = int((fiscalyearend[:2]))\n monthpart = int((filingperiod[4:-2]))\n except ValueError:\n continue\n datarow.update({'entityId': document[\"entityId\"], 'companyName': document[\"companyName\"], 'stockSymbol': symbol,'cik':document[\"cik\"]})\n monthsCycle = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] #order of months in descending order for creating cyclic list\n OrderedMonths = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] #ordered months\n if months > 5:\n if months in OrderedMonths:\n print(months)\n cycled = cycle(monthsCycle)\n skipped = dropwhile(lambda x: x != months, cycled) #skip all months until current fiscalyearend's Month\n sliced = islice(skipped, None, 15) #create a cyclic list from the current starting Month\n result = list(sliced) # create a list from iterator\n #print(result)\n az0 = result[9] #array to access the list items\n az1 = result[10]\n az2 = result[11]\n bz0 = result[6]\n bz1 = result[7]\n bz2 = result[8]\n cz0 = result[3]\n cz1 = result[4]\n cz2 = result[5]\n dz0 = result[0]\n dz1 = result[1]\n dz2 = result[2]\n Q1 = [az0, az1, az2]\n Q2 = [bz0, bz1, bz2]\n Q3 = [cz0, cz1, cz2]\n FY = [dz0, dz1, dz2] #Q4 is FY\n\n if monthpart in Q1:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n resul1 = d.year\n concatenatedFYFQ = str(resul1) + \"Q1\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in Q2:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n resul2 = d.year\n concatenatedFYFQ = str(resul2) + \"Q2\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in Q3:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n resul3 = d.year\n concatenatedFYFQ = str(resul3) + \"Q3\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in FY:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n resul4 = d.year\n concatenatedFYFQ = str(resul4) + \"FY\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n else: #for FYE less than 5\n if months in OrderedMonths:\n cycled = cycle(monthsCycle)\n skipped = dropwhile(lambda x: x != months, cycled)\n sliced = islice(skipped, None, 15)\n result = list(sliced) # create a list from iterator\n az0 = result[9]\n az1 = result[10]\n az2 = result[11]\n bz0 = result[6]\n bz1 = result[7]\n bz2 = result[8]\n cz0 = result[3]\n cz1 = result[4]\n cz2 = result[5]\n dz0 = result[0]\n dz1 = result[1]\n dz2 = result[2]\n Q1 = [az0, az1, az2]\n Q2 = [bz0, bz1, bz2]\n Q3 = [cz0, cz1, cz2]\n FY = [dz0, dz1, dz2]\n if monthpart in Q1:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n d1 = d - dateutil.relativedelta.relativedelta(months=3)\n resul1 = int(d1.year)\n concatenatedFYFQ = str(resul1) + \"Q1\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in Q2:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n d2 = d - dateutil.relativedelta.relativedelta(months=3)\n resul2 = int(d2.year)\n concatenatedFYFQ = str(resul2) + \"Q2\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in Q3:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n d3 = d - dateutil.relativedelta.relativedelta(months=3)\n resul3 = int(d3.year)\n concatenatedFYFQ = str(resul3) + \"Q3\"\n datarow.update({concatenatedFYFQ: document[\"stockSymbol\"]})\n\n elif monthpart in FY:\n d = datetime.datetime.strptime(filingperiod, \"%Y%m%d\")\n resul4 = int(d.year) - 1\n concatenatedFYFQ = str(resul4) + \"FY\"\n datarow.update({concatenatedFYFQ : document[\"stockSymbol\"]})\n writer.writerow(datarow)\n\nfilename1='output_issue11'+'.csv'\nfieldnames = ['entityId','companyName','stockSymbol','cik','No_of_filings','count_of_NULL','pcnt_count',\"startFYFQ\",\"endFYFQ\"]\nwith open(filename1, 'w') as csvfile:\n for n in range(starting, ending_for_range):\n fieldnames.extend([str(n) + 'Q1', str(n) + 'Q2', str(n) + 'Q3', str(n) + \"FY\"])\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', lineterminator='\\n')\n writer.writeheader()\n with open('splitFYFQ.csv', 'r') as csvfile1:\n reader = csv.DictReader(csvfile1)\n headers = reader.fieldnames\n for row in reader:\n FYFQ_from_csv = []\n for n in range(starting, ending_for_range):\n #print(row[\"2009Q1\"])\n FYFQ_from_csv.append(row[str(n) + 'Q1'])\n FYFQ_from_csv.append(row[str(n) + 'Q2'])\n FYFQ_from_csv.append(row[str(n) + 'Q3'])\n FYFQ_from_csv.append(row[str(n) + 'FY'])\n skippedheader = dropwhile(lambda x: x != \"2008Q1\", headers)\n #print(skippedheader)\n slicedheader = islice(skippedheader, None, 36)\n resultheader =list(slicedheader)\n skipped = dropwhile(lambda x: x != row[\"stockSymbol\"], FYFQ_from_csv)\n skipped1 = dropwhile(lambda x: x == None, FYFQ_from_csv)#removes leading elements from list which are not stockSymbols\n sliced = islice(skipped, None, 38)\n result = list(sliced)\n sliced1 = islice(FYFQ_from_csv, None, 36)\n result1 = list(sliced1)\n print(result1)\n #ab = result1.index(row[\"stockSymbol\"])\n #print(ab)\n try:\n #print(result)\n while not result[-1]: #removes trailing elements from list which are not stockSymbols\n result.pop()\n No_of_filings = len(result) #counting no of filings\n countofNULL = result.count('') #counting no of NULLS\n #print(result.count(''))\n pcnt_count= countofNULL/No_of_filings #calculating Percentage count\n row.update({\"No_of_filings\":No_of_filings,\"count_of_NULL\":countofNULL, \"pcnt_count\":pcnt_count})\n a = [i for i, x in enumerate(result1) if x != '']\n print(a)\n b = a[0]\n c=a[-1]\n row.update({\"startFYFQ\": resultheader[b],\"endFYFQ\":resultheader[c]})\n writer.writerow(row)\n except IndexError:\n continue\nstarting = 2008 #argument for starting year\nending = 2016 #argument for ending year\nending_for_range = ending + 1\ns= 20090000 #for Mongo Query\ne= 20161231\nfull = []\ncompany = [] # stores stockSymbols of all companies in entityReferences\neref = db.EntityReferences.find()\nfor stocksymbol in eref:\n company.append(stocksymbol[\"stockSymbol\"])\nfilename3 = \"issue11_termResults1\"+\".csv\"\nfieldnames2 = ['stockSymbol']\nwith open(filename3, 'w') as csvfile:\n for n in range(starting, ending_for_range):\n fieldnames2.extend([str(n) + 'Q1', str(n) + 'Q2', str(n) + 'Q3', str(n) +\"Q4\", str(n) + \"FY\"])\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames2, delimiter=',', lineterminator='\\n')\n writer.writeheader()\n for symbol in company: #replace company by ss to run test list of stockSymbols\n termresults = db.TermResults.find({\"termName\": \"Total Assets\", \"stockSymbol\": symbol})\n datarow = {}\n for result in termresults:\n if result[\"FY\"]>starting and result[\"FY\"] 0]\ndf1.to_csv(\"filter_missingfilings_only.csv\")\nfilename1= 'issue11_missingFilingsfinalresult.csv'\nwith open(filename1, 'w') as csvfile:\n fieldnames=['stockSymbol','companyName','startFYFQ','endFYFQ','missingFilings']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=',', lineterminator='\\n')\n writer.writeheader()\n\n with open('filter_missingfilings_only.csv', 'r') as csvfile1:\n reader1 = csv.DictReader(csvfile1)\n headers = reader1.fieldnames\n for row in reader1:\n FYFQ_from_csv = []\n for n in range(starting, ending_for_range):\n FYFQ_from_csv.append(row[str(n) + 'Q1'])\n FYFQ_from_csv.append(row[str(n) + 'Q2'])\n FYFQ_from_csv.append(row[str(n) + 'Q3'])\n FYFQ_from_csv.append(row[str(n) + 'FY'])\n datarow = {'stockSymbol': row[\"stockSymbol\"],'companyName': row[\"companyName\"],'startFYFQ': row[\"startFYFQ\"],'endFYFQ': row[\"endFYFQ\"]}\n skippedheader = dropwhile(lambda x: x != \"2008Q1\", headers)\n slicedheader = islice(skippedheader, None, 36)\n resultheader = list(slicedheader)\n a= resultheader.index(row[\"startFYFQ\"])\n b = resultheader.index(row[\"endFYFQ\"])\n #print(a)\n slice1 = resultheader[a:b+1]\n #print(slice)\n #print(resultheader)\n slice2=FYFQ_from_csv[a:b+1]\n #print(slice1)\n print(slice2)\n real =[]\n for i, j in enumerate(slice2):\n if j == '':\n aaaa=1\n abc=i\n real.append(slice1[i]+';')\n\n print(slice1[i])\n datarow.update({'missingFilings': real})\n writer.writerow(datarow)\nprint(\"completed program successfully\")","sub_path":"InternTestData/Test Scripts/Data Verification/Test-Scripts/issue11final.py","file_name":"issue11final.py","file_ext":"py","file_size_in_byte":14639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"300309940","text":"# Copyright 2019 The Fuchsia Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom typing import Sequence, TypeVar, Generic, List, Tuple, Callable\n\nfrom difl.ir import Declaration\nfrom difl.changes import Change, DeclAdded, DeclRemoved\n\nD = TypeVar('D', bound=Declaration)\n\n\nclass DeclarationIntersection(Generic[D]):\n '''Find which declarations are removed, shared or added between the lists supplied'''\n\n def __init__(self, old: Sequence[D], new: Sequence[D]):\n # dictionaries of declarations by name\n olds = {d.name: d for d in old}\n news = {d.name: d for d in new}\n # immutable sets of declaration names\n old_names = frozenset(olds.keys())\n new_names = frozenset(news.keys())\n\n self.removed = [olds[n] for n in old_names - new_names]\n self.common = [(olds[n], news[n])\n for n in old_names.intersection(new_names)]\n self.added = [news[n] for n in new_names - old_names]\n\n\ndef intersect_changes(before: Sequence[D], after: Sequence[D],\n compare: Callable[[D, D], List[Change]]) -> List[Change]:\n # dictionaries of declarations by name\n before_by_name = {d.name: d for d in before}\n after_by_name = {d.name: d for d in after}\n # immutable sets of declaration names\n before_names = frozenset(before_by_name.keys())\n after_names = frozenset(after_by_name.keys())\n\n changes: List[Change] = []\n\n for decl in [after_by_name[n] for n in after_names - before_names]:\n changes.append(DeclAdded(before=None, after=decl))\n for decl in [before_by_name[n] for n in before_names - after_names]:\n changes.append(DeclRemoved(before=decl, after=None))\n for before_decl, after_decl in [\n (before_by_name[n], after_by_name[n])\n for n in before_names.intersection(after_names)\n ]:\n changes.extend(compare(before_decl, after_decl))\n\n return changes\n","sub_path":"garnet/public/lib/fidl/tools/difl/intersection.py","file_name":"intersection.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"321558691","text":"# -*- coding: utf-8 -*-\n\"\"\"Constants\n\nThis module contains constants used in the Cognite Python SDK.\n\nThis module is protected and should not used by end-users.\n\nAttributes:\n BASE_URL (str): Base url for Cognite API. Should have correct version number.\n LIMIT (int): Limit on how many datapoints should be returned from the API when fetching data using the\n timeseries module.\n RETRY_LIMIT (int): Number of retries to perform if a request to the API should fail.\n\"\"\"\nimport os\n\n# GLOBAL CONSTANTS\nBASE_URL = \"https://api.cognitedata.com\"\nLIMIT = 100000\nLIMIT_AGG = 10000\nRETRY_LIMIT = 3\nNUM_OF_WORKERS = 10\n\n# DATA TRANSFER SERVICE\nTIMESERIES = \"timeSeries\"\nAGGREGATES = \"aggregates\"\nGRANULARITY = \"granularity\"\nSTART = \"start\"\nEND = \"end\"\nMISSING_DATA_STRATEGY = \"missingDataStrategy\"\nLABEL = \"label\"\n","sub_path":"cognite/_constants.py","file_name":"_constants.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"313790164","text":"#Mirka Monzon 18139\n#Lab1 Filling any polygon \n\nimport struct \n\n#Definicion\ndef char(c):\n return struct.pack('=c' , c.encode('ascii'))\n\ndef word(c):\n return struct.pack('=h', c)\n\ndef dword(c):\n return struct.pack('=l', c)\n\ndef color(r, g, b):\n return bytes([b, g, r])\n\n#Constructor\nclass Bitmap(object):\n \n def __init__(self, height, width):\n\n self.height = height\n self.width = width\n self.framebuffer = []\n self.clear_color = color(0, 0, 0)\n self.vertex_color = color(255, 0, 0)\n self.glClear()\n\n #Inicializacion de software render \n def glInit(self):\n pass\n\n#Funciones de render \n #Inicializacion de framebuffer\n def glCreateWindow(self, height, width):\n self.height = height\n self.width = width\n self.glClear()\n\n #Creacion de espacio para dibujar\n def glViewPort(self, x, y, width, height):\n self.x = x\n self.y = y\n self.vpx = width\n self.vpy = height\n\n #Mapa de bits de un solo color\n def glClear(self):\n self.framebuffer = [\n [self.clear_color for x in range(self.width)] for y in range(self.height)\n ]\n \n #Cambio de color de glClear\n def glClearColor(self, r, g, b):\n try:\n self.rc = round(255*r)\n self.gc = round(255*g)\n self.bc = round(255*b)\n self.clear_color = color(self.rc, self.rg, self.rb)\n except ValueError:\n print('\\nERROR: Ingrese un número entre 1 y 0\\n')\n \n #Cambio de color de punto en pantalla\n def glVertex(self, x, y):\n if x <= 1 and x>= -1 and y >= -1 and y <= 1:\n \n if x > 0:\n self.vx = self.x + round(round(self.vpx/2)*x) - 1\n if y > 0:\n self.vy = self.y + round(round(self.vpy/2)*y) - 1\n if x <= 0:\n self.vx = self.x + round(round(self.vpx/2)*x)\n if y <= 0:\n self.vy = self.y + round(round(self.vpy/2)*y)\n \n self.glPoint(self.vx,self.vy, self.vertex_color)\n else:\n pass\n \n #Cambio de color con el que funciona glVertex\n def glColor(self, r, g, b):\n try:\n self.rv = round(255*r)\n self.gv = round(255*g)\n self.bv = round(255*b)\n self.vertex_color = color(self.rv,self.gv,self.bv)\n except ValueError:\n print('\\nERROR: Ingrese un número entre 1 y 0\\n')\n\n #Da el color al punto en pantalla \n def glPoint(self, x, y, color):\n x = int(round((x+1) * self.width / 2))\n y = int(round((y+1) * self.height / 2))\n try:\n self.framebuffer[y][x] = color\n except IndexError:\n print(\"\\nEl pixel está fuera de los límites de la imagen.\\n\")\n \n #Funcion para linea \n def glLine(self, x0, y0, x1, y1):\n #Convierte los valores entre -1 a 1 a cordenadas DMC\n x0 = int(round((x0 + 1) * self.width / 2))\n y0 = int(round((y0 + 1) * self.height / 2))\n x1 = int(round((x1 + 1) * self.width / 2))\n y1 = int(round((y1 + 1) * self.height / 2))\n\n dy = abs(y1 - y0)\n dx = abs(x1 - x0)\n\n steep = dy > dx\n \n #Si dy es mayor que dx entonces intercambiamos cada una de las coordenadas\n if steep:\n x0, y0 = y0, x0\n x1, y1 = y1, x1\n \n #Si el punto de inicio en x es mayor que el punto final, intercambia los puntos\n if x0 > x1:\n x0, x1 = x1, x0\n y0, y1 = y1, y0\n \n dy = abs(y1 - y0)\n dx = abs(x1 - x0)\n\n #Determina los puntos que formarán la línea\n offset = 0.5 * 2 * dx\n threshold = 0.5 * 2 * dx\n y = y0\n\n #Rellena la línea con puntos sin dejar espacios\n for x in range(x0, x1 + 1):\n if steep:\n self.glPoint((float(y)/(float(self.width)/2))-1,(float(x)/(float(self.height)/2))-1,self.vertex_color)\n else:\n self.glPoint((float(x)/(float(self.width)/2))-1,(float(y)/(float(self.height)/2))-1,self.vertex_color)\n offset += dy\n\n if offset >= threshold:\n y += 1 if y0 < y1 else -1\n threshold += 1 * dx\n\n def glFillPolygon(self, polygon):\n #Point-in-Polygon (PIP) Algorithm\n for y in range(self.height):\n for x in range(self.width):\n i = 0\n j = len(polygon) - 1\n draw_point = False\n #Verifica si el punto está entre los límites\n for i in range(len(polygon)):\n if (polygon[i][1] < y and polygon[j][1] >= y) or (polygon[j][1] < y and polygon[i][1] >= y):\n if polygon[i][0] + (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) * (polygon[j][0] - polygon[i][0]) < x:\n draw_point = not draw_point\n j = i\n if draw_point:\n self.glPoint((float(x)/(float(self.width)/2))-1,(float(y)/(float(self.height)/2))-1,self.vertex_color)\n \n def glWrite(self, file_name):\n bmp_file = open(file_name, 'wb')\n\n #Header\n bmp_file.write(char('B'))\n bmp_file.write(char('M'))\n bmp_file.write(dword(14 + 40 + self.width * self.height))\n bmp_file.write(dword(0))\n bmp_file.write(dword(14 + 40))\n \n #image header \n bmp_file.write(dword(40))\n bmp_file.write(dword(self.width))\n bmp_file.write(dword(self.height))\n bmp_file.write(word(1))\n bmp_file.write(word(24))\n bmp_file.write(dword(0))\n bmp_file.write(dword(self.width * self.height * 3))\n bmp_file.write(dword(0))\n bmp_file.write(dword(0))\n bmp_file.write(dword(0))\n bmp_file.write(dword(0))\n\n for x in range(self.height):\n for y in range(self.width):\n bmp_file.write(self.framebuffer[x][y])\n \n bmp_file.close()","sub_path":"gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590385952","text":"# DISEMVOWEL\n#\n# Your task is to write a function that takes a string and\n# return a new string with all vowels removed.\n# For example, the string \"This website is for losers LOL!\" would become\n# \"Ths wbst s fr lsrs LL!\".\n# Note: for this kata y isn't considered a vowel.\n\nfrom unittest import TestCase\n\n\ndef disemvowel(string):\n vowels = ['a', 'e', 'i', 'o', 'u']\n\n string_list = list(string)\n\n vowels_in_string = [letter for letter in string if letter.lower() in vowels]\n\n for letter in string:\n if letter in vowels_in_string:\n string_list.remove(letter)\n return \"\".join(string_list)\n\n\nprint(disemvowel(\"\"\"No offense but,\nYour writing is among the worst I've ever read\"\"\"))\n\nclass DisemvowelTest(TestCase):\n def test_disemvowel(self):\n self.assertEqual(disemvowel(\"This website is for losers LOL!\"),\n \"Ths wbst s fr lsrs LL!\")\n\n","sub_path":"Exercises/Algorithms/disemvowel.py","file_name":"disemvowel.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168081905","text":"\"\"\"\nPlot fgout frames and also motion of particles using velocities\ninterpolated from fgout.\n\nRotate so x in vertical direction as in Figures from paper and videos.\n\"\"\"\n\nimport sys\nif 'matplotlib' not in sys.modules:\n import matplotlib\n #matplotlib.use('Agg') # Use an image backend\n\n\nfrom pylab import *\nimport os,sys\nfrom matplotlib import colors\nimport matplotlib.animation as animation\nfrom clawpack.visclaw import animation_tools, plottools, geoplot\n\nsys.path.insert(0,'../../common_python')\nimport fgout_particles as P\n\n\nif 1:\n from clawpack.geoclaw import fgout_tools\n graphics_dir = os.path.abspath('../../../graphics')\nelse:\n # local versions for self-contained directory:\n import fgout_tools\n graphics_dir = './'\n \n#outdir = os.path.abspath('../SWE2d/_output_no_obst')\noutdir = os.path.abspath('../SWE2d/_output_no_obst_no_dtopo')\noutput_format = 'binary32'\n\nif 'mmfs1' in outdir:\n # on hyak:\n outdir = outdir.replace('mmfs1/home','gscratch/tsunami')\n\nprint('Looking for output in ',outdir)\n\n\n# List of frames to use for making debris paths and animation:\n#fgframes = range(1,121)\nfgframes = range(1,31)\n#fgframes = range(10,21)\n\n\nbgimage = None\n#plot_extent = [34, 43.75, -3, 3]\nxlimits = [-3, 3]\nylimits = [30, 41.29]\n#flipud = lambda A: fliplr(flipud(A)) # x is vertical in plots\nflipud = lambda A: A\n\ncolor = 'k'\nlinewidth = 2\n\n# stationary blocks:\nx1b1 = 35.29\nx2b1 = x1b1 + 0.4\ny1b1 = -0.6\ny2b1 = y1b1 + 0.4\n\nx1b2 = 35.29\nx2b2 = x1b2 + 0.4\ny1b2 = 0.2\ny2b2 = y1b2 + 0.4\n\n\n# Instantiate object for reading fgout frames:\nfgout_grid = fgout_tools.FGoutGrid(1, outdir, output_format)\n\n\n# Deterime time t0 of first fgout frame, to initialize particles\nframeno0 = fgframes[0]\nfgout0 = fgout_grid.read_frame(frameno0)\nt0 = fgout0.t\n\nx1fg,x2fg,y1fg,y2fg = fgout0.extent_edges\nfgout_extent = [y1fg,y2fg,x2fg,x1fg] # for rotated\nprint('fgout0.extent_edges = ', fgout0.extent_edges)\nprint('fgout_extent = ', fgout_extent)\n\ndef timeformat(t):\n \"\"\"\n Convert t in seconds to string in format hh:mm:ss\n \"\"\"\n from numpy import mod\n hours = int(t/3600.)\n tmin = mod(t,3600.)\n min = int(tmin/60.)\n sec = int(mod(tmin,60.))\n timestr = '%s:%s:%s' % (hours,str(min).zfill(2),str(sec).zfill(2))\n return timestr\n\ndef timeformat(t): \n timestr = '%.3f seconds' % t \n return timestr\n \n# Initialize debris_paths dictionary and set\n# initial debris particle locations (x0,y0) at time t0.\n# Require a list of dbnos and each array \n# debris_paths[dbno]\n# in the dictionary is a 2d array with a single row [t0, x0, y0] to start.\n\ndebris_paths = {}\ngrounding_depth = {}\ndrag_factor = {}\nwface = {}\nhface = {}\nmass = {}\ndradius = {}\nKspring = 0.5\n#nsubsteps = 40\nnsubsteps = 20\n\ndbnos = []\ndbnosA = []\ndbnosB = []\ndbnosC = []\n\n# set initial velocities to 0 (or may want to interpolate from fgout0 if t0>0?)\nu0 = 0.\nv0 = 0.\nlength = 0.6 # * sqrt(2)\n\n# centers of circles in rectangular grid:\ndd = 0.153 # distance between centers\nxg1 = arange(31.29+0.5*dd, 31.29+4*dd, dd)\nyg1 = arange(-2*dd, 2.1*dd, dd)\n#xg1 = array([31.29+3.5*dd])\n#yg1 = array([-2*dd])\n\nxgg = []\nygg = []\nfor xg in xg1:\n for yg in yg1:\n xgg.append(xg)\n ygg.append(yg)\n \ngrounding_depth_common = 0. #0.04\ndrag_factor_common = 0.2\n\nmass_hdpe = 0.5237 # = 987*V, V = 0.102*0.102*0.051 m^3\nmass_wood = 0.3438 # = 648*V\nwface_common = 0. #0.102 # width of face of each debris block\nhface_hdpe = 0.05034 # = 0.051 * density/density_water\nhface_wood = 0.03305\n\ndradius_common = 0.051\n#dradius_common = 5.76 # same area as 10.2 x 10.2 square\n\n#Ktether = {}\n#Ktether_common = 50.\n\ndef tether(dbno1,dbno2):\n Dtether = nan\n Ktether = 0.\n if mod(dbno1-dbno2,10000)==0:\n # points in same square\n if max(dbno1,dbno2) < 4000:\n if abs(dbno1-dbno2) in [1000,3000]:\n # adjacent corners of square\n Dtether = length\n Ktether = 50.\n else:\n # diagonal corners of square\n Dtether = sqrt(2)*length\n Ktether = 50.\n else:\n # center and a corner of same square\n Dtether = 0.5*sqrt(2)*length\n Ktether = 100.\n return Dtether,Ktether\n\nfor k in range(len(xgg)):\n dbno = k\n db = array([[t0, xgg[k], ygg[k], u0, v0]])\n debris_paths[dbno] = db\n dbnos.append(dbno)\n \n #if mod(k,2)==0:\n if 0:\n mass[dbno] = mass_hdpe\n hface[dbno] = hface_hdpe\n drag_factor[dbno] = drag_factor_common\n grounding_depth[dbno] = hface_hdpe\n dbnosA.append(dbno)\n else:\n mass[dbno] = mass_wood\n hface[dbno] = hface_wood\n drag_factor[dbno] = drag_factor_common\n grounding_depth[dbno] = hface_wood\n dbnosB.append(dbno)\n \n wface[dbno] = wface_common\n dradius[dbno] = 0.1*length\n \n if 0:\n # add paired particles for square debris:\n dbno1 = dbno + 1000\n db = array([[t0, xgg[k], ygg[k]+length, u0, v0]])\n debris_paths[dbno1] = db\n dbnos.append(dbno1)\n grounding_depth[dbno1] = grounding_depth_common\n drag_factor[dbno1] = drag_factor_common \n mass[dbno1] = mass_common\n wface[dbno] = wface_common\n hface[dbno] = hface_common\n dradius[dbno1] = 0.1*length\n\n dbno2 = dbno + 2000\n db = array([[t0, xgg[k]+length, ygg[k]+length, u0, v0]])\n debris_paths[dbno2] = db\n dbnos.append(dbno2)\n grounding_depth[dbno2] = grounding_depth_common\n drag_factor[dbno2] = drag_factor_common \n mass[dbno2] = mass_common\n wface[dbno] = wface_common\n hface[dbno] = hface_common\n dradius[dbno2] = 0.1*length\n \n dbno3 = dbno + 3000\n db = array([[t0, xgg[k]+length, ygg[k], u0, v0]])\n debris_paths[dbno3] = db\n dbnos.append(dbno3)\n grounding_depth[dbno3] = grounding_depth_common\n drag_factor[dbno3] = drag_factor_common \n mass[dbno3] = mass_common\n wface[dbno] = wface_common\n hface[dbno] = hface_common\n dradius[dbno3] = 0.1*length\n \n # center point:\n dbno4 = dbno + 4000 \n db = array([[t0, xgg[k]+0.5*length, ygg[k]+0.5*length, u0, v0]])\n debris_paths[dbno4] = db\n dbnos.append(dbno4)\n grounding_depth[dbno4] = 0.04\n drag_factor[dbno4] = drag_factor_common \n mass[dbno4] = mass_common\n wface[dbno] = wface_common\n hface[dbno] = hface_common\n dradius[dbno4] = 0.5*length\n\nif 0:\n # add particles for square obstacles:\n xg1 = [x1b1+0.1, x1b1+0.3]\n yg1 = [y1b1+0.1, y1b1+0.3, y1b2+0.1, y1b2+0.3]\n #xg1 = [x1b1+0.1, x1b1+0.3]\n #yg1 = [y1b1+0.1]\n xgg = []\n ygg = []\n for xg in xg1:\n for yg in yg1:\n xgg.append(xg)\n ygg.append(yg)\n \n for k in range(len(xgg)):\n db = array([[t0, xgg[k], ygg[k], u0, v0]])\n dbno = 9000 + k\n debris_paths[dbno] = db\n dbnos.append(dbno)\n dbnosC.append(dbno)\n\n grounding_depth[dbno] = 0.\n drag_factor[dbno] = None\n mass[dbno] = 1.\n wface[dbno] = 0.\n hface[dbno] = 0.\n dradius[dbno] = 0.099\n\nprint('Created %i initial debris particles' % len(dbnos))\n#import pdb; pdb.set_trace()\n\nif 1:\n # add massless tracer particles:\n\n xgg = []\n ygg = []\n for xg in linspace(30.5,31.5,5):\n for yg in linspace(-2,2,17):\n xgg.append(xg)\n ygg.append(yg)\n \n #xgg = [31]\n #ygg = [2] \n \n dbnosT = [] \n for k in range(len(xgg)):\n dbno = 5000+k\n db = array([[t0, xgg[k], ygg[k], u0, v0]])\n debris_paths[dbno] = db\n dbnos.append(dbno)\n dbnosT.append(dbno) # list of tracer particles\n grounding_depth[dbno] = 0.\n drag_factor[dbno] = None\n mass[dbno] = 1.\n wface[dbno] = 0.\n hface[dbno] = 0.\n dradius[dbno] = None\n \n print('Created %i tracer particles' % len(dbnosT))\n\n# Compute debris path for each particle by using all the fgout frames\n# in the list fgframes (first frame should be frameno0 used to set t0 above):\n\nprint('*** dbno, xdb, ydb:')\n\nfor dbno in sort(list(debris_paths.keys())):\n db = debris_paths[dbno]\n print('%6i: %.4f %.4f' % (dbno,db[0,1],db[0,2]))\n\ndebris_paths = P.make_debris_paths_substeps(fgout_grid, fgframes, debris_paths,\n dbnos, drag_factor, grounding_depth, \n mass, wface, hface, dradius, Kspring, tether, nsubsteps)\n \n \ndef make_dbABCD(t, debris_paths, dbnosA):\n # to plot squares\n xdAB = []\n ydAB = []\n \n for k in range(len(dbnosA)):\n dbnoA = dbnosA[k]\n dbnoB = dbnoA + 1000\n dbnoC = dbnoA + 2000\n dbnoD = dbnoA + 3000\n dbnoE = dbnoA + 4000\n dbA = debris_paths[dbnoA]\n dbB = debris_paths[dbnoB]\n dbC = debris_paths[dbnoC]\n dbD = debris_paths[dbnoD]\n dbE = debris_paths[dbnoE]\n try:\n j = where(abs(dbA[:,0]-t) < 1e-6)[0].max()\n except:\n print('Did not find path for dbno=%i at t = %.3f' % (dbno,t))\n j = -1\n if j > -1:\n xA = dbA[j,1]\n yA = dbA[j,2]\n xB = dbB[j,1]\n yB = dbB[j,2]\n xC = dbC[j,1]\n yC = dbC[j,2]\n xD = dbD[j,1]\n yD = dbD[j,2]\n xE = dbE[j,1]\n yE = dbE[j,2]\n xdAB = xdAB + [xA,xB,xC,xD,xA,xE,nan]\n ydAB = ydAB + [yA,yB,yC,yD,yA,yE,nan]\n #import pdb; pdb.set_trace()\n xdAB = array(xdAB)\n ydAB = array(ydAB)\n #print('+++ xdAB = ',xdAB)\n #print('+++ ydAB = ',ydAB)\n return xdAB,ydAB\n\ndef make_dbT(t, debris_paths, dbnosT):\n xdT = []\n ydT = []\n \n for k in range(len(dbnosT)):\n dbnoT = dbnosT[k]\n dbT = debris_paths[dbnoT]\n try:\n j = where(abs(dbT[:,0]-t) < 1e-6)[0].max()\n except:\n print('Did not find path for dbno=%i at t = %.3f' % (dbno,t))\n j = -1\n if j > -1:\n xA = dbT[j,1]\n yA = dbT[j,2]\n xdT.append(xA)\n ydT.append(yA)\n xdT = array(xdT)\n ydT = array(ydT)\n return xdT,ydT \n\n\ndef make_dbDisks(t, debris_paths, dbnosC):\n xdDisks = []\n ydDisks = []\n \n theta = linspace(0, 2*pi, 50)\n \n for k in range(len(dbnosC)):\n dbnoC = dbnosC[k] # center of disk\n dbC = debris_paths[dbnoC]\n try:\n rad = dradius[dbnoC]\n except:\n rad = dradius_common\n try:\n j = where(abs(dbC[:,0]-t) < 1e-6)[0].max()\n except:\n print('Did not find path for dbno=%i at t = %.3f' % (dbno,t))\n j = -1\n if j > -1:\n xC = dbC[j,1]\n yC = dbC[j,2]\n xcirc = xC + rad*cos(theta)\n ycirc = yC + rad*sin(theta)\n xdDisks = xdDisks + list(xcirc) + [nan]\n ydDisks = ydDisks + list(ycirc) + [nan]\n \n xdDisks = array(xdDisks)\n ydDisks = array(ydDisks)\n return xdDisks,ydDisks \n \n \n# First initialize plot with data from initial frame,\n# do this in a way that returns an object for each plot attribute that\n# will need to be changed in subsequent frames.\n# In tis case, the color image of the water depth, plots of particles, and \n# title (which includes the time) will change.\n# The background image, colorbar, etc. do not change.\n\nfgout = fgout0\n\nfig,ax = subplots(figsize=(6,7))\n\nax.set_xlim(xlimits)\nax.set_ylim(ylimits)\n\nif 0:\n # plot obstacles\n ax.plot([y1b1,y1b1,y2b1,y2b1,y1b1], [x1b1,x2b1,x2b1,x1b1,x1b1], 'g')\n ax.plot([y1b2,y1b2,y2b2,y2b2,y1b2], [x1b2,x2b2,x2b2,x1b2,x1b2], 'g')\n\nimqoi = 'Depth'\n\nif imqoi=='Depth':\n # depth\n\n a = 1.\n cmap_depth = mpl.colors.ListedColormap([\n [.6,.6,1,a],[.3,.3,1,a],[0,0,1,a], [1,.8,.8,a],[1,.6,.6,a],\n [1,0,0,a]])\n cmap_depth = mpl.colors.ListedColormap([\n [.8,.8,1,a],[.7,.7,1,a],[.6,.6,1,a],[.5,.5,1,a]])\n # Set color for value exceeding top of range to purple:\n cmap_depth.set_over(color=[0.4,0.4,1,a])\n\n if bgimage:\n # Set color to transparent where s < 1e-3:\n cmap_depth.set_under(color=[1,1,1,0])\n else:\n # Set color to white where s < 1e-3:\n cmap_depth.set_under(color=[1,1,1,a])\n\n #bounds_depth = np.array([0,1,2,3,4,5])\n bounds_depth = np.array([0.001,0.04,0.08,0.12,0.16,0.20,0.24])\n bounds_depth = np.array([0.001,0.01,0.02,0.03,0.05])\n\n norm_depth = colors.BoundaryNorm(bounds_depth, cmap_depth.N)\n \n #eta_water = where(fgout.h>0, fgout.h, nan)\n eta_water = np.ma.masked_where(fgout.h < 1e-3, fgout.h)\n \n im = imshow(flipud(eta_water), extent=fgout_extent,\n #cmap=geoplot.tsunami_colormap)\n cmap=cmap_depth, norm=norm_depth)\n im.set_clim(-5,5)\n \n cb = colorbar(im, extend='max', shrink=0.7)\n cb.set_label('meters')\n #contour(fgout.X, fgout.Y, fgout.B, [0], colors='g', linewidths=0.5)\n\n #ax.set_aspect(1./cos(ylat*pi/180.))\n ticklabel_format(useOffset=False)\n xticks(rotation=20)\n ax.set_xlim(xlimits)\n ax.set_ylim(ylimits)\n \n t = fgout.t\n t_str = timeformat(t)\n title_text = title('%s at t = %s' % (imqoi,t_str))\n \nelif imqoi=='Speed':\n # speed\n s_units = 'm/s'\n if s_units == 'knots':\n s = fgout.s * 1.9438 # convert m/s to knots\n bounds_speed = np.array([1e-3,3,4,6,9,12]) # knots\n else:\n s = fgout.s\n bounds_speed = np.array([1e-3,1.5,2,3,4.5,6]) # m/s\n bounds_speed = np.array([1e-3,0.1,0.2,0.3,0.4,0.5]) # m/s\n bounds_speed = np.array([1e-3,0.2,0.4,0.6,1.,1.5]) # m/s\n\n a = 1.\n cmap_speed = mpl.colors.ListedColormap([\n [.3,.3,1,a],[0,0,1,a], [1,.8,.8,a],[1,.6,.6,a],\n [1,0,0,a]])\n\n # Set color for value exceeding top of range to purple:\n cmap_speed.set_over(color=[1,0,1,a])\n\n if bgimage:\n # Set color to transparent where s < 1e-3:\n cmap_speed.set_under(color=[1,1,1,0])\n else:\n # Set color to white where s < 1e-3:\n cmap_speed.set_under(color=[1,1,1,a])\n\n norm_speed = colors.BoundaryNorm(bounds_speed, cmap_speed.N)\n\n im = imshow(flipud(s), extent=fgout_extent,\n cmap=cmap_speed, norm=norm_speed)\n cb = colorbar(im, extend='max', shrink=0.7)\n cb.set_label(s_units)\n #contour(fgout.X, fgout.Y, fgout.B, [0], colors='g', linewidths=0.5)\n\n #ax.set_aspect(1./cos(ylat*pi/180.))\n ticklabel_format(useOffset=False)\n xticks(rotation=20)\n ax.set_xlim(xlimits)\n ax.set_ylim(ylimits)\n\n t = fgout.t\n t_str = timeformat(t)\n title_text = title('%s at t = %s' % (imqoi,t_str))\n\nelif imqoi=='xVelocity':\n\n u = fgout.u\n bounds_u = np.array([-10,-0.1,0.1,10]) # m/s\n\n a = 1.\n cmap_u = mpl.colors.ListedColormap([[.8,.8,1,a],[1,1,1,a],[.5,.5,1,a]])\n\n # Set color for value exceeding top of range to purple:\n cmap_u.set_over(color=[1,0,1,a])\n\n if bgimage:\n # Set color to transparent where s < 1e-3:\n cmap_u.set_under(color=[1,1,1,0])\n else:\n # Set color to white where s < 1e-3:\n cmap_u.set_under(color=[1,1,1,a])\n\n norm_u = colors.BoundaryNorm(bounds_u, cmap_u.N)\n\n im = imshow(flipud(u), extent=fgout_extent,\n cmap=cmap_u, norm=norm_u)\n cb = colorbar(im, extend='both', shrink=0.7)\n cb.set_label('m/s')\n #contour(fgout.X, fgout.Y, fgout.B, [0], colors='g', linewidths=0.5)\n\n #ax.set_aspect(1./cos(ylat*pi/180.))\n ticklabel_format(useOffset=False)\n xticks(rotation=20)\n ax.set_xlim(xlimits)\n ax.set_ylim(ylimits)\n\n t = fgout.t\n t_str = timeformat(t)\n title_text = title('%s at t = %s' % (imqoi,t_str))\n \n \nxdT,ydT = make_dbT(t, debris_paths, dbnosT)\ndbpoints, = ax.plot(ydT,xdT,'.',color='b',markersize=4)\n#print('+++ dbpoints xdT=', xdT)\n#print('+++ dbpoints ydT=', ydT)\n\nxdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosA)\ndisks1, = ax.plot(xdDisks, ydDisks, color='r', linestyle='-', linewidth=1)\n\nxdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosB)\ndisks2, = ax.plot(xdDisks, ydDisks, color='yellow', linestyle='-', linewidth=2)\n\nxdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosC)\ndisks3, = ax.plot(xdDisks, ydDisks, color='k', linestyle='-', linewidth=1)\n\n#print('+++ disks1 = ',disks1)\n\n# The function update below should have arguments num (for the frame number)\n# plus things listed here in fargs.\n\nfargs = (im,disks1,disks2,disks3,dbpoints,title_text)\n\n# fargs should be initialized above and are the plot Artist objects \n# whose data change from one frame to the next.\n\n\ndef update(num, im, disks1,disks2,disks3, dbpoints, title_text):\n \n fgframe = fgframes[num]\n # note: uses fgframes to specify fgout frames to use\n \n # Read fgout data for this frame:\n #fgout = P.read_fgout_frame(fgno, fgframe, plotdata)\n fgout = fgout_grid.read_frame(fgframe)\n \n # Reset the plot objects that need to change from previous frame:\n\n # title:\n t = fgout.t \n t_str = timeformat(t)\n title_text.set_text('%s at t = %s' % (imqoi,t_str))\n \n # color image:\n if imqoi == 'Depth':\n eta_water = np.ma.masked_where(fgout.h < 1e-3, fgout.h)\n im.set_data(flipud(eta_water))\n else:\n im.set_data(flipud(fgout.s))\n\n # particle locations:\n \n xdAB,ydAB = make_dbT(t, debris_paths, dbnosA)\n xdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosA)\n disks1.set_data(ydDisks, xdDisks)\n\n if len(dbnosB) > 0:\n xdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosB)\n disks2.set_data(ydDisks, xdDisks)\n if len(dbnosC) > 0:\n xdDisks,ydDisks = make_dbDisks(t, debris_paths, dbnosC)\n disks3.set_data(ydDisks, xdDisks)\n \n xdT,ydT = make_dbT(t, debris_paths, dbnosT)\n dbpoints.set_data(ydT,xdT)\n\n # must now return all the objects listed in fargs:\n return im,disks1,disks2,disks3,dbpoints,title_text\n\nif 1:\n print('Making anim...')\n anim = animation.FuncAnimation(fig, update,\n frames=len(fgframes), \n fargs=fargs,\n interval=200, blit=True)\n\n fname_mp4 = 'debris_disks.mp4'\n fps = 5\n print('Making mp4...')\n animation_tools.make_mp4(anim, fname_mp4, fps)\n","sub_path":"nthmp_debris_2023/BM2/case2/debris_disks_fgout_animate.py","file_name":"debris_disks_fgout_animate.py","file_ext":"py","file_size_in_byte":18469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"236861891","text":"\n\n@tf_export('tpu.experimental.initialize_tpu_system')\ndef initialize_tpu_system(cluster_resolver=None):\n 'Initialize the TPU devices.\\n\\n Args:\\n cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver,\\n which provides information about the TPU cluster.\\n Returns:\\n The tf.tpu.Topology object for the topology of the TPU cluster.\\n\\n Raises:\\n RuntimeError: If no TPU devices found for eager execution.\\n '\n job = None\n if (cluster_resolver is None):\n if context.executing_eagerly():\n curr_device = device.DeviceSpec.from_string(context.context().device_name)\n if (curr_device.job is not None):\n job = '{}/replica:0/task:0'.format(curr_device.job)\n cluster_resolver = TPUClusterResolver('')\n assert isinstance(cluster_resolver, TPUClusterResolver)\n tpu_name = compat.as_text(cluster_resolver._tpu)\n if (tpu_name in _INITIALIZED_TPU_SYSTEMS):\n logging.warning('TPU system %s has already been initialized. Reinitializing the TPU can cause previously created variables on TPU to be lost.')\n logging.info('Initializing the TPU system: %s', tpu_name)\n if context.executing_eagerly():\n if (tpu_name not in _LOCAL_MASTERS):\n job = '{}/replica:0/task:0'.format(cluster_resolver.get_job_name())\n\n @function.defun\n def _tpu_init_fn():\n return tpu.initialize_system(job=job)\n with ops.device(tpu._tpu_system_device_name(job)):\n output = _tpu_init_fn()\n logging.info('Clearing out eager caches')\n context.context()._clear_caches()\n serialized_topology = output.numpy()\n context.context().mirroring_policy = context.MIRRORING_ALL\n else:\n master = cluster_resolver.master()\n cluster_spec = cluster_resolver.cluster_spec()\n session_config = config_pb2.ConfigProto(allow_soft_placement=True)\n if cluster_spec:\n session_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def())\n with ops.Graph().as_default():\n with session_lib.Session(config=session_config, target=master) as sess:\n serialized_topology = sess.run(tpu.initialize_system())\n logging.info('Finished initializing TPU system.')\n tpu_topology = topology.Topology(serialized=serialized_topology)\n _INITIALIZED_TPU_SYSTEMS[tpu_name] = tpu_topology\n return tpu_topology\n","sub_path":"Data Set/bug-fixing-1/b8f2fcdf40a5202b18f90979682223183a964d15--bug.py","file_name":"b8f2fcdf40a5202b18f90979682223183a964d15--bug.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408477791","text":"import codecs\r\nprint(\"Добрый день!\\nПодождите, идет выполнение первой части программы...\")\r\nanswerline = \"\"\r\nwith open (\"textfortest.txt\", 'r', encoding=\"utf-8\") as file:\r\n lines = file.readlines()\r\n #1\r\n for line in lines:\r\n if line.find(\"союз\") != -1:\r\n answerline += line\r\n print(answerline)\r\n print(\"================================================================================\")\r\n\r\n #2\r\n print(\"Подождите, идет выполнение второй части программы...\")\r\n answerline = \"\"\r\n ipm = 0\r\n for line in lines:\r\n if line.find(\"сущ\") != -1 and line.find(\"жен\") != -1 and line.find(\"ед\") != -1:\r\n answerline += line.split(\" \")[0]\r\n answerline += \", \"\r\n ipm += float(line.split(\" | \")[-1])\r\n print(\"Вот список всех существительных женского рода единственного числа:\\n\", answerline[:-2], \"\\n\\nIPM равняется\", ipm)\r\n print(\"================================================================================\")\r\n\r\n #3\r\n print(\"Добро пожаловать в третью часть программы!\")\r\n lever = 0\r\n while 2+2==4: \r\n word2find = input(\"Введите слово, которое вам хотелось бы найти:\")\r\n if word2find == \"\":\r\n break\r\n\r\n for line in lines:\r\n if word2find == line.split(\" | \")[0]:\r\n print(\"Вот морфологическая информация о данном слове:\", line.split(\" | \")[1], \"\\nIPM слова <\", word2find, \"> равно\", line.split(\" | \")[-1], \"\\n\")\r\n lever = 1\r\n break\r\n if lever == 0:\r\n print(\"Извините, такого слова в данном словаре найти не удалось, попробуйте найти что-то другое\\n\")\r\n lever = 0\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"19804808","text":"import sys\nimport time\nimport os\n\n\ndef test_positivite(y):\n if y != 0:\n return 1\n else:\n return 0\n\n\ndef listeur_grille(Grille):\n p = 0\n liste = []\n for i in range(0, 9):\n for j in range(0, 9):\n if Grille[i][j] == 0:\n liste.append((i, j))\n p = p + 1\n return liste\n\n\ndef afficher_grille(Grille):\n for p in Grille:\n print(*p, sep=' ')\n return 0\n\n\ndefault = [1, 2, 3, 4, 5, 6, 7, 8, 9] # colonne ou ligne par défaut\n\n\ndef tester_colonne(i, j, Grille):\n col = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n for p in list(range(0, i)) + list(range(i + 1, 8)):\n if Grille[p][j] != 0:\n # print('colonne={}'.format(col))\n # print('Grille[i][j]={}'.format(Grille[i][j]))\n # print('i={} j={}'.format(i, j))\n sys.stdout.flush()\n col.remove(Grille[p][j])\n return col\n\n\ndef tester_ligne(i, j, Grille):\n lin = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n for p in list(range(0, j)) + list(range(j + 1, 8)):\n if Grille[i][p] != 0:\n # print('ligne={}'.format(lin))\n # print('Grille[i][j]={}'.format(Grille[i][j]))\n # print('i={} j={}'.format(i, j))\n lin.remove(Grille[i][p])\n return lin\n\n\ndef tester_carre(i, j, Grille):\n car = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n range_i = []\n range_j = []\n\n if (i % 3 == 0):\n range_i = [i, i + 1, i + 2]\n if (i % 3 == 1):\n range_i = [i - 1, i, i + 1]\n if (i % 3 == 2):\n range_i = [i - 2, i - 1, i]\n\n if (j % 3 == 0):\n range_j = [j, j + 1, j + 2]\n if (j % 3 == 1):\n range_j = [j - 1, j, j + 1]\n if (j % 3 == 2):\n range_j = [j - 2, j - 1, j]\n\n # print('range_i={}'.format(range_i))\n # print('range_j={}'.format(range_j))\n\n for m in range_i:\n for p in [x for x in range_j if (x != j or m != i)]:\n if Grille[m][p] != 0:\n # print(\"Grille[m][p] = {}\".format(Grille[m][p]))\n # print (car)\n car.remove(Grille[m][p])\n\n return car\n\n\ndef list_solution(i, j, Grille):\n col = tester_colonne(i, j, Grille)\n lin = tester_ligne(i, j, Grille)\n car = tester_carre(i, j, Grille)\n # print('col = {} lin = {} car = {}'.format(col, lin, car))\n col = set(col)\n lin = set(lin)\n car = set(car)\n sol = col.intersection(lin, car)\n # print('list = {}'.format(sol))\n # sys.stdout.flush()\n sol = list(sol)\n # print('list = {}'.format(sol))\n # sys.stdout.flush()\n sol.sort\n return sol\n\n\nGrille = []\nGrille.append([0, 1, 0, 0, 2, 5, 0, 9, 8])\nGrille.append([0, 5, 0, 0, 0, 9, 0, 2, 6])\nGrille.append([0, 0, 0, 0, 8, 0, 5, 7, 0])\nGrille.append([5, 3, 0, 0, 6, 0, 2, 1, 9])\nGrille.append([0, 0, 0, 0, 0, 0, 0, 0, 0])\nGrille.append([7, 6, 2, 0, 9, 0, 0, 3, 4])\nGrille.append([0, 4, 5, 0, 3, 0, 0, 0, 0])\nGrille.append([1, 7, 0, 4, 0, 0, 0, 6, 0])\nGrille.append([2, 8, 0, 9, 1, 0, 0, 4, 0])\n\n# afficher_grille(Grille)\nliste_cases = listeur_grille(Grille)\n# print(liste_cases)\npossibilites = [[default for i in range(9)] for j in range(9)]\ncompteur = [0 for i in range(len(liste_cases))]\ntaille = len(liste_cases)\nk = 0\nt = 0\ncondition = 0\n\nfor i in range(9):\n for j in range(9):\n possibilites[i][j] = [list_solution(i, j, Grille)]\n\n\n# Début de l'algorithme============================================================\nwhile condition != 81:\n # print('(i,j)={}'.format(liste_cases[k]))\n i = liste_cases[k][0]\n j = liste_cases[k][1]\n possibilites[i][j] = list_solution(i, j, Grille)\n if len(possibilites[i][j]) > 0 + compteur[k] <= len(possibilites[i][j]):\n # print(\"k = {} , compteur[k] = {}\".format(k, compteur[k]))\n # print(\"k = {}/{} , case {}\".format(k, taille, liste_cases[k]))\n # print('possibilités={}'.format(possibilites[i][j]))\n # print(compteur)\n Grille[i][j] = possibilites[i][j][compteur[k]]\n for s in range(k + 1, taille):\n compteur[s] = 0\n # print('possibilité retenue={}'.format(possibilites[i][j][compteur[k]]))\n compteur[k] = compteur[k] + 1\n k = k + 1\n afficher_grille(Grille)\n os.system('clear')\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\")\n\n # time.sleep(1)\n else:\n # print(\"/!\\ incohérence\")\n # print('(i,j)={}'.format(liste_cases[k - 1]))\n i = liste_cases[k - 1][0]\n j = liste_cases[k - 1][1]\n Grille[i][j] = 0\n # print('i={} j={}'.format(i, j))\n # print(liste_cases[k - 1])\n # possibilites[i][j].pop(0)\n # print('possibilités dans le else={}'.format(possibilites[i][j]))\n # print(possibilites)\n k = k - 1\n\n t = t + 1\n s = [test_positivite(y) for x in Grille for y in x]\n condition = sum(s)\n # print(\"nombre de cases remplies = {}/81\".format(condition))\n\nprint('programme terminé correctment. Résultat : ')\nafficher_grille(Grille)\n","sub_path":"intro2.py","file_name":"intro2.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115993086","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 19 21:54:53 2019\n\n@author: sinjinibose\n\"\"\"\n\nimport email\nimport pandas as pd\nfrom datetime import datetime\nfrom nltk.tokenize import word_tokenize\n\n\ndata = pd.read_csv(\"..//emails.csv\")\ndata = pd.DataFrame(data)\nli_attributes = ['Message-ID','Subject','To','From','Date','X-cc','X-bcc','X-Folder']\nactual_data = pd.DataFrame()\nactual_data['message_body'] = data['message'].apply(lambda x: email.message_from_string(x).get_payload())##getting the email bodies and storing \n\nfor i in li_attributes:\n actual_data[i] = data['message'].apply(lambda x: email.message_from_string(x).get(i))## getting the rest pf the attributes and storing them in the final dataset\ncopy = pd.DataFrame() \n#creating a copy of the original dataset \ncopy = actual_data.copy()\n##removing \\n and \\t from the message body\ntemp = actual_data['message_body'].apply(lambda x : x.replace(\"\\n\",\"\"))\nactual_data['message_body'] = temp.apply(lambda x : x.replace(\"\\t\",\"\"))\n\n##formatting the dates(don't think we need to keep the time or timezone and the days)\nonly_date_and_time = (actual_data['Date']).apply(lambda x : x.split(\",\")[1].split(\"-\")[0].strip())\nformatted = only_date_and_time.apply(lambda x : datetime.strptime(x,\"%d %b %Y %H:%M:%S\"))\nactual_data['Date'] = formatted.apply(lambda x : x.strftime(\"%m/%d/%Y\"))\nactual_data = actual_data.dropna()\nactual_data = actual_data.reset_index(drop=True)\n##formatting the folder names into just inbox, sent items, etc , like removing the employee names\nactual_data['X-Folder'] = actual_data['X-Folder'].apply(lambda x : x.split(\"\\\\\")[-1])\n\n\n#filtering data on duplicate messages\nduplicate_data = actual_data[actual_data['message_body'].duplicated()==True]##257263 duplicate mails\n\n#getting the forwarded mails (duplicate mails with FW: tag in subject, because they will be of importance)\nForwarded_mails = duplicate_data[duplicate_data['Subject'].apply(lambda x : x.__contains__(\"FW:\")) == True] ## 11250 duplicate mails that have been forwarded\nindices = Forwarded_mails.index.tolist()##indexes of the forwarded mails\n\n##removing the subset of forwarded mails from the duplicate mails (these are the actual rows to be dropped)\ndata_to_be_dropped = duplicate_data.drop(labels = indices).reset_index(drop=True) ##257263-11250 = 246013\nindices_ = data_to_be_dropped.index.tolist()\n\n\nrevised_data = pd.DataFrame()\n##dropping the actual duplicates from the original data \nrevised_data = actual_data.drop(labels=indices_).reset_index(drop=True)\n\nunique_folder_names = revised_data['X-Folder'].unique() ## 1145 unique folders\n\n#filtering the data based on sender and receiver mappings\n\n\nunique_senders = revised_data['From'].unique().tolist()#12816\nunique_receivers = revised_data[\"To\"].unique().tolist()#32575\noutside_receivers = [i for i in unique_receivers if i.__contains__(\"@enron.com\") == False] ##6163 0utsiders\noutside_senders = [i for i in unique_senders if i.__contains__(\"@enron.com\") == False] ## 8335 Outsiders\nenron_receivers = [i for i in unique_receivers if i not in outside_receivers]#26412\nenron_senders=[i for i in unique_senders if i not in outside_senders]#4481\n\n##checking if both sender and receiver is an outsider, so that we can eliminate such cases\n##in cases where there is a group of receivers, even if there's one receiver from enron,\n##then we will have to consider such cases.\n\nrows_to_be_dropped = []\nfor i in outside_senders:\n temp_list = revised_data[revised_data['From'] ==i]['To'].apply(lambda x : x.__contains__('@enron.com')).tolist()\n if(temp_list.count(True) == 0):\n rows_to_be_dropped.append(revised_data[revised_data['From']==i].index.tolist())\n \n##dropping the duplicate rows from the revised data\nrows_to_be_dropped_ = [i for j in rows_to_be_dropped for i in j] \n\n##final dataset on which we will begin our analysis \nrevised_data = revised_data.drop(labels=rows_to_be_dropped_)\nrevised_data = revised_data.reset_index(drop = True)\n\n##word_tokens generated and being stored in the column named tokens\nrevised_data['tokens']=revised_data['message_body'].apply(lambda x : word_tokenize(x))\n\npd.to_csv('..//emails_with_tokens.csv')","sub_path":"Enron_mail_analytics(Data_Preparation).py","file_name":"Enron_mail_analytics(Data_Preparation).py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434384075","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Checks if a str is a word(unique),\n# or an expression (more than one word).\nis_expression = lambda s: ' ' in s.strip()\n\n\n# Lambda function which tranforms a ConfigParser items\n# list of tuples object into a dictionnary,\n# doesn't use dict comprehension in order to keep 2.6\n# backward compatibility.\ndef items_to_dict(items):\n res = {}\n\n for k, v in items:\n res[k] = v\n return res\n\n# Iterates through a sequence of size `clen`\nchunks = lambda seq, clen: [seq[i:(i + clen)] for i in xrange(0, len(seq), clen)]\n\n# Decodes a list content from a given charset\nldecode = lambda list, charset: [string.decode(charset) for string in charset]\n\n# Encodes a list content from a given charset\nlencode = lambda list, charset: [string.encode(charset) for string in charset]\n\n# Checks if a sequence is ascendently sorted\nasc_sorted = lambda seq: all(seq[i] <= seq[i + 1] for i in xrange(len(seq) - 1))\n\n# idem descending\ndesc_sorted = lambda seq: all(seq[i] >= seq[i + 1] for i in xrange(len(seq) - 1))\n\n# Convert bytes to Mo\nfrom_bytes_to_mo = lambda bytes: bytes / 1048576\n\n#Convert Mo to bytes\nfrom_mo_to_bytes = lambda mo: mo * 1048576\n\n# Convert seconds to milliseconds\nsec_to_ms = lambda s: s * 1000\n","sub_path":"elevator/utils/snippets.py","file_name":"snippets.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54311045","text":"import re\nimport requests\nimport textwrap\nfrom bs4 import BeautifulSoup\n\ndef handle_url_ricemedia(url):\n \"\"\"\n URL handler function\n @url: string, url of article\n @output: dictionary, with \"title\" and \"body\"\n \"\"\"\n html = requests.get(url).text\n soup = BeautifulSoup(html, \"html.parser\")\n\n # https://stackoverflow.com/a/24618186\n # We only want article text, not inline scripts or inline jss\n for script in soup([\"script\", \"style\"]):\n script.extract()\n\n # Plant markers to denote the start and end of the article\n start_marker = \"EXTRACT_START\"\n end_marker = \"EXTRACT_END\"\n soup.find(name=\"div\", class_=\"post-date\").insert(0, start_marker)\n soup.find(name=\"span\", class_=\"author-name\").append(end_marker)\n\n unwrapped_body = re.search(f\"{start_marker}(.+?){end_marker}\", soup.text).group(1)\n article_body = \"\\n\".join(textwrap.wrap(unwrapped_body, 80))\n article_body = article_body.replace(\"\\n\", \"\\n\\n\") # Markdown requires 2 \\n to create a new paragraph\n article_title = soup.find(name=\"h2\", class_=\"post-title\").text\n\n return { \"title\" : article_title , \"body\" : article_body.replace(\"\\xa0\", \" \") }\n\n### Test Portion | Run HandleURLRiceMedia.py to test ###\nif __name__ == \"__main__\":\n url = 'http://ricemedia.co/culture-life-the-politics-of-the-50-ang-bao/'\n print(handle_url_ricemedia(url)) ","sub_path":"URLHandlers/HandleURLRiceMedia.py","file_name":"HandleURLRiceMedia.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631084892","text":"# hello.py\n\n\n\ndef add(m,n):\n s = m\n s += n\n return s\n\n\ndef max(m,n):\n if m > n :\n return m\n else :\n return n\n\n\nprint('hello python!')\n\na = 1\nb = 1\nif a>0:\n print('big');\n print('small');\n print('aaaa');\n\nfor i in range(1,10):\n print('-->',i)\n\nprint('end')\n\nprint(add(5,7))\nprint(max(5,8))","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599334941","text":"\n\ndef FlipTree(fw,tree,idx):\n \"\"\"\n 0. input idx: 문제의 시작\n 0. tree[idx] != 'x'이면 문제 종료\n 0. idx가 tree 길이 넘는지 체크 필요없음\n 1. 첫번째 부분 문제의 시작 인덱스를 찾는다.\n 2. 시작 인덱스 이후의 문자열을 재귀로 돌린다\n 3. 해당 문제의 끝 인덱스를 리턴 받는다\n 4. 다음 인덱스에 대해서 재귀를 돌린다\n 5. 4번 반복하면 문제가 끝나있다\n \"\"\"\n \"\"\"\n * Flip Tree 의 시간 복잡도는?\n \"\"\"\n\n if tree[idx] != 'x':\n #fw.write('{}'.format(tree[idx]))\n return (idx + 1),tree[idx]\n #fw.write('{}'.format(tree[idx]))\n\n fliplist = {}\n idx = idx + 1\n for i in range(0,4):\n idx,fliped = FlipTree(fw,tree,idx)\n fliplist[i] = fliped\n\n fliped = fliplist[2] + fliplist[3] + fliplist[0] + fliplist[1]\n fliped = 'x' + fliped\n return idx,fliped\n\n\n\n\nf = open('.\\Divide_and_Conquer\\QUADTREE.txt', 'r')\nfw = open('.\\Divide_and_Conquer\\QUADTREE_answer.txt', 'w')\n\nk = 0\nn = int(f.readline())\nwhile k < n:\n tree = f.readline().split()\n tree = tree[0]\n idx,fliped = FlipTree(fw,tree,0)\n fw.write(fliped)\n fw.write('\\n')\n k = k + 1\nfw.close()\nf.close()\n","sub_path":"divde_conquer/QUADTREE.py","file_name":"QUADTREE.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"498478166","text":"from nose.tools import assert_equals\nfrom nose import with_setup\nimport rowingdata\nimport datetime\nimport numpy as np\nimport pandas as pd\nfrom nose_parameterized import parameterized\nimport unittest\n\nclass TestBasicRowingData:\n row = rowingdata.rowingdata(csvfile='testdata/testdata.csv')\n\n def test_filetype(self):\n assert_equals(rowingdata.get_file_type('testdata/testdata.csv'),'csv')\n \n def test_basic_rowingdata(self):\n assert_equals(self.row.rowtype,'Indoor Rower')\n assert_equals(self.row.dragfactor,104.42931937172774)\n assert_equals(self.row.number_of_rows,191)\n assert_equals(self.row.rowdatetime,datetime.datetime(2016,5,20,13,41,26,962390))\n totaldist = self.row.df['cum_dist'].max()\n totaltime = self.row.df['TimeStamp (sec)'].max()-self.row.df['TimeStamp (sec)'].min()\n totaltime = totaltime+self.row.df.ix[0,' ElapsedTime (sec)']\n assert_equals(totaltime, 540.04236011505122)\n assert_equals(totaldist, 2000)\n\n def test_intervals_rowingdata(self):\n ts,ds,st = self.row.intervalstats_values()\n assert_equals(ts,[139.7,0.0,130.1,0.0,134.4,0.0,132.8,0.0])\n assert_equals(ds,[510,0,499,0,498,0,491,0])\n assert_equals(st,[4,3,4,3,4,3,4,3])\n sum = int(10*np.array(ts).sum())/10.\n assert_equals(sum,537.0)\n self.row.updateinterval_string('4x500m')\n assert_equals(len(self.row.df[' lapIdx'].unique()),4)\n ts,ds,st = self.row.intervalstats_values()\n assert_equals(ts,[137.0,0.0,130.2,0.0,134.8,0.0,135.1,0.0])\n assert_equals(ds,[500,0,500,0,500,0,500,0])\n assert_equals(st,[5,3,5,3,5,3,5,3])\n sum = int(10*np.array(ts).sum())/10.\n assert_equals(sum,537.0)\n \n \nclass TestErgData:\n def testergdata(self):\n csvfile = 'testdata/ergdata_example.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'ergdata')\n r = rowingdata.ErgDataParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,180)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,1992)\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,520)\n\nclass TestpainsledDesktopParser:\n def testpainsleddesktop(self):\n csvfile = 'testdata/painsled_desktop_example.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'painsleddesktop')\n r = rowingdata.painsledDesktopParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,638)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,7097)\n assert_equals(row.rowdatetime,datetime.datetime(2016,3,29,16,41,27))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,1802)\n\nclass TestBoatCoachParser:\n def testboatcoach(self):\n csvfile = 'testdata/boatcoach.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'boatcoach')\n r = rowingdata.BoatCoachParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,132)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,499)\n assert_equals(row.rowdatetime,datetime.datetime(2016,11,28,7,37,2))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,118)\n \nclass TestspeedcoachParser:\n def testspeedcoach(self):\n csvfile = 'testdata/speedcoachexample.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'speedcoach')\n r = rowingdata.speedcoachParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,476)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,9520)\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,3176.5)\n \nclass TestErgStickParser:\n def testergstick(self):\n csvfile = 'testdata/ergstick.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'ergstick')\n r = rowingdata.ErgStickParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,2400)\n totaldist = row.df['cum_dist'].max()\n assert_equals(int(totaldist),4959)\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(int(totaltime),1201)\n \nclass TestMysteryParser:\n def testmystery(self):\n csvfile = 'testdata/mystery.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'mystery')\n r = rowingdata.MysteryParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,4550)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,7478)\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(int(totaltime),2325)\n \nclass TestRowProParser:\n def testrowpro(self):\n csvfile = 'testdata/RP_testdata.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'rp')\n r = rowingdata.RowProParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,988)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,10000)\n assert_equals(row.rowdatetime,datetime.datetime(2016,3,15,18,49,48))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(int(10*totaltime),22660)\n\nclass TestRowProParserIntervals:\n def testrowprointervals(self):\n csvfile = 'testdata/RP_interval.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'rp')\n r = rowingdata.RowProParser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,1674)\n totaldist = row.df['cum_dist'].max()\n assert_equals(int(totaldist),19026)\n assert_equals(row.rowdatetime,datetime.datetime(2016,1,12,18,23,10))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,4800)\n \nclass TestSpeedCoach2Parser:\n def testspeedcoach2(self):\n csvfile = 'testdata/SpeedCoach2example.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'speedcoach2')\n r = rowingdata.SpeedCoach2Parser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,97)\n totaldist = row.df['cum_dist'].max()\n assert_equals(int(10*totaldist),7516)\n assert_equals(row.rowdatetime,datetime.datetime(2016,7,28,11,35,1,500000))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(totaltime,170)\n \nclass TestSpeedCoach2_v127Parser:\n def testspeedcoach2v127(self):\n csvfile = 'testdata/SpeedCoach2Linkv1.27.csv'\n assert_equals(rowingdata.get_file_type(csvfile),'speedcoach2')\n r = rowingdata.SpeedCoach2Parser(csvfile=csvfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,1408)\n totaldist = row.df['cum_dist'].max()\n assert_equals(totaldist,14344.5)\n assert_equals(row.rowdatetime,datetime.datetime(2016,11,5,10,2,3,200000))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(int(10*totaltime),45018)\n \nclass TestFITParser:\n def testfit(self):\n fitfile = 'testdata/3x250m.fit'\n assert_equals(rowingdata.get_file_type(fitfile),'fit')\n r = rowingdata.FITParser(fitfile)\n row = rowingdata.rowingdata(df=r.df)\n assert_equals(row.number_of_rows,94)\n totaldist = row.df['cum_dist'].max()\n assert_equals(int(totaldist),750)\n assert_equals(row.rowdatetime,datetime.datetime(2016,7,28,9,35,29))\n totaltime = row.df['TimeStamp (sec)'].max()-row.df['TimeStamp (sec)'].min()\n assert_equals(int(10*totaltime),4870)\n\nclass TestSequence(unittest.TestCase):\n list = pd.read_csv('testdata/testdatasummary.csv')\n lijst = []\n for i in list.index:\n filename = list.ix[i,'filename']\n expected = list.ix[i,1:]\n lijst.append(\n (filename,filename,expected)\n )\n\n @parameterized.expand(lijst)\n \n def test_check(self, name, filename, expected):\n f2 = 'testdata/'+filename\n res = rowingdata.checkdatafiles.checkfile(f2)\n if res != 0:\n for key,value in res.iteritems():\n if expected[key] != 0:\n assert_equals(value,expected[key]) \n\n\n \n","sub_path":"tests/test_rowingdata.py","file_name":"test_rowingdata.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80795193","text":"from goatools import obo_parser\nfrom goatools.go_enrichment import GOEnrichmentStudy\nfrom goatools.goea.go_enrichment_ns import GOEnrichmentStudyNS\nfrom Bio.UniProt.GOA import gafiterator\nimport gzip\nimport pandas as pd\nfrom goatools.godag_plot import plot_gos, plot_results, plot_goid2goobj\nimport sys\nimport statistics\nfrom scipy.stats import iqr\n\nFILE_IN = sys.argv[1]\nFILE_OUT = sys.argv[2]\nPVAL_CUT = float(sys.argv[3])\n\n#initialze U_ID -> Gene\n# df = pd.read_csv('../../Data/uniprot_mapping.csv')\n# umap = df.groupby('Gene')['Uniprot_ID'].apply(list).to_dict()\n\ngo = obo_parser.GODag('../../Data/GO/go-basic.obo')\n\nfilename = '../../Data/Yeast/sgd.gaf.gz'\nwith gzip.open(filename, 'rt') as fp:\n d = {}\n\n for annotation in gafiterator(fp):\n Yeast_ID = annotation.pop('Synonym')[0]\n d[Yeast_ID] = annotation\n\npopulation = d.keys()\n#print(d.keys())\n\nassociation = {}\nfor elem in d:\n if elem not in association:\n association[elem] = set()\n association[elem].add(str(d[elem]['GO_ID']))\n\nmethods = ['fdr']\n\ng = GOEnrichmentStudy(population, association, go, methods=methods)\n\n\nresults = []\nresults_sig = []\n#run on each cluster\nfile = open(FILE_IN)\n\nfor line in file.readlines():\n if line.__contains__('Singleton'):\n break\n\n if line.__contains__('Cluster'):\n continue\n\n genes = line.split(', ')\n #genes.remove('\\n')\n\n #get g_res for each cluster\n map = genes#[umap[gene][0] for gene in genes if gene in umap.keys()]\n #print(map)\n h = dict.fromkeys(map)\n study = h.keys()\n\n g_res = g.run_study(study)\n g_res_sig = [r for r in g_res if r.p_fdr < PVAL_CUT]\n\n results.append(g_res)\n results_sig.append(g_res_sig)\n\n# file = open('pvals.txt', 'a')\n# pvals = [g.p_fdr for r in results_sig for g in r]\n# file.write(FILE_IN+': '+str(statistics.median(pvals))+' '+str(iqr(pvals)))\n\nfile = open(FILE_OUT, 'w')\nfor result, i in zip(results_sig, range(1, len(results_sig)+1)):\n file.write('Cluster '+str(i)+' - \\n')\n for obj in result:\n file.write(str(obj))\n file.write('\\n')\n file.write('\\n')\n#\n# counter = 0\n# for result in results_sig:\n# counter+=1\n# plot_results(\"cluster\"+str(counter)+\"_0.1_{NS}.png\", result)\n","sub_path":"Code/Goatools/yeast.py","file_name":"yeast.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79161470","text":"import pyglet\n\nwindow=pyglet.window.Window()\nlabel=pyglet.text.Label(\"Hello Pyglet Application\", font_name='Times New Roman',\n font_size=40,\n x=window.width/2,\n y=window.height/2,\n anchor_x='center',\n anchor_y='center')\n\n@window.event\ndef on_key_press(symbol, modifiers):\n print(\"A Key Was pressed\")\n\n @window.event\n def on_draw():\n window.clear()\n label.draw()\n\n# @window.event\n# def on_draw():\n# window.clear()\n\npyglet.app.run()","sub_path":"pythonEvent.py","file_name":"pythonEvent.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112797023","text":"from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import Http404, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils import timezone\n\nfrom comments.forms import CommentForm\nfrom comments.models import Comment\nfrom .forms import PostForm\nfrom .models import Post\n# from .utils import get_read_time\n\n\n# Create your views here.\n\n\ndef home(request, template_name='index.html'):\n\tactive_post_list = Post.objects.active()\n\n\n\tlatest_post = active_post_list.order_by(\"-publish_date\").first()\n\trecent_posts = active_post_list.order_by(\"-publish_date\")[:7]\n\tpost_list = active_post_list.order_by(\"-publish_date\")[1:3]\n\t\n\treturn render(request, template_name, {'post_list':post_list, 'latest_post':latest_post, 'recent_posts':recent_posts})\n\ndef view_more(request, template_name='view-more.html'):\n\n\tactive_post_list = Post.objects.active()\n\n\tlatest_post = active_post_list.order_by(\"-publish_date\").first()\n\trecent_posts = active_post_list.order_by(\"-publish_date\")[:7]\n\n\tpost_list_obj = active_post_list.order_by(\"-publish_date\")[3:]\n\n\n\n\tpage = request.GET.get('page', 1)\n\n\tpaginator = Paginator(active_post_list, 5)\n\n\ttry:\n\t\tpost_list = paginator.page(page)\n\texcept PageNotAnInteger:\n\t\tpost_list = paginator.page(1)\n\texcept EmptyPage:\n\t\tpost_list = paginator.page(paginator.num_pages)\n\t\n\treturn render(request, template_name, {'post_list':post_list, 'latest_post':latest_post, 'recent_posts':recent_posts})\n\ndef about(request, template_name='about.html'):\n\n\n\n\treturn render(request, template_name, {})\n\n\ndef archives(request, template_name='archives.html'):\n\t\n\tqueryset_list = Post.objects.active()\n\n\n\tpage = request.GET.get('page', 1)\n\n\tpaginator = Paginator(queryset_list, 6)\n\n\ttry:\n\t\tpost_list = paginator.page(page)\n\texcept PageNotAnInteger:\n\t\tpost_list = paginator.page(1)\n\texcept EmptyPage:\n\t\tpost_list = paginator.page(paginator.num_pages)\n\n\t\n\treturn render(request, template_name, {'post_list':post_list})\n\ndef post_create(request, template_name=\"post-form.html\"):\n\n\tif not request.user.is_authenticated() or not request.user.is_superuser:\n\t\traise Http404\n\n\tform = PostForm(request.POST or None, request.FILES or None)\n\tcreate_title = \"Create a New Post\"\n\n\tif form.is_valid():\n\t\tpost = form.save(commit=False)\n\t\tpost.user = request.user\n\t\tpost.save()\n\t\treturn HttpResponseRedirect(post.get_absolute_url())\n\n\t\n\treturn render(request, template_name, {'form':form, 'title':create_title})\n\ndef post_edit(request, template_name=\"post-form.html\", slug=None):\t\n\n\tif not request.user.is_authenticated() or not request.user.is_superuser:\n\t\traise Http404\n\n\tpost_obj = get_object_or_404(Post, slug=slug)\n\tform = PostForm(request.POST or None, request.FILES or None, instance=post_obj)\n\tedit_title = \"Edit Post\"\n\n\tif form.is_valid():\n\t\tpost = form.save(commit=False)\n\t\tpost.save()\n\t\treturn HttpResponseRedirect(post.get_absolute_url())\n\n\treturn render(request, template_name, {'form':form, 'title':edit_title})\n\n\ndef post_details(request, template_name=\"post-details.html\", slug=None):\t\n\tpost_obj = get_object_or_404(Post, slug=slug)\n\n\n\tif post_obj.publish_date > timezone.now().date() or post_obj.draft:\n\t\tif not request.user.is_authenticated():\n\t\t\traise Http404\n\n\t# initial_data = {\n\n\t# 'post_obj':post_obj.id,\n\n\t# }\n\n\tcomment_form = CommentForm(request.POST or None)\n\n\tif comment_form.is_valid():\n\t\tcontent = comment_form.cleaned_data.get('content')\n\t\tparent_obj = None\n\n\t\ttry:\n\t\t\tparent_id = int(request.POST.get('parent_id'))\n\t\texcept:\n\t\t\tparent_id = None\n\t\t\n\t\tif parent_id:\n\t\t\tparent_qs = Comment.objects.filter(id=parent_id)\n\t\t\t\n\t\t\tif parent_qs.exists():\n\t\t\t\tparent_obj = parent_qs.first()\n\n\t\tnew_comment, created = Comment.objects.get_or_create(\n\t\t\t\tuser = request.user,\n\t\t\t\tpost = post_obj,\n\t\t\t\tcontent = content,\n\t\t\t\tparent = parent_obj,\n\t\t\t)\n\t\treturn HttpResponseRedirect(new_comment.post.get_absolute_url()) \n\n\tcomments = post_obj.comments\n\n\tif post_obj.is_liked(request):\n\n\t\tcss_class = 'liked'\n\telse:\n\t\tcss_class = ''\n\n\t# read_time = get_read_time(post_obj.get_markdown())\n\treturn render(request, template_name, {'post':post_obj, 'css_class':css_class, 'comments':comments, 'comment_form':comment_form,})\n\n\ndef like_post(request):\n\n\tdata = dict()\n\n\tif not request.user.is_authenticated():\n\t\traise Http404\n\n\tuser = request.user\n\tpost_slug = request.GET.get('post_slug')\n\tliked_post = get_object_or_404(Post, slug=post_slug)\n\n\tif liked_post.likes.filter(id=user.id).exists():\n\t\tdata['remove_like'] = True\n\t\tliked_post.likes.remove(user)\n\t\t\n\telse:\n\t\tdata['add_like'] = True\n\t\tliked_post.likes.add(user)\n\t\t\n\n\treturn JsonResponse(data)","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496695555","text":"from chalicelib.methods.utils import get_dynamo_table\nfrom chalicelib.models.data import DataModel\nimport arrow\n\ntable = get_dynamo_table('Data')\n\ndef get_all_data():\n data = table.scan()['Items']\n return sorted(data, key=lambda x: arrow.get(x['time']).datetime)\n\ndef post_data(data):\n table.put_item(\n Item=DataModel().dump(data).data\n )\n\n\ndef post_all_data(data):\n with table.batch_writer() as batch:\n for d in data:\n batch.put_item(\n Item=DataModel().dump(d).data\n )\n","sub_path":"chalicelib/methods/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245326917","text":"#import sys\n#for line in sys.stdin:\n\nline = \"I love testing very much\"\n\nline = line.strip()\nkeys = line.split(\" \")\nfor key in keys:\n value = 1\n print('{0}\\t{1}'.format(key, value))\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309906912","text":"import mysql.connector as con\nfrom flask import flash\n\nclass insert:\n\n def __init__(self):\n self.db= con.connect(\n host = \"localhost\",\n user = \"root\",\n password = \"snehasindhu@3\",\n database = \"dbpro\"\n )\n self.cur = self.db.cursor(buffered=True)\n\n def insert_user(self,uname,upass,uphone,umail):\n sql = \"\"\"insert into user1(uname,upass,uphone,umail) values (%s,%s,%s,%s)\"\"\"\n val = (uname,upass,uphone,umail)\n self.cur.execute(sql,val)\n self.db.commit()\n\n def enroll_user(self,cid, uid):\n sql = \"insert into enroll values(%s,%s)\"\n val = (cid,uid)\n self.cur.execute(sql,val)\n self.db.commit()\n\n\n def insert_courses(self, cname,cdura):\n sql1 = \"\"\"insert into course(cname,cduration) values (%s,%s)\"\"\"\n sql2 = \"\"\"select cid from course where cname=%s\"\"\"\n val1 = (cname,)\n val2 = (cdura,)\n val3 = (cname,cdura)\n self.cur.execute(sql2,val1)\n cthere = self.cur.fetchone()\n if cthere[0] == None:\n self.cur.execute(sql1,val3)\n else:\n error =\"course already exists\"\n return error\n self.db.commit()\n\n\n def topics(self, cname, topicname, topicdur):\n sql1 = \"CALL call_cid1(%s,@a)\"\n val1 = (cname,)\n self.cur.execute(sql1,val1)\n self.cur.execute(\"SELECT @a\")\n cidd = self.cur.fetchone()\n sql2=\"\"\"select tid from topics where tname=%s\"\"\"\n val2=(topicname,)\n self.cur.execute(sql2,val2)\n tidd=self.cur.fetchone()\n print(cidd)\n print(tidd)\n if cidd[0]==None:\n error = \"course doesnot exist\"\n return error\n if tidd==None:\n sql2 = \"\"\"insert into topics(tname,tduration,cid) values (%s,%s,%s)\"\"\"\n val2 = (topicname,topicdur,cidd[0])\n self.cur.execute(sql2,val2)\n self.db.commit()\n else:\n error=\"topic already exists\"\n return error\n\n\n def quest(self, cname, quest,answer,options):\n sql1 = \"\"\"select cid from course where cname =%s\"\"\"\n val1 = (cname,)\n self.cur.execute(sql1,val1)\n cidd = self.cur.fetchone()\n if cidd==None:\n error = \"course doesnot exist\"\n return error\n else:\n sql2 = \"\"\"insert into test1(answer,quest,cid,options) values (%s,%s,%s,%s)\"\"\"\n val2 = (answer,quest,cidd[0],options)\n self.cur.execute(sql2,val2)\n self.db.commit()\n\n\n def collection(self, topicname, coll,col_type):\n sql3 = \"\"\"select tid from topics where tname=%s\"\"\"\n val3 = (topicname,)\n print(val3)\n self.cur.execute(sql3,val3)\n tidd = self.cur.fetchone()\n print(tidd)\n if tidd[0] == None:\n error = \"topic doesnot exist\"\n return error\n sql4 = \"\"\"insert into collection1(coltype,collink,tid) values(%s,%s,%s)\"\"\"\n val4 = (col_type,coll,tidd[0])\n print(val4)\n self.cur.execute(sql4,val4)\n self.db.commit()\n\n def insert_profile(self,cid, uid):\n sql3=\"insert into profile1 values(%s,%s)\"\n val3 =(uid,cid)\n self.cur.execute(sql3,val3)\n self.db.commit()\n\n# if __name__==\"__main__\":\n# innn= insert()\n# chc = input(\"do you want to enter a course? yes/no\")\n# if chc=='yes':\n# while True:\n# n=input(\"enter the new course name\")\n# d = input(\"enter the duration of the course\")\n# innn.insert_courses(n,d)\n# choice = input(\"do you want to insert another course? yes/no\")\n# if choice=='no':\n# break\n# cht = input(\"do you want to insert a topic under any course? yes/no\")\n# if cht == 'yes':\n# while True:\n# cname = input(\"enter the course name under which topic is to be inserted\")\n# topicname = input(\"enter the topic name\")\n# tdur= input(\"enter the topic duration\")\n# y=innn.topics(cname,topicname,tdur)\n# if y==0:\n# break\n# choi = input(\"do you want to add more topics? yes/no\")\n# if choi == \"no\":\n# break\n# chc = input(\"do you want to insert collection for any topic? yes/no\")\n# if chc == \"yes\":\n# while True:\n# tname = input(\"enter the topic name under which collection has to be inserted\")\n# colink = input(\"enter the collection link\")\n# coltype= input(\"enter the collection type\")\n# x=innn.collection(tname,colink,coltype)\n# if x==0:\n# break\n# ch = input(\"do you still want to add the collection under this topic?\")\n# if ch=='no':\n# break\n# print(\"thank you\")\n","sub_path":"blog/Dbms Project/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"255071080","text":"#!/usr/bin/env python3\nimport sys\n\nfrom pandas import DataFrame, read_csv\n\n\ndef analysis(chat_id: int):\n history_df: DataFrame = read_csv(\"data/%s-history.csv\" % chat_id)\n members_df: DataFrame = read_csv(\"data/%s-members.csv\" % chat_id)\n\n grouped_df: DataFrame = history_df.groupby(\"User ID\") \\\n .size() \\\n .reset_index(name=\"Count\") \\\n .merge(members_df, on=\"User ID\", how=\"inner\") \\\n .sort_values(\"Count\", ascending=False)\n grouped_df \\\n .to_csv(\"data/%s-grouped.csv\" % chat_id, index=False, encoding=\"utf-8-sig\")\n available_df = grouped_df[grouped_df[\"Count\"] > 3]\n available_df \\\n .to_csv(\"data/%s-available.csv\" % chat_id, index=False, encoding=\"utf-8-sig\")\n\n diff = (members_df[\"Status\"] == \"member\") & \\\n (~members_df[\"User ID\"].isin(available_df[\"User ID\"]))\n members_df[diff] \\\n .to_csv(\"data/%s-removable.csv\" % chat_id, index=False, encoding=\"utf-8-sig\")\n\n\ndef main():\n for chat_id in sys.argv[1:]:\n analysis(int(chat_id))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554389061","text":"import os\nimport argparse\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nfrom keras.models import Model, load_model\nfrom keras.layers import Conv2D, BatchNormalization, UpSampling2D, MaxPooling2D, concatenate, Input\nfrom keras.optimizers import Adam\nfrom keras.applications.vgg19 import VGG19\nfrom keras.layers.advanced_activations import LeakyReLU\nimport cv2\nimport numpy\n\ndef create_crn():\n minput = Input(shape=(1024, 2048, 1), name=\"crn_input\")\n L8 = minput\n L7 = MaxPooling2D(pool_size=2, strides=2, name=\"mod7_pool\")(L8)\n L6 = MaxPooling2D(pool_size=2, strides=2, name=\"mod6_pool\")(L7)\n L5 = MaxPooling2D(pool_size=2, strides=2, name=\"mod5_pool\")(L6)\n L4 = MaxPooling2D(pool_size=2, strides=2, name=\"mod4_pool\")(L5)\n L3 = MaxPooling2D(pool_size=2, strides=2, name=\"mod3_pool\")(L4)\n L2 = MaxPooling2D(pool_size=2, strides=2, name=\"mod2_pool\")(L3)\n L1 = MaxPooling2D(pool_size=2, strides=2, name=\"mod1_pool\")(L2)\n L0 = MaxPooling2D(pool_size=2, strides=2, name=\"mod0_pool\")(L1)\n # module 0\n x = L0\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod0_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod0_lrelu1\")(x)\n x = BatchNormalization(name=\"mod0_norm1\")(x)\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod0_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod0_lrelu2\")(x)\n x = BatchNormalization(name=\"mod0_norm2\")(x)\n # module 1\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L1])\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod1_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod1_lrelu1\")(x)\n x = BatchNormalization(name=\"mod1_norm1\")(x)\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod1_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod1_lrelu2\")(x)\n x = BatchNormalization(name=\"mod1_norm2\")(x)\n # module 2\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L2])\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod2_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod2_lrelu1\")(x)\n x = BatchNormalization(name=\"mod2_norm1\")(x)\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod2_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod2_lrelu2\")(x)\n x = BatchNormalization(name=\"mod2_norm2\")(x)\n # module 3\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L3])\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod3_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod3_lrelu1\")(x)\n x = BatchNormalization(name=\"mod3_norm1\")(x)\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod3_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod3_lrelu2\")(x)\n x = BatchNormalization(name=\"mod3_norm2\")(x)\n # module 4\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L4])\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod4_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod4_lrelu1\")(x)\n x = BatchNormalization(name=\"mod4_norm1\")(x)\n x = Conv2D(filters=1024, kernel_size=3, padding=\"same\", name=\"mod4_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod4_lrelu2\")(x)\n x = BatchNormalization(name=\"mod4_norm2\")(x)\n # module 5\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L5])\n x = Conv2D(filters=512, kernel_size=3, padding=\"same\", name=\"mod5_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod5_lrelu1\")(x)\n x = BatchNormalization(name=\"mod5_norm1\")(x)\n x = Conv2D(filters=512, kernel_size=3, padding=\"same\", name=\"mod5_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod5_lrelu2\")(x)\n x = BatchNormalization(name=\"mod5_norm2\")(x)\n # module 6\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L6])\n x = Conv2D(filters=512, kernel_size=3, padding=\"same\", name=\"mod6_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod6_lrelu1\")(x)\n x = BatchNormalization(name=\"mod6_norm1\")(x)\n x = Conv2D(filters=512, kernel_size=3, padding=\"same\", name=\"mod6_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod6_lrelu2\")(x)\n x = BatchNormalization(name=\"mod6_norm2\")(x)\n # module 7\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L7])\n x = Conv2D(filters=128, kernel_size=3, padding=\"same\", name=\"mod7_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod7_lrelu1\")(x)\n x = BatchNormalization(name=\"mod7_norm1\")(x)\n x = Conv2D(filters=128, kernel_size=3, padding=\"same\", name=\"mod7_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod7_lrelu2\")(x)\n x = BatchNormalization(name=\"mod7_norm2\")(x)\n # module 8\n x = UpSampling2D(size=2)(x)\n x = concatenate([x, L8])\n x = Conv2D(filters=32, kernel_size=3, padding=\"same\", name=\"mod8_conv1\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod8_lrelu1\")(x)\n x = BatchNormalization(name=\"mod8_norm1\")(x)\n x = Conv2D(filters=32, kernel_size=3, padding=\"same\", name=\"mod8_conv2\")(x)\n x = LeakyReLU(alpha=0.2, name=\"mod8_lrelu2\")(x)\n x = BatchNormalization(name=\"mod8_norm2\")(x)\n moutput = Conv2D(filters=3, kernel_size=1, activation=None, name=\"crn_output\")(x)\n model = Model(inputs=minput, outputs=moutput)\n return model\n\ndef create_vgg():\n vgg = VGG19(include_top=False, weights=\"imagenet\", input_shape=(1024, 2048, 3))\n vgg2 = Model(inputs=vgg.input, outputs=[\n vgg.input,\n vgg.get_layer(\"block1_conv2\").output,\n vgg.get_layer(\"block2_conv2\").output,\n vgg.get_layer(\"block3_conv2\").output,\n vgg.get_layer(\"block4_conv2\").output,\n vgg.get_layer(\"block5_conv2\").output\n ])\n vgg2.trainable = False;\n for l in vgg2.layers:\n l.trainable = False\n return vgg2\n\ndef create_training_model(crn, vgg):\n output = vgg(crn.output)\n model = Model(inputs=crn.input, outputs=output)\n model.compile(\n optimizer=Adam(lr=0.0001),\n loss=[\n \"mean_absolute_error\",\n \"mean_absolute_error\",\n \"mean_absolute_error\",\n \"mean_absolute_error\",\n \"mean_absolute_error\",\n \"mean_absolute_error\"\n ],\n loss_weights=[1.0, 1/2.6, 1/4.8, 1/3.7, 1/5.6, 10.0/1.5]\n )\n return model\n\ndef create_testing_model(model):\n return Model(inputs=model.input, outputs=model.get_layer(\"crn_output\").output)\n\ndef size_data(loc):\n inputNames = sorted(os.listdir(loc))\n return len(inputNames)\n\ndef load_data(loc, start, end):\n inputNames = sorted(os.listdir(loc))[start:end]\n ndata = len(inputNames)\n ishape = (ndata, 1024, 2048, 1)\n data = numpy.ndarray(shape=ishape, dtype=numpy.uint8)\n for i in range(ndata):\n data[i] = cv2.imread(loc + \"/\" + inputNames[i], cv2.IMREAD_GRAYSCALE).reshape((1024, 2048, 1))\n return data\n\ndef load_labels(loc, start, end):\n outputNames = sorted(os.listdir(loc))[start:end]\n ndata = len(outputNames)\n oshape = (ndata, 1024, 2048, 3)\n labels = numpy.ndarray(shape=oshape, dtype=numpy.uint8)\n for i in range(ndata):\n labels[i] = cv2.imread(loc + \"/\" + outputNames[i], cv2.IMREAD_COLOR).reshape((1024, 2048, 3))\n return labels\n\ndef proc_args():\n parser = argparse.ArgumentParser(description=\"Cascaded Refinement Networks for photorealistic image synthesis.\")\n subparsers = parser.add_subparsers(dest=\"subparser\")\n subparser1 = subparsers.add_parser(\"train\", help=\"Train the model using semantic layouts as input and ground truth images as output.\")\n subparser1.add_argument(\"load\", help=\"Load the model from this file.\")\n subparser1.add_argument(\"save\", help=\"Save the model with architecture, weights, training configuration, and optimization state to this file.\")\n subparser1.add_argument(\"vgg\", help=\"Load VGG19 from this file.\")\n subparser1.add_argument(\"semantic\", help=\"Directory in which the semantic layouts are stored.\")\n subparser1.add_argument(\"truth\", help=\"Directory in which the ground truth images are stored.\")\n subparser1.add_argument(\"-b\", \"--batchsize\", help=\"Number of samples per gradient update.\", type=int, default=5)\n subparser1.add_argument(\"-e\", \"--epochs\", help=\"Number of epochs to train the model. An epoch is an iteration over the entire x and y data provided.\", type=int, default=1)\n subparser2 = subparsers.add_parser(\"generate\", help=\"Synthesize images using semantic layouts as input.\")\n subparser2.add_argument(\"load\", help=\"Load the model from this file.\")\n subparser2.add_argument(\"semantic\", help=\"Directory in which the semantic layouts are stored.\")\n subparser2.add_argument(\"synthesized\", help=\"Directory to which the synthesized images are written.\")\n subparser3 = subparsers.add_parser(\"prepcrn\", help=\"Prepare CRN for use.\")\n subparser3.add_argument(\"save\", help=\"Save CRN to this file.\")\n subparser3.add_argument(\"vgg\", help=\"Load VGG19 from this file.\")\n subparser4 = subparsers.add_parser(\"prepvgg\", help=\"Prepare VGG19 for use.\")\n subparser4.add_argument(\"save\", help=\"Save VGG19 to this file.\")\n args = parser.parse_args()\n return args\n\ndef main():\n args = proc_args()\n if args.subparser == \"train\":\n batch_file = \"batch\"\n epoch_file = \"epoch\"\n b = 0\n if os.path.isfile(batch_file):\n file1 = open(batch_file, \"r\")\n b = int(file1.read())\n file1.close()\n e = 0\n if os.path.isfile(epoch_file):\n file2 = open(epoch_file, \"r\")\n e = int(file2.read())\n file2.close()\n training_model = load_model(args.load)\n vgg = load_model(args.vgg)\n data_size = size_data(args.semantic)\n while args.epochs > e:\n while b < data_size:\n b2 = b + args.batchsize\n data = load_data(args.semantic, b, b2)\n raw_labels = load_labels(args.truth, b, b2)\n labels = vgg.predict(raw_labels)\n training_model.train_on_batch(x=data, y=labels)\n training_model.save(args.save)\n file1 = open(batch_file, \"w\")\n file1.write(str(b2))\n file1.flush()\n file1.close()\n b = b2\n e += 1\n file2 = open(epoch_file, \"w\")\n file2.write(str(e))\n file2.flush()\n file2.close()\n elif args.subparser == \"generate\":\n testing_model = create_testing_model(load_model(args.load))\n result = testing_model.predict(load_data(args.semantic))\n for i in range(data.shape[0]):\n cv2.imwrite(args.outputs + \"/\" + str(i) + \".png\", result[i])\n elif args.subparser == \"prepcrn\":\n create_training_model(create_crn(), load_model(args.vgg)).save(args.save)\n elif args.subparser == \"prepvgg\":\n create_vgg().save(args.save)\n else:\n print(\"No commands. Try --help.\")\n return\n\nmain()","sub_path":"crn.py","file_name":"crn.py","file_ext":"py","file_size_in_byte":10818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"195572711","text":"from urllib import request\nimport re\nreq = request.urlopen(r\"https://mm.taobao.com/self/aiShow.htm?spm=719.7763510.1998643336.100.ni80NG&userId=458607786\")\nres = req.read().decode(\"GBK\")\nurls = re.findall('src=\"//(.{10,300}?)jpg\"', res, re.S)\ni = 60\nfor url in urls:\n print(url + 'jpg')\n f = open(str(i) + '.jpg', 'wb')\n f.write(request.urlopen('http://' + url + 'jpg').read())\n i = i + 1\n","sub_path":"HAHAHAH/Spy.py","file_name":"Spy.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"478215155","text":"#!/usr/bin/python\n\nDOCUMENTATION = '''\n---\nmodule: distil_acl\n\nshort_description: Manages access-control lists for Distil Networks\n\noptions:\n token:\n description:\n - API token for Distil API\n required: true\n account:\n description:\n - UUID account id, required when creating ACLs.\n name:\n description:\n - Name of the ACL\n required: true\n state:\n description:\n - Create or delete an ACL\n required: false\n default: 'present'\n choices: [ \"present\", \"absent\" ]\n rules:\n description:\n - List of rules to enforce with this ACL (see example).\n - If no rules are provided, we'll create an empty ACL.\n scope:\n description:\n - List of scopes where this ACL applies (see examples).\n - ACLs aren't enforced unless applied to at least one scope.\n\nauthor:\n - Bob Gregory (bob@made.com)\n'''\n\nEXAMPLES = '''\n# Create an ACL with a single ip rule\n- name: Allow office ip to all paths\n distil_acl:\n name: Allow office IP\n token: abc-123\n account: abc-123\n rules:\n - type: ip\n description: office\n value: 172.31.0.1\n scope:\n # By default scopes apply to an entire domain\n - domain: example.com\n\n# Create a temporary exemption for an IP range to hit a path\n- distil_acl:\n token: abc-123\n account: abc-123\n name: Allow temporary access for $PARTNER\n expires: \"2019-02-01\"\n description: \"Need to have access for the next couple of weeks so they can ransack our data and break our website.\"\n rules:\n - type: ip\n description: $PARTNER\n value: 172.17.0.0/24\n scope:\n - domain: example.org\n # Scopes can be limited to a path. This scope matches any path\n # containing the substring \"api\"\n path: api\n\n# Whitelist all traffic from an IP range matching a path pattern\n- distil_acl:\n token: abc-123\n account: abc-123\n name: Allow temporary access for $PARTNER\n expires: \"2019-02-01\"\n description: \"Need to have access for the next couple of weeks so they can ransack our data and break our website.\"\n rules:\n - type: ip\n description: $PARTNER\n value: 172.17.0.0/24\n scope:\n - domain: example.org\n # Scopes can use a lua pattern instead of a contains match.\n pattern: \"^/api/\"\n\n# Delete an ACL\n- name: Remove old office\n token: abc-123\n account: abc-123\n name: Allow office IP\n state: absent\n\n# Whitelist a header value\n- distil_acl:\n token: abc-123\n account: abc-123\n name: Whitelist developers\n description: \"Allow developers to access the site by passing magic header\"\n rules:\n - type: header\n name: x-magic\n value: 1\n scope:\n - domain: example.com\n - domain: example.org\n\n# Blacklist a user agent\n- distil_acl:\n token: abc-123\n account: abc-123\n name: Blacklist FROOTPOT\n blacklist: yes\n description: Crazy frootpot people keep DOSing the website\n rules:\n - type: user_agent\n value: FROOTPOT\n - type: ip\n value: 172.17.0.128/30\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom collections import namedtuple\nimport requests\n\nAPI_ROOT = \"https://api.distilnetworks.com/api/v1/\"\n\nAclRecord = namedtuple(\n '_acl_record',\n [\"id\", \"name\", \"global_link\", \"global_access_control_list_id\"])\n\nAccessRule = namedtuple('_acl_rule', [\n \"id\", \"access_control_list_id\", \"updated_at\", \"list\", \"type\", \"name\",\n \"value\", \"expires\", \"note\", \"global_link\", \"global_rule_id\", \"created_at\"\n])\n\nRuleSpec = namedtuple('_acl_rule_spec',\n [\"type\", \"list\", \"name\", \"value\", \"expires\", \"note\"])\n\nRuleScope = namedtuple('_rule_scope', [\n 'id', 'type', 'match', 'lua_pattern_enabled', 'domain',\n 'access_control_list_ids'\n])\n\nScopeSpec = namedtuple('_rule_scope_spec', ['domain', 'match'])\n\n\ndef matches(spec, scope):\n \"\"\"\n Compare a ScopeSpec to a RuleScope to see if they match.\n \"\"\"\n\n if spec.match == 'all':\n return (scope.match == 'default' and scope.type == 'default'\n and scope.domain == spec.domain)\n\n match_type, match = spec.match\n\n if match_type == 'path':\n return (scope.match == match and scope.type == 'path'\n and scope.lua_pattern_enabled == False)\n\n if match_type == 'pattern':\n return (scope.match == match and scope.type == 'path'\n and scope.lua_pattern_enabled == True)\n\n\nclass ScopeCollection(list):\n def find(self, spec):\n for scope in self:\n if matches(spec, scope):\n return scope\n\n def find_by_acl(self, acl_id):\n return [\n scope for scope in self if acl_id in scope.access_control_list_ids\n ]\n\n\nclass Client:\n def __init__(self, token, account=None):\n self.token = token\n self.account = account\n\n def _req_uri(self, method, resource, body, *args, **kwargs):\n if \"auth_token\" not in kwargs:\n kwargs[\"auth_token\"] = self.token\n\n if self.account and not \"account_id\" in kwargs:\n kwargs[\"account_id\"] = self.account\n kw = {\"params\": kwargs}\n\n if body:\n import json\n kw[\"json\"] = body\n\n resp = requests.request(method, API_ROOT + resource.format(*args),\n **kw)\n resp.raise_for_status()\n try:\n return resp.json()\n except ValueError:\n pass\n\n def _get_uri(self, resource, *args, **kwargs):\n return self._req_uri(\"GET\", resource, None, *args, **kwargs)\n\n def _get_list(self, resource, *args, **kwargs):\n page = 1\n page_size = 30\n is_last_page = False\n result = []\n\n while not is_last_page:\n kwargs[\"page\"] = page\n kwargs[\"page_size\"] = page_size\n\n resp = self._get_uri(resource, *args, **kwargs)\n items = list(resp.items())\n assert len(items) in [1, 2]\n\n meta = None\n data = []\n\n for key, value in items:\n if key == \"meta\":\n meta = value\n else:\n data = value\n\n result.extend(data)\n\n if not meta:\n break\n\n returned_page = meta.get(\"page\")\n total_pages = meta.get(\"total_pages\")\n\n if not returned_page or total_pages == 0:\n break\n\n is_last_page = returned_page == total_pages\n page += 1\n\n return result\n\n def _post_uri(self, resource, body, *args, **kwargs):\n return self._req_uri(\"POST\", resource, body, *args, **kwargs)\n\n def _delete_uri(self, resource, *args, **kwargs):\n return self._req_uri(\"DELETE\", resource, None, *args, **kwargs)\n\n def get_acls(self, **kwargs):\n resp = self._get_list(\"access_control_lists\", **kwargs)\n\n return [AclRecord(**json) for json in resp]\n\n def get_acl_by_name(self, name):\n return list(\n filter(lambda x: x.name == name, self.get_acls(search=name)))\n\n def get_rules(self, acl_id):\n resp = self._get_list(\"access_control_lists/{0}/rules\", acl_id)\n\n return list(AccessRule(**json) for json in resp)\n\n def delete_acl(self, acl_id):\n resp = self._delete_uri(\"access_control_lists/{0}\", acl_id)\n\n def create_acl(self, name):\n return self._post_uri(\"access_control_lists\",\n {\"access_control_list\": {\n \"name\": name\n }})\n\n def create_rules(self, acl_id, rules):\n if not rules:\n return\n\n return self._post_uri(\"access_control_lists/{0}/rules/batch_create\",\n {\"rules\": [rule._asdict() for rule in rules]},\n acl_id)\n\n def delete_rules(self, acl_id, rules):\n if not rules:\n return\n\n return self._req_uri(\"DELETE\",\n \"access_control_lists/{0}/rules/batch_destroy\",\n {\"ids\": rules}, acl_id)\n\n def get_domains(self):\n resp = self._get_list(\"platform/domains\")\n\n return {domain['name']: domain['id'] for domain in resp}\n\n def get_scopes(self):\n resp = self._get_list(\"rule_scopes\")\n\n return ScopeCollection((RuleScope(\n id=scope['id'],\n type=scope['type'],\n match=scope['match'],\n lua_pattern_enabled=scope['lua_pattern_enabled'],\n domain=scope['domain'],\n access_control_list_ids=scope['access_control_list_ids'])\n for scope in resp))\n\n def create_scope(self, spec, acl_id):\n domains = self.get_domains()\n\n if spec.domain not in domains:\n raise KeyError(\n \"Unrecognised domain {}. Domains must be configured in the portal.\"\n % spec.domain)\n\n return self._post_uri(\n \"rule_scopes\", {\n \"type\": \"default\" if spec.match == \"all\" else \"path\",\n \"match\": \"default\" if spec.match == \"all\" else spec.match[1],\n \"lua_pattern_enabled\": spec.match[0] == \"pattern\",\n \"access_control_list_id\": acl_id\n },\n domain_id=domains[spec.domain])\n\n def disassociate_acl_from_scopes(self, acl_id, scope_ids):\n if not scope_ids:\n return\n self._req_uri(\"DELETE\",\n \"access_control_lists/{0}/rule_scopes/batch_destroy\", {\n \"ids\": scope_ids,\n }, acl_id)\n\n def associate_acl_to_scopes(self, acl_id, scope_ids):\n if not scope_ids:\n return\n self._post_uri(\"access_control_lists/{0}/rule_scopes/batch_create\",\n {\"ids\": scope_ids}, acl_id)\n\n def delete_scope(self, scope_id):\n self._delete_uri(\"rule_scopes/{0}\", scope_id)\n\n\ndef extract_spec(rule):\n \"\"\"\n Extracts a RuleSpec from an AccessRule\n \"\"\"\n return RuleSpec(rule.type, rule.list, rule.name, rule.value,\n rule.expires, rule.note)\n\n\ndef identify_rule_changes(existing, desired):\n \"\"\"\n Given a set of existing AccessRules and a set of desired RuleSpecs\n work out what changes we need to make to an acl.\n \"\"\"\n ids = {extract_spec(r): r.id for r in existing}\n existing = set(ids.keys())\n desired = set(desired)\n\n missing = desired - existing\n outdated = existing - desired\n\n return {\n \"to_delete\": [ids[r] for r in outdated],\n \"to_create\": list(missing),\n }\n\n\ndef identify_scope_changes(existing, desired, acl_id):\n \"\"\"\n Given a ScopeCollection of all the rule scopes active on an account, plus\n a desired list of ScopeSpecs, calculate the changes we need to make.\n \"\"\"\n create_scope = []\n add_rule = []\n remove_rule = []\n destroy_scope = []\n\n # Start off by assuming that all of the existing rules for this ACL\n # are no longer needed. If we find them in the desired specs, we'll\n # remove them from this list.\n orphaned_scopes = existing.find_by_acl(acl_id)\n\n for spec in desired:\n scope = existing.find(spec)\n\n if not scope:\n create_scope.append(spec)\n\n continue\n\n if acl_id in scope.access_control_list_ids:\n orphaned_scopes.remove(scope)\n\n continue\n\n add_rule.append(scope.id)\n\n # What's remaining in orphans is now unused associations.\n # IF the scope has several rules attached, we need to keep it\n # but if this is the only rule attached, we can delete the scope\n # UNLESS it's the magic 'all paths' scope.\n\n for scope in orphaned_scopes:\n if len(scope.access_control_list_ids) > 1:\n remove_rule.append(scope.id)\n elif scope.type == 'default':\n remove_rule.append(scope.id)\n else:\n destroy_scope.append(scope.id)\n\n return {\n 'to_create': create_scope,\n 'to_destroy': destroy_scope,\n 'add_to': add_rule,\n 'remove_from': remove_rule\n }\n\n\ndef remove_acl(module):\n \"\"\"\n Delete an ACL from the API.\n \"\"\"\n client = Client(module.params[\"token\"])\n acl = client.get_acl_by_name(module.params[\"name\"])\n\n if acl:\n [acl] = acl\n client.delete_acl(acl.id)\n module.exit_json(changed=True, changes={\"deleted\": acl})\n else:\n module.exit_json(changed=False)\n\n\ndef create_acl(module, result):\n \"\"\"\n Create a new ACL\n \"\"\"\n client = Client(module.params[\"token\"], module.params[\"account\"])\n acl = client.create_acl(module.params[\"name\"])\n acl_id = acl[\"access_control_list\"][\"id\"]\n result['created_acl'] = acl_id\n\n\ndef parse_rules(module):\n \"\"\"\n Convert from the published yaml format into a list of RuleSpec instances.\n \"\"\"\n raw = module.params[\"rules\"] or []\n parsed = []\n\n for rule in raw:\n parsed.append(\n RuleSpec(\n type=rule.get(\"type\"),\n list=\"blacklist\" if\n (rule.get(\"deny\") == True) else \"whitelist\",\n name=rule.get(\"name\"),\n value=rule.get(\"value\"),\n expires=rule.get(\"expires\"),\n note=rule.get(\"description\") or \"\"))\n\n return parsed\n\n\ndef parse_scopes(module):\n raw = module.params[\"scope\"] or []\n parsed = []\n for scope in raw:\n match = \"all\"\n if \"domain\" not in scope:\n module.fail_json(msg=\"No domain found for scope\")\n else:\n if \"pattern\" in scope:\n match = (\"pattern\", scope[\"pattern\"])\n elif \"path\" in scope:\n match = (\"path\", scope[\"path\"])\n parsed.append(ScopeSpec(scope[\"domain\"], match))\n\n return parsed\n\n\ndef apply_scope_changes(module, acl_id, result):\n client = Client(module.params[\"token\"], module.params[\"account\"])\n existing = client.get_scopes()\n desired = parse_scopes(module)\n\n changes = identify_scope_changes(existing, desired, acl_id)\n\n for scope in changes[\"to_create\"]:\n client.create_scope(scope, acl_id)\n\n client.associate_acl_to_scopes(acl_id, changes[\"add_to\"])\n client.disassociate_acl_from_scopes(acl_id, changes[\"remove_from\"])\n\n for scope in changes[\"to_destroy\"]:\n client.delete_scope(scope)\n\n result[\"scope_changes\"] = changes\n if changes[\"to_create\"] or changes[\"to_destroy\"] or changes[\n \"add_to\"] or changes[\"remove_from\"]:\n result[\"changed\"] = True\n\n\ndef apply_rule_changes(module, acl_id, result):\n \"\"\"\n Given an AclRecord, fetch the set of rule changes that need to be made.\n \"\"\"\n client = Client(module.params[\"token\"], module.params[\"account\"])\n existing = client.get_rules(acl_id)\n desired = parse_rules(module)\n\n changes = identify_rule_changes(existing, desired)\n client.delete_rules(acl_id, changes[\"to_delete\"])\n client.create_rules(acl_id, changes[\"to_create\"])\n result[\"rule_changes\"] = changes\n\n if changes[\"to_delete\"] or changes[\"to_create\"]:\n result[\"changed\"] = True\n\n\ndef main():\n argument_spec = dict(\n name=dict(required=True, type='str'),\n account=dict(),\n token=dict(required=True, type='str'),\n rules=dict(type='list'),\n scope=dict(type='list'),\n state=dict(\n default='present', type='str', choices=['present', 'absent']),\n )\n\n module = AnsibleModule(\n argument_spec=argument_spec, supports_check_mode=True)\n\n if module.params[\"state\"] == 'absent':\n return remove_acl(module)\n\n result = dict()\n client = Client(module.params[\"token\"])\n acl = client.get_acl_by_name(module.params[\"name\"])\n if acl:\n acl_id = acl[0].id\n else:\n create_acl(module, result)\n acl_id = result['created_acl']\n\n apply_rule_changes(module, acl_id, result)\n apply_scope_changes(module, acl_id, result)\n\n module.exit_json(changed=(\"changed\" in result), changes=result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"distil_acl.py","file_name":"distil_acl.py","file_ext":"py","file_size_in_byte":16241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483287344","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy\nnumpy.set_printoptions(threshold=numpy.inf)\n\n\ndata = pd.read_csv(\"./data/FDAXON2.csv\")\ndata = data.dropna()\n\nprint(data['Success'].value_counts())\nprint(data)\n\nplt.matshow(data.corr())\nplt.show()\n\n# print (data.corr())\n\n# with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n# print(data.corr())","sub_path":"overnightstrat/tools/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377384343","text":"'''\n/*문제 정보 */\n11725번 - 트리의 부모 찾기\n난이도 - 실버 3\n/*풀이 방법 */\ndfs 로 1 부터 graph 를 돌아서 parent 에 부모 노드 번호를 저장해 주었다.\ngraph[a] = [b] 라면 parent[b] = [a] 식으로 저장해주었다.\n방문처리를 하여 parent 에 저장하는데 오류가 나지 않게 하였다.\n'''\nimport sys\nsys.setrecursionlimit(10**7)\ninput = sys.stdin.readline\n\nn = int(input())\ngraph = [[] for _ in range(n+1)]\nvisited = [0] * (n+1)\nparent = [0] * (n+1)\n\nfor i in range(n-1):\n a,b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n\ndef dfs(x):\n visited[x] = 1\n for i in graph[x]:\n if visited[i] == 0:\n parent[i] = x\n dfs(i)\n\ndfs(1)\nfor j in range(2, n+1):\n print(parent[j])\n\n\n'''\n/*오답 노트*/\n처음에는 반복문으로 찾아야 할 값 i 를 주고 graph[1] 에서부터 dfs 로 재귀를\n사용해 부모 노드를 찾으려 했는데, 복잡해 질 것 같아서 parent 리스트를 만들어\ngraph 를 진작에 다 돌아 parent 에 저장해 준 뒤 값을 찾아내는 방식으로 했다.\n/*느낀 점*/\nRecursionError: maximum recursion depth exceeded in comparison\n라는 오류가 떴었는데, 내가 처음에 dfs를 작성하는데 오류가 난 줄 알고 검색해보니\n파이썬에서 재귀 호출 횟수를 제한하고 있어 나는 오류라고 한다.\nsys 모듈에서 setrecursionlimit 함수를 사용해 깊이를 늘려주어 해결 할 수 있었다.\n'''","sub_path":"season2/season2/week8/sunghoon/11725.py","file_name":"11725.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389277882","text":"from django.contrib import admin\nfrom payments.models import Account\n\n\nclass AccountAdmin(admin.ModelAdmin):\n list_display = [\n 'username',\n 'currency',\n 'created',\n 'modified',\n 'balance',\n 'removed',\n ]\n ordering = ('-created',)\n list_filter = ['currency']\n\n\nadmin.site.register(Account, AccountAdmin)\n","sub_path":"payments/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623547775","text":"#!/usr/bin/env python\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.image import Image\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.graphics import Color\nfrom kivy.graphics import Rectangle\nfrom kivy.uix.screenmanager import ScreenManager, Screen\n\nimport ipdb\n\n\nclass HomePage(BoxLayout, Screen):\n pass\n\n\nclass AmpleButton(Image, ButtonBehavior, AnchorLayout):\n def __init__(self, **kwargs):\n super(AmpleButton, self).__init__(**kwargs)\n\n \"\"\" To instantiate a new Rectangle every time when the button is clicked,\n can lead to artefacts, when the the winow is reszized. Need to clear and\n draw everything again (in order to do it correctly).\"\"\"\n\n def on(self):\n with self.canvas.before:\n Color(0.9, 0.9, 0.9, mode=\"rgb\")\n self.rect = Rectangle(pos=self.pos, size=self.size)\n\n def off(self):\n with self.canvas.before:\n Color(1, 1, 1, mode=\"rgb\")\n self.rect = Rectangle(pos=self.pos, size=self.size)\n\n\nclass Header(BoxLayout):\n pass\n\n\nclass PrinterPage(GridLayout, Screen):\n def __init__(self, **kwargs):\n super(PrinterPage, self).__init__(**kwargs)\n self._printing = False\n\n def handle_press(self, *args):\n # ipdb.set_trace()\n if len(args) != 1:\n raise ValueError(\"There must be at least one arg in args. Expected String\")\n if args[0]:\n self._printing = True\n self.ids.green.on()\n self.ids.red.off()\n else:\n self._printing = False\n self.ids.green.off()\n self.ids.red.on()\n\n\nclass AmpleManApp(App):\n def build(self):\n sm = ScreenManager()\n sm.add_widget(HomePage(name=\"homepage\"))\n sm.add_widget(PrinterPage(name=\"printerpage\"))\n return sm\n\n def on_pause(self):\n return True\n\n\nif __name__ == \"__main__\":\n AmpleManApp().run()\n","sub_path":"AmplemanApp.py","file_name":"AmplemanApp.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289684816","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('clients', '__first__'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PipeInsulation',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('start_date', models.DateTimeField(verbose_name=b'Registered Date')),\n ('name', models.CharField(default=b'', max_length=128, verbose_name=b'Pipe Insulation Description')),\n ('nps_pipe_size_inches', models.FloatField(default=0.5, verbose_name=b'NPS Pipe Size (inches)', choices=[(0.5, 0.5), (0.75, 0.75), (1.0, 1.0), (1.25, 1.25), (1.5, 1.5), (2.0, 2.0), (2.5, 2.5), (3.0, 3.0), (3.5, 3.5), (4.0, 4.0), (4.5, 4.5), (5.0, 5.0), (6.0, 6.0), (7.0, 7.0), (8.0, 8.0), (9.0, 9.0), (10.0, 10.0), (12.0, 12.0), (14.0, 14.0), (16.0, 16.0), (18.0, 18.0), (20.0, 20.0), (24.0, 24.0), (30.0, 30.0), (36.0, 36.0), (48.0, 48.0)])),\n ('length_of_pipe', models.FloatField(default=0, verbose_name=b'Length of Pipe (feet)')),\n ('working_fluid', models.CharField(default=b'Steam', max_length=128, verbose_name=b'Working Fluid', choices=[(b'Steam', b'Steam'), (b'Condensate', b'Condensate'), (b'Heating Hot Water', b'Heating Hot Water'), (b'Domestic Hot Water', b'Domestic Hot Water')])),\n ('process_temp_or_pressure', models.IntegerField(default=0, help_text=b'Noel Chambers: Select the temperature of the working fluid if the fluid a liquid. If the working fluid is steam please select the working pressure of the system.', verbose_name=b'Process Temp or Pressure')),\n ('system_efficiency', models.FloatField(default=80, verbose_name=b'System Efficiency')),\n ('ambient_temp', models.FloatField(default=70, verbose_name=b'Ambient Temp')),\n ('system_hours_per_year', models.FloatField(default=8760, verbose_name=b'System Hours / Year')),\n ('wind_speed_mph', models.FloatField(default=0, verbose_name=b'Wind Speed (MPH)')),\n ('location', models.CharField(default=b'Indoors', max_length=128, verbose_name=b'Location', choices=[(b'Indoors', b'Indoors'), (b'Outdoors', b'Outdoors')])),\n ('base_metal', models.CharField(default=b'Steel', max_length=128, verbose_name=b'Base Metal', choices=[(b'Steel', b'Steel'), (b'Copper', b'Copper'), (b'PVC', b'PVC')])),\n ('insulation', models.CharField(default=b'850', max_length=128, verbose_name=b'Insulation', choices=[(b'850', b'850F Mineral Fiber PIPE, Type I, C547-11'), (b'1200', b'1200F Mineral Fiber PIPE, Types II and III, C547-11'), (b'1000', b'1000F Mineral Fiber PIPE, Type IV, C547-11'), (b'Poly', b'Polystyrene PIPE, Type XIII, C578-11b')])),\n ('insulation_thickness', models.FloatField(default=0.5, verbose_name=b'Insulation Thickness', choices=[(0.5, 0.5), (0.75, 0.75), (1, 1), (1.5, 1.5), (2, 2), (2.5, 2.5), (3, 3), (3.5, 3.5), (4, 4), (4.5, 4.5), (5, 5), (6, 6), (7, 7), (8, 8)])),\n ('jacket_material', models.CharField(default=b'', max_length=128, verbose_name=b'Jacket Material')),\n ('client', models.ForeignKey(to='clients.Client')),\n ('owner', models.ForeignKey(related_name='pipe_insulation', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('name',),\n },\n ),\n ]\n","sub_path":"pipe_insulation/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"547640096","text":"#-*-encoding:utf-8-*-\nimport os\nwith open(\"MindField(Ep-1).txt\", 'rb') as f:\n a = f.read()\n a = str(a)\n infile = open(\"MindField1(Ep-1).txt\",'w')\n b = a.replace('.', '. \\n')\n infile.writelines(b)\n infile.close()\n print(type(b))\n","sub_path":"English/MindField/formattxt.py","file_name":"formattxt.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489854846","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n#------------------ AnKoA -----------------------#\n# Made with love by grm34 (FRIPOUILLEJACK) #\n# ........fripouillejack@gmail.com ....... #\n# Greetz: thibs, Rockweb, c0da, Hydrog3n, Speedy76 #\n#--------------------------------------------------#\n\"\"\"\n folder........: source path (ex: /home/toto/torrents/)\n thumb.........: result path (ex: /home/toto/encodes/)\n tag...........: your team name (ex: KULTURA)\n team..........: MEDIAINFO 'Proudly Present' Tag (ex: TEAM KULTURA)\n announce......: your favorite tracker url announce\n tmdb_api_key..: API Key from https://www.themoviedb.org/documentation/api\n tag_thumb.....: Thumbnails tag (ex: )\n\"\"\"\n\ndef option():\n\n folder = \"XXX001\"\n thumb = \"XXX002\"\n tag = \"XXX003\"\n team = \"TEAM XXX003\"\n announce = \"XXX004\"\n tmdb_api_key = \"XXX005\"\n tag_thumb = \"\"\n\n values = (folder, thumb, tag, team, announce, tmdb_api_key, tag_thumb)\n return (values)\n","sub_path":"app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251211475","text":"# -*- coding: utf-8 -*-\n# Author : Seungyeon Jo\n# e-mail : syjo@seculayer.co.kr\n# Powered by Seculayer © 2018 AI-Core Team\n\nfrom mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract\n\n\nclass LongToIP(ConvertAbstract):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n def apply(self, data):\n result = 0\n \n try:\n result = self._longToIp(data)\n except Exception as e:\n self.LOGGER.error(e)\n \n return [result]\n\n def _longToIp(self, ipint):\n return '.'.join([str(ipint >> (i << 3) & 0xFF) for i in range(4)[::-1]])\n\n\nif __name__ == \"__main__\":\n _ipint = 16909060 # 1.2.3.4\n print(LongToIP(stat_dict=None, arg_list=[]).apply(_ipint))\n","sub_path":"mlps/core/data/cnvrtr/functions/LongToIP.py","file_name":"LongToIP.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"504839468","text":"#! python3\r\n\r\nimport itertools\r\n\r\nwith open('input.txt') as f:\r\n lines = f.readlines()\r\n\r\nnums = []\r\nfor i in lines:\r\n nums.append(int(i.strip()))\r\n\r\ncombs = itertools.combinations(nums, 3)\r\n\r\nanswer = 0\r\nfor j in combs:\r\n if sum(j) == 2020:\r\n answer = j[0]*j[1]*j[2]\r\n\r\nprint(answer)\r\n \r\n","sub_path":"2020/Day1b.py","file_name":"Day1b.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"486466412","text":"\"\"\"\nthis component pulls the config of this device from the IPL \ncomponent and sets up all the DIO on that controller (resource \nin the configuration). \n\nTo use this component: \n1. Setup the ipl component instructions\n2. create custom_component/binary_sensor and place ipldio.py into that folder \n3. make note of the Name of the IPL you want to use the relays on,\n from the name used in the ipl component. as that is how this \n components communicates with that device\n\n4. create a yaml entry as per below \n\nipl: \n - name: deviceName\n ...\n\nExample Yaml configuration \nbinary_sensor:\n - platform: ipldio\n name: deviceName\n\"\"\"\nimport logging\nimport voluptuous as vol\nfrom datetime import timedelta\nfrom homeassistant.components.binary_sensor import BinarySensorDevice\nfrom homeassistant.const import CONF_NAME, CONF_TYPE,CONF_FRIENDLY_NAME\nimport homeassistant.helpers.config_validation as cv\nimport custom_components.ipl as IPL\n_LOGGER = logging.getLogger(__name__)\n\nDEPENDENCIES = ['ipl']\n\nPIN_SCHEMA = vol.Schema({\n vol.Required(CONF_NAME): cv.string,\n})\n\nSCAN_INTERVAL = timedelta(seconds=10)\n\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n \"\"\"Set up the IPL DIO platform.\"\"\"\n if IPL.ComsDict == {}:\n _LOGGER.error(\"A connection has not been made to the IPL\")\n return False\n else:\n dio = []\n Name = config.get(CONF_NAME)\n Coms = IPL.ComsDict[Name]\n for x in Coms.Controllers[Coms.ConType]['DIO']['Ports']:\n dio.append(IPLDIO('{0}:{1}'.format(Name,x),x,'Digital Input',Coms))\n\n add_devices(dio)\n\nclass IPLDIO(BinarySensorDevice):\n \"\"\" IPL binary sensor.\"\"\"\n\n def __init__(self, name,DeviceNumber,device_class,Coms):\n \"\"\"Initialize the sensor.\"\"\"\n self._name = name\n self._sensor_type = device_class\n self.Coms = Coms\n self.DeviceNumber = DeviceNumber\n\n @property\n def device_class(self):\n \"\"\"Return the class of this sensor.\"\"\"\n return self._sensor_type\n\n @property\n def should_poll(self):\n \"\"\"always poll.\"\"\"\n return True\n\n @property\n def name(self):\n \"\"\"Return the name of the binary sensor.\"\"\"\n return self._name\n\n @property\n def is_on(self):\n \"\"\"Return true if the binary sensor is on.\"\"\"\n return self.Coms.GetInput(self.DeviceNumber)\n\n def update(self):\n \"\"\"Update device state.\"\"\"\n self.Coms.Update(self.DeviceNumber)","sub_path":"binary_sensor/ipldio.py","file_name":"ipldio.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"218297905","text":"'''\nUtilities for the interface\n'''\nimport os, subprocess, json\nimport shutil as sh\nopd, opb, opj = os.path.dirname, os.path.basename, os.path.join\nfrom sys import platform as _platform\nimport threading, webbrowser\n\ndef find_platform():\n '''\n Find which platform is currently used\n '''\n print('platform is ',_platform)\n if _platform == \"linux\" or _platform == \"linux2\":\n platf = 'lin'\n elif _platform == \"darwin\":\n platf = 'mac'\n elif _platform == \"win32\":\n platf = 'win'\n return platf\n\ndef try_nb(s):\n try:\n return int(s)\n except ValueError:\n pass\n try:\n return float(s)\n except ValueError:\n pass\n return s\n\ndef translate_params(p):\n '''\n '''\n print(f\"##### p is {p}\")\n if ':' in p:\n ps = p.split(':')\n if ',' in ps[1]:\n return { ps[0]:'[{}]'.format(ps[1]) } # list case\n else:\n if '&' in ps[1]:\n if ps[0] == 'select_model':\n part = ps[1].split('&')\n dic_mod_with_event = { 'model': part[0], 'model_events': part[1] }\n print(f\"dic is {dic_mod_with_event} \")\n return dic_mod_with_event\n else:\n return { ps[0]: try_nb(ps[1]) } # return key/value\n else:\n return { p:True } # return a boolean\n\ndef clean_dir(dir):\n '''\n Clear folder dir\n '''\n try:\n for f in glob.glob(opj(dir, '*.*')):\n os.remove(f)\n except:\n print(f\"can't clean {dir}\")\n\ndef open_folder(path):\n '''\n Open folder\n '''\n if platf == 'win':\n os.startfile(path)\n elif platf == 'mac':\n subprocess.Popen([\"open\", path])\n else:\n subprocess.Popen([\"xdg-open\", path])\n\ndef rm_make_upload(config):\n '''\n '''\n upload = config['UPLOADED_PATH']\n try:\n sh.rmtree(upload) # Reinitializes the upload folder\n except:\n print(f\"cannot find {upload}\")\n os.mkdir(upload)\n\ndef init(config):\n '''\n Prepare interface.\n '''\n rm_make_upload(config)\n\ndef save_with_date(dest='previous_proc', debug=0):\n '''\n Save the processing with full structure in previous_proc\n Folders saved are Processings and Controls\n File saved is list_proc.json\n '''\n now = datetime.now()\n path_static = opj(os.getcwd(), 'static')\n dproc, dctrl = opj(path_static, 'processings'), opj(path_static, 'controls')\n dlist_proc = opj(path_static, 'list_proc.json')\n dest_path = opj(path_static, dest)\n try:\n os.mkdir(dest_path) # path for previous processings\n print(\"########## made new dest_path !!!! \")\n except:\n # print(\"#### In except loop !!!!\")\n # print(dest_path)\n # print(os.path.exists(dest_path))\n # sh.rmtree(dest_path)\n # os.mkdir(dest_path)\n # # print(\"########## removed dest_path !!!! \")\n print(\"Possible issue with previous_proc\")\n #path_static = opj(os.getcwd(), 'static')\n date = f\"{now.year}-{now.month}-{now.day}-{now.hour}-{now.minute}\"\n ppdate = opj(dest_path, date)\n try:\n sh.copytree(dproc, opj(ppdate,'processings'))\n except:\n print(\"yet existing folder\")\n if debug>0: print(\"copied dproc\")\n try:\n sh.copytree(dctrl, opj(ppdate,'controls'))\n except:\n print(\"yet existing folder\")\n try:\n sh.copy(dlist_proc, ppdate)\n except:\n print(\"yet existing file\")\n if debug>0: print(\"copied dlist_proc\")\n sh.make_archive(ppdate, \"zip\", ppdate) # Zip the archive\n return ppdate +'.zip'\n\ndef find_chrome_path(platf):\n '''\n '''\n # MacOS\n if platf == 'mac':\n chrome_path = 'open -a /Applications/Google\\ Chrome.app %s'\n # Linux\n elif platf == 'lin':\n chrome_path = '/usr/bin/google-chrome %s'\n else:\n chrome_path = False\n return chrome_path\n\ndef launch_browser(port, host, platf):\n '''\n Launch Chrome navigator\n '''\n chrome_path = find_chrome_path(platf)\n url = f\"http://{host}:{port}\" #\n if platf != 'win':\n b = webbrowser.get(chrome_path)\n threading.Timer(1.25, lambda: b.open_new(url)).start() # open a page in the browser.\n else:\n try:\n print('using first path')\n subprocess.Popen(f'\"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\" {url}')\n except:\n print('using second path')\n subprocess.Popen(f'\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\" {url}')\n","sub_path":"simple_interface/modules/util_interf.py","file_name":"util_interf.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159154369","text":"# -*- coding: utf-8 -*-\n\n__metaclass__ = type\n# This class is not in use #\n\n\nclass GetSetAttributes():\n\n def __init__(self):\n pass\n\n def set_attributes(self, key, value):\n self._attributes[key] = value\n return\n\n def get_attributes(self, key):\n return self._attributes.get(key, None)\n\n\nclass Node_old(GetSetAttributes):\n\n __nodeID = None\n __x = None\n __y = None\n __z = None\n\n def __init__(self, **kvargs):\n self._attributes = kvargs\n\n def __str__(self):\n return \"ID: {} x: {} y: {} z: {}\".format(\n self._attributes.get('__nodeID', None),\n self._attributes.get('__x', None),\n self._attributes.get('__y', None),\n self._attributes.get('__z', None))\n\n\nclass Element_old(GetSetAttributes):\n\n # Static variables\n __elementID = None\n __nodeList = None\n __elementType = None\n __elementOrder = None\n\n def __init__(self, **kvargs):\n self._attributes = kvargs\n\n def __str__(self):\n nodeIDList = []\n nodeList = self._attributes.get('__nodeList', None)\n for node in nodeList:\n nodeIDList.append(node._attributes.get('__nodeID', None))\n return \"ID: {} ElementType: {} Nodes: {} Order {} \".format(\n self._attributes.get('__elementID', None),\n self._attributes.get('__elementType', None),\n nodeIDList,\n self._attributes.get('__elementOrder', None))\n\n\n\n\nclass Node():\n\n def __init__(self):\n self.ID = None\n self.x = None\n self.y = None\n self.z = None\n\n @property\n def ID(self):\n return self.__ID\n\n @ ID.setter\n def ID(self, ID):\n self.__ID = ID\n\n @property\n def x(self):\n return self.__x\n\n @ x.setter\n def x(self, x):\n self.__x = x\n\n @property\n def y(self):\n return self.__y\n\n @ y.setter\n def y(self, y):\n self.__y = y\n\n @property\n def z(self):\n return self.__z\n\n @ z.setter\n def z(self, z):\n self.__z = z\n\n\n\n\nclass __Element():\n\n\n def __init__(self):\n self.ID = None\n self.type = None\n self.order = None\n self.nodeList = []\n self.shape = None\n self.den = None\n self.eModul = None\n self.heatKoeff = None\n self.xc = None\n self.yc = None\n self.zc = None\n\n @property\n def xc(self):\n return self.__xc\n\n @ xc.setter\n def xc(self, xc):\n self.__xc = xc\n\n @property\n def yc(self):\n return self.__yc\n\n @ yc.setter\n def yc(self, yc):\n self.__yc = yc\n\n @property\n def zc(self):\n return self.__zc\n\n @ zc.setter\n def zc(self, zc):\n self.__zc = zc\n\n @property\n def ID(self):\n return self.__ID\n\n @ ID.setter\n def ID(self, ID):\n self.__ID = ID\n\n # Type of the element (thermal, mechanic)\n @property\n def type(self):\n return self.__type\n\n @ type.setter\n def type(self, type):\n self.__type = type\n # Order of the element\n @property\n def order(self):\n return self.__order\n\n @ order.setter\n def order(self, order):\n self.__order = order\n # Nodes in Element\n @property\n def nodeList(self):\n return self.__nodeList\n\n @ nodeList.setter\n def nodeList(self, nodeList):\n self.__nodeList = nodeList\n # Shape of the element\n @property\n def shape(self):\n return self.__shape\n\n @ shape.setter\n def shape(self, shape):\n self.__shape = shape\n\n # Density\n @property\n def den(self):\n return self.__den\n\n @ den.setter\n def den(self, den):\n self.__den = den\n\n # eModul\n @property\n def eModul(self):\n return self.__eModul\n\n @ eModul.setter\n def eModul(self, eModul):\n self.__eModul = eModul\n\n # Heat koeff\n @property\n def heatKoeff(self):\n return self.__heatKoeff\n\n @ heatKoeff.setter\n def heatKoeff(self, heatKoeff):\n self.__heatKoeff = heatKoeff\n\n\n\nclass TetElement(__Element):\n\n def __init__(self):\n self.ID = None\n self.type = None\n self.order = None\n self.nodeList = []\n self.shape = 'Tetraeder'\n self.den = None\n self.eModul = None\n self.heatKoeff = None\n\nclass WedElement(__Element):\n\n def __init__(self):\n self.ID = None\n self.type = None\n self.order = None\n self.nodeList = []\n self.shape = 'Wedge'\n self.den = None\n self.eModul = None\n self.heatKoeff = None\n\nclass HexElement(__Element):\n\n def __init__(self):\n self.ID = None\n self.type = None\n self.order = None\n self.nodeList = []\n self.shape = 'Hexaeder'\n self.den = None\n self.eModul = None\n self.heatKoeff = None\n\ndef get_element_type(line):\n nodeNumber = 0\n elementListOrder1 = [\"C3D4\", \"C3D6\", \"C3D8\",\n \"DC3D4\", \"DC3D6\", \"DC3D8\",\n \"DCC3D4\", \"DCC3D6\", \"DCC3D8\"]\n elementListOrder2 = [\"C3D10\", \"C3D15\", \"C3D20\",\n \"DC3D10\", \"DC3D15\", \"DC3D20\",\n \"DCC3D10\", \"DCC3D15\", \"DCC3D20\"]\n for elemType in elementListOrder1:\n if elemType in line:\n nodeNumber = int(elemType[-1])\n return elemType, nodeNumber, 1\n for elemType in elementListOrder2:\n if elemType in line:\n nodeNumber = int(elemType[-2] + elemType[-1])\n return elemType, nodeNumber, 2\n return 0, 0, 0\n\n\ndef get_center_of_elem(nodeList):\n\n xc = 0\n yc = 0\n zc = 0\n for node in nodeList:\n xc = node.x + xc\n yc = node.y + yc\n zc = node.z + zc\n n = len(nodeList)\n return [xc / n, yc / n, zc / n]\n\n\n\n\ndef import_elements_nodes_as_dic(FilePath):\n '''The following method reads an a file and extracts the nodes\n and elements\n\n O: Dictonary: With all nodes and their position\n O: Dictonary: With all elements and their node IDs\n '''\n nodeDic = {} # nodeID, xPos, yPos, zPos\n elemDic = {} # elemID, NodeID1, NodeID2 ... NodeID8\n NodeReadingIsActivated = False\n ElementReadingIsActivated = False\n NodeLineReadingIsActivated = False\n inputFile = open(FilePath, \"r\")\n for line in inputFile:\n words = line[0:-1].split(\",\")\n firstWord = words[0]\n if len(firstWord) == 0:\n continue\n firstLetter = firstWord[0]\n if (firstWord[0:5] == \"*Node\"):\n NodeReadingIsActivated = True\n ElementReadingIsActivated = False\n continue\n elif (firstWord[0:8] == \"*Element\"):\n ElementReadingIsActivated = True\n elemType, nodeInEleType, eleOrder = get_element_type(line)\n print (\"Elementtype {} is used\".format(elemType))\n NodeReadingIsActivated = False\n continue\n elif (firstLetter == \"*\"):\n NodeReadingIsActivated = False\n ElementReadingIsActivated = False\n continue\n if ElementReadingIsActivated:\n if not (NodeLineReadingIsActivated):\n nodeList = []\n counter = 0\n for word in words:\n counter += 1\n if counter == 1 and not(NodeLineReadingIsActivated):\n elemID = int(word)\n else:\n nodeList.append(nodeDic[int(word)])\n if not(nodeInEleType == len(nodeList)):\n NodeLineReadingIsActivated = True\n continue\n NodeLineReadingIsActivated = False\n nodeNumber = len(nodeList)\n if nodeNumber == 4 or nodeNumber == 10:\n elem = TetElement()\n elif nodeNumber == 6 or nodeNumber == 15:\n elem = WedElement()\n elif nodeNumber == 8 or nodeNumber == 20:\n elem = HexElement()\n elem.ID = elemID\n elem.nodeList = nodeList\n centerElem = get_center_of_elem(nodeList)\n elem.xc = centerElem[0]\n elem.yc = centerElem[1]\n elem.zc = centerElem[2]\n elem.type = elemType\n elem.order = eleOrder\n elemDic[elemID] = elem\n continue\n if NodeReadingIsActivated and len(words) >= 4:\n nID = int(firstWord)\n nPosX = float(words[1])\n nPosY = float(words[2])\n nPosZ = float(words[3])\n node = Node()\n node.x = nPosX\n node.y = nPosY\n node.z = nPosZ\n node.ID = nID\n nodeDic[nID] = node\n continue\n inputFile.close()\n print (\"Used nodes: \" + str(len(nodeDic)))\n print (\"Used elements: \" + str(len(elemDic)))\n return nodeDic, elemDic\n\n\ndef elem_node_write_in_file(self, solverFile):\n '''The following method reads an a file and extracts the nodes\n and elements\n\n O: Dictonary: With all nodes and their position\n O: Dictonary: With all elements and their node IDs\n '''\n solverFile.write(\"*Node, NSET=Nall \\n\")\n for NodeID in self.nDic:\n xPos = self.nDic[NodeID][0]\n yPos = self.nDic[NodeID][1]\n zPos = self.nDic[NodeID][2]\n solverFile.write(str(NodeID) + \", \" + str(xPos) + \", \" +\n str(yPos) + \", \" + str(zPos) + \"\\n\")\n solverFile.write(\"*Element, TYPE = C3D8, ELSET=Eall\\n\")\n for ElementID in self.eDic:\n solverFile.write(str(ElementID))\n for NodeID in self.eDic[ElementID]:\n solverFile.write(\", \" + str(NodeID))\n solverFile.write(\"\\n\")\n\n\n\n\n\n\n\n# Old class object\nclass NodesElement:\n\n def __init__(self):\n self.nDic = {}\n self.eDic = {}\n\n def get_node_dic(self):\n return self.nDic\n\n def get_elem_dic(self):\n return self.eDic\n\n def set_nDic(self, newNodeDic):\n self.nDic = newNodeDic\n\n def set_eDic(self, newElemDic):\n self.eDic = newElemDic\n\n def add_node(self, ID, positionList):\n self.nDic[ID] = positionList\n\n def add_elem(self, ID, nodeList):\n self.eDic[ID] = nodeList\n\n\n\n def set_nDic_empty(self):\n self.nDic = {}\n\n def set_eDic_empty(self):\n self.eDic = {}\n\n def add_element_node_from_file(self, inputFileName, Type=\"Calculix\"):\n '''The following method reads an a file and extracts the nodes\n and elements\n\n O: Dictonary: With all nodes and their position\n O: Dictonary: With all elements and their node IDs\n '''\n nodeDic = {} # nodeID, xPos, yPos, zPos\n elemDic = {} # elemID, NodeID1, NodeID2 ... NodeID8\n # Activation parameter for start saving elements and nodes\n if Type == \"Calculix\" or Type == \"Abaqus\":\n NodeReadingIsActivated = False\n ElementReadingIsActivated = False\n inputFile = open(inputFileName, \"r\")\n for line in inputFile:\n words = line[0:-1].split(\",\")\n firstWord = words[0]\n if len(firstWord) == 0:\n continue\n firstLetter = firstWord[0]\n if (firstWord[0:5] == \"*Node\"):\n NodeReadingIsActivated = True\n ElementReadingIsActivated = False\n continue\n elif (firstWord == \"*Element\"):\n ElementReadingIsActivated = True\n NodeReadingIsActivated = False\n continue\n elif (firstLetter == \"*\"):\n NodeReadingIsActivated = False\n ElementReadingIsActivated = False\n continue\n if ElementReadingIsActivated:\n nodeList = []\n counter = 0\n for word in words:\n counter += 1\n if counter == 1:\n elemID = int(word)\n else:\n nodeList.append(int(word))\n elemDic[elemID] = nodeList\n continue\n if NodeReadingIsActivated and len(words) >= 4:\n nodeID = int(firstWord)\n nodePosX = float(words[1])\n nodePosY = float(words[2])\n nodePosZ = float(words[3])\n nodeDic[nodeID] = [nodePosX, nodePosY, nodePosZ]\n continue\n inputFile.close()\n for nodeID in nodeDic:\n self.nDic[nodeID] = nodeDic[nodeID]\n for elemID in elemDic:\n self.eDic[elemID] = elemDic[elemID]","sub_path":"BlenderPlugin/ToOptiX/ElementNodes.py","file_name":"ElementNodes.py","file_ext":"py","file_size_in_byte":12836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"288817857","text":"import base64\n\nclass Security:\n def __init__(self, s):\n self.en = \"\"\n self.de = \"\"\n self.s = s\n\n def security_encode(self):\n bytesString = self.s.encode()\n code = base64.b64encode(bytesString)\n self.en = code.decode()\n return self.en\n\n def security_decode(self):\n bytesString = self.s.encode()\n code = base64.b64decode(bytesString)\n self.de = code.decode()\n return self.de\n\n","sub_path":"message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317268260","text":"import threading\nimport time\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG,\n format='(%(threadName)-10s) %(message)s',)\n\ndef daemon():\n logging.debug('starting')\n time.sleep(2)\n logging.debug('exiting')\n\nx=threading.Thread(name='daemon', target=daemon)\nx.setDaemon(True)\n\n\ndef nondaemon():\n logging.debug('starting')\n logging.debug('exiting')\n\n\n\ny=threading.Thread(name='non-daemon', target=nondaemon)\n\nx.start()\ny.start()\n\n","sub_path":"Advance Python/Multithreading/DaemonNonDaemon.py","file_name":"DaemonNonDaemon.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"234636952","text":"import math\n\n\nclass LCDDisplayDesigner:\n def __init__(self, max_width=20, top_left=None, top_right=None, bottom_left=None, bottom_right=None,\n center_top=None, center_bottom=None, bottom=None, top=None):\n\n # check preconditions\n self._ensure_exclusive(top, center_top, [top_left, top_right], False)\n self._ensure_exclusive(bottom, center_bottom, [bottom_left, bottom_right], True)\n self.max_width = max_width\n\n self._top_left = None\n self._top_right = None\n self._center_top = None\n self._top = None\n self._bottom_left = None\n self._bottom_right = None\n self._center_bottom = None\n self._bottom = None\n\n if top_left:\n self.top_left = top_left\n if top_right:\n self.top_right = top_right\n if bottom_left:\n self.bottom_left = bottom_left\n if bottom_right:\n self.bottom_right = bottom_right\n if center_bottom:\n self.center_bottom = center_bottom\n if center_top:\n self.center_top = center_top\n if top:\n self.top = top\n if bottom:\n self.bottom = bottom\n\n @property\n def top_left(self):\n return self._top_left\n\n @top_left.setter\n def top_left(self, value):\n self._top_left = value\n self._center_top = None\n self._top = None\n\n @property\n def top_right(self):\n return self._top_right\n\n @top_right.setter\n def top_right(self, value):\n self._top_right = value\n self._center_top = None\n self._top = None\n\n @property\n def bottom_left(self):\n return self._bottom_left\n\n @bottom_left.setter\n def bottom_left(self, value):\n self._bottom_left = value\n self._center_bottom = None\n self._bottom = None\n\n @property\n def bottom_right(self):\n return self._bottom_right\n\n @bottom_right.setter\n def bottom_right(self, value):\n self._bottom_right = value\n self._center_bottom = None\n self._bottom = None\n\n @property\n def center_top(self):\n return self._center_top\n\n @center_top.setter\n def center_top(self, value):\n self._top_right = None\n self._top_left = None\n self._center_top = value\n self._top = None\n\n @property\n def center_bottom(self):\n return self._center_bottom\n\n @center_bottom.setter\n def center_bottom(self, value):\n self._bottom_right = None\n self._bottom_left = None\n self._center_bottom = value\n self._bottom = None\n\n @property\n def top(self):\n if self._top is not None:\n return self._top\n\n if self._center_top is not None:\n left_spacing, right_spacing = self._get_center_spacing(self.center_top)\n return \" \" * left_spacing + self.center_top + \" \" * right_spacing\n\n if self._top_left is not None or self._top_right is not None:\n return self._get_aligned_format(self.top_left, self.top_right)\n\n return \"\"\n\n @top.setter\n def top(self, value):\n self._top_right = None\n self._top_left = None\n self._center_top = None\n self._top = value\n\n @property\n def bottom(self):\n if self._bottom is not None:\n return self._bottom\n\n if self._center_bottom is not None:\n left_spacing, right_spacing = self._get_center_spacing(self.center_bottom)\n return \" \" * left_spacing + self.center_bottom + \" \" * right_spacing\n\n if self._bottom_left is not None or self._bottom_right is not None:\n return self._get_aligned_format(self.bottom_left, self.bottom_right)\n\n return \"\"\n\n @bottom.setter\n def bottom(self, value):\n self._bottom_right = None\n self._bottom_left = None\n self._center_bottom = None\n self._bottom = value\n\n @staticmethod\n def _ensure_exclusive(a, b, l, is_bottom):\n\n s = \"\"\n if is_bottom:\n s = \"Only ether bottom_left and bottom_right, center_bottom, or bottom may be assigned\"\n else:\n s = \"Only ether top_left and top_right, center_top, or top may be assigned\"\n has_content = False\n is_error = False\n\n if a is not None:\n has_content = True\n\n if b is not None:\n if not has_content:\n has_content = True\n elif has_content:\n is_error = True\n if l[0] is not None or l[1] is not None:\n if has_content:\n is_error = True\n\n if is_error:\n raise RuntimeError(s)\n\n def _get_center_spacing(self, center_text):\n n = (self.max_width - len(center_text)) / 2\n if n < 0:\n n = 0\n return math.ceil(n), math.floor(n)\n pass\n\n def _get_aligned_format(self, left_text, right_text):\n left_text = left_text if left_text is not None else \"\"\n right_text = right_text if right_text is not None else \"\"\n\n n = self.max_width - (len(left_text) + len(right_text))\n if n < 0:\n n = 0\n return left_text + \" \" * n + right_text\n\n def __str__(self):\n return \"['\" + self.top + \"', '\" + self.bottom + \"']\"\n\n def __getitem__(self, item):\n if item == 0:\n return self.top\n else:\n return self.bottom\n","sub_path":"panels/lcddisplaydesigner.py","file_name":"lcddisplaydesigner.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119958578","text":"from matrix import Matrix\n\"\"\" TASK ONE \"\"\"\n\n\nif __name__ == '__main__':\n \n # Loading a Matrix from a file.\n\n # I prefer to use JSON for this format, so see attached *.json files.\n M = Matrix()\n M.load_file('example_mtx_two.json')\n print(M)\n\n\n # A matrix times a matrix.\n A = Matrix()\n A.load_file('matrix_two.json')\n C = A * M\n print(C)\n\n\n\n\n# a times b\n# implemented. need to finalize and test. \n\n\n\n# a transpose\n# done\n# times b\n\n# create a thing in transpose.\n\n\n# a = a transpose in csr format\n\n\n\n# c = a times b in transpose\n\n# gmres algorithm\n\n\n\n\n\n# Config parser ? \n#\n# Have options available be :\n# display matrix from file (file args need to be provided.)\n# transpose a matrix (args: -f [FILE] -f [new file name])\n# multiply two matricies (args -f [FILE] -f [FILE] -n [NEW FILE NAME])\n\n\n# Perhaps do RESTFUL style where you can provide action ? \n# or you can have two files with a matrix and an arg that means to multiply\n# GMRES option. needs the arguments to be passed in. \n\n\n","sub_path":"gmres.py","file_name":"gmres.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"634099167","text":"import importlib\nimport sys\nimportlib.reload(sys)\nimport os\nimport pymysql\nimport pymysql.cursors\nimport time\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom flask import *\n\nfrom preLogin import loginResult\nfrom showData import show\nfrom ehallTool.aiutil import airoot\n\nfrom config import *\n\n\napp = Flask(__name__)\napp.secret_key = os.urandom(24)\n\nusername = '20161040170'\n\n@app.route('/')\ndef prelogin():\n return redirect(url_for(\"login\")) # 重定向到登录\n\n@app.route('/login/', methods=['GET', 'POST'])\ndef login():\n if request.method == 'GET': # get 登录界面\n return render_template(\"login.html\")\n\n if request.method == \"POST\": # 在登录界面提交表单\n global username\n\n username = request.form.get(\"username\") # 获取username\n password = request.form.get(\"password\") # 获取password\n\n \"\"\" 登录校验 \"\"\"\n if username != '' and password != '' and username.isdigit() and len(username)==11:\n login_result = loginResult.get_result(username, password)\n\n if login_result:\n # 登录成功\n flash(\"登录成功!\")\n return redirect(url_for(\"index\", username=username)) # 登录成功跳转首页\n\n else:\n # 登录失败\n flash(\"登录失败!\") # 页面显示闪现消息\n return render_template(\"login.html\")\n else:\n flash(\"登录失败!\") # 页面显示闪现消息\n return render_template(\"login.html\")\n\n\n@app.route('/index/')\ndef index():\n username = request.args.get(\"username\")\n\n return render_template(\"index.html\", username=username)\n\n\n@app.route('/ai_root/', methods=['GET', 'POST'])\ndef ai_root():\n if request.method == 'POST':\n word = request.form.get('word')\n # 这里调用对象的方法\n res = airoot().getword(word)\n return render_template('ai_root.html', res=res)\n else:\n return render_template('ai_root.html', res='')\n\n\n\n@app.route('/welcome/')\ndef welcome():\n username = request.args.get(\"username\")\n return render_template(\"welcome.html\", username=username)\n\n\n# 初始化学期,默认显示入学第一学期信息\nterm = str(int(username) - 1) + '-' + username[:4] + \"-2\"\n\n\n@app.route('/index//course/', methods=['POST', 'GET'])\ndef course(username):\n\n global term\n\n if request.method == 'GET':\n courses = show.Show(username).course(term)\n\n if courses is not None:\n return render_template(\"course.html\", courses=courses, term=int(username[:4]), username=username)\n else:\n term = \"2017-2018-1\"\n return render_template(\"nothing.html\")\n\n if request.method == 'POST':\n chooseTerm = request.get_data().decode(\"utf-8\")\n\n year = chooseTerm[:4]\n season = \"1\"\n if chooseTerm[5] == \"秋\":\n season = \"2\"\n\n term = str(int(year)-1) + \"-\" + year + \"-\" + season\n print(term)\n return \"选取学期\", term\n\n\n@app.route('/index//grades/', methods=['POST', 'GET'])\ndef grades(username):\n\n global term\n\n if request.method == \"GET\":\n grades = show.Show(username).grades(term)\n if grades is not None:\n return render_template(\"grades.html\", grades=grades, term=int(username[:4]), username=username)\n else:\n term = \"2017-2018-1\"\n return render_template(\"nothing.html\")\n\n if request.method == 'POST':\n chooseTerm = request.get_data().decode(\"utf-8\")\n\n year = chooseTerm[:4]\n season = \"1\"\n if chooseTerm[5] == \"秋\":\n season = \"2\"\n\n term = str(int(year) - 1) + \"-\" + year + \"-\" + season\n print(term)\n return \"选取学期\", term\n\n\n@app.route('/index//exams/', methods=['POST', 'GET'])\ndef exams(username):\n global term\n\n if request.method == \"GET\":\n exams = show.Show(username).exam(term)\n if exams is not None:\n return render_template(\"exams.html\", exams=exams, term=int(username[:4]), username=username)\n else:\n term = \"2017-2018-1\"\n return render_template(\"nothing.html\")\n\n if request.method == 'POST':\n chooseTerm = request.get_data().decode(\"utf-8\")\n\n year = chooseTerm[:4]\n season = \"1\"\n if chooseTerm[5] == \"秋\":\n season = \"2\"\n\n term = str(int(year) - 1) + \"-\" + year + \"-\" + season\n print(term)\n return \"选取学期\", term\n\n\n# 增加\n\n# 连接数据库\ndef connectdb():\n db = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=DATABASE, charset='utf8')\n cursor = db.cursor()\n db.autocommit(True)\n\n return (db, cursor)\n\ndef createdb():\n (db, cursor) = connectdb()\n\n \"\"\" 创建表 \"\"\"\n sql = \"\"\"CREATE TABLE IF NOT EXISTS `Blog` (\n `id` int(20) NOT NULL AUTO_INCREMENT,\n `title` char(100) NOT NULL ,\n `content` varchar(16383) DEFAULT NULL,\n `timestamp` char(255) DEFAULT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8; \"\"\"\n cursor.execute(sql)\n\n# 关闭数据库\ndef closedb(db,cursor):\n db.close()\n cursor.close()\n\n\n# 首页 /index//exams/\n@app.route('/blog/')\ndef blog():\n createdb()\n return render_template('blog.html')\n\n\n# 处理表单提交\n@app.route('/handle', methods=['POST'])\ndef handle():\n # 获取post数据\n data = request.form\n\n # 连接数据库\n (db,cursor) = connectdb()\n\n # 添加数据\n cursor.execute(\"INSERT INTO Blog(title, content, timestamp) VALUES(%s, %s, %s)\",\n [data['title'] + \" 作者:\"+ username, data['content'], str(int(time.time()))])\n\n # 最后添加行的id\n post_id = cursor.lastrowid\n\n # 关闭数据库\n closedb(db,cursor)\n\n return redirect(url_for('post', post_id=post_id))\n\n# 文章列表页\n@app.route('/list')\ndef listb():\n # 连接数据库\n (db,cursor) = connectdb()\n\n # 获取数据\n cursor.execute(\"SELECT * FROM Blog\")\n posts = cursor.fetchall()\n\n # 格式化时间戳\n new_posts = []\n for post in posts:\n post = list(post)\n post[-1] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(post[-1])))\n\n new_posts.append(list(post))\n\n # 关闭数据库\n closedb(db,cursor)\n\n # 后端向前端传递数据\n return render_template('list.html', posts=new_posts)\n\n\n# 文章详情页\n@app.route('/post/')\ndef post(post_id):\n # 连接数据库\n (db,cursor) = connectdb()\n\n # 查询数据\n cursor.execute(\"SELECT * FROM Blog WHERE id = %s\", [post_id])\n post = cursor.fetchone()\n\n # 格式化时间戳\n post = list(post)\n post[-1] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(post[-1])))\n\n # 关闭数据库\n closedb(db,cursor)\n\n # 后端向前端传递数据\n return render_template('post.html', post=post)\n\n\nif __name__ == '__main__':\n app.run(host=WEB_HOST, port=WEB_PORT, debug=DEBUG)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"542381275","text":"\"\"\"This is our birthday module.\"\"\"\n\nimport csv\n\n\"\"\"Open list_of_guitarists.csv file and turn it to dictionary.\"\"\"\n\nreader = csv.reader(open('guitarists_package/list_of_guitarists.csv', 'r'))\nguitarists_list = {}\nfor row in reader:\n k, v = row\n guitarists_list[k] = v\n\n\n\"\"\"These are the functions.\"\"\"\n\n\ndef check_guitarist(guitar_player):\n if guitar_player in guitarists_list:\n return guitarists_list[guitar_player]\n else:\n return False\n\ndef check_band(band_name):\n for guitarist, band in guitarists_list.items():\n if band == band_name:\n return guitarist\n \n return False","sub_path":"guitarists_package/guitarists_band_check.py","file_name":"guitarists_band_check.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"149924205","text":"import time\nfrom math import *\n\n\ndef loadMatrix(filename):\n matrix = []\n lines = open(filename, \"r\").readlines()\n for line in lines:\n row = []\n for token in line.replace('\\n', '').split(','):\n row.append(int(token))\n matrix.append(row)\n return matrix\n\ndef isPrime(m):\n if m == 1:\n return False\n if m == 2 or m == 3:\n return True\n for i in range(2, int(sqrt(m))+1):\n if m % i == 0:\n return False\n return True\n\ndef primesUpTo(m):\n tStart = time.time()\n sieve = getSieve(m)\n primes = [2]\n for i in range(3, m, 2):\n if sieve[i]:\n primes.append(i)\n print(len(primes), \"prime numbers below\", m, \"in \" + str(time.time() - tStart), \"s\")\n return primes\n \ndef getSieve(m):\n sieve = [True] * m\n sieve[1] = False\n i = 3\n while i*i < m:\n if sieve[i]:\n for j in range(i*i,m,i):\n sieve[j] = False\n i += 2\n return sieve\n \ndef totient(n, primes):\n factors = getSinglePrimeFactors(n, primes)\n tot = n\n for p in factors:\n tot -= tot//p\n return tot\n \ndef rad(a, primes):\n factors = getSinglePrimeFactors(a, primes)\n p = 1\n for f in factors:\n p *= f\n return p\n \ndef getSinglePrimeFactors(n, primes):\n factors = []\n for p in primes:\n if n % p == 0:\n factors.append(p)\n n = n // p\n while n % p == 0:\n n = n // p\n if n == 1:\n return factors\n if p*p > n:\n factors.append(n)\n return factors\n factors.append(n)\n return factors\n \ndef conFraction(a):\n root = sqrt(a)\n if root == int(root):\n return [int(root)]\n \n current = [1,int(root),1,int(root)]\n all, res = [], []\n while not current in all:\n all.append(current)\n res.append(current[3])\n current = nextCF(a, current)\n return res\n \n\ndef nextCF(a, input):\n x = input[0]\n y = input[1]\n w = input[2]\n z = int((x*w*sqrt(a)+x*y)/(w**2*a-y**2))\n output = []\n output.append(w*a-y**2)\n output.append(-x*y+z*a*w**2-z*y**2)\n output.append(x*w)\n output.append(z)\n minimizeCF(output)\n return output\n \n \ndef minimizeCF(list):\n if list[0] < 0:\n list[0] = -list[0]\n list[1] = -list[1]\n list[2] = -list[2]\n g = trgcd(list[0],list[1],list[2])\n list[0] = list[0]//g\n list[1] = list[1]//g\n list[2] = list[2]//g\n\ndef trgcd(a,b,c):\n return gcd(a,gcd(b,c))\n\ndef gcd(a,b):\n if b == 0:\n return a\n else:\n return gcd(b, a % b)","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"38892889","text":"import sys\nimport os.path\n\ndef xxd(file_path):\n f=open(file_path,'r')\n s=0\n while True:\n r=f.read(16)\n d=r\n if not r:\n break\n he=[]\n for i in r:\n he.append('%02x'%ord(i))\n he2=[]\n for z in range(0,len(he),2):\n he2.append(''.join((he[z:z+2])))\n ch=[]\n for c in d:\n cc=ord(c)\n if cc<32 or cc>127:\n ch.append('.')\n else:\n ch.append(c)\n step=('%08x'%(s*16))\n print('{0}: {1:<39} {2}'.format(step,' '.join(he2),''.join(ch)))\n s=s+1\n\nif not os.path.exists(sys.argv[1]):\n print('your enter is wrong')\n sys.exit(1)\nxxd(sys.argv[1])\n","sub_path":"assignment01.py","file_name":"assignment01.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350414634","text":"# Simple program to create a log file\nimport datetime\n\n\ndef create_log(path, message):\n try:\n f = open(path, \"a\")\n except OSError as e:\n print(\"something went wrong: \" + e.strerror)\n quit()\n x = datetime.datetime.now()\n f.write(x.strftime(\"%D/%Y, %H:%M:%S\") + \" \" + message + \"\\n\")\n f.close()\n\n\ncreate_log(\"C:\\\\Users\\\\yitzh\\\\Documents\\\\my_log.txt\", \"new log entry\")\n","sub_path":"Lecture_2/exercise_1.py","file_name":"exercise_1.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112803388","text":"class State:\n \n def __init__(self, grid, row, col, endRow, endCol, targetVal, currentVal, gridRows, gridCols, history):\n self.grid = grid\n self.currentRow = row\n self.currentCol = col\n self.history = history\n self.endRow = endRow\n self.endCol = endCol\n self.targetValue = targetVal\n self.currentValue = currentVal\n self.gridRows = gridRows\n self.gridCols = gridCols\n\n def changeGrid(self, row, col, value):\n # changes position in grid to a different value \n self.grid[int(row)][int(col)] = value\n\n def __str__(self): # returns string of the current state (need to fix formating)\n tab = \" \"\n gridstring = \"\"\n for r in range(self.gridRows): # traverse through rows of grid\n gridstring += \"\\n \"\n for c in range(self.gridCols): # traverse through columns in each row\n gridstring += str(self.grid[r][c])\n if self.grid[r][c] == \"X\": # spaces for X\n gridstring += \" \"\n elif int(self.grid[r][c]) < 10: # spaces for 1 digit nums\n gridstring += \" \"\n elif int(self.grid[r][c]) < 100: # spaces for 2 digit nums\n gridstring += \" \"\n else: # spaces for 3 digit nums \n gridstring += \" \"\n return tab + \"Grid:\" + gridstring + \"\\n\" + tab + \"history:\" + str(self.history) + \"\\n\" + tab + \"start point: (\" + str(self.currentRow) + \",\" + str(self.currentCol) + \")\" +\"\\n\" + tab + \"sum so far: \" + str(self.currentValue) +\"\\n\"\n\ndef isValidMove(state, row, col):\n if row < 0 or col < 0 or row >= state.gridRows or col >= state.gridCols: # if its in the boundaries of the maze\n return False\n elif state.grid[row][col] == \"X\": # if there isn't a bread crumb there \n return False\n else: \n return True \n\ndef solve(thisState):\n # this will recursively solve a maze represented by thisState\n print(\"Is this a goal state?\") \n if thisState.currentValue == thisState.targetValue and thisState.endRow == thisState.currentRow and thisState.endCol == thisState.currentCol:\n print(\"Yes!\") \n return thisState.history # the maze is solved :)\n \n elif thisState.currentValue > thisState.targetValue: # if the sum has gone too high\n print(\"Target exceeded: abandoning path\")\n \n # need to figure out how to remove X from wrong path and value from history\n # current value backtracks but grid and history do not... so what is the problem? what is different between the two?\n # if only the Xs would just go away when backtracking then it would find the solution and not get stuck :(\n \n \n else: # still need to do work to solve the maze\n print(\"No.\")\n print(\"Can I move right?\") \n if isValidMove(thisState, thisState.currentRow, thisState.currentCol + 1): # moving right valid\n print(\"Yes!\")\n print(\"Paused... \\n\")\n # create a new State one space right \n newState = State(thisState.grid, thisState.currentRow, thisState.currentCol + 1, thisState.endRow, thisState.endCol, thisState.targetValue, thisState.currentValue, thisState.gridRows, thisState.gridCols, thisState.history) \n # append the new location to the state history\n newState.history.append(newState.grid[newState.currentRow][newState.currentCol])\n # add to the sum \n newState.currentValue = thisState.currentValue + int(newState.grid [newState.currentRow] [newState.currentCol])\n # change the current position in the grid to a x\n newState.changeGrid(newState.currentRow, newState.currentCol, \"X\")\n print(\"Problem is now:\")\n print(newState) # (for debugging purposes)\n\n result = solve(newState)\n if result != None:\n return newState.history\n\n print(\"No.\")\n print(\"Can I move up?\") \n if isValidMove(thisState, thisState.currentRow - 1, thisState.currentCol): # Moving up is valid\n print(\"Yes!\")\n print(\"Paused... \\n\")\n # create a new State one space up\n newState = State(thisState.grid, thisState.currentRow - 1, thisState.currentCol, thisState.endRow, thisState.endCol, thisState.targetValue, thisState.currentValue, thisState.gridRows, thisState.gridCols, thisState.history)\n # append the new location to the state history\n newState.history.append(newState.grid[newState.currentRow][newState.currentCol])\n # add to the sum \n newState.currentValue = thisState.currentValue + int(newState.grid [newState.currentRow] [newState.currentCol])\n # change the current position in the grid to a X\n newState.changeGrid(newState.currentRow, newState.currentCol, \"X\")\n print(\"Problem is now:\")\n print(newState) # (for debugging purposes)\n\n result = solve(newState) # recursively keep solving \n if result != None:\n return newState.history\n \n print(\"No.\")\n print(\"Can I move down?\") \n if isValidMove(thisState, thisState.currentRow + 1, thisState.currentCol): # moving down is valid\n print(\"Yes!\")\n print(\"Paused... \\n\")\n # create a new State one space down \n newState = State(thisState.grid,thisState.currentRow + 1,thisState.currentCol, thisState.endRow, thisState.endCol, thisState.targetValue, thisState.currentValue, thisState.gridRows, thisState.gridCols, thisState.history)\n # append the new location to the state history\n newState.history.append(newState.grid[newState.currentRow][newState.currentCol])\n # add to the sum \n newState.currentValue = thisState.currentValue + int(newState.grid [newState.currentRow] [newState.currentCol])\n # change the current position in the grid to a x\n newState.changeGrid(newState.currentRow, newState.currentCol, \"X\")\n print(\"Problem is now:\")\n print(newState) # (for debugging purposes)\n\n result = solve(newState) # recursively keep solving \n if result != None:\n return newState.history\n \n print(\"No.\")\n print(\"Can I move left?\") \n if isValidMove(thisState, thisState.currentRow, thisState.currentCol - 1): # moving left valid\n print(\"Yes!\")\n print(\"Paused... \\n\")\n # create a new State one space left\n newState = State(thisState.grid, thisState.currentRow, thisState.currentCol - 1, thisState.endRow, thisState.endCol, thisState.targetValue, thisState.currentValue, thisState.gridRows, thisState.gridCols, thisState.history) \n \n # append the new location to the state history\n newState.history.append(newState.grid[newState.currentRow][newState.currentCol])\n # add to the sum \n newState.currentValue = thisState.currentValue + int(newState.grid [newState.currentRow] [newState.currentCol])\n # change the current position in the grid to a x\n newState.changeGrid(newState.currentRow, newState.currentCol, \"X\")\n print(\"Problem is now:\")\n print(newState) # (for debugging purposes)\n\n result = solve(newState)\n if result != None:\n return newState.history\n \n\n print(\"Couldn't move in any direction. Backtracking.\")\n \n return None\n\n\ndef main():\n\n f = open(\"MazeData.txt\", \"r\") # opens text for reading file\n line = f.readline() # reads a line\n commandList = line.split() # splits line up at spaces into list\n\n # read the number of rows, number of columns, startRow, and startCol\n targetValue = int(commandList[0])\n grid_rows = int(commandList[1])\n grid_cols = int(commandList[2])\n start_row = int(commandList[3])\n start_col = int(commandList[4])\n end_row = int(commandList[5])\n end_col = int(commandList[6]) \n\n # read in the grid\n grid = []\n line = f.readline() # move on to next line\n rowList = []\n while line != \"\":\n inputList = line.split() \n grid.append(inputList)\n line = f.readline()\n\n # set up start state\n thisState = State(grid, start_row, start_col, end_row, end_col, targetValue, 0, grid_rows, grid_cols, []) # create a new State object\n thisState.history.append(thisState.grid[start_row][start_col]) # add starting point to history \n thisState.currentValue = int(thisState.grid [start_row][start_col]) # add starting point to sum \n thisState.changeGrid(start_row, start_col, 'X') # mark the current position with a X\n print(thisState) # for debugging purposes \n \n\n result = solve(thisState) # result will be None or the goal state's history\n\n if result == None:\n print(\"No solution exists\")\n else:\n print(\"The solution is: \",result)\n\nmain()\n","sub_path":"SumMaze.py","file_name":"SumMaze.py","file_ext":"py","file_size_in_byte":8905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175731975","text":"import pygame\nimport random\nimport math\n\nclass Ball():\n\n def __init__(self, x_loc, y_loc): # Constructor class for the \"Ball\" object\n self.x_loc = x_loc\n self.y_loc = y_loc\n self.direction = random.randrange(0, 360)\n self.color = [random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256)]\n self.size = 20\n\n def move(self):\n path = math.radians(self.direction) # Converts the degrees path we have to an equivalent in radians\n self.x_loc += math.cos(path) # Math\n self.y_loc -= math.sin(path) # Math\n\n def draw(self, screen):\n # pygrame draws a circle to (screem we made, color list we defined, [x coordinate of ball, y coordinate of ball], radius equal to the size of the ball)\n pygame.draw.circle(screen, self.color, [int(self.x_loc), int(self.y_loc)], self.size)\n\n def changeColor(self, r, g, b): # Change color method takes in 3 values to change color of ball\n self.color = [r, g, b] # Sets the color list of the ball to be a list equal to the inputted rgb values\n\ndef main():\n ball_main = Ball(SCREEN_WIDTH/2, SCREEN_HEIGHT/2) # The original ball\n ball_list = [] # Constructing the array of all the balls\n ball_list.append(ball_main) # Adding the original ball to the list of balls\n\n exitFlag = False\n while not exitFlag:\n event = pygame.event.poll() # Checks if an even was performed\n if event.type == pygame.QUIT: # If the event performed was \"clicking the red x to exit\"\n exitFlag = True # Exit the program\n if event.type == pygame.MOUSEBUTTONDOWN: # If the event performed was \"clicking the mouse\"\n ball_list.append(Ball(event.pos[0], event.pos[1])) # Add a ball to the list with the mouse coordinates as the x_loc and y_loc\n # THE GAME\n for ball in ball_list: # Iterates through the list of ball\n ball.move() # Use the ball objects move function to move the ball slightly\n ball.draw(screen) # Draws the ball to the scren\n pygame.display.flip() # Update the display\n screen.fill((0, 0, 0)) # Covers all previous actions of the display\n\n # Loops through the list of ball, if a ball meets the condiiton of hitting an edge, reflects it\n for ball in ball_list:\n if (ball.x_loc < 0 + ball.size or ball.x_loc > SCREEN_WIDTH - ball.size): # If ball hits left or right\n if (ball.x_loc < 0 + ball.size): # If ball hits left\n ball.changeColor(0, 0, 255) # Change the color to blue\n else: # If ball hits right\n ball.changeColor(255, 0, 0) # Change the color to red\n ball.direction = 180 - ball.direction # Direction change for left and right\n elif (ball.y_loc < 0 + ball.size or ball.y_loc > SCREEN_HEIGHT - ball.size): # If ball hits top or bot\n if (ball.y_loc < 0 + ball.size): # If ball hits top\n ball.changeColor(0, 255, 0) # Change the color to green\n else: # If ball hits bot\n ball.changeColor(255, 0, 255)# Change the color to purple\n\n ball.direction = 360 - ball.direction # Direction change for top and bottom\n\nSCREEN_WIDTH = 800 # The intended width of the screen\nSCREEN_HEIGHT = 600 # The intended height of the screen\nscreen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # Creates the screen using the pre-set width and height we have defined\nmain()\n","sub_path":"balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235038057","text":"#!/usr/bin/env python\n\n# This node publishes wave, spectrogram and volume topics from microphone\n\nfrom sound_classification.msg import Spectrum, Volume, Wave\nimport numpy as np\nimport os.path as osp\nimport pyaudio\nimport rospkg\nimport rospy\nimport sys\n\n\nclass ListenMicrophone:\n\n def __init__(self):\n # init rospy node\n rospy.init_node('listen_microphone', anonymous=True)\n self.p = pyaudio.PyAudio()\n # config for microphone\n self.microphone_name = rospy.get_param('/microphone/name', 'default')\n self.length = rospy.get_param('/microphone/length', 512) # length relates hamming window range\n self.rate = rospy.get_param('/microphone/rate', 44100)\n self.channels = 1\n self.format = pyaudio.paFloat32\n rospack = rospkg.RosPack()\n file_path = osp.join(rospack.get_path(\n 'sound_classification'), 'scripts', 'mean_noise_sound.npy')\n if osp.exists(file_path):\n self.mean_noise_sound = np.load(file_path)\n else:\n rospy.logerr('create mean noise sound by rosrun sound_classification save_noise_sound.py')\n exit()\n # search for microphone\n self.device_index = True\n for index in range(0, self.p.get_device_count()):\n device_info = self.p.get_device_info_by_index(index)\n if self.microphone_name in device_info['name']:\n self.device_index = device_info['index']\n if self.device_index is True:\n print('Cannot find audio device!')\n sys.exit()\n # config for fft\n self.data = np.zeros((self.length, self.channels))\n self.window = np.hamming(self.length)\n self.stream = self.p.open(format=self.format,\n channels=self.channels,\n rate=self.rate,\n input=True,\n output=False,\n input_device_index=self.device_index,\n frames_per_buffer=self.length)\n\n # publisher\n self.wave_pub = rospy.Publisher( # sound wave data, the length is self.length\n '/microphone/wave', Wave, queue_size=1)\n self.spectrum_raw_pub = rospy.Publisher( # sound spectrum, which is fft of wave data\n '/microphone/sound_spec_raw', Spectrum, queue_size=1)\n self.spectrum_pub = rospy.Publisher( # sound spectrum, which is fft of wave data\n '/microphone/sound_spec', Spectrum, queue_size=1)\n self.vol_pub = rospy.Publisher( # current volume\n '/microphone/volume', Volume, queue_size=1)\n\n # published msg\n self.wave_msg = Wave()\n self.spec_raw_msg = Spectrum()\n self.spec_msg = Spectrum()\n self.vol_msg = Volume()\n\n def process(self):\n stamp = rospy.Time.now()\n tmp = self.stream.read(self.length) # sound input -> float32 array\n data = np.fromstring(tmp, np.float32)\n self.data = np.array(data)\n\n # calc wave\n wave = self.data\n self.wave_msg.wave = wave\n self.wave_msg.header.stamp = stamp\n\n # calc volume\n vol = np.sqrt(np.mean(self.data**2)) # effective value\n self.vol_msg.volume = vol\n self.vol_msg.header.stamp = stamp\n\n # calc spectrum\n spec = np.abs(np.fft.fft(wave*self.window))\n self.spec_raw_msg.spectrum = spec\n self.spec_raw_msg.header.stamp = stamp\n try:\n spec = spec - self.mean_noise_sound\n spec = np.where(spec > 0, spec, self.mean_noise_sound * 0.01) # Spectral Subtraction method\n except ValueError:\n rospy.logwarn('mean_noise_sound.npy may be old. $ roslaunch sound_classification save_noise_sound.launch')\n self.spec_msg.spectrum = spec\n self.spec_msg.header.stamp = stamp\n\n # publish msg\n self.wave_pub.publish(self.wave_msg)\n self.vol_pub.publish(self.vol_msg)\n self.spectrum_raw_pub.publish(self.spec_raw_msg)\n self.spectrum_pub.publish(self.spec_msg)\n\n def destruct(self):\n self.stream.stop_stream()\n self.stream.close()\n self.p.terminate()\n\n def run(self):\n try:\n while not rospy.is_shutdown():\n self.process()\n except rospy.ROSInterruptException:\n self.destruct()\n\n\nif __name__ == '__main__':\n lm = ListenMicrophone()\n lm.run()\n","sub_path":"scripts/listen_microphone.py","file_name":"listen_microphone.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78106355","text":"import gmpy2\nfrom binascii import hexlify\nfrom Crypto.Util import number\nfrom Crypto.Hash import SHA256\nfrom Crypto.Cipher import AES\n\n\ndef do_hash(data):\n h = SHA256.new()\n h.update(data)\n return h\n\nn_len = 128\n\nwhile True:\n p = number.getPrime(n_len)\n q = number.getPrime(n_len)\n n = p * q\n phi = n - (p + q - 1)\n\n e = 3\n if number.GCD(e, phi) == 1:\n break\n print(\"gcd != 1\")\n\nprint(\"p: {}\".format(p))\nprint(\"q: {}\".format(q))\nprint(\"n: {}\".format(n))\n\nd = number.inverse(e, phi)\nprint(\"d: {}\".format(d))\n\nh = do_hash(number.long_to_bytes(d))\nprint(h.hexdigest())\nkey = h.digest()\n\nflag = b\"UiO-CTF{look_ma_i_know_how_to_crypto}\"\n\niv = \"\\x00\" * AES.block_size\ncipher = AES.new(key, AES.MODE_CFB, iv)\nmsg = cipher.encrypt(flag)\n\nprint(hexlify(msg))\n","sub_path":"crypto/rsa/src/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"44681398","text":"# Linear Regression with Tensorflow\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\ntf.compat.v1.disable_v2_behavior()\ntf.compat.v1.disable_eager_execution()\n# tf.debugging.set_log_device_placement(True)\nprint(\"tf.test.is_gpu_available?\",tf.test.is_gpu_available())\n\ndatabase = np.genfromtxt('database/Data Set.csv',delimiter=',')\n\nx1 = (database[1:,2]-460.27)/180.3 # RF POWER\nx2 = (database[1:,3]-900)/48.9 # Pressure\nx3 = (database[1:,4]-98.7)/23.7 # SiH4 sccm\nx4 = (database[1:,5]-66.2)/9.5 # NH3 sccm\nx5 = (database[1:,6]-1526.9)/311.3 # N2 sccm\ny = database[1:,7] # Tensile Stress\nn = len(y)\n\nX1 = tf.compat.v1.placeholder(tf.float32)\nX2 = tf.compat.v1.placeholder(tf.float32)\nX3 = tf.compat.v1.placeholder(tf.float32)\nX4 = tf.compat.v1.placeholder(tf.float32)\nX5 = tf.compat.v1.placeholder(tf.float32)\nY = tf.compat.v1.placeholder(tf.float32)\n\nW1 = tf.Variable(np.random.randn(), name = \"W1\")\nW2 = tf.Variable(np.random.randn(), name = \"W2\")\nW3 = tf.Variable(np.random.randn(), name = \"W3\")\nW4 = tf.Variable(np.random.randn(), name = \"W4\")\nW5 = tf.Variable(np.random.randn(), name = \"W5\")\nb = tf.Variable(np.random.randn(), name = \"b\")\n\nC = []\n\nlearning_rate = 0.02\ntraining_epochs = 1000\n\n# Hypothesis\n### y_pred = tf.add(tf.add(tf.add(tf.add(tf.add(tf.multiply(X1, W1), tf.multiply(X2, W2)), tf.multiply(X3, W3)), tf(multiply(X4,W4))),tf(multiply(X5,W5))),b)\ny_pred = X1*W1 + X2*W2 + X3*W3 + X4*W4 + X5*W5 + b\n\n# Mean Squared Error Cost Function\ncost = tf.reduce_sum(tf.pow(y_pred - Y, 2)) / (2 * n)\n\n# Gradient Descent Optimizer\noptimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# Global Variables Initializer\ninit = tf.compat.v1.global_variables_initializer()\n\n# Starting the Tensorflow Session\nwith tf.compat.v1.Session() as sess:\n # Initializing the Variables\n sess.run(init)\n\n # Iterating through all the epochs\n for epoch in range(training_epochs):\n\n # Feeding each data point into the optimizer using Feed Dictionary\n for (_x1, _x2, _x3, _x4, _x5, _y) in zip(x1, x2, x3, x4, x5, y):\n sess.run(optimizer, feed_dict={X1:_x1, X2:_x2,X3:_x3,X4:_x4,X5:_x5, Y:_y})\n\n # Displaying the result after every 50 epochs\n if (epoch + 1) % 50 == 0:\n # Calculating the cost a every epoch\n c = sess.run(cost, feed_dict={X1:_x1, X2:_x2,X3:_x3,X4:_x4,X5:_x5, Y:_y})\n print(\"Epoch\", (epoch + 1), \": cost =\", c, \"W1 =\", sess.run(W1), \"W2 =\", sess.run(W2),\"W3 =\", sess.run(W3),\"W4 =\", sess.run(W4),\"W5 =\", sess.run(W5),\"b =\", sess.run(b))\n C.append(c)\n # Storing necessary values to be used outside the Session\n training_cost = sess.run(cost, feed_dict={X1:_x1, X2:_x2,X3:_x3,X4:_x4,X5:_x5, Y:_y})\n weight1 = sess.run(W1)\n weight2 = sess.run(W2)\n weight3 = sess.run(W3)\n weight4 = sess.run(W4)\n weight5 = sess.run(W5)\n bias = sess.run(b)\n\n#Normalized Weights\nprint(weight1, weight2, weight3, weight4, weight5, bias)\nprint(C)\n","sub_path":"Regression_Model_without_Devset.py","file_name":"Regression_Model_without_Devset.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502668688","text":"import scrapy\n\nfrom scrapy.selector import Selector\nfrom lspiders.items import LspidersItem\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com','httpbin.org']\n start_urls = ['https://maoyan.com/films?showType=3']\n\n def start_requests(self):\n # for week01 homework target, set range max value is 1\n for i in range(0 ,1):\n url = f'https://maoyan.com/films?showType=3&offset={i*30}'\n yield scrapy.Request(url=url, callback=self.parse,errback=self.on_err)\n \n # 确实作业异常部分有点让人费解,感觉任何异步回调的框架本身就应该是带捕获处理的,所以这里加异常大多不应该针对框架完成的主流程(请求、通过代理请求等)\n def on_err(self,failure):\n print(\"FAIL\")\n self.logger.error(failure)\n\n # 还没来得及改批改部分,仅增加了一些打印\n def parse(self, response):\n # 这里纯粹是为了强行加上异常处理,按说一个字典的key应该这么费劲么\n try:\n debug_info = response.request.meta['proxy']\n print(f\"PARSE proxy : {response.url},{debug_info}\")\n except KeyError as e:\n self.logger.critical(f'proxy key ? : {e}')\n print(f\"PARSE without proxy : {response.url},{response.request.meta}\")\n \n '''\n + 下面这个httpbin仅为调试用\n + 纯粹是为了瞜一眼到底用没用代理... \n - 一开始以为是httpbin.org慢,最后才发现应该是maoyan在start_requests里面就没用代理...\n - 慢的都是用了代理之后的请求\n + 本来想象的调试异常的case是:\n - 配置错误的代理地址,然后捕获相关异常,把异常的作业部分完成\n - 不过就是试图调这个case时候,发现,捅猫眼确实没用代理啊,response.request.meta 中才是检查是否设置了代理的正牌检查方法\n + 最后我是把middlewares里面抄的老师的代码稍微改了一下走了代理\n\n '''\n yield scrapy.Request(url='https://httpbin.org/ip', callback=self.checkIp)\n divs_with_hover = Selector(response=response).xpath('//div[@class=\"movie-item-hover\"]')\n divs_with_hover = divs_with_hover[:10]\n print(len(divs_with_hover))\n for div in divs_with_hover:\n\n print(div.xpath(\"./a/@href\").get())\n\n # 时间所限,还没顾得上去按批改意见改进以下内容\n item_divs = div.xpath('.//div[@class=\"movie-hover-title\"]')\n item_divs_time = div.xpath('.//div[@class=\"movie-hover-title movie-hover-brief\"]')\n item_divs = item_divs+ item_divs_time\n\n item = LspidersItem()\n for item_div in item_divs:\n text_content = item_div.get()\n # print(text_content)\n if '类型' in text_content:\n item['title'] = item_div.attrib[\"title\"]\n item['genre'] = \"\".join(item_div.xpath('./text()').getall()).strip()\n elif '上映时间' in text_content:\n item['release_time'] = \"\".join(item_div.xpath('./text()').getall()).strip()\n yield item\n \n # 调试用的,看看到底特么用没用代理\n def checkIp(self,response):\n print(f\"PARSE: {response.url},{response.request.meta}\")\n # 好像应该证明是真用了\n print(f'IP is {response.text}')\n\n","sub_path":"week02/w02-homework-scrapy-selector/lspiders/lspiders/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"55267035","text":"\"\"\"CircuitPython Essentials Storage logging boot.py file\"\"\"\r\nfrom sys import implementation\r\nif implementation.name.upper() == \"CIRCUITPYTHON\":\r\n import board\r\n try:\r\n board.SCK\r\n except:\r\n import kfw_pico_board as board\r\n import digitalio\r\n import storage\r\n\r\n# PyDOSReadOnly of False sets the PyDOS file system to Read/Write status for next power cycle\r\n# This selection is ignored if D2 is grounded, if so the PyDOS file system is set to readonly\r\n# giving the host computer write access to the flash\r\n\r\n PyDOSReadOnly = False\r\n\r\n# For Gemma M0, Trinket M0, Metro M0/M4 Express, ItsyBitsy M0/M4 Express\r\n # switch = digitalio.DigitalInOut(board.D2)\r\n\r\n# For Feather M0/M4 Express\r\n switch = digitalio.DigitalInOut(board.D5)\r\n\r\n# For Circuit Playground Express, Circuit Playground Bluefruit\r\n # switch = digitalio.DigitalInOut(board.D7)\r\n\r\n switch.direction = digitalio.Direction.INPUT\r\n switch.pull = digitalio.Pull.UP\r\n\r\n# If the switch pin is connected to ground (switch.value == False) allow host to write to the drive\r\n if switch.value == False:\r\n # Mounts so Host computer can write to micro-flash\r\n storage.remount(\"/\", True)\r\n print(\"Switch False (pin grounded), FS is ReadOnly\")\r\n else:\r\n storage.remount(\"/\", PyDOSReadOnly)\r\n print(\"Switch True (not grounded), \",end=\"\")\r\n if PyDOSReadOnly:\r\n print(\"FS is ReadOnly\")\r\n else:\r\n print(\"FS is ReadWrite\")\r\n","sub_path":"boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169954842","text":"from collections import OrderedDict as _OrderedDict\nfrom flask_sse import ServerSentEvent as _ServerSentEvent\n\n\nsse_keepalive_data = {'event': 'keepalive'}\nsse_close_data = {'event': 'close'}\nsse_test_data = [\n {'data': '1166aa5d-195b-4a7a-8289-b95347aa2185'},\n {'event': 'event2'},\n {'data': '82055a6c-8da5-404f-bd6e-b748c7bb468d', 'event': 'event3', 'id': 3},\n {'data': _OrderedDict([('item1', '1'), ('item2', 2), ('item3', 3.99)]), 'event': 'event4', 'id': 4},\n {'retry': 10000, 'data': '7be75703-aca9-4be4-a758-e9a78588a2f2'}\n]\n\nsse_keepalive_obj = _ServerSentEvent(**sse_keepalive_data)\nsse_close_obj = _ServerSentEvent(**sse_close_data)\nsse_test_objects = [\n _ServerSentEvent(**sse_test_data[0]),\n _ServerSentEvent(**sse_test_data[1]),\n _ServerSentEvent(**sse_test_data[2]),\n _ServerSentEvent(**sse_test_data[3]),\n _ServerSentEvent(**sse_test_data[4])\n]\n\nsse_keepalive_str = 'data: -\\nevent: keepalive\\n\\n'\nsse_close_str = 'data: -\\nevent: close\\n\\n'\nsse_test_str = [\n 'data: 1166aa5d-195b-4a7a-8289-b95347aa2185\\n\\n',\n 'data: -\\nevent: event2\\n\\n',\n 'data: 82055a6c-8da5-404f-bd6e-b748c7bb468d\\nevent: event3\\nid: 3\\n\\n',\n 'data: {\"item1\": \"1\", \"item2\": 2, \"item3\": 3.99}\\nevent: event4\\nid: 4\\n\\n',\n 'retry: 10000\\ndata: 7be75703-aca9-4be4-a758-e9a78588a2f2\\n\\n'\n]\n","sub_path":"test/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60848706","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport cv2\nimport numpy as np\n\n# 指定图片的人脸识别然后存储\nimg = cv2.imread(r\"D:\\mycode\\CarRecognition\\test\\morenthanoneperson.jpg\")\ncolor = (0, 255, 0)\n\ngrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nclassfier = cv2.CascadeClassifier(r\"D:\\mycode\\CarRecognition\\bin\\haarcascade_frontalface_default.xml\")\n\nfaceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))\nif len(faceRects) > 0: # 大于0则检测到人脸\n\tfor faceRect in faceRects: # 单独框出每一张人脸\n\t\tx, y, w, h = faceRect\n\t\tcv2.rectangle(img, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 3) # 5控制绿色框的粗细\n\n# 写入图像\ncv2.imwrite('./aaa.jpg', img)","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"313686600","text":"import firebase_admin\nimport csv\nfrom firebase_admin import credentials, firestore\n\n\nif __name__ == \"__main__\":\n name = \"main\"\n\n cred = credentials.Certificate(\"./service-account.json\")\n firebase_app = firebase_admin.initialize_app(cred)\n\n db = firestore.client()\n\n artworks_collection_ref = db.collection(\"projects\").document(\n \"main\").collection(\"artworks\")\n artwork_array = []\n\n artwork_db = artworks_collection_ref.stream()\n\n for artwork in artwork_db:\n artwork_dict = artwork.to_dict()\n artwork_dict[\"uid\"] = artwork.id\n artwork_array.append(artwork_dict)\n\n operators_array = []\n\n operators_db = db.collection(\"operators\").stream()\n\n failed_to_write = []\n\n for operator in operators_db:\n operator_dict = operator.to_dict()\n operator_dict[\"uid\"] = operator.id\n operators_array.append(operator_dict)\n\n for art in artwork_array:\n artwork_uid = art[\"uid\"]\n operator_uid = art[\"operator\"][\"uid\"]\n\n print(artwork_uid, operator_uid)\n operator = list(\n filter(lambda op: op[\"uid\"] == operator_uid, operators_array))\n\n if(len(operator) != 1):\n failed_to_write.append(art)\n print(f\"Failed to update {art['operator']['name']}\")\n else:\n artworks_collection_ref.document(artwork_uid).update(\n {f\"operator\": operator[0]})\n print(f\"Updated artwork {artwork_uid} with operator!\")\n\n print(\"Failed to update the following:\")\n print(failed_to_write)\n","sub_path":"update-operator-in-artwork.py","file_name":"update-operator-in-artwork.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274125653","text":"from time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n# init driver\ndriver = webdriver.Chrome(executable_path='drivers/chromedriver.exe')\n\n# open the url\ndriver.get('https://www.amazon.com/')\n\nsleep(1)\n\n# find \"Try Prime\" Button on the main paige and click on it\ndriver.find_element(By.XPATH, \"//a[@id='nav-link-prime']/span[@class='nav-line-2 ']\").click()\n\nsleep(1)\n\n# click \"Try Prime\" Button in the pop-up window\n\ndriver.find_element(By.XPATH, \"//div[@class='prime-button-try']/a\").click()\n\nsleep(3)\n\nassert 'https://www.amazon.com/amazonprime' in driver.current_url\n\ndriver.quit()\n\n\n\n\n\n","sub_path":"sample_srcipt_amazon.py","file_name":"sample_srcipt_amazon.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"303387633","text":"import experiment, log, utils, learning\n\n\nclass Evaluator:\n def __init__(self, expn, exp_path, Config_class, model, loglevel=log.NO):\n self.EXPN = expn\n self.EXP_PATH = exp_path\n self.CONFIG_CLASS = Config_class\n self.LOGLEVEL = loglevel\n self.MODEL = model\n\n\n def evaluate(self, label, selected_energy_levels, test_batch_size=50):\n prefixed = label + '_'\n given_labels = list(filter(lambda x: x.startswith(prefixed), utils.listdir(self.CONFIG_CLASS().RAW_PATH)))\n evaluation = dict()\n\n for tmp_label in given_labels:\n if tmp_label == label + '_0':\n self.CONFIG_CLASS.SPLITTING_INFO = {\n 'regular': [tmp_label]\n }\n else:\n self.CONFIG_CLASS.SPLITTING_INFO = {\n 'chaotic': [tmp_label]\n }\n val_exper = experiment.Experiment(self.EXPN, self.EXP_PATH, self.CONFIG_CLASS (), self.LOGLEVEL)\n val_exper.prepare_validation()\n val_loader = val_exper.get_validation_loader(test_batch_size, selected_energy_levels)\n evaluation[tmp_label] = learning.test(self.MODEL, val_loader)\n val_exper.remove()\n return evaluation\n\n\nif __name__ == '__main__':\n raise RuntimeError('Not a main file')\n","sub_path":"billiards/src/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384010593","text":"'''You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\n\nThere is at least one empty seat, and at least one person sitting.\n\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized. \n\nReturn that maximum distance to the closest person.'''\n\nclass Solution:\n def maxDistToClosest(self, seats):\n occupied = [idx for idx, state in enumerate(seats) if state == 1]\n # print(occupied)\n res = -1\n res = max(occupied[0] - 0, len(seats) - 1 - occupied[-1])\n # print(res)\n for loc1, loc2 in zip(occupied[:-1], occupied[1:]):\n res = max(res, int((loc2 - loc1)/2))\n # print(res)\n\n return res\n\n\nif __name__ == '__main__':\n sol = Solution()\n seats = [1,0,0,1,0,0,0,1,0,0,0]\n print(sol.maxDistToClosest(seats))\n ","sub_path":"Mock Interview/8/Maximize Distance to Closest Person.py","file_name":"Maximize Distance to Closest Person.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142881871","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n1.先将versionSourcePath中的文件列出,并写入文件\n2.将versionDestPath中的文件对应写入文件\n3.对比md5是否一致\n\"\"\"\nfrom utils.pathutil import get_file_list\nfrom utils.yamlutil import yamlUtil\nfrom utils.md5util import get_md5_value, md5compare\nimport os\nfrom utils.logUtil import init_logging\nlogger = init_logging()\nimport csv\n\n\ndef list_source_path():\n src_path = yamlUtil().get('data').get('versionSourcePath')\n files = get_file_list(src_path)[0]\n src_m5 = list()\n for fl in files:\n file_md5 = get_md5_value(fl)\n src_m5.append(fl.split(os.sep)[-1] + ',' + fl + ',' + file_md5)\n return src_m5\n\n\ndef list_dest_path():\n dest_path = yamlUtil().get('data').get('versionDestPath')\n files = get_file_list(dest_path)[0]\n dest_md5 = list()\n for fl in files:\n logger.info(fl)\n file_md5 = get_md5_value(fl)\n dest_md5.append(fl.split(os.sep)[-1] + ',' + fl + ',' + file_md5)\n return dest_md5\n\n# 'Axure RP 核心训练(翻译).pdf,F:\\\\01_Document\\\\Axure RP 核心训练(翻译).pdf,e20adf976fe4c1dcda4ca5d38c889407'\n\n\ndef write_to_csv():\n src_list = list_source_path()\n dest_list = list_dest_path()\n src_list.extend(dest_list)\n\n with open('version.csv', 'a+', encoding='GBK') as f:\n for sd in src_list:\n f.write(sd + '\\n')\n\n\nif __name__ == '__main__':\n write_to_csv()\n","sub_path":"versionCheck.py","file_name":"versionCheck.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503037102","text":"# %load q05_read_csv_data/build.py\n# Default imports\nimport numpy as np\n\npath = './data/ipl_matches_small.csv'\ndtype = float\n\ndef read_ipl_data_csv(path=path,dtype=dtype):\n ipl_matches_array = np.genfromtxt(path, dtype='|S50', skip_header=1, delimiter=',')\n return ipl_matches_array\n\n\n\n","sub_path":"q05_read_csv_data/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63586348","text":"from random import expovariate as exp\n\nfrom entities.demand import Demand\nfrom entities.wrapper import DevicesWrapper\nfrom logs import *\nfrom progress_bar import ProgressBar\nfrom statistics import Statistics\nfrom utils import *\n\n\nclass SplitMergeSystem:\n \"\"\"Class describing the simulation model split-merge simulation model of a queuing system\n\n Two classes of demand, two queues for demand.\n The progression of simulation time is from event to event.\n Events: arrival demand, start service demand and leaving demand\n\n \"\"\"\n\n def __init__(self,\n params: Params,\n statistics: Statistics):\n \"\"\"\n\n :param params: network configuration parameters\n :param statistics: variable for counting and calculating statistics\n\n \"\"\"\n\n self.params = params\n self.statistics = statistics\n\n self.lambdas = {\n \"lambda1\": params.lambda1,\n \"lambda2\": params.lambda2,\n \"lambda\": params.get_lambda()\n }\n self.prob1 = self.lambdas[\"lambda1\"] / self.lambdas[\"lambda\"]\n\n self.times = {\n \"current\": 0,\n \"arrival\": exp(self.lambdas[\"lambda\"]),\n \"service_start\": float('inf'),\n \"leaving\": float('inf')\n }\n\n # network configuration - number of queues and devices\n self.config = {\n \"queues\": list([] for _ in range(len(params.fragments_amounts))), # view: [[], []]\n \"devices\": DevicesWrapper(params.mu, params.devices_amount)\n }\n\n # data for calculating statistics\n self.stat = {\n \"demands_in_network\": [],\n \"served_demands\": []\n }\n\n def arrival_of_demand(self):\n \"\"\"Event describing the arrival of a demand to the system\"\"\"\n\n class_id = define_arriving_demand_class(self.prob1)\n demand = Demand(self.times[\"arrival\"], class_id, self.params.fragments_amounts[class_id])\n\n if len(self.config[\"queues\"][class_id]) < self.params.queues_capacities[class_id]:\n self.times[\"service_start\"] = self.times[\"current\"]\n self.config[\"queues\"][class_id].append(demand)\n log_arrival(demand, self.times[\"current\"])\n else:\n log_full_queue(demand, self.times[\"current\"])\n\n self.times[\"arrival\"] += exp(self.lambdas[\"lambda\"])\n\n def demand_service_start(self):\n \"\"\"Event describing the start of servicing a demand\"\"\"\n\n # take demand from all queues in direct order\n for class_id in range(len(self.params.fragments_amounts)):\n while self.config[\"devices\"].can_occupy(class_id, self.params) and self.config[\"queues\"][class_id]:\n demand = self.config[\"queues\"][class_id].pop(0)\n self.config[\"devices\"].distribute_fragments(demand, self.times[\"current\"])\n self.stat[\"demands_in_network\"].append(demand)\n demand.service_start_time = self.times[\"current\"]\n log_service_start(demand, self.times[\"current\"])\n\n self.times[\"service_start\"] = float('inf')\n\n # take the near term of the end of servicing demands\n if self.config[\"devices\"].get_id_demands_on_devices():\n self.times[\"leaving\"] = self.config[\"devices\"].get_min_end_service_time_for_demand()\n\n def leaving_demand(self):\n \"\"\"Event describing a demand leaving the system\"\"\"\n\n leaving_demand_id = self.config[\"devices\"].get_demand_id_with_min_end_service_time()\n self.config[\"devices\"].to_free_demand_fragments(leaving_demand_id)\n demand = None\n\n for d in self.stat[\"demands_in_network\"]:\n if d.id == leaving_demand_id:\n demand = d\n self.stat[\"demands_in_network\"].remove(demand)\n break\n\n demand.leaving_time = self.times[\"current\"]\n self.stat[\"served_demands\"].append(demand)\n set_events_times(self.times, self.config, self.params)\n\n log_leaving(demand, self.times[\"current\"])\n\n def imitation(self, simulation_time: int):\n \"\"\"\n\n :param simulation_time: model simulation duration\n \"\"\"\n\n bar = ProgressBar(0, 'Progress: ')\n\n while self.times[\"current\"] <= simulation_time:\n self.times[\"current\"] = min(self.times[\"arrival\"], self.times[\"service_start\"], self.times[\"leaving\"])\n\n bar.print_progress(self.times[\"current\"], simulation_time)\n log_network_state(self.times, self.config[\"devices\"])\n\n if self.times[\"current\"] == self.times[\"arrival\"]:\n self.arrival_of_demand()\n continue\n if self.times[\"current\"] == self.times[\"service_start\"]:\n self.demand_service_start()\n continue\n if self.times[\"current\"] == self.times[\"leaving\"]:\n self.leaving_demand()\n continue\n\n self.statistics.calculate_stat(self.stat[\"served_demands\"])\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491096351","text":"#!/usr/bin/env python\n\n# Copyright (C) 2013-2014 SignalFuse, Inc.\n\n# Start script for ElasticSearch.\n# Requires python-yaml for configuration writing.\n\nimport os\nimport yaml\n\nfrom maestro.guestutils import *\n\nELASTICSEARCH_CONFIG_FILE = os.path.join('config', 'elasticsearch.yml')\nELASTICSEARCH_LOGGING_CONFIG = os.path.join('config', 'logging.yml')\nDEFAULT_ELASTICSEARCH_ZONE = 'ether'\nLOG_PATTERN = \"%d{yyyy'-'MM'-'dd'T'HH:mm:ss.SSSXXX} %-5p [%-35.35t] [%-36.36c]: %m%n\"\n\nos.chdir(os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n '..'))\n\ndef env_as_bool(k, default=True):\n if k in os.environ:\n v = os.environ[k].lower()\n return v == 'true'\n return default\n\n# Prepare the YAML configuration and write it.\nwith open(ELASTICSEARCH_CONFIG_FILE, 'w+') as conf:\n data = {\n 'cluster': {\n 'name': os.environ.get('CLUSTER_NAME',\n '{}-elasticsearch'.format(get_environment_name())),\n 'routing.allocation.awareness.attributes': 'zone',\n },\n\n # Node configuration\n 'node': {\n 'name': get_container_name(),\n 'zone': os.environ.get('ZONE_NAME', DEFAULT_ELASTICSEARCH_ZONE),\n 'data': env_as_bool('IS_DATA_NODE'),\n 'master': env_as_bool('IS_MASTER_NODE'),\n },\n\n # Index/replica configuration\n 'index': {\n 'number_of_replicas': int(os.environ.get('NUM_INDEX_REPLICAS', 1)),\n 'number_of_shards': int(os.environ.get('NUM_INDEX_SHARDS', 5)),\n },\n\n 'path': {\n 'data': os.environ.get('PATH_DATA', '/var/lib/elasticsearch').split(','),\n 'logs': '/var/log/elasticsearch',\n },\n\n 'transport.tcp.port': get_port('peer', 9300),\n\n 'http': {\n 'enabled': env_as_bool('HTTP_ENABLED'),\n 'port': get_port('http', 9200),\n },\n\n # Network and discovery.\n 'network': {\n 'publish_host': get_container_host_address(),\n },\n 'discovery': {\n 'type': 'com.sonian.elasticsearch.zookeeper.discovery.ZooKeeperDiscoveryModule',\n 'zen.multicast.enabled': False,\n },\n 'sonian.elasticsearch.zookeeper': {\n 'settings.enabled': False,\n 'client.host': ','.join(get_node_list('zookeeper', ports=['client'])),\n 'discovery.state_publishing.enabled': True,\n },\n 'zookeeper.root': os.environ.get('ZOOKEEPER_BASE',\n '/{}/elasticsearch'.format(get_environment_name())),\n\n # Marvel plugin configuration.\n 'marvel': {\n 'agent': {\n 'enabled': env_as_bool('MARVEL_ENABLED'),\n # TODO: improve this, ideally we want to figure this out\n # automatically.\n 'exporter.es.hosts': \\\n os.environ.get('MARVEL_TARGETS', 'localhost:9200').split(','),\n },\n },\n\n # AWS Cloud plugin configuration.\n 'cloud': {\n 'aws': {\n 'region': os.environ.get('ZONE_NAME', DEFAULT_ELASTICSEARCH_ZONE),\n },\n },\n }\n\n if os.environ.get('AWS_ACCESS_KEY') and os.environ.get('AWS_SECRET_KEY'):\n data['cloud']['aws'].update({\n 'access_key': os.environ['AWS_ACCESS_KEY'],\n 'secret_key': os.environ['AWS_SECRET_KEY'],\n })\n\n yaml.dump(data, conf, default_flow_style=False)\n\n# Setup the logging configuration\nwith open(ELASTICSEARCH_LOGGING_CONFIG, 'w+') as conf:\n yaml.dump({\n 'es.logger.level': 'INFO',\n 'rootLogger': '${es.logger.level},R',\n 'logger': {\n 'action': 'DEBUG',\n 'com.amazonaws': 'WARN',\n },\n 'appender': {\n 'R': {\n 'type': 'rollingFile',\n 'File': '${path.logs}/%s.log' % get_container_name(),\n 'MaxFileSize': '100MB',\n 'MaxBackupIndex': '10',\n 'layout': {\n 'type': 'pattern',\n 'ConversionPattern': LOG_PATTERN,\n },\n },\n },\n }, conf, default_flow_style=False)\n\n# Start ElasticSearch\nos.execl('bin/elasticsearch', 'elasticsearch')\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599381883","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.views.generic import RedirectView\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^home/', include('bookshelf.urls')),\n url(r'^account/', include('account.urls')),\n url(r'^',\n RedirectView.as_view(\n pattern_name='bookshelf:books',\n permanent=False\n ))\n]","sub_path":"AuthAndBook/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514713011","text":"#!/usr/bin/env python\nimport sys\nimport re\n\nfrom pllvm import *\n\n\nclass PhiResolver(object):\n\n @classmethod\n def convert(cls, mod):\n for f in mod.functions:\n for b in f:\n for i in b.instructions():\n if i.opcode_name == \"phi\":\n for var, label in i.incoming_vars:\n block = f[label]\n mov = PInstruction(i.name, i.type, \"mov\", [var])\n # Insert move before the last instruction of block,\n # which is got to be control transfer instruction.\n block.insert(len(block) - 1, mov)\n b.remove(i)\n\n\nif __name__ == \"__main__\":\n with open(sys.argv[1]) as asm:\n mod = Module.from_assembly(asm)\n out_mod = IRConverter.convert(mod)\n #print \"=============\"\n PhiResolver.convert(out_mod)\n IRRenderer.render(out_mod)\n","sub_path":"phi_resolver.py","file_name":"phi_resolver.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488794568","text":"#coding:utf-8\nimport requests\ndef get_url():\n city_url = []\n with open('../测试.txt','r',encoding='GBK')as f_in:\n for line in f_in:\n short=line.split()\n city_name=short[2].lower()\n url='http://qy.58.com/%s_245/?PGTID=0d211266-0000-00b1-40b7-f2a14c69a2d3&ClickID=1'%(city_name)\n # if requests.get(url).status_code==200:\n city_url.append(url)\n return city_url\nif __name__ == '__main__':\n print (get_url())","sub_path":"company_scrapy/spiders/get_url.py","file_name":"get_url.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26772313","text":"#!/usr/bin/python\r\n################################################################\r\n# Name : process_ngram.py\r\n# Desc : convert n-gram feature into sparse arff format for weka\r\n################################################################\r\nimport csv\r\nimport os\r\nfrom global_variable import *\r\n\r\n########################################################\r\n# Global Variables\r\n########################################################\r\n# input:\r\nall_fv_file = '../results/dialog_all_ngrams'\r\nmeta_fv = meta_info_file\r\n# output:\r\nword_fv_file = '../results/word_fv'\r\n\r\n# groc_fv_file = '../results/dialog_grocery_ngrams'\r\n# wine_fv_file = '../results/dialog_wine_ngrams'\r\n\r\nnum_unigram = 2498\r\nnum_bigram = 2648\r\nnum_trigram = 608\r\n\r\n# find valid ID\r\n\r\nmeta_file = open(meta_fv,'r')\r\nmeta_csv = csv.reader(meta_file,delimiter='\\t')\r\nmeta = [w for w in meta_csv]\r\nmeta_file.close()\r\nID = [int(w[0]) for w in meta[1:]] # list of ID\r\n\r\n########################################################\r\n# Data conversion\r\n########################################################\r\n\r\n# compute mapping from n-gram ID to feature index\r\n\r\nuni_id_str = [\"%d-%04d\"%(1,ii) for ii in range(1,num_unigram+1)]\r\nbi_id_str = [\"%d-%04d\"%(2,ii) for ii in range(1,num_bigram+1)]\r\ntri_id_str = [\"%d-%04d\"%(3,ii) for ii in range(1,num_trigram+1)]\r\n\r\nfv_name = uni_id_str+bi_id_str+tri_id_str\r\n\r\n# load n-gram feature file and convert it to sparse arff format\r\n\r\ndef ngram_csv2arff(file_name):\r\n f = open(file_name+'.csv','r')\r\n f_reader = csv.reader(f,delimiter = '\\n')\r\n data = [w for w in f_reader]\r\n f.close()\r\n fv = [w[0].split(',')[1:] for w in data] # feature vectors\r\n fv_id = [int(w[0].split(',')[0]) for w in data] # ID associated with fv\r\n # feature vector = [1-gram, 2-gram, 3-gram]\r\n index = [i for i in range(len(fv_id)) if fv_id[i] in ID]\r\n fv = [fv[i] for i in range(len(fv)) if i in index]\r\n fv_csv = []\r\n for row in fv:\r\n fv_temp = [0]*len(fv_name)\r\n for w in row:\r\n id = w[:6]\r\n count = w[7:]\r\n idx = fv_name.index(id)\r\n fv_temp[idx] = int(count)\r\n \r\n fv_csv.append(fv_temp)\r\n \r\n # write to a .csv file\r\n f = open(word_fv_file+'.csv','w')\r\n f_writer = csv.writer(f)\r\n fv_csv = [fv_name] + fv_csv\r\n # add joint profit to the last column of extracted feature\r\n meta_reader = csv.reader(open(meta_fv),delimiter = '\\t')\r\n meta_data = [w for w in meta_reader]\r\n for i in range(len(fv_csv)):\r\n fv_csv[i] = fv_csv[i]+[meta_data[i][-1]]\r\n\r\n f_writer.writerows(fv_csv)\r\n f.close()\r\n \r\n # convert to arff file\r\n weka_cmd1 = 'java -cp weka.jar weka.core.converters.CSVLoader %s > %s' % (word_fv_file+'.csv', file_name+'_d.arff')\r\n # convert dense arff file to sparse arff\r\n weka_cmd2 = 'java -cp weka.jar weka.filters.unsupervised.instance.NonSparseToSparse -i %s -o %s' % (file_name+'_d.arff', word_fv_file+'.arff')\r\n os.system(weka_cmd1)\r\n os.system(weka_cmd2)\r\n \r\nngram_csv2arff(all_fv_file)\r\n# ngram_csv2arff(groc_fv_file)\r\n# ngram_csv2arff(wine_fv_file)\r\n\r\n\r\n# cmd = 'cp %s > %s' % (all_fv_file+'_new.csv', word_fv_file+'.csv')\r\n# os.system(cmd) \r\n\r\n","sub_path":"submit/code/process_ngram.py","file_name":"process_ngram.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"367768713","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wechat', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),\n ('email', models.EmailField(default='', max_length=50)),\n ('content', models.CharField(default='', max_length=100)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n ]\n","sub_path":"wechat/migrations/0002_comment.py","file_name":"0002_comment.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592302483","text":"# Write a function remove_whitespace that removes extra whitespace (spaces, new line, tab)\n# from the beginning and end of a string. You should implement the functionality on your own\n# and not use system functions.\n\n\ndef remove_whitespace(string):\n whitespace = [' ', '\\n', '\\t']\n while True:\n if (string[0] not in whitespace) and (string[-1] not in whitespace):\n # if beginning and end of string are whitespace free -> process is complete\n return string\n if string[0] in whitespace: # remove a whitespace char from beginning of string\n string = string[1:]\n if string[-1] in whitespace: # remove a whitespace char from end of string\n string = string[:-1]\n\n# After you’ve done that, find a system function that does this , and write a new function\n# remove_whitespace_revised that uses the new function you’ve found\n\n\ndef remove_whitespace_revised(string):\n return string.strip()\n\nstring = ' \\t \\n a b \\n c d \\n e'\n\nprint(remove_whitespace(string)) # debug output\nprint(remove_whitespace_revised(string)) # debug output\n","sub_path":"Ex7 - Whitespace Removal.py","file_name":"Ex7 - Whitespace Removal.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353237003","text":"#!/usr/bin/python\n#\n# Renfield 4th Gen Globalz Variables\n\n\n# Python Imports\nimport Queue\n\n\n# Polecat Importz\nfrom actionpotential import *\n\n\n# Internal\n#ActionPotential = actionpotential.ActionPotential()\n\n# Globalz\nincoming = Queue.Queue()\n\noutgoing = Queue.Queue()\n\nisAlive = True\n\nonline = False\n\ndone = False\n\nauthed = False\n\ndoReload = False\n\ndidReload = False\n\nthreadList = []\n\nthreadCount = 0\n\n# Command Array\ncmds = []\n\n# Filter Array\ndipnet = {}\n\n# Response Function Array\nresponseFunc = {}\n\n# A.I. module list\naimods = []\naipluginz = {}\n\n\n# A.I. command functions\naicmds = {}\naicmdalias = {}\n\n\n\n# IRC Section\nrate = 3.0\nseconds = 4.0\nquota = rate\nlastCheck = 0.0\n\n# EOF","sub_path":"polepack/globalz.py","file_name":"globalz.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"628088591","text":"class UnionFind:\n\n def __init__(self, n):\n\n self.parents = list(range(n))\n self.size = {i: 1 for i in range(n)}\n\n def find(self, node):\n\n if self.parents[node] != node:\n self.parents[node] = self.find(self.parents[node])\n\n return self.parents[node]\n\n def union(self, node_1, node_2):\n\n root_1 = self.find(node_1)\n root_2 = self.find(node_2)\n\n if root_1 != root_2:\n\n if self.size[root_1] > self.size[root_2]:\n self.parents[root_2] = root_1\n self.size[root_1] += self.size[root_2]\n\n else:\n self.parents[root_1] = root_2\n self.size[root_2] += self.size[root_1]\n\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n\n # All connected indices can move characters between each other\n\n n = len(s)\n disjoint_set = UnionFind(n)\n components = {}\n ans = ''\n\n for index1, index2 in pairs:\n disjoint_set.union(index1, index2)\n\n for index, character in enumerate(s):\n component = disjoint_set.find(index)\n\n if component not in components:\n components[component] = []\n components[component].append(character)\n\n for array in components.values():\n array.sort(reverse=True)\n\n for index in range(n):\n character = components[disjoint_set.find(index)].pop()\n ans += character\n\n return ans\n","sub_path":"1202_Smallest_String_With_Swaps.py","file_name":"1202_Smallest_String_With_Swaps.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179644180","text":"#auth: starkizard\nt=int(input())\nfor _ in range(t):\n n=int(input())\n m=n//2\n sum1,sum2=0,0\n i=1\n l=list(range(1,n+1))\n sum1+=2**n\n sum1+=2*(2**(m-1) -1)\n \n sum2=((2**(n+1)) -2)-sum1\n print(abs(sum2-sum1))\n","sub_path":"Codeforces/Codeforces Round #638 (Div 2)/A-phoenixAndBalance.py","file_name":"A-phoenixAndBalance.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"522851461","text":"import binascii\n\nfrom .storage import Storage\nfrom .transport import Transport\nfrom .node import Node, GetHeaders, GetBlocks\n\ndef sync(store, node, addr, genesis, genesis_prev):\n headers_worker = node.client(addr, GetHeaders)\n\n current_epoch = 0\n current_epoch_db = None\n\n print('get tip')\n hdr = headers_worker([], None)[0]\n network_tip = hdr.hash()\n\n while True:\n local_tip = store.tip()\n if not local_tip:\n # get genesis block.\n blk = node.client(addr, GetBlocks)(genesis, genesis)[0]\n assert blk.header().prev_header() == genesis_prev and blk.header().slot() == (0, None), 'invalid genesis block.'\n assert current_epoch_db == None, 'impossible'\n current_epoch_db = store.open_epoch_db(0)\n current_epoch_db.put(b'genesis', blk.header().hash())\n current_epoch_db.put(blk.header().hash(), blk.raw())\n current_epoch_db.put(b'tip', blk.header().hash())\n store.append_block(blk)\n continue\n\n if local_tip == network_tip:\n print('sync finished')\n break\n\n print('get headers')\n hdrs = list(headers_worker([local_tip], network_tip))\n print('get blocks')\n blocks = list(node.client(addr, GetBlocks)(hdrs[-1].hash(), hdrs[0].hash()))\n assert blocks[0].header().prev_header() == local_tip, 'validate fail.'\n\n print('store blocks')\n for blk in blocks:\n hdr = blk.header()\n epoch, slotid = hdr.slot()\n hash = hdr.hash()\n if not current_epoch_db or epoch != current_epoch:\n current_epoch = epoch\n current_epoch_db = store.open_epoch_db(epoch)\n current_epoch_db.put(hash, blk.raw())\n current_epoch_db.put(b'tip', hash) # update tip\n if slotid == None:\n # is genesis\n print('set genesis', current_epoch)\n current_epoch_db.put(b'genesis', hash)\n store.append_block(blk)\n print('finish', blk.header().slot())\n\nif __name__ == '__main__':\n import sys\n store = Storage(sys.argv[1])\n node = Node(Transport().endpoint())\n genesis = binascii.unhexlify(b'89d9b5a5b8ddc8d7e5a6795e9774d97faf1efea59b2caf7eaf9f8c5b32059df4')\n genesis_prev = binascii.unhexlify(b'5f20df933584822601f9e3f8c024eb5eb252fe8cefb24d1317dc3d432e940ebb')\n try:\n sync(store, node, 'relays.cardano-mainnet.iohk.io:3000:0', genesis, genesis_prev)\n finally:\n store = None\n import gc\n gc.collect()\n","sub_path":"cardano/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"640372885","text":"import re\nimport copy\nimport random\nimport numpy as np\nfrom .base import MujocoEnv\nimport xml.etree.ElementTree as ET\n\nclass Particle(MujocoEnv):\n def __init__(self):\n super().__init__('Particle.xml', frame_skip=2)\n\n def init_task(self, root):\n option = root.find(\"option\")\n option.set(\"gravity\", \"0 0 0\")\n worldbody = root.find(\"worldbody\")\n self.path_names = []\n path = ET.Element(\"body\")\n path.set(\"name\", \"path\")\n path.set(\"pos\", \"0 0 0\")\n for i in range(10):\n name = f\"path{i}\"\n point = ET.Element(\"body\")\n point.set(\"name\", name)\n point.set(\"pos\", \"0 0 0\")\n point.append(ET.fromstring(\"\"))\n path.append(point)\n self.path_names.append(name)\n worldbody.append(path)\n self.range = 1.0\n self.origin = np.array([0, -0.2, 0.3])\n self.size = np.array([0.1, 0.2, 0])\n self.space = \"box\"\n size = self.size[0] if self.space == \"sphere\" else np.maximum(self.size, 0.001)\n size_str = lambda x: ' '.join([f'{p}' for p in x])\n space = f\"\"\n worldbody.append(ET.fromstring(space))\n target = \"\"\n worldbody.append(ET.fromstring(target))\n return root\n\n def reset_task(self, xoffset=-1):\n origin = self.origin + xoffset*np.array([0.1, 0, 0.05])\n target_pos = origin + self.range*self.size*np.random.uniform(-1, 1, size=self.size.shape)\n ef_pos = origin + self.range*self.size*np.random.uniform(-1, 1, size=self.size.shape)\n self.model.body_pos[self.model.body_names.index(\"target\")] = target_pos\n self.model.body_pos[self.model.body_names.index(\"space\")] = origin\n points = np.linspace(ef_pos, target_pos, len(self.path_names))\n path_indices = [self.model.body_names.index(name) for name in self.path_names]\n for i,point in zip(path_indices, points):\n self.model.body_pos[i] = point\n qvel = self.init_qvel + np.random.uniform(low=-.005, high=.005, size=self.model.nv)\n self.set_state(ef_pos, qvel)\n\n def task_reward(self):\n ef_pos = self.get_body_pos(\"fingertip\")\n target_pos = self.get_body_pos(\"target\")\n path = [self.get_body_pos(name) for name in self.path_names]\n target_dist = ef_pos-target_pos\n path_dists = [ef_pos-path_pos for path_pos in path]\n reward_goal = -np.linalg.norm(target_dist)*2\n reward_path = -np.min(np.linalg.norm(path_dists, axis=-1))\n reward = reward_goal + reward_path\n return reward\n\n def task_state(self):\n path = [self.get_body_pos(name) for name in self.path_names]\n return np.concatenate([*path])\n\n def task_done(self):\n ef_pos = self.get_body_pos(\"fingertip\")\n target_pos = self.get_body_pos(\"target\")\n return np.linalg.norm(ef_pos-target_pos)<0.005\n\n def observation(self):\n pos = self.get_body_pos(\"fingertip\")\n return np.concatenate([super().observation(), pos])\n\n def sample_tasks(self, num_tasks):\n tasks = [-1 for i in range(num_tasks)]\n return tasks\n","sub_path":"maml_rl/envs/laser/Laser/envs/particle.py","file_name":"particle.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"620584687","text":"#!/usr/bin/env python3\n\n#\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# NVIDIA CORPORATION and its licensors retain all intellectual property\n# and proprietary rights in and to this software, related documentation\n# and any modifications thereto. Any use, reproduction, disclosure or\n# distribution of this software and related documentation without an express\n# license agreement from NVIDIA CORPORATION is strictly prohibited.\n#\n\nimport os.path\nimport os\nimport subprocess\n\nfrom setuptools import setup, find_packages, Extension\n\nfrom Cython.Build import cythonize\n\n\nclass CMakeWrapper():\n \"\"\"Class to encapsulate building a CMake project.\"\"\"\n\n def __init__(self, cmake_root_dir, cmake_build_path=\"cmake_build\", cmake_extra_args=\"\"):\n \"\"\"\n Class constructor.\n\n Args:\n cmake_root_dir : Root directory of CMake project\n cmake_install_dir : Install location for CMake project\n cmake_extra_args : Extra string arguments to be passed to CMake during setup\n \"\"\"\n self.build_path = os.path.abspath(cmake_build_path)\n self.cmake_root_dir = os.path.abspath(cmake_root_dir)\n self.cmake_install_dir = os.path.join(self.build_path, \"install\")\n self.cmake_extra_args = cmake_extra_args\n self.cuda_toolkit_root_dir = os.environ.get(\"CUDA_TOOLKIT_ROOT_DIR\")\n\n def run_cmake_cmd(self):\n cmake_args = ['-DCMAKE_INSTALL_PREFIX=' + self.cmake_install_dir,\n '-DCMAKE_BUILD_TYPE=' + 'Release',\n '-DCMAKE_INSTALL_RPATH=' + os.path.join(self.cmake_install_dir, \"lib\")]\n cmake_args += [self.cmake_extra_args]\n\n if self.cuda_toolkit_root_dir:\n cmake_args += [\"-DCUDA_TOOLKIT_ROOT_DIR=%s\" % self.cuda_toolkit_root_dir]\n\n if not os.path.exists(self.build_path):\n os.makedirs(self.build_path)\n\n subprocess.check_call(['cmake', self.cmake_root_dir] + cmake_args, cwd=self.build_path)\n\n def run_build_cmd(self):\n build_args = ['--', '-j16', 'install']\n subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=self.build_path)\n\n def build(self):\n self.run_cmake_cmd()\n self.run_build_cmd()\n\n def get_installed_path(self, component=\"\"):\n installed_path = os.path.abspath(os.path.join(self.cmake_install_dir, component))\n if (not os.path.exists(installed_path)):\n raise RuntimeError(\"No valid path for requested component exists\")\n return installed_path\n\n\n# Initialize builds.\npycga_directory = os.path.dirname(os.path.realpath(__file__))\ncmake_root_dir = os.path.dirname(pycga_directory)\ncmake_proj = CMakeWrapper(cmake_root_dir,\n cmake_build_path=os.path.join(pycga_directory, \"cga_build\"),\n cmake_extra_args=\"-Dcga_build_shared=ON\")\ncmake_proj.build()\n\nextensions = [\n Extension(\n \"*\",\n sources=[os.path.join(pycga_directory, \"claragenomics/**/*.pyx\")],\n include_dirs=[\n \"/usr/local/cuda/include\",\n os.path.join(cmake_root_dir, \"cudapoa/include\"),\n os.path.join(cmake_root_dir, \"cudaaligner/include\"),\n ],\n library_dirs=[\"/usr/local/cuda/lib64\", cmake_proj.get_installed_path(\"lib\")],\n runtime_library_dirs=[\"/usr/local/cuda/lib64\", cmake_proj.get_installed_path(\"lib\")],\n libraries=[\"cudapoa\", \"cudaaligner\", \"cudart\"],\n language=\"c++\",\n extra_compile_args=[\"-std=c++14\"],\n )\n]\n\n# Run from the pycga directory\nos.chdir(pycga_directory)\n\nsetup(name='pyclaragenomics',\n version='0.3.0',\n description='NVIDIA genomics python libraries an utiliites',\n author='NVIDIA Corporation',\n packages=find_packages(where=pycga_directory),\n ext_modules=cythonize(extensions, compiler_directives={'embedsignature': True}),\n scripts=[os.path.join(pycga_directory, 'bin', 'genome_simulator'),\n os.path.join(pycga_directory, 'bin', 'assembly_evaluator')],\n )\n","sub_path":"pyclaragenomics/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518186013","text":"\n\ndef __CheckEvaluationInput(y, yPredicted):\n # Check sizes\n if(len(y) != len(yPredicted)):\n raise UserWarning(\"Attempting to evaluate between the true labels and predictions.\\n Arrays contained different numbers of samples. Check your work and try again.\")\n\n # Check values\n valueError = False\n for value in y:\n if value not in [0, 1]:\n valueError = True\n for value in yPredicted:\n if value not in [0, 1]:\n valueError = True\n\n if valueError:\n raise UserWarning(\"Attempting to evaluate between the true labels and predictions.\\n Arrays contained unexpected value. Must be 0 or 1.\")\n\ndef Accuracy(y, yPredicted):\n __CheckEvaluationInput(y, yPredicted)\n\n correct = []\n for i in range(len(y)):\n if(y[i] == yPredicted[i]):\n correct.append(1)\n else:\n correct.append(0)\n\n return sum(correct)/len(correct)\n\ndef numCorrect(y, yPredicted):\n __CheckEvaluationInput(y, yPredicted)\n\n correct = []\n for i in range(len(y)):\n if(y[i] == yPredicted[i]):\n correct.append(1)\n else:\n correct.append(0)\n\n return sum(correct)\n\ndef Precision(y, yPredicted):\n falsePositives = 0\n truePositives = 0\n \n for i in range(len(y)):\n if(yPredicted[i] == 1):\n if(y[i] == 1):\n truePositives += 1\n else:\n falsePositives += 1\n\n #handle the no-positive-predictions case\n if((truePositives + falsePositives) == 0):\n return 1.0\n \n return truePositives / (truePositives + falsePositives)\n\ndef Recall(y, yPredicted):\n falseNegatives = 0\n truePositives = 0\n \n for i in range(len(y)):\n if(y[i] == 1):\n if(yPredicted[i] == 1):\n truePositives += 1\n else:\n falseNegatives += 1\n\n #handle the no-positive-labels case\n if((truePositives + falseNegatives) == 0):\n return 1.0\n\n return truePositives / (truePositives + falseNegatives)\n\ndef FalseNegativeRate(y, yPredicted):\n falseNegatives = 0\n negativePredictions = 0\n \n for i in range(len(y)):\n if(yPredicted[i] == 0):\n negativePredictions += 1\n if(y[i] == 1):\n falseNegatives += 1\n\n #handle the no-negative-predictions case\n if(negativePredictions== 0):\n return 1.0\n\n return falseNegatives / negativePredictions\n\ndef FalsePositiveRate(y, yPredicted):\n falsePositives = 0\n negativeLabels = 0\n \n for i in range(len(y)):\n if(y[i] == 0):\n negativeLabels += 1\n if(yPredicted[i] == 1):\n falsePositives += 1\n\n #handle the no-negative-labels case\n if(negativeLabels == 0):\n return 1.0\n\n return falsePositives / negativeLabels\n\ndef ConfusionMatrix(y, yPredicted):\n buckets = [0,0,0,0]\n for i in range(len(y)):\n # 2 bit encoding of result to bucket\n bucket = 2 * y[i] + yPredicted[i]\n buckets[bucket] += 1\n\n print(\"\\t\\t|\\tLabel Positive\\t|\\tLabel Negative\\t|\")\n print(\"-----------------------------------------------------------------\")\n print(\"Pred Positive\\t|\\t{0}\\t\\t|\\t{1}\\t\".format(buckets[3], buckets[1]))\n print(\"-----------------------------------------------------------------\")\n print(\"Pred Negative\\t|\\t{0}\\t\\t|\\t{1}\\t\".format(buckets[2], buckets[0]))\n print(\"-----------------------------------------------------------------\")\n\ndef ExecuteAll(y, yPredicted):\n print(ConfusionMatrix(y, yPredicted))\n print(\"Accuracy:\", Accuracy(y, yPredicted))\n print(\"Precision:\", Precision(y, yPredicted))\n print(\"Recall:\", Recall(y, yPredicted))\n print(\"FPR:\", FalsePositiveRate(y, yPredicted))\n print(\"FNR:\", FalseNegativeRate(y, yPredicted))\n \n","sub_path":"Python/EvaluationsStub.py","file_name":"EvaluationsStub.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436008026","text":"\"\"\"\nA small script for saving version information to `meta.json`.\n\nThis is intended to be used as part of a larger toolchain - it exists because\nwe need to publish a build artifact when working with Azure, in order to tag\nreleases automatically.\n\"\"\"\n\nimport json\nimport subprocess\n\ngit_hash = subprocess.check_output(\n (\"git\", \"rev-parse\", \"--long\", \"HEAD\")\n).decode(\"UTF-8\").split(\"\\n\")[1]\n\npackage_version = subprocess.check_output(\n (\"python\", \"setup.py\", \"--version\")\n).decode(\"UTF-8\").strip(\"\\n\")\n\n\ndata = {\n \"tag\": package_version,\n \"hash\": git_hash\n}\n\n\nwith open(\"meta.json\", \"w\") as fh:\n json.dump(data, fh)\n\nprint(f\"meta.json written: {package_version} ({git_hash})\")\n","sub_path":"scripts/save-versions.py","file_name":"save-versions.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139897169","text":"import os\nimport numpy as np\n\nimport random\nfrom random import shuffle\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom glob import glob\n\ndef get_raw_data(path):\n '''Get raw data pair from path\n \n Parameters\n ----------\n path : str\n target path\n \n Returns\n -------\n tuple\n data pair xs, ys\n '''\n\n paths = glob(os.path.join(path, '**/*.*'), recursive=True)\n \n data_dict = {}\n for p in paths:\n ppp = p.split('/')\n cat = ppp[-2]\n if cat in data_dict:\n data_dict[cat].append(p)\n else:\n data_dict[cat] = [p]\n \n return convert_dict_to_pair(data_dict)\n\ndef stat(arr, name=''):\n '''Print statistic of given array\n \n Parameters\n ----------\n arr : list\n list of number for statistic\n \n '''\n arr = np.array(arr)\n print((name, arr.shape, 'min:', np.min(arr), 'max:', np.max(arr), 'std:', np.std(arr), 'mean:', np.mean(arr), 'median:', np.median(arr)))\n\ndef get_weight_dict(xs, ys, multiply=10):\n '''Automatically generate dictionary of weight for each class\n \n Parameters\n ----------\n xs : list\n list of every x value\n ys : list\n list of label for every given x value\n multiply : int, optional\n each of weight will be multiply by this value (the default is 10)\n \n Returns\n -------\n dict\n dictionary of class weight\n '''\n\n _, stat_key, stat_num = statistic_data(xs, ys)\n maxx = np.max(stat_num)\n stat_weights = maxx/stat_num\n stat_weights = stat_weights*multiply/np.sum(stat_weights)\n\n weights_dict = {}\n for k, w in zip(stat_key, stat_weights):\n weights_dict[k] = w\n \n return weights_dict\n\ndef statistic_data(xs, ys, title=None):\n '''Combine raw value to dictionary\n \n Parameters\n ----------\n xs : list\n list of all x value\n ys : list\n list of class of all given x value\n title : bool, optional\n Wheather plot graph or not (the default is None, which is not draw graph by default)\n \n Returns\n -------\n tuple\n Data dictionary, all classes, number of item of each class\n '''\n\n data_dic = {}\n for y, p in zip(ys, xs):\n if y in data_dic:\n data_dic[y] = data_dic[y] + [p]\n else:\n data_dic[y] = [p]\n\n keys = list(data_dic.keys())\n nums = [len(data_dic[k]) for k in keys]\n \n if title:\n print(title, 'sum:', np.sum(nums))\n plt.bar(keys, nums)\n plt.show()\n\n print(nums)\n stat(nums)\n \n return data_dic, keys, nums\n\ndef divide_data(xs, ys, chunk_num=5, keeps=[]):\n '''Divide given raw data to several chunk, which have same distribution\n \n Parameters\n ----------\n xs : list\n all item of x value\n ys : list\n all class of every given x value\n chunk_num : int, optional\n number of divided chunk (the default is 5)\n keeps : list, optional\n all data of given class indice will be keep when devide\n \n Returns\n -------\n list\n list of divided dictionary\n '''\n\n assert chunk_num > 2, 'Chunnk size must greater than 2'\n \n def get_sample(arr, chunk_num):\n shuffle(arr)\n \n percent = float(1/chunk_num)\n size = int(percent*len(arr))\n \n f = arr[:size]\n if chunk_num == 3:\n s = arr[size:size+size]\n l = arr[size + size:]\n return [f, s, l]\n \n res = [f]\n for i in range(1,chunk_num - 1):\n res.append(arr[size*i:size*i + size])\n \n res.append(arr[(chunk_num - 1)*size:])\n \n return res\n \n stat_dic, _, _ = statistic_data(xs, ys)\n \n res = []\n for _ in range(0, chunk_num):\n res.append({})\n \n for k in stat_dic:\n if k in keeps:\n for d in res:\n d[k] = stat_dic[k]\n else:\n samples = get_sample(stat_dic[k], chunk_num)\n for d, s in zip(res, samples):\n d[k] = s\n \n return res\n\ndef upsample_data(xs, ys):\n '''Upsampling data\n \n Parameters\n ----------\n xs : list\n All data item x\n ys : list\n All class for each given data x\n \n Returns\n -------\n tuple\n Upsampled data, number item of each class will be balanced\n '''\n\n data_dic, keys, nums = statistic_data(xs, ys, title='before')\n\n nums_arr = np.array(nums)\n maxx = np.max(nums_arr)\n scalenum = (maxx/nums_arr + 0.5).astype(np.uint8)\n\n for key, scale in zip(keys, scalenum):\n data_dic[key] = (data_dic[key]*scale)[:maxx]\n\n numdata11, numdata22 = convert_dict_to_pair(data_dic)\n\n _, _, _ = statistic_data(numdata11, numdata22, title='after')\n \n return numdata11, numdata22\n\ndef convert_dict_to_pair(data_dic):\n '''Convert dictionary to raw data\n \n Parameters\n ----------\n data_dic : dict\n target data dictionary, keys of data_dic is class name, while value of each keys is array of x values belong to that class\n \n Returns\n -------\n tuple\n tuple of raw data\n '''\n\n numdata1 = []\n numdata2 = []\n for k in data_dic:\n numdata1.extend(data_dic[k])\n numdata2.extend([k]*len(data_dic[k]))\n\n pair = [(a, b) for a, b in zip(numdata1, numdata2)]\n shuffle(pair)\n numdata11 = [a[0] for a in pair]\n numdata22 = [a[1] for a in pair]\n \n return numdata11, numdata22\n\ndef split_data(xs, ys, alpha=0.9, maxx=None):\n '''Split given raw data into 2 chunk\n \n Parameters\n ----------\n xs : list\n All data x\n ys : list\n Class of each given x\n alpha : float, optional\n Split ratio if alpha < 1.0, otherwise is the number of item for each classes in first chunk (the default is 0.9, which means first chunk will contain 90% data of given xs, second chunk contain the rest)\n maxx : int, optional\n Maximum number of item for each first chunk, maxx will not makes any affect if alpha > 1 (the default is None, which means no affect)\n \n Returns\n -------\n tuple\n tuple of raw dataof 2 chunks\n '''\n\n data_dic, _, _ = statistic_data(xs, ys)\n \n assert alpha > 0, 'alpha must be greater than 0'\n if maxx is not None:\n assert maxx > 0, 'maxx must be greater than 0'\n\n if alpha < 1.0:\n def get_sample(arr, alpha=0.9, maxx=None):\n shuffle(arr)\n i = int(alpha*len(arr))\n if maxx:\n if alpha <= 0.5:\n if i > maxx:\n i=maxx\n else:\n if len(arr) - i > maxx:\n i = len(arr) - maxx\n return arr[:i], arr[i:]\n else:\n def get_sample(arr, alpha=1000, maxx=None):\n shuffle(arr)\n i = alpha\n return arr[:i], arr[i:]\n\n sdict_1, sdict_2 = {}, {}\n for k in data_dic:\n a1, a2 = get_sample(data_dic[k], alpha, maxx)\n sdict_1[k] = a1\n sdict_2[k] = a2\n \n x1, y1 = convert_dict_to_pair(sdict_1)\n x2, y2 = convert_dict_to_pair(sdict_2)\n return x1, y1, x2, y2\n","sub_path":"ailabtools/statistic.py","file_name":"statistic.py","file_ext":"py","file_size_in_byte":7165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565459272","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import svm, metrics\nfrom sklearn import tree\nfrom sklearn.decomposition import PCA\nimport tensorflow as tf\nimport matplotlib\nmatplotlib.use(\"Pdf\")\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport math\n\n\n# Tensor Weight variable\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n\n# Tensor bias variable\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\n# Convolution function\n# Strides of 1, no padding\ndef conv2d(x, w):\n return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')\n\n\n# Pooling will be 2x2\n# Max pooling\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\n# Avg pooling\ndef avg_pool_2x2(x):\n return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\n# Returns 1 if the value matches the master\ndef convert_any(val, master):\n if val == master:\n return 1\n else:\n return 0\n\n\ndef trim_fraction(text):\n if '.0' in text:\n return text[:text.rfind('.0')]\n return text\n\n\n# function to export results\ndef export_results(predictions, result_file):\n # Create a pandas dataframe with our predictions\n stats_frame = pd.DataFrame(predictions, columns=['Label'])\n stats_frame.Label.astype(int)\n stats_frame.index += 1\n stats_frame.to_csv(result_file, index_label='ImageId')\n\n\n# A basic decision tree, no optimization of parameters\ndef model_basic_tree(train_data, test_data, result_file='results/basic_tree_results.csv'):\n # Create a simple Decision Tree Classifier\n clf = tree.DecisionTreeClassifier()\n clf_fit = clf.fit(train_data[0::, 1::], train_data[0::, 0])\n\n # Get our predictions for the test data\n output = clf_fit.predict(test_data[0::, 0::])\n\n # Create a pandas dataframe with our predictions\n export_results(output, result_file)\n\n\n# A basic svm model, no optimization of parameters\ndef model_basic_svm(train_data, test_data, result_file='results/basic_svm_results.csv'):\n # For the SVM, we need to trim down the data some\n # We'll do principal component analysis with\n # SVD (singular value decomposition)\n pca = PCA(n_components=0.8, whiten=True)\n train_x = train_data[0::, 1::]\n test_x = test_data\n train_x = pca.fit_transform(train_x)\n test_x = pca.transform(test_x)\n\n # Use default parameters to build the SVM model\n model = svm.SVC(kernel='rbf')\n\n # Fit the data\n model = model.fit(train_x, train_data[0::, 0])\n\n # Get our predictions for the test data\n print(len(test_x[0]))\n output = model.predict(test_x)\n\n # Create a pandas dataframe with our predictions\n export_results(output, result_file)\n\n\n# A basic svm model, no SVD\ndef model_basic_svm_no_svd(train_data, test_data, result_file='results/basic_svm_results.csv'):\n # Use default parameters to build the SVM model\n model = svm.SVC(kernel='rbf')\n\n # Fit the data\n model = model.fit(train_data[0::, 1::], train_data[0::, 0])\n\n # Get our predictions for the test data\n output = model.predict(test_data)\n\n # Create a pandas dataframe with our predictions\n export_results(output, result_file)\n\n\n# Converts label to a one-hot vector\ndef one_hot_vector_conversion(df):\n # Convert the labels to one-hot vectors\n df.insert(0, 'label9', df['label'].apply(convert_any, args=(9,)))\n df.insert(0, 'label8', df['label'].apply(convert_any, args=(8,)))\n df.insert(0, 'label7', df['label'].apply(convert_any, args=(7,)))\n df.insert(0, 'label6', df['label'].apply(convert_any, args=(6,)))\n df.insert(0, 'label5', df['label'].apply(convert_any, args=(5,)))\n df.insert(0, 'label4', df['label'].apply(convert_any, args=(4,)))\n df.insert(0, 'label3', df['label'].apply(convert_any, args=(3,)))\n df.insert(0, 'label2', df['label'].apply(convert_any, args=(2,)))\n df.insert(0, 'label1', df['label'].apply(convert_any, args=(1,)))\n df.insert(0, 'label0', df['label'].apply(convert_any, args=(0,)))\n df.drop('label', 1, inplace=True)\n\n return df\n\n\n# A basic softmax neural network, one layer only\ndef model_basic_softmax_nn(train_data, test_data, result_file='results/basic_softmax_20k_results.csv'):\n # Some standard varaibles\n run_iterations = 20000\n stochastic_size = 100\n\n # x variable\n # This will be the images we pass in to the net\n x = tf.placeholder(tf.float32, [None, 784])\n\n # W and b\n # These variables will the the weights (W)\n # and biases (b)\n # 10 represents the number of classes returned (0-9 digits)\n # (b) is just added to each output, as it's a bias\n W = tf.Variable(tf.zeros([784, 10]))\n b = tf.Variable(tf.zeros([10]))\n\n # softmax neural net formula\n # W*x + b\n y = tf.nn.softmax(tf.matmul(x, W) + b)\n\n # Create a variable to hold the actual values\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n # We'll minimize the cross-entropy function\n # -sum(y_ log(y))\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n\n # Train using Gradient Descent, minimizing cross entropy\n # This will setup back propogation\n train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n # Initialize\n init = tf.initialize_all_variables()\n sess = tf.Session()\n sess.run(init)\n\n # Let's grab 5000 as a validation set\n # validation_list = np.random.randint(len(train_data), size=5000)\n # validation_x = train_data[validation_list, 10::] / 255\n # validation_y = train_data[validation_list, 0:10]\n\n # Run through iterations\n for i in range(run_iterations):\n # Get a random 100 values\n rand_list = np.random.randint(len(train_data), size=stochastic_size)\n batch_xs = train_data[rand_list, 10::] / 255\n batch_ys = train_data[rand_list, 0:10]\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n print(i)\n\n # Process test data\n # Create the prediction function\n predict = tf.argmax(y, 1)\n\n # Initialize the predicted value array\n predicted_labels = np.zeros(test_data.shape[0])\n for i in range(0, len(test_data)):\n predicted_labels[i] = sess.run(predict, feed_dict={x: [test_data[i, 0::]]})\n\n # Export the results to a file\n export_results(predicted_labels, result_file=result_file)\n\n\n# a two convolution layer (with pooling) network\ndef model_dual_convolution_nn(train_data, test_data, result_file='results/two_conv_nn_results.csv'):\n # x variable\n # This will be the images we pass in to the net\n x = tf.placeholder(tf.float32, shape=[None, 784])\n\n # Create a variable to hold the actual values\n y_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n # Setup our variables for the convolution layer\n # 32 features for 5x5 areas\n # bias for each feature\n W_conv1 = weight_variable([5, 5, 1, 32])\n b_conv1 = bias_variable([32])\n\n # Reshape our image to a 4D tensor\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n # Multiply our new image by the weight tensor, add bias, apply ReLU\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n\n # Max Pool our convolution layer\n h_pool1 = max_pool_2x2(h_conv1)\n\n # Second convolution and pooling layer\n # 64 features for 5x5 areas\n W_conv2 = weight_variable([5, 5, 32, 64])\n b_conv2 = bias_variable([64])\n\n # 2x2 pooling again\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n\n # Now for the densely connected layer\n # takes the 7x7\n # applies 1024 neurons\n W_fc1 = weight_variable([7 * 7 * 64, 1024])\n b_fc1 = bias_variable([1024])\n\n # Reshape into vectors and apply ReLU\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n # Dropout\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n # Readout layer, softmax\n # takes the 1024 neurons from before and\n # outputs 10, our possible outputs\n W_fc2 = weight_variable([1024, 10])\n b_fc2 = bias_variable([10])\n\n # apply the softmax, with weights and bias\n y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n # Setup some of the training variables\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n # Prepare for visualization\n # display 32 features in 4 by 8 grid\n layer1 = tf.reshape(h_conv1, (-1, 28, 28, 4, 8))\n # reorder so the channels are in the first dimension, x and y follow.\n layer1 = tf.transpose(layer1, (0, 3, 1, 4, 2))\n layer1 = tf.reshape(layer1, (-1, 28 * 4, 28 * 8))\n\n # display 64 features in 2 by 4 grid\n layer2 = tf.reshape(h_conv2, (-1, 28, 28, 2, 4))\n # reorder so the channels are in the first dimension, x and y follow.\n layer2 = tf.transpose(layer2, (0, 3, 1, 4, 2))\n layer2 = tf.reshape(layer2, (-1, 28 * 2, 28 * 4))\n\n # Let's train the model\n # Initialize\n init = tf.initialize_all_variables()\n sess = tf.Session()\n sess.run(init)\n\n # Grab 5000 random images for validation accuracy\n validation_list = np.random.randint(len(train_data), size=5000)\n validation_x = train_data[validation_list, 10::] / 255\n validation_y = train_data[validation_list, 0:10]\n\n # Running logfile\n f = open(\"stats/deep_nn_run.log\", 'w')\n\n # sess.run(tf.initialize_all_variables())\n for i in range(20000):\n # Get a random 50 values\n rand_list = np.random.randint(len(train_data), size=50)\n batch_xs = train_data[rand_list, 10::] / 255\n batch_ys = train_data[rand_list, 0:10]\n\n # Should we test and log accuracy?\n if i % 100 == 0:\n train_accuracy = sess.run(accuracy, feed_dict={\n x: batch_xs, y_: batch_ys, keep_prob: 1.0})\n validation_accuracy = sess.run(accuracy, feed_dict={\n x: validation_x, y_: validation_y, keep_prob: 1.0})\n f.write(\"step %d, training accuracy %g, validation accuracy %g\" % (i, train_accuracy, validation_accuracy))\n\n # Train! And print percentage done\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})\n print(str(20000-i))\n\n # Close the logfile\n f.close()\n\n # Process test data\n # Create the prediction function\n predict = tf.argmax(y, 1)\n\n # Initialize the predicted value array\n predicted_labels = np.zeros(test_data.shape[0])\n for i in range(0, len(test_data)):\n predicted_labels[i] = sess.run(predict, feed_dict={x: [test_data[i, 0::]], keep_prob: 1.0})\n\n # Export the results to a file\n export_results(predicted_labels, result_file=result_file)\n\n # Print out the first and second convolution layers\n layer1_grid = sess.run(layer1, feed_dict={x: [train_data[0, 10::] / 255], keep_prob: 1.0})\n plt.axis('off')\n plt.imshow(layer1_grid[0], cmap=cm.seismic)\n plt.savefig('plots/nn_conv_layer_1.png')\n\n layer2_grid = sess.run(layer2, feed_dict={x: [train_data[0, 10::] / 255], keep_prob: 1.0})\n plt.axis('off')\n plt.imshow(layer2_grid[0], cmap=cm.seismic)\n plt.savefig('plots/nn_conv_layer_2.png')\n\n# a two convolution layer (with pooling) network\ndef model_three_convolution_nn(train_data, test_data, result_file='results/three_conv_nn_results.csv'):\n # x variable\n # This will be the images we pass in to the net\n x = tf.placeholder(tf.float32, shape=[None, 784])\n\n # Create a variable to hold the actual values\n y_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n # Setup our variables for the convolution layer\n # 16 features for 5x5 areas\n # bias for each feature\n W_conv1 = weight_variable([5, 5, 1, 16])\n b_conv1 = bias_variable([16])\n\n # Reshape our image to a 4D tensor\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n # Multiply our new image by the weight tensor, add bias, apply ReLU\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n\n # Max Pool our convolution layer\n h_pool1 = max_pool_2x2(h_conv1)\n\n # Second convolution and pooling layer\n # 16 features for 5x5 areas\n W_conv2 = weight_variable([5, 5, 16, 16])\n b_conv2 = bias_variable([16])\n\n # 2x2 pooling again\n h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n\n # Third convolution and pooling layer\n # 16 features for 5x5 areas\n W_conv3 = weight_variable([5, 5, 16, 16])\n b_conv3 = bias_variable([16])\n\n # We skip pooling on this layer\n h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)\n\n # Now for the densely connected layer\n # takes the 7x7\n # applies 1024 neurons\n W_fc1 = weight_variable([7 * 7 * 16, 1024])\n b_fc1 = bias_variable([1024])\n\n # Reshape into vectors and apply ReLU\n h_pool3_flat = tf.reshape(h_conv3, [-1, 7 * 7 * 16])\n h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)\n\n # Dropout\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n # Readout layer, softmax\n # takes the 1024 neurons from before and\n # outputs 10, our possible outputs\n W_fc2 = weight_variable([1024, 10])\n b_fc2 = bias_variable([10])\n\n # apply the softmax, with weights and bias\n y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n # Setup some of the training variables\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n # Let's train the model\n # Initialize\n init = tf.initialize_all_variables()\n sess = tf.Session()\n sess.run(init)\n\n # Grab 5000 random images for validation accuracy\n validation_list = np.random.randint(len(train_data), size=5000)\n validation_x = train_data[validation_list, 10::] / 255\n validation_y = train_data[validation_list, 0:10]\n\n # Running logfile\n f = open(\"stats/deep_three_nn_run.log\", 'w')\n\n # sess.run(tf.initialize_all_variables())\n for i in range(20000):\n # Get a random 50 values\n rand_list = np.random.randint(len(train_data), size=50)\n batch_xs = train_data[rand_list, 10::] / 255\n batch_ys = train_data[rand_list, 0:10]\n\n # Should we test and log accuracy?\n if i % 100 == 0:\n train_accuracy = sess.run(accuracy, feed_dict={\n x: batch_xs, y_: batch_ys, keep_prob: 1.0})\n validation_accuracy = sess.run(accuracy, feed_dict={\n x: validation_x, y_: validation_y, keep_prob: 1.0})\n f.write(\"step %d, training accuracy %g, validation accuracy %g\\n\" % (i, train_accuracy, validation_accuracy))\n\n # Train! And print percentage done\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})\n print(str(20000-i))\n\n # Close the logfile\n f.close()\n\n # Process test data\n # Create the prediction function\n predict = tf.argmax(y, 1)\n\n # Initialize the predicted value array\n predicted_labels = np.zeros(test_data.shape[0])\n for i in range(0, len(test_data)):\n predicted_labels[i] = sess.run(predict, feed_dict={x: [test_data[i, 0::]], keep_prob: 1.0})\n\n # Export the results to a file\n export_results(predicted_labels, result_file=result_file)\n\n\ndef get_matrix(pixel_list):\n # Create a 28 x 28 array of 8 bit unsigned integers\n data = np.zeros((28, 28, 1), dtype=np.uint8)\n\n # Create the matrix\n for j in range(0, 784):\n rgb = pixel_list[j]\n data[math.floor(j/28), j % 28] = rgb\n\n # Return the data matrix\n return data\n\n\n# Splits a matrix of an image into 16 different sub images\n# Each sub image is a [size] x [size] image, default 7x7\ndef split_image(image, size=7):\n # Split the image into size x size images\n image_list = []\n this_image = get_matrix(image)\n # Run through the image in 16 sections\n # 4 horizontal, 4 vertical\n for i in range(0, int(len(this_image)/size)):\n # Column by column\n for j in range(0, int(len(this_image)/size)):\n sub_image = []\n # Now grab all pixels in this section of the image\n for m in range(0, size):\n for n in range(0, size):\n sub_image.extend(this_image[(i * size) + m, (j * size) + n].astype(np.int64))\n image_list.append(np.asarray(sub_image).astype(np.int64))\n\n # Return the list of image sections\n return image_list\n\n\ndef split_train_test_images(train_data, test_data, size=14):\n # Start by turning the training set into\n # groups of images\n train_data_split = []\n for image in train_data[0::, 0::]:\n label = image[0]\n my_images = split_image(image[1::], size)\n my_final_images = []\n for val in my_images:\n my_val = np.insert(val, 0, label)\n my_final_images.append(my_val)\n train_data_split.append(my_final_images)\n\n # Make the resulting array a Numpy Array\n train_data_split = np.array(train_data_split, dtype=np.int64)\n\n # Now put the test data into the same format\n test_data_split = []\n for image in test_data[0::, 0::]:\n label = image[0]\n my_images = split_image(image[0::], size)\n my_final_images = []\n for val in my_images:\n # my_val = np.insert(val, 0, label)\n my_final_images.append(val)\n test_data_split.append(my_final_images)\n\n # Make the resulting array a Numpy Array\n test_data_split = np.array(test_data_split, dtype=np.int64)\n\n # Return both\n return [train_data_split, test_data_split]\n\n\n# Load the training data into a data frame\ntraining_data = pd.read_csv('train.csv')\n\n# Load the test data into a data frame\ntesting_data = pd.read_csv('test.csv')\n\n# Create one-hot vector versions of the training_data\ntraining_data_one_hot = one_hot_vector_conversion(training_data)\n\n# Predictions for a basic tree\nmodel_basic_tree(training_data.values, testing_data.values)\n\n# Predictions for a basic SVM\nmodel_basic_svm(training_data.values, testing_data.values)\n\n# Predictions for a basic TensorFlow Neural Network (SoftMax)\nmodel_basic_softmax_nn(training_data_one_hot.values, testing_data.values)\n\n# Predictions for a two convolution layer neural network with dropout\nmodel_dual_convolution_nn(training_data_one_hot.values, testing_data.values)\n\n# Predictions for a three convolution layer neural network with dropout\nmodel_three_convolution_nn(training_data_one_hot.values, testing_data.values)\n\n\n# print(test_data)\n","sub_path":"MNIST/digits_run.py","file_name":"digits_run.py","file_ext":"py","file_size_in_byte":19001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297982047","text":"import os,time\nimport sys\n\nmatriz = []\ncount_value = 0\npar = 0\nx = \"X\"\n\ndef count(count = False): \n global count_value \n if count == True:\n count_value = count_value + 1 \n pass \n return count_value\n\ndef trocaUsuario(count = False): \n global count_value \n if count == True:\n par = par + 1 \n pass \n return par\n\ndef pares(count = False): \n global par \n if count == True:\n par = par + 1 \n pass \n return par\n\ndef jogar(matriz):\n global x\n vencedor = False\n escolha = 0\n\n while (verificarVencedor(matriz,x) != True) and (count() < 9):\n # Pedi para o usúario a escolha\n try:\n escolha = int(input(\"Digite um número para a sua jogada \"+x+ \": \"))\n except ValueError as e:\n print(\"Opção invalida!\")\n\n #verificar se a escolha é de 1 a 9\n if (escolha > 0) and (escolha < 10):\n #Primeira Linha da matriz\n if (escolha > 0) and (escolha < 4):\n linha = 0\n #Verifica o campo já foi preenchido e insere na matriz\n if matriz[linha][escolha-1] == \"X\" or matriz[linha][escolha-1] == \"O\":\n print(\"Esse número já está preenchido!\")\n else:\n matriz[linha][escolha-1] = x\n verificarVencedor(matriz,x)\n count(True)\n if verificarVencedor(matriz,x) != True:\n if pares() % 2 == 0:\n x = \"O\"\n else:\n x = \"X\"\n pares(True)\n \n #Segunda Linha da matriz.\n elif (escolha > 3) and (escolha < 7):\n linha = 1\n\n #Verifica o campo já foi preenchido e insere na matriz.\n if matriz[linha][escolha-4] == \"X\" or matriz[linha][escolha-4] == \"O\":\n print(\"Esse número já está preenchido!\")\n else:\n matriz[linha][escolha-4] = x\n vencedor = verificarVencedor(matriz,x)\n count(True)\n if verificarVencedor(matriz,x) != True:\n if pares() % 2 == 0:\n x = \"O\"\n else:\n x = \"X\"\n pares(True)\n #Terceira Linha da matriz.\n else:\n linha = 2\n\n #Verifica o campo já foi preenchido e insere na matriz.\n if matriz[linha][escolha-7] == \"X\" or matriz[linha][escolha-7] == \"O\":\n print(\"Esse número já está preenchido!\")\n else:\n matriz[linha][escolha-7] = x\n vencedor = verificarVencedor(matriz,x)\n count(True)\n if verificarVencedor(matriz,x) != True:\n if pares() % 2 == 0:\n x = \"O\"\n else:\n x = \"X\"\n pares(True)\n tabuleiro(matriz)\n\n if verificarVencedor(matriz,x) != False:\n print(\"+\"*25)\n print(\"O jogador\",x,\"venceu!\")\n print(\"+\"*25)\n sys.exit(0)\n else:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"+\"*25)\n print(\" Deu velha!\")\n print(\"+\"*25)\n sys.exit(0)\n\n\ndef verificarVencedor(matriz,x):\n for i in range(3):\n #horizontais\n if (matriz[i][0] == matriz[i][1]) and (matriz[i][1] == matriz[i][2]):\n return True\n #verticais\n elif (matriz[0][i] == matriz[1][i]) and (matriz[1][i] == matriz[2][i]):\n return True\n else:\n #diagonais\n if (matriz[0][0] == matriz[1][1]) and (matriz[1][1] == matriz[2][2]):\n return True\n elif (matriz[0][2] == matriz[1][1]) and (matriz[1][1] == matriz[2][0]):\n return True\n else:\n\t return False\n\ndef preencherMatriz():\n matriz = []\n cont = 0\n for i in range(3):\n coluna = [0]*3\n matriz.append(coluna)\n\n for i in range(3):\n for j in range(3):\n cont = cont + 1\n matriz[i][j] = cont\n tabuleiro(matriz)\n\ndef tabuleiro(matriz): \n print(\"+\"*30)\n print(\" \"*7,\"Jogo da velha\")\n print(\"+\"*30)\n tabuleiro = ''' \n | | \n {} | {} | {}\n _____|_____|_____\n | |\n {} | {} | {}\n _____|_____|_____\n | |\n {} | {} | {}\n | |\n '''.format(matriz[0][0], matriz[0][1], matriz[0][2], matriz[1][0], matriz[1][1], matriz[1][2], matriz[2][0], matriz[2][1],matriz[2][2])\n print(tabuleiro)\n print(\"Jogador 1: X Jogador 2: O\")\n jogar(matriz)\n\npreencherMatriz()\n","sub_path":"jogoDaVelha.py","file_name":"jogoDaVelha.py","file_ext":"py","file_size_in_byte":4890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241289272","text":"import os\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\n\ncolor = {'coor_t': [159, 67, 255], # Purple\n 0: [216, 30, 54], # Red\n 'full_action_space': [204, 0, 204], # Magenta\n 1: [254, 151, 0], # Orange\n 'plus_r': [0, 0, 0], # Black background\n 'h_resac': [180, 180, 180], # Grey board walls\n 2: [0, 255, 0], # Green apples\n '7': [255, 255, 0], # Yellow fining beam\n '9': [159, 67, 255], # Purple player\n\n # Colours for agents. R value is a unique identifier\n 3: [2, 81, 154], # Blue\n 'q-q': [100, 255, 255], # Cyan\n 'cen': [83, 134, 139], # Lavender\n 'plus_v': [250, 204, 255], # Pink\n 'cen_control': [238, 223, 16],\n 'social_influence': [238, 232, 170]}\ncolor = {key: np.array(value) / 255. for key, value in color.items()}\n\npath = './results/pic_replays'\nfiles = []\n\nfor r, d, f in os.walk(path):\n for file in f:\n if file == 'role_frequency.pkl':\n files.append(os.path.join(r, file))\n\nfiles.sort()\nfiles = files[1:]\n\nfre = []\n\nfor file in files:\n with open(file, \"rb\") as f:\n data = pickle.load(f)\n\n fre.append(data)\n\nfre = np.array(fre)\nhbos = np.linspace(100, 5200, 100)\n\nfigure = plt.figure()\nfor i in range(fre.shape[1]):\n plt.plot(fre[:, i], c=color[i])\n\nplt.legend([str(i) for i in range(fre.shape[1])])\nplt.title('Role Frequency')\nplt.savefig('role_frequency.png')\nplt.close()\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429980904","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, api\nfrom odoo.exceptions import ValidationError\n\n\nwrite_origin = models.BaseModel.write\n\n\n@api.multi\ndef write(self, vals):\n result = write_origin(self, vals)\n\n approval_cannot_write(self)\n return result\n\n\ndef approval_cannot_write(self):\n \"\"\"审批后不能执行修改动作\"\"\"\n # 安装本模块时不执行\n if not self.env.registry.models.get('increase.type'):\n return\n\n for res in self:\n approval_flow = self.env['approval.flow'].get_approval_flow(self._name, res.id)\n # 没有对应的流程\n if not approval_flow:\n continue\n\n # 文档在审批过程中,不能删除\n res_state = self.env['record.approval.state'].search([('model', '=', self._name), ('res_id', '=', res.id)])\n # if res_state.approval_state in ['active', 'pause']:\n # approval = self.env['approval'].search([('model_name', '=', self._name), ('res_id', '=', res.id)], limit=1, order='id desc')\n # if approval.action_type != u'拒绝':\n # raise ValidationError(u'单据在审批过程中,不能修改!')\n\n if res_state.approval_state in ['active']:\n context = self._context or {}\n if 'approval_callback' not in context:\n model_name = self.env['ir.model'].sudo().search([('model', '=', self._name)]).name\n raise ValidationError(u'单据: \"%s\", ID: \"%s\"在审批过程中,不能修改!请先完成审批。' % (model_name, res.id))\n\n approval_cannot_run = approval_flow.approval_cannot_run or ''\n approval_cannot_run = map(lambda x: x.strip(), approval_cannot_run.split(','))\n if 'write' in approval_cannot_run:\n res_state = self.env['record.approval.state'].search([('model', '=', self._name), ('res_id', '=', res.id)]) # 记录审批状态\n if res_state and res_state.approval_state == 'complete':\n raise ValidationError(u'审批完成,不能修改记录!')\n\n\nmodels.BaseModel.write = write\n\n\n\n","sub_path":"my_addons/web_approval/models/model_write.py","file_name":"model_write.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45572990","text":"import time\nfrom me_handle import MeHandle\nfrom public_handle import PublicHandle\nfrom action_method import ActionMethod\nstarttime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())\n\nclass MeBusiness:\n def __init__(self,i):\n self.me_handle=MeHandle(i)\n self.pubilc_handle = PublicHandle(i)\n #self.action_method=ActionMethod(i)\n\n def modify_user_name(self):\n '''修改用户名'''\n self.me_handle.click_user_name()\n self.me_handle.click_name()\n self.me_handle.input_name(starttime)\n self.pubilc_handle.click_top_bar_right()\n self.pubilc_handle.click_confirm()\n self.pubilc_handle.click_return_key()\n\n def get_current_integral(self):\n '''获取当前积分'''\n self.me_handle.click_integral()\n self.me_handle.get_current_integral()\n current_integral=self.me_handle.get_current_integral()\n print(current_integral)\n self.pubilc_handle.click_return_key()\n\n def delete_emergency_contact(self):\n '''删除紧急联系人'''\n self.me_handle.click_emergency_contact()\n self.action_method.swipe_left(470,160,180,160)\n self.me_handle.click_delete_emergency_contact()\n\n\n\n\n\n","sub_path":"4business/me_business.py","file_name":"me_business.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637440794","text":"#!/usr/bin/env python\nfrom decision_trees.c45 import C45\nfrom decision_trees.visualizer import Visualizer\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nc1 = C45(\"../data/iris/iris.data\", \"../data/iris/iris.names\")\nc1.fetch_data()\n\nc1.pre_process_data()\nc1.generate_tree()\n\n# Visualization logic is separate\nprinter = Visualizer()\n\nprinter.print(c1)\n","sub_path":"decision_trees/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643165505","text":"\nimport acm\n\ndef CreateFileSelection(filter):\n fs = acm.FFileSelection()\n fs.PickExistingFile(False)\n fs.FileFilter = filter\n return fs\n \n\ndef WriteToFile(commonobjects, formatterclass, fileSelection):\n gen = acm.FAMBAMessageGenerator()\n ambamessages = acm.FAMBAMessage()\n ambamessages.Type(\"MESSAGES\")\n for commonobject in commonobjects:\n ambamessages.AddMessage(gen.Generate(commonobject))\n output = acm.FCharacterOutputFileStream(fileSelection.SelectedFile())\n taggedmessformatter = formatterclass()\n taggedmessformatter.FormatStream(output, ambamessages)\n output.Close()\n \n \n \ndef ExportCommonObjectAsXMLCB(eii):\n commonobj = eii.ExtensionObject() \n fs = CreateFileSelection(\"XML Files (*.xml)|*.xml|All files (*.*)|*.*||\")\n shell = eii.Parameter('shell')\n if acm.UX().Dialogs().BrowseForFile(shell, fs ):\n WriteToFile(commonobj, acm.FTaggedMessageXMLFormatter, fs)\n \n \n \ndef ExportCommonObjectAsXMLCBFromAppMenu(eii):\n commonobj = eii.ExtensionObject().CurrentObject() \n fs = CreateFileSelection(\"XML Files (*.xml)|*.xml|All files (*.*)|*.*||\")\n shell = eii.Parameter('shell')\n if not commonobj:\n acm.UX().Dialogs().MessageBoxInformation(shell, 'No FCommonObject Selected!')\n elif acm.UX().Dialogs().BrowseForFile(shell, fs ):\n WriteToFile([commonobj], acm.FTaggedMessageXMLFormatter, fs) \n \n\n\n","sub_path":"Extensions/FAMBUtils/FPythonCode/FExportCommonObject.py","file_name":"FExportCommonObject.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33543011","text":"#! /usr/bin/env python\n\nfrom Tkinter import *\nimport sys\nI=0\ndef Dialog():\n global I\n I = I + 1\n \n Window = Toplevel()\n Window.title(sys.argv[0] + \":\" + str(I))\n Label(Window,\n text=(\"Window: \" + str(I) + \" Make me go away\")).pack()\n Button(Window,\n text=\"OK\",\n command=Window.destroy).pack()\nRoot = Tk()\nRoot.title(sys.argv[0])\nButton(Root, text=\"Pop Up A Window\",\n command=Dialog).pack()\nRoot.mainloop()\n","sub_path":"Lab13/examples/Lec-11-Old/0_BARE_BONES/8A_Pop_Lots.py","file_name":"8A_Pop_Lots.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"530430014","text":"import os\nimport json\nfrom conf import setting\n\ndef save_json(username,userinfo):\n user_path = os.path.join(setting.DB_PATH,f'{username}.json')\n with open(user_path,'w',encoding='utf8') as fw:\n json.dump(userinfo,fw)\n\n\ndef read_json(username):\n user_path = os.path.join(setting.DB_PATH, f'{username}.json')\n with open(user_path, 'r', encoding='utf8') as fr:\n data = json.load(fr)\n return data\n","sub_path":"db/db_handler.py","file_name":"db_handler.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476043015","text":"file = open('crime_rates.csv', 'r')\ndata = file.read()\n#print(data)\nrows = data.split('\\n')\n#print(rows)\nfinal_data = []\n#print(\"final data:\", final_data)#Create an empty list. And also when program execute 2nd time, we need a clean list.\nfor row in rows:\n split_row = row.split(',')\n #print(split_row)\n final_data.append(split_row)\n\nfive_elements=final_data[0:5]\nprint(\"five_elements:\", five_elements)\ncrime_rates = []\nfor row in five_elements:\n # row is a list variable, not a string.\n crime_rate = row[1]\n # crime_rate is a string, the crime rate of the city.\n crime_rates.append(crime_rate)\nprint(crime_rates)\n","sub_path":"part_1/1_Files_Loops_ConditionalLogic/10_Looping Through A List Of Lists.py","file_name":"10_Looping Through A List Of Lists.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34205406","text":"from hms import app\nfrom datetime import datetime\nfrom flask import render_template, session, url_for, request, redirect, flash, session,g\nfrom .Forms import Login_form,Patient_create,Patient_delete,delete_result\nfrom .Models import UserStore, Patient_test, Patient_Medicine, Patient_details, Diagnosis, Medicine\nfrom .Config import db\n\n\npid = 0\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef main():\n if session.get('username'):\n return render_template('index.html', user=session['username'])\n form = Login_form()\n if request.method == 'POST':\n # Validate the form\n if form.validate_on_submit():\n # Check the credentials\n if request.form.get('username') == '12345678@A' and request.form.get('password') == '12345678@A':\n flash(\"Login successful\",\"success\")\n #g.user = \"Admin\"\n session['username'] = request.form.get('username')\n return redirect(url_for('create_patient'))\n else:\n flash(\"Invalid credentials\",\"danger\")\n return render_template('login.html', alert='failed', title=\"Login\", form=form)\n return render_template('login.html', title=\"Login\", form=form)\n\n\n@app.route(\"/index\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/CreatePatient\", methods=['GET', 'POST'])\ndef create_patient():\n if 'username' not in session or not session['username']:\n flash('Please Login first!','danger')\n return redirect('login')\n # If form has been submitted\n form=Patient_create()\n if request.method == 'POST':\n if form.validate_on_submit():\n \n \n ssn_id = form.ssn_id.data\n name = form.patient_name.data\n age = form.patient_age.data\n date = form.date.data\n bed_type = form.Type_of_bed.data\n address = form.address.data\n state = request.form.get('state_list')\n city = request.form.get('stt')\n #if(Patient_details.query.filter_by())\n details = Patient_details(\n name, age, ssn_id, date, bed_type, address, city, state, status=\"Admitted\")\n db.session.add(details)\n db.session.commit()\n flash(\"Patient creation initiated successfully\",\"success\")\n return render_template(\"create_patient.html\", title=\"Create Patient\",form=form)\n\n\n@app.route(\"/DeletePatient\",methods=[\"GET\",\"POST\"])\ndef delete_patient():\n if 'username' not in session:\n return redirect('login')\n form=Patient_delete() \n if form.validate_on_submit():\n global pid \n pid = int(form.patient_id.data)\n patient=Patient_details.query.filter(Patient_details.id==int(form.patient_id.data))\n for patient_1 in patient:\n if patient_1:\n form2=delete_result()\n flash(\"patient found\",\"success\")\n return render_template(\"delete_patient2.html\",title=\"Delete patient\",patient=patient,form=form2)\n flash(\"patient not found\",\"danger\")\n return render_template(\"delete_patient.html\", title=\"Delete Patient\",form=form)\n\n@app.route(\"/deletepatient2\",methods=[\"GET\",\"POST\"])\ndef delete_patient2():\n form2=delete_result()\n if form2.validate_on_submit():\n global pid\n print(pid)\n #delete query\n Patient_details.query.filter_by(id=pid).delete()\n db.session.commit()\n flash(\"patient deleted successfully\",\"success\")\n \n return redirect(url_for('delete_patient'))\n else:\n flash(\"patient delete failed . Please try again\",\"danger\") \n return redirect(url_for('delete_patient'))\n\n\n@app.route(\"/SearchPatient\",methods=[\"GET\",\"POST\"])\ndef search_patient():\n if 'username' not in session:\n return redirect('login')\n form=Patient_delete()\n if request.method == 'POST': \n if form.validate_on_submit():\n global pid \n pid = int(form.patient_id.data)\n patient=Patient_details.query.filter(Patient_details.id==int(form.patient_id.data))\n for patient_1 in patient:\n if patient_1:\n flash(\"patient found\",\"success\")\n return render_template(\"search_patient.html\",title=\"Search patient\",patient=patient, form=form)\n flash(\"patient not found\",\"danger\")\n return render_template(\"search_patient.html\", title=\"Search Patient\",form=form)\n\n@app.route(\"/UpdatePatient\")\ndef update_patient():\n if 'username' not in session:\n return redirect('login')\n return render_template(\"update_patient.html\", title=\"Update Patient\")\n\n\n@app.route(\"/logout\")\ndef logout():\n if session['username']:\n #return render_template('index.html', user=session['username'])\n session['username'] = None\n return redirect(url_for('main'))","sub_path":"hms/Routes.py","file_name":"Routes.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356868545","text":"__author__ = 'glen'\n\nimport os, sys\nfrom os import rename\nfrom os.path import isfile\n\nsys.path.append(os.path.abspath('..'))\nsys.path.append(os.path.abspath('../lib'))\n\nimport xml.etree.ElementTree as ET\nimport requests\n\nfrom contact.contactxmlrecord import ContactImportRecord\nfrom organizationcsv2dict import OrganizationDict\nfrom organizationxmlrecord import OrganizationImports, OrganizationImportRecord\n\nimport importutils\n\n#refname_pattern = \"urn:cspace:core.collectionspace.org:orgauthorities:name(%s):item:name(%s)'%s'\"\n#oc_namespace = \"http://collectionspace.org/services/organization\"\n\n\"\"\"organizationdict2xml : a script that instantiates the classes for creating Organization import records\n\"\"\"\n\nif len(sys.argv) > 1:\n csvfile = sys.argv[1]\nelse:\n csvfile = \"csv/organization_spreadsheet.csv\"\n\nif not isfile(csvfile):\n print(\"{} is not a readable file\".format(csvfile))\n sys.exit(1)\n\nif len(sys.argv) > 2:\n configfile = sys.argv[2]\nelse:\n configfile = \"config/authorities.conf\"\n\nif not isfile(configfile):\n print(\"{} is not a readable file\".format(configfile))\n sys.exit(1)\n\n# create an instance of the csv2dict class for organizations\norganization_dict = OrganizationDict(csvfile, configfile)\n\ndef exit_with_message(msg, msg_status=0):\n organization_dict.logit(\"LOG: {}\".format(msg))\n sys.exit(msg_status)\n\nif not organization_dict.status == 0:\n organization_dict.logit(\"Organization dict returned an invalid status code - exiting...\")\n sys.exit(organization_dict.status)\n\nif not organization_dict.is_valid():\n organization_dict.logit(\"Organization dict is not valid\")\n\n\ncomplex_group_items = organization_dict.get_complex_groups()\norganization_defaults = organization_dict.get_organization_defaults()\ncontact_groups = organization_dict.get_contact_group('contact-groups')\n\ndef add_defaults(term_list, mapped_terms):\n for term in term_list:\n trace(\"Checking for %s in mapped_terms\" % term)\n if not term in mapped_terms and term in organization_defaults:\n trace(\"Adding term {} = {} to mapped_terms\".format(term, organization_defaults[term]))\n mapped_terms[term] = organization_defaults[term]\n\ndef lookup_inAuthority():\n \"\"\"lookup_inAuthority makes a services call to the CSpace server to fetch\n an organization record which is parsed to discover the \"csid\" string. This\n string is then used as the \"inAuthority\" value for Person and Organization\n import records.\n\n :return: the csid string or None\n \"\"\"\n print(\"Looking up inAuthority CSID with {} {} {} {}\".format('hostname', 'port', 'cspaceuser', 'cspacepass'), file=sys.stderr)\n\n host = organization_dict.get_organization_from_app_value('cspacehost')\n port = organization_dict.get_organization_from_app_value('cspaceport')\n user = organization_dict.get_organization_from_app_value('cspaceadmin')\n passwd = organization_dict.get_organization_from_app_value('cspacepass')\n\n print(\"Looked up inAuthority CSID with {} {} {} {}\".format(host, port, user, passwd), file=sys.stderr)\n\n if host and port and user and passwd:\n res = requests.get('{}:{}/cspace-services/orgauthorities/urn:cspace:name(organization)'.format(host, port),\n auth=('{}'.format(user), '{}'.format(passwd)))\n\n print(\"status code: {}\".format(res.status_code))\n\n if res.status_code == 200:\n xmldoc = ET.ElementTree(ET.fromstring(res.text))\n for c in xmldoc.iter('csid'):\n print(\"Found csid {}\".format(c.text))\n return c.text\n else:\n print(\"Wrong status code {}\".format(res.status_code))\n else:\n print(\"WRONG: {}\".format(res.status_code))\n return None\n\ndef add_refName():\n key = 'shortIdentifier'\n col_name = organization_dict.get_organization_columns_map_value(key, key)\n\n if col_name:\n short_id = row_dict[col_name]\n else:\n trace(\"No key or shortIdentifier column found in current CSV row - unable to proceed\")\n return False\n\n if not short_id:\n trace(\"No key founnd in current CSV row - unable to proceed\")\n return False\n\n termDisplayName = 'termDisplayName'\n col_name = organization_dict.get_organization_columns_map_value(termDisplayName, termDisplayName)\n\n display_name = None\n\n if col_name:\n if col_name in row_dict:\n display_name = row_dict[col_name]\n else:\n trace(\"No display name column found in current CSV row - unable to proceed\")\n return False\n\n if not display_name:\n display_name = row_dict[\"{} 1\".format(col_name)]\n\n if display_name:\n return import_rec.set_refName(short_id, display_name)\n else:\n trace(\"No display name found in current CSV row - unable to proceed\")\n\n return False\n\ndef add_shortIdentifier():\n key = 'shortIdentifier'\n col_name = organization_dict.get_organization_columns_map_value(key, key)\n trace(\"Using key {}\".format(key))\n\n short_id = None\n if col_name:\n if col_name in row_dict:\n short_id = row_dict[col_name]\n\n if short_id:\n return import_rec.set_shortIdentifier(short_id)\n\n return False\n\ndef add_simple_element(tag_name):\n col_name = organization_dict.get_organization_columns_map_value(tag_name, tag_name)\n\n if not col_name:\n trace(\"No col_name for tag_name %s\" % tag_name)\n return False\n elif col_name in row_dict:\n item_term = row_dict[col_name]\n\n if item_term:\n try:\n method_name = \"%s_%s\" % ('set', tag_name)\n trace( \"METHOD_NAME: %s\" % method_name)\n\n method = getattr(import_rec, method_name)\n trace(\"CALLING METHOD: %s\" % str(method))\n return method(item_term)\n except KeyError as keyerr:\n trace(\"Key Error: {0}\".format(keyerr))\n except NameError as nameerr:\n trace(\"Name Error: {0}\".format(nameerr))\n except:\n trace(\"Unexpected error:\", sys.exc_info()[0])\n return False\n return True\n\n\ndef add_simple_repeating(tag_name):\n return True\n\ndef add_simple_repeating_element(tag_name):\n \"\"\"Adds a simple repeating element to a parent element.\n A simple repeating element would be something like:\n \n fb1\n fb2\n fb3\n \n\n :param: tag_name: The name of an element to be added to the import record\n :returns: True / False\n \"\"\"\n col_name = organization_dict.get_organization_columns_map_value(tag_name, tag_name)\n\n if not col_name:\n trace(\"No col_name for tag_name {}\".format(tag_name))\n return False\n elif col_name in row_dict:\n item_term = row_dict[col_name]\n else:\n item_term = None\n\n if item_term:\n try:\n method_name = \"%s_%s\" % ('set', tag_name)\n trace( \"METHOD_NAME: %s\" % method_name)\n\n method = getattr(import_rec, method_name)\n trace(\"CALLING METHOD: {}\".format(str(method)))\n return method(item_term)\n except KeyError as keyerr:\n trace(\"Key Error: {0}\".format(keyerr))\n except NameError as nameerr:\n trace(\"Name Error: {0}\".format(nameerr))\n except:\n trace(\"Unexpected error: {}\".format(sys.exc_info()[0]))\n return False\n return True\n\n\ndef add_orgTermGroup():\n term_list = organization_dict.get_complex_group('orgTermGroup')\n mapped_terms = {}\n\n for term in term_list:\n trace(\"Looking up {} for orgTermGroup\".format(term), 6)\n col_name = organization_dict.get_organization_columns_map_value(term, term)\n\n col_value = None\n\n if col_name in row_dict:\n col_value = row_dict[col_name]\n trace(\"Found term {} : {}\".format(col_name, col_value), 6)\n\n if col_value:\n mapped_terms[term] = col_value\n trace(\"Added {} to mapped_terms\".format(col_value))\n else:\n trace(\"Skipping {}\".format(term), 6)\n print(\"Mapped terms: {}\".format(str(mapped_terms)))\n\n if len(mapped_terms) > 0:\n add_defaults(term_list, mapped_terms)\n import_rec.set_orgTermGroup(mapped_terms)\n else:\n num = 1\n\n while True:\n for term in term_list:\n trace(\"Looking up (1) {} for orgTermGroup\".format(term), 6)\n col_name = organization_dict.get_organization_columns_map_value(term, term)\n col_namex = \"{} {}\".format(col_name, num)\n\n if col_namex in row_dict:\n col_value = row_dict[col_namex]\n trace(\"Found term (1) {} : {}\".format(col_namex, col_value), 6)\n else:\n col_value = None\n\n if col_value:\n mapped_terms[term] = col_value\n trace(\"Added (1) {} to mapped_terms\".format(col_value), 6)\n else:\n trace(\"Skipping (1)\", 6)\n\n if len(mapped_terms) > 0:\n add_defaults(term_list, mapped_terms)\n import_rec.set_orgTermGroup(mapped_terms)\n mapped_terms = {}\n num += 1\n else:\n trace(\"Done with organization terms\", 6)\n break\n\n\n# begin (founding or dissolution)DateGroup\ndef add_DateGroup(date_group):\n\n term_list = organization_dict.get_complex_group('dateGroup')\n\n trace(\"ADDING DATE GROUP WITH %s\" % str(term_list))\n mapped_terms = {}\n\n for term in term_list:\n trace(\"Looking up %s for %s\" % (term, date_group))\n col_name = organization_dict.get_date_columns_map_value(\"%s_%s\" % (date_group, term))\n trace(\"Using column name: %s\" % col_name)\n\n if col_name in row_dict:\n col_value = row_dict[col_name]\n trace(\"Found term %s : %s\" % (col_name, col_value))\n else:\n col_value = None\n\n if col_value:\n mapped_terms[term] = col_value\n trace(\"Added %s to mapped_terms\" % col_value)\n else:\n trace(\"Skipping\")\n\n if len(mapped_terms) > 0:\n return import_rec.set_DateGroup(date_group, mapped_terms)\n else:\n return True\n\n# groups\ndef add_groups():\n groups = 'groups'\n group = 'group'\n\n col_name = organization_dict.get_organization_columns_map_value(group, group)\n\n trace(\"COL NAME : %s\" % col_name)\n\n group_text = row_dict[col_name]\n\n if group_text:\n trace(\"%s : %s\" % (group, group_text))\n return import_rec.set_group(group_text)\n else:\n trace(\"%s notfound for %s\" % (group, col_name))\n num = 1\n col_namex = \"%s %s\" % (col_name, num)\n trace(\"Looking up %s\" % col_namex)\n\n while col_namex in row_dict:\n group_text = row_dict[col_namex]\n\n if group_text:\n trace(\"Found %s : %s\" % (group, group_text))\n import_rec.set_group(group_text)\n num += 1\n col_namex = \"%s %s\" % (col_name, num)\n trace(\"Looking for next %s : %s\" % (group, col_namex))\n else:\n break\n\n\ndef add_contact_group(group):\n \"\"\"This method should work with any contact info that fits the pattern\n of an outer list container element with repeating child elements, The\n child elements can have an arbitrary number of simple, non-repeating\n child elements.\n\n It assembles column values from a data source, typically a csv file,\n and sends them to the contact xml record builder (ContactImportRecord).\n The values are selected based on column names from a config file using\n the \"group\" parameter as the lookup key. The return value is a list of\n the tag names of the top level \"List\" element and the repeating \"Group\"\n tag followed by the tag names of all the non-repeating leaf elements\n\n The assembled column values are packed into a python dictionary.\n\n :param group: The tag name of the repeating group element\n :return: True/False\n \"\"\"\n contact_group = group\n contact_group = organization_dict.get_contact_group(contact_group)\n\n term_list = contact_group[2:]\n trace(\"Add {} with {}\".format(str(contact_group), str(term_list)))\n\n num = 0\n\n while num >= 0:\n mapped_terms = {}\n for term in term_list:\n trace(\"Looking up {} for {}\".format(term, group))\n col_name = organization_dict.get_contact_columns_map_value(term, term)\n\n if num == 0:\n col_namex = col_name\n else:\n col_namex = \"{} {}\".format(col_name, num)\n\n trace(\"Using column name: |{}|\".format(col_namex))\n\n if col_namex in row_dict:\n col_value = row_dict[col_namex]\n trace(\"Found term {} : {}\".format(col_namex, col_value))\n else:\n col_value = None\n\n if col_value:\n mapped_terms[term] = col_value\n trace(\"Added {} to mapped_terms\".format(col_value))\n else:\n trace(\"Skipping\")\n\n if num == 0:\n if len(mapped_terms) > 0:\n return contact_rec.set_contact_group(contact_group, mapped_terms)\n else:\n num += 1\n elif len(mapped_terms) > 0:\n if not contact_rec.set_contact_group(contact_group, mapped_terms):\n return False\n num += 1\n else:\n break\n return True\n\n\ncsid_log_file = 'logs/org_csid_list.txt'\n\n# Save old csid_log\n# if isfile(csid_log_file):\n# n = 1\n# while isfile(\"%s.%s\" % (csid_log_file, str(n))):\n# n += 1\n#\n# print(\"Renaming %s to %s\" % (csid_log_file, \"%s.%s\" % (csid_log_file, str(n))))\n# rename(csid_log_file, \"%s.%s\" % (csid_log_file, str(n)))\n\nimportutils.savefile(csid_log_file)\n\n# A new file to record csid, shortid, and displayname.\ncsid_file = open(csid_log_file, 'w')\n\n# Get the org authority (inAuthority) CSID\n# First try a services lookup\nin_authority = lookup_inAuthority()\n\nif in_authority:\n print(\"Lookup in_authority: {}\".format(in_authority))\nelse:\n inauth_key = 'auth-csid'\n in_authority = organization_dict.get_organization_from_app_value(inauth_key)\n print(\"Config in_authority: {}\".format(in_authority))\n\nif not in_authority:\n exit_with_message(\"Unable to find required CSID for organization inAuthority\")\n\n\n# The outer \"imports\" element, the parent of the \"import\" elements\nimports = OrganizationImports()\n\nfor row_num in range(len(organization_dict)):\n import_rec = OrganizationImportRecord(in_authority)\n contact_rec = ContactImportRecord('Organization', import_rec.CSID, in_authority)\n\n import_rec.trace_level = 0\n\n trace = getattr(import_rec, 'trace')\n\n rec_csid = import_rec.CSID\n\n trace(\"CSID: %s\" % rec_csid)\n\n row_dict = organization_dict.get_row_dict(row_num)\n\n if not add_shortIdentifier():\n exit_with_message(\"Unable to set shortIdentifier for row {}\".format(str(row_num)), 1)\n\n if not add_refName():\n exit_with_message(\"Unable to set a refName for row {}\".format(str(row_num)), 1)\n\n if not add_simple_repeating_element(\"function\"):\n exit_with_message(\"Unable to set function for row {}\".format(str(row_num)), 1)\n\n if not add_simple_repeating_element(\"contactName\"):\n exit_with_message(\"Unable to set contact name for row {}\".format(str(row_num)), 1)\n\n if not add_simple_repeating_element(\"historyNote\"):\n exit_with_message(\"Unable to set history note for row {}\".format(str(row_num)), 1)\n\n if not add_simple_repeating_element(\"group\"):\n exit_with_message(\"Unable to set group for row {}\".format(str(row_num)), 1)\n\n if not add_DateGroup('dissolutionDateGroup'):\n exit_with_message(\"Unable to set dissolutionDateGroup for row {}\".format(str(row_num)), 1)\n\n if not add_DateGroup('foundingDateGroup'):\n exit_with_message(\"Unable to set foundingDateGroup for row {}\".format(str(row_num)), 1)\n\n if not add_orgTermGroup():\n organization_dict.logit(\"LOG: Unable to set orgTermGroup for row {}\".format(str(row_num)))\n\n #Iterate over the list of contact_groups, adding them to the contact record\n for contact_group in contact_groups:\n trace(\"Beginning contact group {}\".format(contact_group))\n if not add_contact_group(contact_group):\n exit_with_message(\"Unable to set contact group {} for row {}\".format(contact_group, row_num), 12)\n\n trace(\"Saving organization record\")\n import_rec.save_rec()\n\n imports.add_import(import_rec.get_import_rec())\n imports.add_import(contact_rec.get_import_rec())\n\n csid_list = [import_rec.CSID, import_rec.shortIdentifier, import_rec.displayName, import_rec.refName]\n csid_file.write(str(csid_list)+'\\n')\n row_num += 1\n\n #print(etree.tostring(root, pretty_print=True))\n #with open(\"out.xml\", 'wb') as outfile:\n #ba outfile.write(etree.tostring(root, pretty_print=True))\n\ncsid_file.close()\n\nimports.save_imports()\n\ntrace(\"All done in organization_records\")\n","sub_path":"python3_code/createOrganizationImport.py","file_name":"createOrganizationImport.py","file_ext":"py","file_size_in_byte":17131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"422489372","text":"'''Run canny'''\n\nimport os\nimport sys\nimport time\n\nimport cv2\nimport numpy as np\nimport skimage.color as skco\nimport skimage.io as skio\nimport skimage.transform as sktr\n\nfrom matplotlib import pyplot as plt\n\ndef run():\n\tdata_dir = '/home/sgarbin/data/ImageNetMini'\n\tj = 0\n\tfor root, dirs, files in os.walk(data_dir):\n\t\tfor f in files:\n\t\t\tif '.JPEG' in f:\n\t\t\t\tfile_name = root + '/' + f\n\t\t\t\tsubfolder = file_name.split('/')[-1].split('_')[0]\n\t\t\t\tim = skio.imread(file_name)\n\t\t\t\tim_size = np.asarray(im.shape)[:2]\n\t\t\t\tnew_size = np.floor(im_size * (481./ np.amax(im_size))).astype(np.int)\n\t\t\t\tim = sktr.resize(im, new_size)\n\t\t\t\tif len(im_size) == 2:\n\t\t\t\t\tim = skco.gray2rgb(im)\n\t\t\t\tif new_size[0] > new_size[1]:\n\t\t\t\t\tim = np.transpose(im, (1,0,2))\n\t\t\t\tskio.imsave(file_name, im)\n\t\t\t\tsys.stdout.write(\"%i\\r\" %(j,))\n\t\t\t\tsys.stdout.flush()\n\t\t\t\tj += 1\n\nif __name__ == '__main__':\n\trun()\n","sub_path":"image_net/resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"246622002","text":"# python3\n\n## 将目录img_test中的图片都变成1136×640分辨率大小 存储在心目录rezise_img中 \nimport os\nfrom PIL import Image\n\ndest_path='resize_img'\nsour_path='img_test'\n\ntry:\n os.mkdir(dest_path)\nexcept FileExistsError:\n print('在已有目录上继续修改')\n\n\nfor filename in os.listdir(sour_path):\n if filename.endswith('.jpg') or filename.endswith('.png'):\n img=Image.open(os.path.join(sour_path,filename))\n filename_old=filename[:-4]\n img_resized=img.resize((640,1136))\n new_path_name=os.path.join(dest_path,filename_old+'_resize.jpg')\n img_resized.save(new_path_name)\n\n\n\n\nprint('DONE!')\n","sub_path":"problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"256420438","text":"from django.shortcuts import render, redirect, reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\n@login_required()\ndef view_cart(request):\n \"\"\"A View that renders the cart contents page\"\"\"\n return render(request, 'cart.html')\n\n\ndef add_to_cart(request, id):\n \"\"\"Add a amount for the upvote to the cart\"\"\"\n amount = int(request.POST.get('amount'))\n\n cart = request.session.get('cart', {})\n if id in cart:\n cart[id] = int(cart[id]) + amount \n else:\n cart[id] = cart.get(id, amount) \n\n request.session['cart'] = cart\n messages.success(request, \"Item added to the cart.\")\n return redirect(reverse('get_tickets'))\n \n \ndef remove_from_cart(request, id):\n cart = request.session.get('cart', {})\n cart.pop(id)\n request.session['cart'] = cart\n return redirect(reverse('view_cart'))\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176757732","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.font_manager as fm\nfrom testing import examples as ex\nfrom scipy.io import loadmat\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nimport matplotlib.patches as patches\n\n\ndef interp(t, x, y, lower, upper):\n i = 0\n while lower < upper:\n i = lower + (upper - lower) // 2\n val = x[i]\n if t == val:\n break\n elif t > val:\n if lower == i:\n break\n lower = i\n elif t < val:\n upper = i\n return (t - x[i]) * (y[i + 1] - y[i]) / (x[i + 1] - x[i]) + y[i]\n\ndef integrate(tp, tq, py, qy, gamma, k, i, l, j):\n e = 0\n a = k\n while a < i:\n gammak_1 = gamma[l] + (tp[a] - tp[k]) * (gamma[j] - gamma[l]) / (tp[i] - tp[k])\n gammak_2 = gamma[l] + (tp[a+1] - tp[k]) * (gamma[j] - gamma[l]) / (tp[i] - tp[k])\n e = e + (0.5 * (py[a] - interp(gammak_1, tq, qy, 0, tq.size)) ** 2\n + 0.5 * (py[a+1] - interp(gammak_2, tq, qy, 0, tq.size)) ** 2) * (tp[a+1] - tp[a]) * 0.5\n a = a + 1\n return e\n\ndef graph(actual_gamma, new_path_seg, old_path_seg, i):\n plt.clf()\n plt.plot(t, actual_gamma, \".-\", color=\"#FC5C5C\")\n plt.plot(new_path_seg[:,0], new_path_seg[:,1], \".-\", color=\"#FF7F00\")\n plt.plot(old_path_seg[:0], old_path_seg[:1], color=\"#00C7A9\")\n plt.gca().add_patch(\n patches.Rectangle(\n (0, 0), # (x,y)\n new_path_seg[-1][0], # width\n new_path_seg[-1, 1], # height\n )\n )\n plt.xticks([])\n plt.yticks([])\n plt.gca().spines['right'].set_visible(False)\n plt.gca().spines['top'].set_visible(False)\n plt.gca().spines['top'].set_visible(False)\n plt.gca().spines['right'].set_visible(False)\n plt.gca().spines['bottom'].set_visible(False)\n plt.gca().spines['left'].set_visible(False)\n plt.gca().set_xlim([0, 1])\n plt.gca().set_ylim([0, 1])\n plt.gca().spines['bottom'].set_color('#FFFFFF')\n plt.gca().spines['left'].set_color('#FFFFFF')\n plt.gca().axhline(y=0, color='#FFFFFF')\n plt.gca().axvline(x=0, color='#FFFFFF')\n plt.savefig('./animation_frames_n_4/frame' + str(i) + '.png', transparent=True,dpi = 300)\ndef find_path():\n path = np.zeros((n, 2), dtype=np.int16)\n path[0][0] = n-1\n path[0][1] = m-1\n i = 0\n while path[i][0] != 0 or path[i][1] != 0:\n result = path_nodes[path[i][0]][path[i][1]]\n path[i+1][0] = result[0]\n path[i+1][1] = result[1]\n i = i + 1\n gamma_range = np.zeros(n)\n i = 1\n previous = 1\n previousIndex = n-1\n j = 0\n gamma_range[path[0][0]] = gamma[path[0][1]]\n while i < path.size // 2 and previousIndex != 0:\n gamma_range[path[i][0]] = gamma[path[i][1]]\n if previousIndex - path[i][0] > 1:\n j = 0\n step_size = (previous - gamma[path[i][1]]) / (previousIndex - path[i][0])\n while j < previousIndex - path[i][0]:\n gamma_range[previousIndex - j] = previous - j * step_size\n j = j + 1\n previousIndex = path[i][0]\n previous = gamma[path[i][1]]\n i = i + 1\ndef find_gamma(p, q, g):\n tp, tq, py, qy, tg, gamma = p[0], q[0], p[1], q[1], g[0], g[1]\n m = gamma.size\n n = tp.size\n min_energy_values = np.zeros((n, m), dtype=np.float64)\n path_nodes = np.zeros((n, m, 2), dtype=np.int16)\n\n min_energy_values[0][0] = (0.5 * (py[0] - interp(gamma[0], tq, qy, 0, tq.size)) ** 2\n + 0.5 * (py[1] - interp(gamma[1], tq, qy, 0, tq.size)) ** 2) * (tp[1] - tp[0]) * 0.5\n path_nodes[1][1][0] = 0\n path_nodes[1][1][1] = 0\n i, j, k, l = 1, 1, 1, 1\n\n while i < n-1:\n j = 1\n while j < m-1:\n min_energy_values[i][j] = integrate(tp, tq, py, qy, gamma, 0, i, 0, j)\n k = 1\n minimum = min_energy_values[i][j]\n while k < i:\n l = 1\n while l < j:\n e = min_energy_values[k, l] + integrate(tp, tq, py, qy, gamma, k, i, l, j)\n if e < minimum:\n minimum = e\n path_nodes[i][j][0] = k\n path_nodes[i][j][1] = l\n l = l + 1\n k = k + 1\n min_energy_values[i][j] = minimum\n j = j + 1\n i = i + 1\n\nm = 256\nn = 256\nt = np.linspace(0.,1., m)\n\np = [0, 0]\n\nq = ex.curve_example('bumps', t)[0]\n\nx_function = InterpolatedUnivariateSpline(t, q[0])\ny_function = InterpolatedUnivariateSpline(t, q[1])\n\n\n\n\ntest = ex.gamma_example(\"sine\")[0](t)\ntest1 = ex.gamma_example(\"sine\")[0](t)\n#\n# test = np.zeros(m)\n#\n# i = 1\n# while i < m:\n# test[i] = np.random.random_sample()\n# i = i + 1\n# test.sort()\n# test[m-1] = 1\n# test[0] = 0\n\np[0] = x_function(test)\np[1] = y_function(test1)\n\n# p = np.array(np.sin(t))\n# q = np.array(np.exp(t)-1)\ntg = np.linspace(0.,1., 64)\ngamma = np.linspace(0., 1., 64)\n\n\nfind_gamma(np.array([t, p[1]]), np.array([t, q[1]]), np.array(tg, gamma))\nprint(\"hi\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"graphs/algorithm_animation.py","file_name":"algorithm_animation.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512936769","text":"# Copyright 2018 Iguazio\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\nfrom ..model import RunObject\nfrom ..utils import update_in, logger, get_in\nfrom .base import MLRuntime, RunError\nfrom os import path\nfrom kubernetes import client, config\nimport yaml\nimport subprocess\n\nclass SparkK8s(MLRuntime):\n kind = 'sparkk8s'\n def __init__(self, run: RunObject):\n super().__init__(run)\n self.dashboard = ''\n\n def set_runtime(self, runtime):\n self.dashboard = runtime.pop(\"command\", '')\n self.runtime = runtime\n\n def _run(self, runobj: RunObject):\n \n runtime = self.runtime\n extra_env = [{'name': 'MLRUN_EXEC_CONFIG', 'value': runobj.to_json()}]\n if self.rundb:\n extra_env.append({'name': 'MLRUN_META_DBPATH', 'value': self.rundb})\n\n update_in(runtime, 'spec.env', extra_env, append=True)\n\n uid = runobj.metadata.uid\n update_in(runtime, 'metadata.labels.mlrun/class', self.kind)\n update_in(runtime, 'metadata.labels.mlrun/uid', uid)\n if runobj.metadata.name:\n update_in(runtime, 'metadata.name', runobj.metadata.name)\n runtime.metadata.name = runobj.metadata.name\n name = get_in(runtime, 'metadata.name', '')\n \n #project = runobj.metadata.project\n\n #if not project or not name:\n # raise RunError('name and a project must be specified in the run to deploy this function')\n\n #addr = deploy_config(runtime, self.dashboard, name, project, create_new=True)\n \n spark_k8s_app = self.sparkk8s_template()\n # IGUAZIO environment\n AUTH_SECRET = get_in(runtime, 'metadata.AUTH_SECRET', \"NONE\")\n FUSE_SECRET = get_in(runtime, 'metadata.FUSE_SECRET', \"NONE\")\n \n WAIT = get_in(runtime, 'metadata.WAIT', False)\n VERBOSE = get_in(runtime, 'metadata.VERBOSE', False)\n \n \n # Iguazio execution config\n #AUTH_SECRET\n spark_k8s_app['spec']['volumes'][3]['secret']['secretName'] = AUTH_SECRET\n spark_k8s_app['spec']['executor']['env'][2]['valueFrom']['secretKeyRef']['name'] = AUTH_SECRET\n spark_k8s_app['spec']['executor']['env'][3]['valueFrom']['secretKeyRef']['name'] = AUTH_SECRET\n spark_k8s_app['spec']['driver']['env'][2]['valueFrom']['secretKeyRef']['name'] = AUTH_SECRET\n spark_k8s_app['spec']['driver']['env'][3]['valueFrom']['secretKeyRef']['name'] = AUTH_SECRET\n\n\n #FUSE_SECRET\n spark_k8s_app['spec']['volumes'][4]['flexVolume']['secretRef']['name'] = FUSE_SECRET\n \n # Application behaviour\n spark_k8s_app['metadata']['name'] = get_in(runtime, 'metadata.APP_NAME', \"APP_NAME\")\n spark_k8s_app['spec']['mainApplicationFile'] = get_in(runtime, 'metadata.mainApplicationFile', 'local:///v3io/users/admin/spark_operator/PySparkTestUHUH.py')\n spark_k8s_app['spec']['restartPolicy'][\"onFailureRetries\"] = get_in(runtime, 'metadata.onFailureRetries', 3)\n spark_k8s_app['spec']['restartPolicy'][\"onFailureRetryInterval\"] = get_in(runtime, 'metadata.onFailureRetryInterval', 10)\n spark_k8s_app['spec']['restartPolicy'][\"onSubmissionFailureRetries\"] = get_in(runtime, 'metadata.onSubmissionFailureRetries', 5)\n spark_k8s_app['spec']['restartPolicy'][\"onSubmissionFailureRetryInterval\"] = get_in(runtime, 'metadata.onSubmissionFailureRetries', 20)\n \n # DRIVER\n spark_k8s_app['spec']['driver']['cores'] = get_in(runtime, 'metadata.driver.cores', .01)\n spark_k8s_app['spec']['driver']['coreLimit'] = get_in(runtime, 'metadata.driver.coreLimit', \"200m\")\n spark_k8s_app['spec']['driver']['memory'] = get_in(runtime, 'metadata.driver.memory', \"512m\")\n # uid of run (we need a unique value to modify the yaml for each run)\n env_runid = {'name' : 'runid', 'value': uid}\n spark_k8s_app['spec']['driver']['env'].append(env_runid)\n \n \n # Executors\n spark_k8s_app['spec']['executor']['cores'] = get_in(runtime, 'metadata.executor.cores', 1)\n spark_k8s_app['spec']['executor']['instances'] = get_in(runtime, 'metadata.executor.instances', 3)\n spark_k8s_app['spec']['executor']['memory'] = get_in(runtime, 'metadata.executor.memory', \"512m\")\n # uid of run (we need a unique value to modify the yaml for each run)\n env_runid = {'name' : 'runid', 'value': uid}\n spark_k8s_app['spec']['executor']['env'].append(env_runid)\n \n # Addtional JARS\n JARS = get_in(runtime, 'metadata.ADDITIONAL_JARS', \"\")\n spark_k8s_app['spec']['deps']['jars'].append(JARS)\n \n file = open(\"/tmp/\" + spark_k8s_app['metadata']['name'] + \".yaml\",\"w\") \n file.write(yaml.dump(spark_k8s_app))\n file.close()\n \n \n \n \n \n # Submit application\n runapp = subprocess.run(['kubectl', 'apply', '-f' , '/tmp/' + spark_k8s_app['metadata']['name'] + \".yaml\"], stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n #runappp = self.apply_yaml(path.join('/tmp/',spark_k8s_app['metadata']['name'] + \".yaml\"))\n logger.info('Kubectl output: ' + runapp.stdout.decode('utf-8').replace(\",\",'') )\n logger.info('Submit exit Status: ' + str(runapp) )\n #logger.info('Submit exit Status: ' + str(runapp) )\n\n # Check for submision errors\n if runapp.returncode != 0:\n raise RunError('Failed to submit application: '+ runapp.stderr.decode('utf-8').replace(\"'\",'') )\n \n # If wait is set\n if WAIT:\n import time\n RUNNING = \"STARTING\"\n while RUNNING not in [ \"RUNNING\", \"COMPLETED\" , \"FAILED\" ]:\n result = subprocess.run(['kubectl', 'get', 'sparkapplications', spark_k8s_app['metadata']['name'],'-o','json',\"-o=jsonpath='{.status.applicationState.state}'\"], stdout=subprocess.PIPE)\n RUNNING = result.stdout.decode('utf-8').replace(\"'\",'')\n time.sleep(10)\n \n logger.info('Application status:' + RUNNING )\n if RUNNING == \"FAILED\":\n raise RunError('Failed to execute application')\n\n wait_cmd = subprocess.run(['kubectl', 'logs', spark_k8s_app['metadata']['name'] + '-driver','-f'], stdout=subprocess.PIPE)\n if VERBOSE:\n logger.info(wait_cmd.stdout.decode('utf-8'))\n \n \n result = subprocess.run(['kubectl', 'get', 'sparkapplications', spark_k8s_app['metadata']['name'],'-o','json',\"-o=jsonpath='{.status.applicationState.state}'\"], stdout=subprocess.PIPE) \n \n logger.info('Application execution status:' + result.stdout.decode('utf-8').replace(\"'\",''))\n return None\n \n\n\n\n def apply_yaml(self,sparkk8s_yaml):\n # Configs can be set in Configuration class directly or using helper\n # utility. If no argument provided, the config will be loaded from\n # default location.\n config.load_kube_config()\n\n with open(sparkk8s_yaml) as f:\n dep = yaml.safe_load(f)\n k8s_apps_v1 = client.AppsV1Api()\n resp = k8s_apps_v1.create_namespaced_deployment(body=dep, namespace=\"default\")\n \n #print(\"Deployment created. status='%s'\" % resp.metadata.name)\n return resp.metadata.name\n\n \n def sparkk8s_template(self):\n template={'apiVersion': 'sparkoperator.k8s.io/v1beta1',\n 'kind': 'SparkApplication',\n 'metadata': {'name': 'APP_NAME', 'namespace': 'default-tenant'},\n 'spec': {'type': 'Python',\n 'pythonVersion': '2',\n 'mode': 'cluster',\n 'image': 'urihoenig/spark-app-23:v01',\n 'imagePullPolicy': 'Always',\n 'mainApplicationFile': 'APP_FILE',\n 'sparkVersion': '2.4.0',\n 'restartPolicy': {'type': 'OnFailure',\n 'onFailureRetries': 'RETRIES',\n 'onFailureRetryInterval': 'RETRY_INTERVAL',\n 'onSubmissionFailureRetries': 'SUBMISSION_FAIL_RETRIES',\n 'onSubmissionFailureRetryInterval': 'SUBMISSION_FAIL_RETRIES_INTERVAL'},\n 'deps': {'jars': ['/igz/java/libs/v3io-hcfs_2.11-2.3_b118_20190707140045.jar',\n '/igz/java/libs/v3io-spark2-streaming_2.11-2.3_b118_20190707140045.jar',\n '/igz/java/libs/v3io-spark2-object-dataframe_2.11-2.3_b118_20190707140045.jar',\n '/igz/java/libs/scala-library-2.11.12.jar'],\n 'files': ['/igz/java/libs/v3io-py-2.3_b118_20190707140045.zip']},\n 'monitoring': {'exposeDriverMetrics': True},\n 'volumes': [{'hostPath': {'path': '/dev/shm/default-tenant', 'type': ''},\n 'name': 'shm'},\n {'hostPath': {'path': '/var/run/iguazio/dayman/default-tenant', 'type': ''},\n 'name': 'v3iod-comm'},\n {'configMap': {'defaultMode': 420, 'name': 'spark-operator-v3io-config'},\n 'name': 'v3io-config'},\n {'name': 'v3io-auth',\n 'secret': {'defaultMode': 420, 'secretName': 'AUTH_SECRET'}},\n {'name': 'v3io-fuse',\n 'flexVolume': {'driver': 'v3io/fuse',\n 'secretRef': {'name': 'FUSE_SECRET'}}},\n {'emptyDir': {}, 'name': 'daemon-health'}],\n 'driver': {'cores': 0.1,\n 'coreLimit': '200m',\n 'memory': '512m',\n 'labels': {'version': '2.4.0'},\n 'serviceAccount': 'spark-operator-spark',\n 'volumeMounts': [{'mountPath': '/etc/config/spark',\n 'name': 'spark-master-config'},\n {'mountPath': '/var/run/iguazio/daemon_health', 'name': 'daemon-health'},\n {'mountPath': '/dev/shm', 'name': 'shm'},\n {'mountPath': '/var/run/iguazio/dayman', 'name': 'v3iod-comm'},\n {'mountPath': '/etc/config/v3io', 'name': 'v3io-config'},\n {'mountPath': '/igz/.igz', 'name': 'v3io-auth'},\n {'mountPath': '/v3io', 'name': 'v3io-fuse'}],\n 'env': [{'name': 'IGZ_DATA_CONFIG_FILE',\n 'value': '/igz/java/conf/v3io.conf'},\n {'name': 'CURRENT_NODE_IP',\n 'valueFrom': {'fieldRef': {'apiVersion': 'v1',\n 'fieldPath': 'status.hostIP'}}},\n {'name': 'V3IO_USERNAME',\n 'valueFrom': {'secretKeyRef': {'key': 'username',\n 'name': 'AUTH_SECRET'}}},\n {'name': 'V3IO_ACCESS_KEY',\n 'valueFrom': {'secretKeyRef': {'key': 'accessKey',\n 'name': 'AUTH_SECRET'}}}]},\n 'executor': {'cores': 'CORES',\n 'instances': 'INSTANCES',\n 'memory': 'MEMORY',\n 'labels': {'version': '2.4.0'},\n 'volumeMounts': [{'mountPath': '/etc/config/spark',\n 'name': 'spark-master-config'},\n {'mountPath': '/var/run/iguazio/daemon_health', 'name': 'daemon-health'},\n {'mountPath': '/dev/shm', 'name': 'shm'},\n {'mountPath': '/var/run/iguazio/dayman', 'name': 'v3iod-comm'},\n {'mountPath': '/etc/config/v3io', 'name': 'v3io-config'},\n {'mountPath': '/igz/.igz', 'name': 'v3io-auth'},\n {'mountPath': '/v3io', 'name': 'v3io-fuse'}],\n 'env': [{'name': 'IGZ_DATA_CONFIG_FILE',\n 'value': '/igz/java/conf/v3io.conf'},\n {'name': 'CURRENT_NODE_IP',\n 'valueFrom': {'fieldRef': {'apiVersion': 'v1',\n 'fieldPath': 'status.hostIP'}}},\n {'name': 'V3IO_USERNAME',\n 'valueFrom': {'secretKeyRef': {'key': 'username',\n 'name': 'AUTH_SECRET'}}},\n {'name': 'V3IO_ACCESS_KEY',\n 'valueFrom': {'secretKeyRef': {'key': 'accessKey',\n 'name': 'AUTH_SECRET'}}}]}}}\n return template\n \n \ndef run_operator():\n import yaml\n import json\n from mlrun import get_or_create_ctx, run_start\n\n\n context = get_or_create_ctx('sparkk8s')\n sparkk8s_spec = context.get_param('sparkk8sspec', {})\n\n\n # IGUAZIO environment\n AUTH_SECRET = sparkk8s_spec.get('metadata.AUTH_SECRET',\"shell-um81v5npue-qh8oc-v3io-auth\")\n FUSE_SECRET = sparkk8s_spec.get('metadata.FUSE_SECRET',\"shell-um81v5npue-qh8oc-v3io-fuse\")\n\n rundb=sparkk8s_spec.get('rundb','')\n run_start(runtime=sparkk8s_spec, rundb=rundb, command='sparkk8s://')\n \nif __name__ == '__main__':\n run_operator()","sub_path":"mlrun/runtimes/spark_k8s.py","file_name":"spark_k8s.py","file_ext":"py","file_size_in_byte":12136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529805236","text":"_base_ = [\n '../../../_base_/models/atss_r50_fpn_zsd.py',\n '../../../_base_/datasets/coco_zero_shot_detection.py',\n '../../../_base_/schedules/schedule_1x_zsd.py', \n '../../../_base_/default_runtime.py'\n]\n\n# optimizer\noptimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)\n\n# distill setting\nmodel = dict(\n bbox_head=dict(\n use_loss_cls = False,\n dist_featuremap = False,\n dist_instance = True,\n )\n )\n","sub_path":"configs/atss/distill_instance/distill_without_loss_cls/atss_r50_fpn_1x_coco_zsd.py","file_name":"atss_r50_fpn_1x_coco_zsd.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641269383","text":"import numpy as np\n\ndef eval_adaBoost_leastSquare(X, alphaK, para):\n # INPUT:\n # para\t\t: parameters of simple classifier (K x (D +1)) \n # : dimension 1 is w0\n # : dimension 2 is w1\n # : dimension 3 is w2\n # and so on\n # alphaK : classifier voting weights (K x 1)\n # X : test data points (numSamples x numDim)\n #\n # OUTPUT:\n # classLabels: labels for data points (numSamples x 1)\n # result : weighted sum of all the K classifier (scalar)\n\n #####Start Subtask 1e#####\n K = para.shape[0]\n N = X.shape[0]\n result = np.zeros(N)\n\n for k in range(K):\n cY = np.sign(np.append(np.ones(N).reshape(N,1), X, axis = 1).dot(para[k])).T\n result = result + cY.dot(alphaK[k])\n\n classLabels = np.sign(result)\n #####End Subtask#####\n\n return [classLabels, result]\n\n","sub_path":"ML/Exercise 3 AdaBoost (22.12.2020)/exercise-03_solutions/q1_adaboost_python/eval_adaBoost_leastSquare.py","file_name":"eval_adaBoost_leastSquare.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408381447","text":"#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nimport time\nimport os\nimport sys\n\nfrom resource_rich.monitor.monitor_impl import MonitorBase\n\nfrom tools.run.util import Teed, Popen, StreamNoTimestamp\n\nDEFAULT_LOG_DIR=\"~/iot-trust-task-alloc/logs\"\n\nparser = argparse.ArgumentParser(description='Adversary runner')\nparser.add_argument('--log-dir', type=str, default=DEFAULT_LOG_DIR, help='The directory to store log output')\n\n# Flash.py\nparser.add_argument(\"--mote\", default=\"/dev/ttyUSB0\", help=\"The mote to flash.\")\nparser.add_argument(\"--mote_type\", choices=[\"zolertia\", \"telosb\"], default=\"zolertia\", help=\"The type of mote.\")\nparser.add_argument(\"--firmware_type\", choices=[\"contiki\", \"riot\"], default=\"contiki\", help=\"The OS that was used to create the firmware.\")\n\nargs = parser.parse_args()\n\nif args.log_dir.startswith(\"~\"):\n args.log_dir = os.path.expanduser(args.log_dir)\n\n# Create log dir if it does not exist\nif not os.path.isdir(args.log_dir):\n os.makedirs(args.log_dir)\n\nhostname = os.uname()[1]\n\nmotelist_log_path = os.path.join(args.log_dir, f\"adversary.{hostname}.motelist.log\")\nflash_log_path = os.path.join(args.log_dir, f\"adversary.{hostname}.flash.log\")\npyterm_log_path = os.path.join(args.log_dir, f\"adversary.{hostname}.pyterm.log\")\n\nprint(f\"Logging motelist to {motelist_log_path}\", flush=True)\nprint(f\"Logging flash to {flash_log_path}\", flush=True)\nprint(f\"Logging pyterm to {pyterm_log_path}\", flush=True)\n\nwith open(motelist_log_path, 'w') as motelist_log:\n teed = Teed()\n motelist = Popen(\n f\"./motelist-zolertia\",\n cwd=os.path.expanduser(\"~/pi-client/tools\"),\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n encoding=\"utf-8\",\n )\n teed.add(motelist,\n stdout=[motelist_log, StreamNoTimestamp(sys.stdout)],\n stderr=[motelist_log, StreamNoTimestamp(sys.stderr)])\n teed.wait()\n motelist.wait()\n\ntime.sleep(0.1)\n\nwith open(flash_log_path, 'w') as flash_log:\n teed = Teed()\n flash = Popen(\n f\"python3 flash.py '{args.mote}' adversary.bin {args.mote_type} {args.firmware_type}\",\n cwd=os.path.expanduser(\"~/pi-client\"),\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n encoding=\"utf-8\",\n )\n teed.add(flash,\n stdout=[flash_log, StreamNoTimestamp(sys.stdout)],\n stderr=[flash_log, StreamNoTimestamp(sys.stderr)])\n teed.wait()\n flash.wait()\n print(\"Flashing finished!\", flush=True)\n\ntime.sleep(0.1)\n\nwith open(pyterm_log_path, 'w') as pyterm_log, \\\n MonitorBase(f\"adversary.{hostname}\", log_dir=args.log_dir) as pcap_monitor:\n teed = Teed()\n\n # stdin=subprocess.PIPE is needed in order to ensure that a stdin handle exists.\n # This is because this script may be called under nohup in which case stdin won't exist.\n pyterm = Popen(\n f\"python3 pyterm -b 115200 -p {args.mote}\",\n cwd=os.path.expanduser(\"~/pi-client/tools\"),\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.PIPE,\n universal_newlines=True,\n encoding=\"utf-8\",\n )\n teed.add(pyterm,\n stdout=[pcap_monitor, pyterm_log, StreamNoTimestamp(sys.stdout)],\n stderr=[pcap_monitor, pyterm_log, StreamNoTimestamp(sys.stderr)])\n teed.wait()\n pyterm.wait()\n print(\"pyterm finished!\", flush=True)\n","sub_path":"tools/run/adversary.py","file_name":"adversary.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81817285","text":"\"\"\"\nHigh level abstraction interfaces to DFFML. These are probably going to be used\nin a lot of quick and dirty python files.\n\"\"\"\nimport pathlib\nfrom typing import Union, Dict, Any, AsyncIterator\n\nfrom .record import Record\nfrom .source.source import Sources, BaseSource\nfrom .source.memory import MemorySource, MemorySourceConfig\n\n\ndef _records_to_sources(*args):\n \"\"\"\n Create a memory source out of any records passed as a variable length list.\n Add all sources found in the variable length list to a list of sources, and\n the created source containing records, and return that list of sources.\n \"\"\"\n # If the first arg is an instance of sources, append the rest to that.\n if args and isinstance(args[0], Sources):\n sources = args[0]\n else:\n sources = Sources(\n *[arg for arg in args if isinstance(arg, BaseSource)]\n )\n # Records to add to memory source\n records = []\n # Make args mutable\n args = list(args)\n # Convert dicts to records\n for i, arg in enumerate(args):\n if isinstance(arg, dict):\n arg = Record(i, data={\"features\": arg})\n if isinstance(arg, Record):\n records.append(arg)\n if isinstance(arg, str) and \".\" in arg:\n filepath = pathlib.Path(arg)\n source = BaseSource.load(filepath.suffix.replace(\".\", \"\"))\n sources.append(source(filename=arg))\n # Create memory source if there are any records\n if records:\n sources.append(MemorySource(MemorySourceConfig(records=records)))\n return sources\n\n\nasync def save(source: BaseSource, *args: Record) -> None:\n \"\"\"\n Update a source's knowledge about given records.\n\n For each record given, call\n :py:func:`update ` on the\n source. Effectively saving all the records to the source.\n\n Parameters\n ----------\n source : BaseSource\n Data source to use. See :doc:`/plugins/dffml_source` for sources and\n options.\n *args : list\n Records to be saved.\n\n Examples\n --------\n\n >>> source = CSVSource(filename=\"save.csv\", allowempty=True, readwrite=True)\n >>>\n >>> async def main():\n ... await save(\n ... source,\n ... Record(\n ... \"myrecord\",\n ... data={\n ... \"features\": {\"Years\": 0, \"Expertise\": 1, \"Trust\": 0.1},\n ... \"prediction\": {\"Salary\": {\"value\": 10, \"confidence\": 1.0}},\n ... }\n ... )\n ... )\n ... print(pathlib.Path(\"save.csv\").read_text().strip())\n >>>\n >>> asyncio.run(main())\n key,tag,Expertise,Trust,Years,prediction_Salary,confidence_Salary\n myrecord,untagged,1,0.1,0,10,1.0\n \"\"\"\n async with source:\n async with source() as sctx:\n for record in args:\n await sctx.update(record)\n\n\nasync def load(source: BaseSource, *args: str) -> AsyncIterator[Record]:\n \"\"\"\n Yields records from a source.\n\n Yields all the records from the source, if record keys are given then only\n those records are yielded.\n\n Parameters\n ----------\n source : BaseSource\n Data source to use. See :doc:`/plugins/dffml_source` for sources and\n options.\n *args : str\n Records to be returned. If empty, all the records in a source will be returned.\n\n Returns\n -------\n asynciterator\n :py:class:`Record ` object\n\n Examples\n --------\n\n >>> source = CSVSource(filename=\"load.csv\", allowempty=True, readwrite=True)\n >>>\n >>> async def main():\n ... await save(\n ... source,\n ... Record(\"1\", data={\"features\": {\"A\": 0, \"B\": 1}}),\n ... Record(\"2\", data={\"features\": {\"A\": 3, \"B\": 4}}),\n ... )\n ...\n ... # All records in source\n ... async for record in load(source):\n ... print(record.export())\n ...\n ... # For specific records in a source\n ... async for record in load(source, \"1\"):\n ... print(record.export())\n >>>\n >>> asyncio.run(main())\n {'key': '1', 'features': {'A': 0, 'B': 1}, 'extra': {}}\n {'key': '2', 'features': {'A': 3, 'B': 4}, 'extra': {}}\n {'key': '1', 'features': {'A': 0, 'B': 1}, 'extra': {}}\n \"\"\"\n async with source:\n async with source() as sctx:\n if args:\n # If specific records are to be loaded\n for record in args:\n yield await sctx.record(record)\n else:\n # All the records are loaded\n async for record in sctx.records():\n yield record\n\n\nasync def train(model, *args: Union[BaseSource, Record, Dict[str, Any]]):\n \"\"\"\n Train a machine learning model.\n\n Provide records to the model to train it. The model should be already\n instantiated.\n\n Parameters\n ----------\n model : Model\n Machine Learning model to use. See :doc:`/plugins/dffml_model` for\n models options.\n *args : list\n Input data for training. Could be a ``dict``, :py:class:`Record`,\n filename, one of the data :doc:`/plugins/dffml_source`, or a filename\n with the extension being one of the data sources.\n\n Examples\n --------\n\n >>> model = SLRModel(\n ... features=Features(\n ... DefFeature(\"Years\", int, 1),\n ... ),\n ... predict=DefFeature(\"Salary\", int, 1),\n ... )\n >>>\n >>> async def main():\n ... await train(\n ... model,\n ... {\"Years\": 0, \"Salary\": 10},\n ... {\"Years\": 1, \"Salary\": 20},\n ... {\"Years\": 2, \"Salary\": 30},\n ... {\"Years\": 3, \"Salary\": 40},\n ... )\n >>>\n >>> asyncio.run(main())\n \"\"\"\n sources = _records_to_sources(*args)\n async with sources as sources, model as model:\n async with sources() as sctx, model() as mctx:\n return await mctx.train(sctx)\n\n\nasync def accuracy(\n model, *args: Union[BaseSource, Record, Dict[str, Any]]\n) -> float:\n \"\"\"\n Assess the accuracy of a machine learning model.\n\n Provide records to the model to assess the percent accuracy of its\n prediction abilities. The model should be already instantiated and trained.\n\n Parameters\n ----------\n model : Model\n Machine Learning model to use. See :doc:`/plugins/dffml_model` for\n models options.\n *args : list\n Input data for training. Could be a ``dict``, :py:class:`Record`,\n filename, one of the data :doc:`/plugins/dffml_source`, or a filename\n with the extension being one of the data sources.\n\n Returns\n -------\n float\n A decimal value representing the percent of the time the model made the\n correct prediction. For some models this has another meaning. Please see\n the documentation for the model your using for further details.\n\n Examples\n --------\n\n >>> model = SLRModel(\n ... features=Features(\n ... DefFeature(\"Years\", int, 1),\n ... ),\n ... predict=DefFeature(\"Salary\", int, 1),\n ... )\n >>>\n >>> async def main():\n ... print(\n ... \"Accuracy:\",\n ... await accuracy(\n ... model,\n ... {\"Years\": 4, \"Salary\": 50},\n ... {\"Years\": 5, \"Salary\": 60},\n ... ),\n ... )\n >>>\n >>> asyncio.run(main())\n Accuracy: 1.0\n \"\"\"\n sources = _records_to_sources(*args)\n async with sources as sources, model as model:\n async with sources() as sctx, model() as mctx:\n return float(await mctx.accuracy(sctx))\n\n\nasync def predict(\n model,\n *args: Union[BaseSource, Record, Dict[str, Any]],\n update: bool = False,\n keep_record: bool = False,\n):\n \"\"\"\n Make a prediction using a machine learning model.\n\n The model must be trained before using it to make a prediction.\n\n Parameters\n ----------\n model : Model\n Machine Learning model to use. See :doc:`/plugins/dffml_model` for\n models options.\n *args : list\n Input data for prediction. Could be a ``dict``, :py:class:`Record`,\n filename, or one of the data :doc:`/plugins/dffml_source`.\n update : boolean, optional\n If ``True`` prediction data within records will be written back to all\n sources given. Defaults to ``False``.\n keep_record : boolean, optional\n If ``True`` the results will be kept as their ``Record`` objects instead\n of being converted to a ``(record.key, features, predictions)`` tuple.\n Defaults to ``False``.\n\n Returns\n -------\n asynciterator\n ``Record`` objects or ``(record.key, features, predictions)`` tuple.\n\n Examples\n --------\n\n >>> model = SLRModel(\n ... features=Features(\n ... DefFeature(\"Years\", int, 1),\n ... ),\n ... predict=DefFeature(\"Salary\", int, 1),\n ... )\n >>>\n >>> async def main():\n ... async for i, features, prediction in predict(\n ... model,\n ... {\"Years\": 6},\n ... {\"Years\": 7},\n ... ):\n ... features[\"Salary\"] = round(prediction[\"Salary\"][\"value\"])\n ... print(features)\n >>>\n >>> asyncio.run(main())\n {'Years': 6, 'Salary': 70}\n {'Years': 7, 'Salary': 80}\n \"\"\"\n sources = _records_to_sources(*args)\n async with sources as sources, model as model:\n async with sources() as sctx, model() as mctx:\n async for record in mctx.predict(sctx.records()):\n yield record if keep_record else (\n record.key,\n record.features(),\n record.predictions(),\n )\n if update:\n await sctx.update(record)\n","sub_path":"dffml/high_level.py","file_name":"high_level.py","file_ext":"py","file_size_in_byte":9827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511723164","text":"# —*- coding: utf-8 -*-\n#! /usr/bin/env python\n\nimport numpy as np\nimport random as rd\nimport matplotlib.pyplot as plt\n\n# @param x, c: np.array\ndef D(x, c):\n\ttmp = x-c\n\treturn np.sum(tmp*tmp, axis=1)\t\n\n# @param class : np.array (matrix)\ndef update(cl):\n\tcnt = np.shape(cl)[0]\n\tsum = np.sum(cl, axis=0)\n\trepresent = sum / cnt * 1.0\n\treturn represent\n\ndef judge(current, prev, threshold):\n\tif False in (D(current, prev) < threshold):\n\t\treturn False\n\telse:\n\t\treturn True\n\n# @param c: np.array\n# @param k: int\ndef init(c,k):\n\trepresent = []\n\trandom = rd.randint(0,c.shape[0]-1)\n\trepresent.append(c[random])\n\tc = np.delete(c,random,axis=0)\n\tfor i in range(k)[1:]:\n\t\tdist = []\n\t\tfor x in c:\n\t\t\tdist.append(np.min(D(x, represent))**2)\n\t\tdist = np.array(dist)\n\t\tdist = dist / np.sum(dist)*1.0\n\t\ty = 1\n\t\tu = 0\n\t\twhile y > dist[u]:\n\t\t\ty = rd.uniform(np.min(dist), np.max(dist))\n\t\t\tu = rd.randint(0,c.shape[0]-1)\n\t\trepresent.append(c[u])\n\t\tc = np.delete(c,u,axis=0)\n\treturn represent\n\t\t\n\t\n\n# main\nc = []\nfor line in open(\"data.txt\", \"r\"):\n\tdata = line.split(\",\")\n\tfor i in range(len(data)-1):\n\t\tdata[i] = float(data[i])\n\tc.append(data[:4])\nc = np.array(c)\n\ncolors = ['b','g','r','k','w']\n\nfor k in [2,3,4,5]:\n\twhile True:\n\t\trepresent = init(c,k)\n\t\tclassified = [[] for i in range(k)]\n\t\tfor x in c:\n\t\t\tj = np.argmin(D(x,represent))\n\t\t\tclassified[j].append(x)\n\t\tcurrent = []\n\t\tfor i in range(k):\n\t\t\tcurrent.append(update(classified[i]))\n\t\tif judge(np.array(current),np.array(represent),0.1):\n\t\t\tbreak\n\t\telse:\n\t\t\trepresent = current\n\tfor i in range(k):\n\t\tplt.scatter(np.array(classified[i]).T[0],np.array(classified[i]).T[1], c=colors[i])\n\tplt.show()\n\t\n# test\nA = np.array([[1,2,3],[2,3,1]])\nB = np.array([[2,1,3],[2,2,3]])\n\n\n","sub_path":"pattern/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335396989","text":"import sqlite3\nfrom sqlite3 import Error\n\nsqlite_file = \"trakt_shows.db\"\ntable_name = \"shows\"\n\np_key_column = \"p_key\"\nstub_column = \"show_stub\"\nshow_column = \"show_name\"\nseason_column = \"season\"\nepisode_number_column = \"episode_number\"\nepisode_title_column = \"episode_title\"\nwatched_status_column = \"watched_status\"\nhidden_status_column = \"hidden_status\"\n\ncreate_table_sql = f'CREATE TABLE {table_name} (' \\\n\t\t\t\t\t\t\t\t\t f'{p_key_column} TEXT PRIMARY KEY, ' \\\n\t\t\t\t\t\t\t\t\t f'{stub_column} TEXT, ' \\\n\t\t\t\t\t\t\t\t\t f'{show_column} TEXT, ' \\\n\t\t\t\t\t\t\t\t\t f'{season_column} INTEGER, ' \\\n\t\t\t\t\t\t\t\t\t f'{episode_number_column} INTEGER, ' \\\n\t\t\t\t\t\t\t\t\t f'{episode_title_column} TEXT, ' \\\n\t\t\t\t\t\t\t\t\t f'{watched_status_column} INTEGER, ' \\\n\t\t\t\t\t\t\t\t\t f'{hidden_status_column} INTEGER)'\n\ndef get_p_key(episode_info):\n\t\"\"\" create the primary key field by concatenating episode information\n\t:param episode_info: Dictionary of a single episode\n\t\"\"\"\n\treturn f'{episode_info[\"show_stub\"]}S{episode_info[\"season\"]}E{episode_info[\"episode\"]}'\n\t\n\ndef execute_sql(conn, query):\n\t\"\"\" execute a provided sql query on a provided connection\n\t:param conn: a database connection object\n\t:param query: a full sql query to execute\n\t\"\"\"\n\ttry:\n\t\t\tc = conn.cursor()\n\t\t\tc.execute(query)\n\texcept Error as e:\n\t\t\tprint(f\"SQL error :{e}\")\n\t\t\tprint(f\"Attempted to run: {query}\")\n\t\t\t\n\treturn c\n\ndef create_connection(db_file):\n\t\"\"\" create a database connection to the SQLite database \n\t:param db_file: the database file to connect to\n\t\"\"\"\n\ttry:\n\t\tconn = sqlite3.connect(db_file)\n\texcept Error as e:\n\t\tprint(e)\n\t\n\treturn conn\n\t\n\t\t\ndef insert_row(conn, episode_info):\n\t\"\"\" inserts a row of episode data into the provided database connection\n\t:param conn: Connection object\n\t:param episode_info: dictionary of episode information\n\t\"\"\"\n\tp_key = get_p_key(episode_info)\n\t\n\tinsert_statement = f'INSERT INTO shows (p_key, show_stub, show_name, season, episode_number, episode_title watched_status, hidden_status) VALUES (\\\"{p_key}\\\", \\\"{episode_info[\"show_stub\"]}\\\", \\\"{episode_info[\"show_name\"]}\\\", {episode_info[\"season\"]}, {episode_info[\"episode_number\"]}, {episode_info[\"episode_title\"]}, {episode_info[\"watched_status\"]}, {episode_info[\"hidden_status\"]});'\n\t\n\texecute_sql(conn, insert_statement)\n\t\t\n\ndef update_status(conn, episode_info, status=\"watched_status\"):\n\t\"\"\" update the watched status on a given row\n\t:param conn: Connection object\n\t:param episode_info: dictionary of episode information\n\t:param status: string, either \"watched_status\" or \"hidden_status\". Defaults to \"watched_status\"\n\t\"\"\"\n\tp_key = get_p_key(episode_info)\n\t\n\tstatus_update = f'UPDATE shows SET watched_status = {episode_info[status]} WHERE p_key = \"{p_key}\";'\n\t\n\texecute_sql(conn, status_update)\n\t\n\t\t\ndef get_latest_unwatched(conn, show_stub):\n\t\t\"\"\" pull the latest episode of a given show that is available to watch and currently unwatched\n\t\t:param show_stub: trak.tv stub of the show to search for\n\t\t\"\"\"\n\t\tsql_query = f'SELECT \"show_name\", \"season\", \"episode_number\", \"episode_title\" FROM shows WHERE show_stub = \"{show_stub}\" AND \"watched_status\" = 0 ORDER BY \"season\", \"episode\"'\n\t\t\n\t\tepisode_list = execute_sql(conn, sql_query).fetchall()\n\t\t\n\t\treturn episode_list\n\t\t\n\nif __name__ == \"__main__\":\n\tconn = create_connection(sqlite_file)\n\t\n\tprint(get_latest_unwatched(conn, 'game-of-thrones'))\n\t\n\tconn.commit()\n\tconn.close()","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"555694171","text":"\"\"\"Performs the statiscal tests to evaluate the best approach\"\"\"\n\nimport math\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport Orange\nimport os\n\nfrom scipy.stats import friedmanchisquare\nfrom nemenyi import NemenyiTestPostHoc\nfrom utils import get_all_proportions_sample, read_all, get_nemenyi_stat\n\nplt.style.use('ggplot')\n\nSIGNIFICANCE_LEVEL = 0.05\n\nMESDIF_COMP = [\n \"mesdif\",\n \"mesdif_a1.0_b1.0\",\n \"mesdif_a1.0_b3.0\",\n \"mesdif_a1.0_b9.0\",\n \"mesdif_a1.0_b27.0\",\n \"mesdif_a1.0_b81.0\"\n]\n\nNMEEF_COMP = [\n \"nmefsd\",\n \"nmefsd_a1.0_b1.0\",\n \"nmefsd_a1.0_b3.0\",\n \"nmefsd_a1.0_b9.0\",\n \"nmefsd_a1.0_b27.0\",\n \"nmefsd_a1.0_b81.0\"\n]\n\nSSDP_COMP = [\n \"ssdp\",\n \"ssdp_a1.0_b1.0\",\n \"ssdp_a1.0_b3.0\",\n \"ssdp_a1.0_b9.0\",\n \"ssdp_a1.0_b27.0\",\n \"ssdp_a1.0_b81.0\"\n]\n\nCOMPETITIONS = {\n \"mesdif\": MESDIF_COMP,\n \"nmefsd\": NMEEF_COMP,\n \"ssdp\": SSDP_COMP,\n \"all\": [\n \"ssdp\",\n \"mesdif_a1.0_b81.0\",\n \"nmefsd_a1.0_b81.0\",\n \"ssdp_a1.0_b81.0\",\n \"mesdif\",\n \"nmefsd\"\n ]\n}\n\ndef format_float(val: float) -> str:\n \"\"\"Formats the float number to be better visualized\"\"\"\n if val < 0.0001:\n return \"{:.2e}\".format(val)\n else:\n return \"{:.4f}\".format(val)\n\ndef fmt(competitor_name: str) -> str:\n \"\"\"Formats the competitor's name\"\"\"\n name = competitor_name.replace(\"_a\", r\" $\\alpha$ \")\n name = name.replace(\"_b\", r\" $\\beta$ \")\n return name\n\ndef compete(algorithms, metric:str):\n \"\"\"Makes the statiscal tests for all competitions using the given metric\"\"\"\n samples = get_all_proportions_sample(metric, algorithms)\n for competition_name in COMPETITIONS:\n competitors = list()\n for competitor in COMPETITIONS[competition_name]:\n competitors.append(samples[competitor])\n _, pvalue = friedmanchisquare(*competitors)\n print(metric + \", \" + competition_name + \": pvalue = \" +\n format_float(pvalue))\n if pvalue < SIGNIFICANCE_LEVEL:\n # Invert the measures, because Nemeyi expects ordering to be from\n # lowest to highest\n measures = list()\n for competitor in COMPETITIONS[competition_name]:\n if metric == \"WRACC\":\n measures.append([0.25 - s for s in samples[competitor]])\n elif metric == \"Support\":\n measures.append([1 - s for s in samples[competitor]])\n else:\n raise ValueError(\"Unknown metric '{0}'\".format(metric))\n nemenyi = NemenyiTestPostHoc(np.asarray(measures))\n mean_ranks, _ = nemenyi.do()\n ncompetitors = len(competitors)\n nemenyistat = get_nemenyi_stat(ncompetitors, SIGNIFICANCE_LEVEL)\n cdiff = nemenyistat * math.sqrt((ncompetitors * (ncompetitors + 1))\\\n / (6 * len(measures[0])))\n Orange.evaluation.graph_ranks(mean_ranks,\n list(map(fmt, COMPETITIONS[competition_name])),\n cd=cdiff, textspace=1.6)\n imgpath = os.path.join(\"images\",\n competition_name + \"_\" + metric + \".pdf\")\n ax = plt.gca()\n ax.text(0.1, 0.9, metric, horizontalalignment=\"center\",\n verticalalignment=\"center\", transform=ax.transAxes)\n plt.savefig(imgpath)\n\ndef main():\n \"\"\"Main function\"\"\"\n algorithms, _ = read_all(\"data\")\n compete(algorithms, \"WRACC\")\n compete(algorithms, \"Support\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/stat_tests.py","file_name":"stat_tests.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"286889949","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Move the SV2 INFO fields that belong to FORMAT where they belong.\n\"\"\"\n\nimport argparse\nimport itertools\nimport logging\nimport sys\n\nimport vcfpy\n\n# White-listed chromosomes.\nCHROMS = tuple(itertools.chain(map(str, range(1, 23)), (\"X\", \"Y\")))\n\n\ndef full_chromosomes(reader):\n \"\"\"Return list of regions of all chromosomes of VCF reader.\"\"\"\n for line in reader.header.get_lines(\"contig\"):\n if line.id in CHROMS:\n name = line.id\n length = line.length\n yield \"{}:{}-{}\".format(name, 1, length)\n\n\nclass InfoToFormatApp:\n \"\"\"Conversion from INFO to FORMAT field\"\"\"\n\n def __init__(self, args):\n #: Command line arguments.\n self.args = args\n # Setup the logging.\n self._setup_logging()\n\n def _setup_logging(self):\n logging.basicConfig(\n format=\"%(asctime)s %(name)-12s %(levelname)-8s %(message)s\", datefmt=\"%m-%d %H:%M\"\n )\n logger = logging.getLogger(\"\")\n if self.args.verbose:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.INFO)\n\n def _print_header(self):\n logging.info(\"INFO to FORMAT\")\n logging.info(\"Arguments: %s\", self.args)\n\n def _process_region(self, region, writer):\n \"\"\"Process a single region and write its result to the writer.\"\"\"\n\n def _augment_header(self, header):\n \"\"\"Augment header information\"\"\"\n header = self._augment_filter(header)\n header = self._augment_info(header)\n header = self._augment_format(header)\n return header\n\n def _augment_filter(self, header):\n \"\"\"Augment header for FILTER column\"\"\"\n return header\n\n def _augment_info(self, header):\n \"\"\"Augment header for INFO column\"\"\"\n return header\n\n def _augment_format(self, header):\n \"\"\"Augment header for FORMAT column\"\"\"\n header.add_info_line(\n vcfpy.OrderedDict(\n [\n (\"ID\", \"SVMETHOD\"),\n (\"Number\", \"1\"),\n (\"Type\", \"String\"),\n (\"Description\", \"Type of approach used to detect SV\"),\n ]\n )\n )\n header.add_format_line(\n vcfpy.OrderedDict(\n [\n (\"ID\", \"FT\"),\n (\"Number\", \".\"),\n (\"Type\", \"String\"),\n (\"Description\", \"Filters from FILTER column of genotyping\"),\n ]\n )\n )\n header.add_format_line(\n vcfpy.OrderedDict(\n [\n (\"ID\", \"DFT\"),\n (\"Number\", \"1\"),\n (\"Type\", \"String\"),\n (\n \"Description\",\n \"Stringent filter status, recommended for de novo mutation discovery\",\n ),\n ]\n )\n )\n header.add_format_line(\n vcfpy.OrderedDict(\n [\n (\"ID\", \"RG\"),\n (\"Number\", \"1\"),\n (\"Type\", \"Float\"),\n (\"Description\", \"Median Phred-adjusted REF genotype likelihood\"),\n ]\n )\n )\n header.add_format_line(\n vcfpy.OrderedDict(\n [\n (\"ID\", \"AF\"),\n (\"Number\", \"1\"),\n (\"Type\", \"String\"),\n (\"Description\", \"Alternate allele frequency,in the range (0,1)\"),\n ]\n )\n )\n return header\n\n def run(self):\n self._print_header()\n with vcfpy.Reader.from_path(self.args.input) as reader:\n # If no regions are given, fall back to all chromosomes.\n regions = full_chromosomes(reader)\n # Extend header with new lines.\n header = self._augment_header(reader.header)\n # Open the VCF writer for writing and process each region.\n with vcfpy.Writer.from_path(self.args.output, header) as writer:\n for region in regions:\n logging.info(\"Processing %s\", region)\n try:\n records = reader.fetch(region)\n except ValueError:\n records = []\n logging.warning(\"Could not fetch records for %s\", region)\n for record in records:\n record = self._process(record)\n writer.write_record(record)\n\n def _process(self, record):\n \"\"\"Process ``record``.\"\"\"\n filters = list(record.FILTER)\n if \"PASS\" in filters and len(filters) > 0:\n filters = [f for f in filters if f != \"PASS\"]\n elif not filters:\n filters = [\"PASS\"]\n record.INFO[\"SVMETHOD\"] = self.args.svmethod\n record.add_format(\"FT\", filters)\n record.add_format(\"RG\", record.INFO.get(\"REF_GTL\"))\n record.add_format(\"DFT\", record.INFO.get(\"DENOVO_FILTER\"))\n record.add_format(\"AF\", record.INFO.get(\"AF\"))\n record.FILTER = []\n del record.INFO[\"REF_GTL\"]\n del record.INFO[\"DENOVO_FILTER\"]\n del record.INFO[\"AF\"]\n return record\n\n\ndef main(argv=None):\n parser = argparse.ArgumentParser(description=\"Move SV2 INFO to FORMAT fields\")\n\n # -----------------------------------------------------------------------\n group = parser.add_argument_group(\"General Options\")\n group.add_argument(\"-v\", \"--verbose\", default=0, action=\"count\")\n\n group = parser.add_argument_group(\"Input / Output Options\")\n group.add_argument(\"--svmethod\", required=True, help=\"name to put into SVMETHOD INFO field\")\n group.add_argument(\"--input\", required=True, help=\"input VCF file\")\n group.add_argument(\"--output\", help=\"output VCF file\", default=\"/dev/stdout\")\n\n args = parser.parse_args(argv)\n return InfoToFormatApp(args).run()\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"snappy_wrappers/wrappers/erds_sv2/info_to_format/info_to_format.py","file_name":"info_to_format.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"4024977","text":"import socket\nimport re\n\n\ndef client(http_server_socket):\n new_socket, addr = http_server_socket.accept()\n print('new from ------>', addr)\n content_addr = './static/'\n a = new_socket.recv(1024).decode().split('\\r\\n')\n if re.fullmatch(r'GET /.+ HTTP/1.1', a[0]):\n content_name = a[0][5:-9]\n print(content_name)\n if content_name.endswith('.py'):\n content_addr = ''\n elif content_name == '':\n content_name = 'index.html'\n\n response_line = 'HTTP/1.1 200 OK' + '\\r\\n'\n response_header = 'Server: miniweb1.0\\r\\n'\n response_header += 'Content-Type: text/html;charset=utf-8\\r\\n'\n try:\n with open(content_addr + content_name, 'rb') as f:\n response_body = f.read()\n except:\n response_body = ''.encode()\n\n response_data = response_line + response_header + '\\r\\n'\n new_socket.send(response_data.encode('utf-8'))\n new_socket.send(response_body)\n new_socket.close()\n print('=====================================')\n\n\ndef main():\n http_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n http_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n http_server_socket.bind(('', 5050))\n http_server_socket.listen(10)\n while True:\n client(http_server_socket)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"week6/day3/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"357584117","text":"# coding:iso-8859-9 Türkçe\r\n# p_31503.py: Çoklu farklı ebatlı altşekiller örneği.\r\n\r\n#import numpy as np\r\nimport matplotlib.pyplot as mp\r\n\r\nmp.style.use (\"dark_background\")\r\nX = [ (3,1,1), (3,3,4), (3,3,5), (3,3,6), (3,1,3)]\r\nfor satır, sütun, aktifNo in X:\r\n mp.subplot (satır, sütun, aktifNo).set_facecolor (\"Tan\")\r\n\r\nmp.tight_layout()\r\nmp.show()\r\n#----------------------------------------------------------------------------------------------------\r\n\r\nşekil =mp.figure (figsize=(6,4))\r\nşekil.subplots_adjust (bottom=0, left=0, top = 1, right=1)\r\nşekil.set_facecolor (\"LightSlateGray\")\r\n\r\nfor i, j, n in X:\r\n altşekil = şekil.add_subplot (i, j, n)\r\n altşekil.set_xticks ([])\r\n altşekil.set_yticks ([])\r\nmp.show()\r\n#----------------------------------------------------------------------------------------------------\r\n\r\nX = [ (3,3,(1,3)), (3,3,4), (3,3,5), (3,3,6), (3,3,(7,9))] # 3 satır 3 kolon ve 9 aktifNo'lar...\r\nşekil =mp.figure (figsize=(6,4))\r\nşekil.subplots_adjust (bottom=0.05, left=0.05, top = 0.95, right=0.95)\r\nşekil.set_facecolor('OliveDrab')\r\n\r\nfor i, j, n in X:\r\n altşekil = şekil.add_subplot (i, j, n)\r\n mp.fill_between ([0,1], [0,1], 0, color='Navy', alpha=.9)\r\n mp.fill_between ([0,1], [0,1],1, color='Brown', alpha=.7)\r\n mp.xlim (0,1)\r\n mp.ylim (0,1)\r\n altşekil.set_xticks ([])\r\n altşekil.set_yticks ([])\r\nmp.show()\r\n","sub_path":"Bernd Klein (520) ile Python/p_31503.py","file_name":"p_31503.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139085527","text":"from __future__ import division\nimport time\nimport Adafruit_PCA9685.PCA9685\nfrom .config import *\n\n\n\nclass RunServos(object):\n def __init__(self):\n\n # top servo controller\n self.tpwm = Adafruit_PCA9685.PCA9685(0x41)\n # bottom servo controller\n self.bpwm = Adafruit_PCA9685.PCA9685(0x40)\n self.tpwm.set_pwm_freq(60)\n self.bpwm.set_pwm_freq(60)\n \n self.commands = 0\n self.c = 0\n\n def testlist(self, x, toppulseDict, channel, lastpulsetop, lastpulsesbot, i):\n try:\n pulse = toppulseDict[channel][x]\n self.last = pulse\n except:\n if CONTROLLER[i] == 1:\n pulse = lastpulsesbot[channel]\n elif CONTROLLER[i] == 2:\n pulse = lastpulsetop[channel]\n pass\n return pulse\n\n def dopwm(self, x,botpulseDict ,toppulseDict, lastpulsestop, lastpulsesbot):\n for i in range(0,self.commands):\n pwm,pulsedict = self.checkpwm(toppulseDict,botpulseDict)\n pwm.set_pwm(CHANNELS[i], 0, self.testlist(x, pulsedict, CHANNELS[i], lastpulsestop, lastpulsesbot, i))\n #print(i)\n\n def checkpwm(self,top,bot):\n if self.c < self.commands:\n if CONTROLLER[self.c] == 1:\n pwm = self.bpwm\n d = bot\n elif CONTROLLER[self.c] == 2:\n pwm = self.tpwm\n d = top\n self.c = self.c + 1\n else:\n self.c = 0\n if CONTROLLER[self.c] == 1:\n pwm = self.bpwm\n d=bot\n elif CONTROLLER[self.c] == 2:\n pwm = self.tpwm\n d=top\n self.c = self.c + 1\n return pwm,d\n\n def servos(self,botpulseDict ,toppulseDict, lastpulsestop, lastpulsesbot):\n self.c = 0\n self.commands = len(CHANNELS)\n #print(self.commands)\n #finds the biggest list in the dictionary\n try:\n maxtopkey = max(toppulseDict, key=lambda x: len(set(toppulseDict[x])))\n maxtoplist = len(toppulseDict[maxtopkey])\n except:\n maxtoplist = 0\n pass\n try:\n maxbotkey = max(botpulseDict, key=lambda x: len(set(botpulseDict[x])))\n maxbotlist = len(botpulseDict[maxbotkey])\n except:\n maxbotlist = 0\n pass\n if maxtoplist > maxbotlist:\n maxlist = maxtoplist\n else:\n maxlist = maxbotlist\n for x in range(0, maxlist):\n self.dopwm(x,botpulseDict ,toppulseDict, lastpulsestop, lastpulsesbot)","sub_path":"projects/drivers/servos/runservos.py","file_name":"runservos.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53624909","text":"import sqlite3\nimport arrow\n\nfrom flask import json, make_response, request\nfrom werkzeug.utils import secure_filename\n\nfrom charminar_explorer_service import app, config, logger\nfrom charminar_explorer_service.models.category import Category\nfrom charminar_explorer_service.models.event import Event\nfrom charminar_explorer_service.utils import category_utils, event_utils\n\n\n@app.route('/events/list-all-events', methods=['GET'])\ndef list_all_events():\n '''\n List all events\n '''\n try:\n\n _future_events = event_utils.get_all_events()\n _past_events = event_utils.get_all_events(past=True)\n\n future_events_list = []\n for e_row in _future_events:\n e = event_utils.create_event_object(e_row)\n future_events_list.append(e.__dict__)\n\n past_events_list = []\n for e_row in _past_events:\n e = event_utils.create_event_object(e_row)\n past_events_list.append(e.__dict__)\n\n response = {\"future_events\": future_events_list,\n \"past_events\": past_events_list}\n\n json_resp = json.dumps(response)\n http_resp = make_response(json_resp, config.HTTP_STATUS_OK)\n http_resp.headers['Content-Type'] = 'application/json'\n return http_resp\n\n except Exception as ex:\n logger.exception(\"Error %s !\", str(ex))\n resp = {\"error\": \"something went wrong !\"}\n return make_response(json.dumps(resp), config.HTTP_STATUS_ERROR)\n","sub_path":"charminar_explorer_service/endpoints/event/list_all_events.py","file_name":"list_all_events.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268900168","text":"#135 - O Escolhido\n\nN = int(input())\nmaiorNota = 0.0\nalMaior = 0\n\nfor k in range(N):\n Mat, Nota = input().split()\n if float(Nota) > maiorNota:\n maiorNota = float(Nota)\n alMaior = int(Mat)\nif maiorNota >= 8.0:\n print(alMaior)\nelse:\n print('Minimum note not reached')\n\n\n\n","sub_path":"URI/135[URI 1983] - O Escolhido.py","file_name":"135[URI 1983] - O Escolhido.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389186031","text":"\"\"\"\n\nQuintic Polynomials Planner\n\nauthor: Atsushi Sakai (@Atsushi_twi)\n\nRef:\n\n- [Local Path planning And Motion Control For Agv In Positioning](http://ieeexplore.ieee.org/document/637936/)\n\n\"\"\"\n\nimport math\n\nimport numpy as np\n\n# parameter\nMAX_T = 20.0 # maximum time to the goal [s]\nMIN_T = 1.0 # minimum time to the goal[s]\n\n\nclass QuinticPolynomial:\n def __init__(self, xs, vxs, axs, xe, vxe, axe, time):\n self.a0 = xs\n self.a1 = vxs\n self.a2 = axs / 2.0\n\n A = np.array([[time ** 3, time ** 4, time ** 5],\n [3 * time ** 2, 4 * time ** 3, 5 * time ** 4],\n [6 * time, 12 * time ** 2, 20 * time ** 3]])\n b = np.array([xe - self.a0 - self.a1 * time - self.a2 * time ** 2,\n vxe - self.a1 - 2 * self.a2 * time,\n axe - 2 * self.a2])\n x = np.linalg.solve(A, b)\n\n self.a3 = x[0]\n self.a4 = x[1]\n self.a5 = x[2]\n\n def calc_point(self, t):\n xt = self.a0 + self.a1 * t + self.a2 * t ** 2 + \\\n self.a3 * t ** 3 + self.a4 * t ** 4 + self.a5 * t ** 5\n\n return xt\n\n def calc_first_derivative(self, t):\n xt = self.a1 + 2 * self.a2 * t + \\\n 3 * self.a3 * t ** 2 + 4 * self.a4 * t ** 3 + 5 * self.a5 * t ** 4\n\n return xt\n\n def calc_second_derivative(self, t):\n xt = 2 * self.a2 + 6 * self.a3 * t + 12 * self.a4 * t ** 2 + 20 * \\\n self.a5 * t ** 3\n\n return xt\n\n def calc_third_derivative(self, t):\n xt = 6 * self.a3 + 24 * self.a4 * t + 60 * self.a5 * t ** 2\n\n return xt\n\n\ndef quintic_polynomials_planner(sx, sy, syaw, sv, sa, gx, gy, gyaw, gv, ga,\n max_accel, max_jerk, dt):\n \"\"\"\n Quintic polynomial planner.\n\n Args\n sx: start x position [m]\n sy: start y position [m]\n syaw: start yaw angle [rad]\n sa: start accel [m/ss]\n gx: goal x position [m]\n gy: goal y position [m]\n gyaw: goal yaw angle [rad]\n ga: goal accel [m/ss]\n max_accel: maximum accel [m/ss]\n max_jerk: maximum jerk [m/sss]\n dt: time tick [s]\n\n Returns\n time: time result\n rx: x position result list\n ry: y position result list\n ryaw: yaw angle result list\n rv: velocity result list\n ra: accel result list\n\n \"\"\"\n\n vxs = sv * math.cos(syaw)\n vys = sv * math.sin(syaw)\n vxg = gv * math.cos(gyaw)\n vyg = gv * math.sin(gyaw)\n\n axs = sa * math.cos(syaw)\n ays = sa * math.sin(syaw)\n axg = ga * math.cos(gyaw)\n ayg = ga * math.sin(gyaw)\n\n time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], []\n\n for T in np.arange(MIN_T, MAX_T, MIN_T):\n xqp = QuinticPolynomial(sx, vxs, axs, gx, vxg, axg, T)\n yqp = QuinticPolynomial(sy, vys, ays, gy, vyg, ayg, T)\n\n time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], []\n\n for t in np.arange(0.0, T + dt, dt):\n time.append(t)\n rx.append(xqp.calc_point(t))\n ry.append(yqp.calc_point(t))\n\n vx = xqp.calc_first_derivative(t)\n vy = yqp.calc_first_derivative(t)\n v = np.hypot(vx, vy)\n yaw = math.atan2(vy, vx)\n rv.append(v)\n ryaw.append(yaw)\n\n ax = xqp.calc_second_derivative(t)\n ay = yqp.calc_second_derivative(t)\n a = np.hypot(ax, ay)\n if len(rv) >= 2 and rv[-1] - rv[-2] < 0.0:\n a *= -1\n ra.append(a)\n\n jx = xqp.calc_third_derivative(t)\n jy = yqp.calc_third_derivative(t)\n j = np.hypot(jx, jy)\n if len(ra) >= 2 and ra[-1] - ra[-2] < 0.0:\n j *= -1\n rj.append(j)\n\n if max([abs(i) for i in ra]) <= max_accel and \\\n max([abs(i) for i in rj]) <= max_jerk:\n print(\"find path!!\")\n break\n\n return time, rx, ry, ryaw, rv, ra, rj\n\n","sub_path":"pylot/planning/frenet_optimal_trajectory/quintic_polynomials.py","file_name":"quintic_polynomials.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366212395","text":"import aiohttp\r\nimport asyncio\r\n\r\nfrom utils.Base_spider import BaseSpider\r\n\r\n\r\nclass IllegalPut(BaseSpider):\r\n \"\"\"\r\n 严重违法爬虫(列入)\r\n \"\"\"\r\n\r\n def __init__(self, *args, **kwargs):\r\n # 继承父类的方法\r\n super().__init__(*args, **kwargs)\r\n\r\n async def detail_one_parse(self, tr, company_name, company_id):\r\n \"\"\"\r\n 单独解析一个tr\r\n :param tr:\r\n :param company_name:\r\n :param company_id:\r\n :return:\r\n \"\"\"\r\n # 列入日期\r\n putDate = ''.join(self.get_xpath('./td[2]//text()', html=tr))\r\n # 列入决定机关\r\n putDepartment = ''.join(self.get_xpath('./td[3]//text()', html=tr))\r\n # 列入严重违法原因\r\n putReason = ''.join(self.get_xpath('./td[4]//text()', html=tr))\r\n\r\n kwargs = {\r\n 'putDate': putDate,\r\n 'putDepartment': putDepartment,\r\n 'putReason': putReason,\r\n 'company_name': company_name,\r\n 'company_id': company_id,\r\n 'illegal_type': '2'\r\n }\r\n\r\n tup = ('removeReason', 'removeDepartment', 'putDate', 'putReason', 'putDepartment', 'removeDate',\r\n 'company_name', 'company_id', 'illegal_type')\r\n values, keys = self.structure_sql_statement(tup, kwargs)\r\n sql = f'insert into das_tm_illegal_info {keys} value {values};'\r\n print(sql)\r\n self.operating.save_mysql(sql)\r\n\r\n async def parse(self, company_id, company_name, ps=20, pn=1, resp=None):\r\n \"\"\"\r\n 对应的ajax接口爬取\r\n :param company_id:\r\n :param company_name:\r\n :param ps:\r\n :param pn:\r\n :param resp:\r\n :return:\r\n \"\"\"\r\n # resp = self.download(\r\n # f'https://www.tianyancha.com/pagination/stockChangeInfo.xhtml?ps={ps}0&pn={pn}&id={company_id}&_={self.get_now_timestamp()}')\r\n # # 获取所有的trs\r\n # try:\r\n # trs = self.get_xpath('//table[@class=\"table\"]/tbody/tr', response=resp.text)\r\n # # 详情解析\r\n # # self.detail_parse(trs, company_name)\r\n # # 对一个tr进行解析\r\n # for tr in trs:\r\n # self.detail_one_parse(tr, company_name, company_id)\r\n #\r\n # except Exception as e:\r\n # pass\r\n\r\n try:\r\n url = f'https://www.tianyancha.com/pagination/illegalPut.xhtml?ps={ps}&pn={pn}&id={company_id}&_={self.get_now_timestamp()}'\r\n async with aiohttp.ClientSession() as session:\r\n async with session.get(url, headers=self.get_headers) as resp:\r\n response = await resp.text() if await resp.text() else '
'\r\n trs = self.get_xpath('//table[@class=\"table -breakall\"]/tbody/tr', response=response)\r\n if trs:\r\n await asyncio.gather(*[self.detail_one_parse(tr, company_name, company_id) for tr in trs])\r\n else:\r\n print('数据为空')\r\n except Exception as e:\r\n print(f'类 - - {IllegalPut.__name__} - - 异步请求出错:', e)\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"Dimension_spider/business_risk/illegal_put_spider.py","file_name":"illegal_put_spider.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609178275","text":"import dash\nimport dash_html_components as html\n\nimport dash_vtk\nfrom dash_vtk.utils import to_volume_state\n\ntry:\n # VTK 9+\n from vtkmodules.vtkImagingCore import vtkRTAnalyticSource\nexcept:\n # Old VTK\n from vtk.vtkImagingCore import vtkRTAnalyticSource\n\n# Use VTK to get some data\ndata_source = vtkRTAnalyticSource()\ndata_source.Update() # <= Execute source to produce an output\ndataset = data_source.GetOutput()\n\n# Use helper to get a volume structure that can be passed as-is to a Volume\nvolume_state = to_volume_state(dataset) # No need to select field\n\ncontent = dash_vtk.View([\n dash_vtk.VolumeRepresentation([\n # GUI to control Volume Rendering\n # + Setup good default at startup\n dash_vtk.VolumeController(),\n # Actual volume\n dash_vtk.ShareDataSet([\n dash_vtk.Volume(state=volume_state),\n ]),\n ]),\n dash_vtk.SliceRepresentation(\n iSlice=10,\n children=[\n dash_vtk.ShareDataSet(),\n ]\n ),\n dash_vtk.SliceRepresentation(\n jSlice=10,\n children=[\n dash_vtk.ShareDataSet(),\n ]\n ),\n dash_vtk.SliceRepresentation(\n kSlice=10,\n children=[\n dash_vtk.ShareDataSet(),\n ]\n ),\n])\n\n# Dash setup\napp = dash.Dash(__name__)\nserver = app.server\n\napp.layout = html.Div(\n style={\"width\": \"100%\", \"height\": \"400px\"},\n children=[content],\n)\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","sub_path":"dash_docs/chapters/dash_vtk/other/examples/t06_shared_dataset.py","file_name":"t06_shared_dataset.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251542748","text":"# Copyright 2020 Google LLC\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# https://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 pathlib\nimport shutil\nimport tempfile\nimport tarfile\n\nfrom docuploader import log, shell, tar\nfrom docuploader.protos import metadata_pb2\nfrom google.protobuf import text_format, json_format\nfrom docpipeline import prepare\n\nimport semver\n\n\nDOCFX_PREFIX = \"docfx-\"\n\nXREFS_DIR_NAME = \"xrefs\"\n\nDEVSITE_SCHEME = \"devsite://\"\n\nDOCFX_JSON_TEMPLATE = \"\"\"\n{{\n \"build\": {{\n \"content\": [\n {{\n \"files\": [\"**/*.yml\", \"**/*.md\"],\n \"src\": \"obj/api\"\n }}\n ],\n \"globalMetadata\": {{\n \"_appTitle\": \"{package}\",\n \"_disableContribution\": true,\n \"_appFooter\": \" \",\n \"_disableNavbar\": true,\n \"_disableBreadcrumb\": true,\n \"_enableSearch\": false,\n \"_disableToc\": true,\n \"_disableSideFilter\": true,\n \"_disableAffix\": true,\n \"_disableFooter\": true,\n \"_rootPath\": \"{path}\",\n \"_projectPath\": \"{project_path}\"\n }},\n \"overwrite\": [\n \"obj/examples/*.md\"\n ],\n \"dest\": \"site\",\n \"xref\": [{xrefs}],\n \"xrefService\": [{xref_services}],\n }}\n}}\n\"\"\"\n\n\ndef clone_templates(dir):\n shell.run(\n [\n \"git\",\n \"clone\",\n \"--depth=1\",\n \"https://github.com/googleapis/doc-templates.git\",\n \".\",\n ],\n cwd=dir,\n hide_output=True,\n )\n\n\ndef setup_templates():\n templates_dir = pathlib.Path(\"doc-templates\")\n if templates_dir.is_dir():\n shutil.rmtree(templates_dir)\n templates_dir.mkdir(parents=True, exist_ok=True)\n log.info(f\"Cloning templates into {templates_dir.absolute()}\")\n clone_templates(templates_dir)\n log.info(f\"Got the templates ({templates_dir.absolute()})!\")\n devsite_template = templates_dir.joinpath(\"third_party/docfx/templates/devsite\")\n\n return templates_dir, devsite_template\n\n\ndef format_docfx_json(metadata):\n pkg = metadata.name\n xrefs = \", \".join([f'\"{xref}\"' for xref in metadata.xrefs if xref != \"\"])\n xref_services = \", \".join([f'\"{xref}\"' for xref in metadata.xref_services])\n path = f\"/{metadata.language}/docs/reference/{pkg}\"\n if pkg != \"help\":\n path += \"/latest\"\n\n return DOCFX_JSON_TEMPLATE.format(\n package=pkg,\n path=path,\n project_path=f\"/{metadata.language}/\",\n xrefs=xrefs,\n xref_services=xref_services,\n )\n\n\ndef setup_local_docfx(tmp_path, api_path, decompress_path, blob):\n for item in blob.iterdir():\n if item.is_dir() and item.name == \"api\":\n decompress_path = tmp_path.joinpath(\"obj\")\n break\n\n shutil.copytree(blob, decompress_path, dirs_exist_ok=True)\n log.info(f\"Decompressed in {decompress_path}\")\n\n return setup_metadata(tmp_path, api_path, decompress_path, blob)\n\n\ndef setup_bucket_docfx(tmp_path, api_path, decompress_path, blob):\n tar_filename = tmp_path.joinpath(blob.name)\n tar_filename.parent.mkdir(parents=True, exist_ok=True)\n\n blob.download_to_filename(tar_filename)\n log.info(f\"Downloaded gs://{blob.bucket.name}/{blob.name} to {tar_filename}\")\n\n # Check to see if api directory exists in the tarball.\n # If so, only decompress things into obj/*\n tar_file = tarfile.open(tar_filename)\n for tarinfo in tar_file:\n if tarinfo.isdir() and tarinfo.name == \"./api\":\n decompress_path = tmp_path.joinpath(\"obj\")\n break\n tar.decompress(tar_filename, decompress_path)\n log.info(f\"Decompressed {blob.name} in {decompress_path}\")\n\n return setup_metadata(tmp_path, api_path, decompress_path, blob)\n\n\ndef setup_metadata(tmp_path, api_path, decompress_path, blob):\n metadata = metadata_pb2.Metadata()\n metadata_path = decompress_path.joinpath(\"docs.metadata.json\")\n if metadata_path.exists():\n json_format.Parse(metadata_path.read_text(), metadata)\n else:\n metadata_path = decompress_path.joinpath(\"docs.metadata\")\n text_format.Merge(metadata_path.read_text(), metadata)\n\n try:\n metadata.xrefs[:] = [\n get_xref(xref, blob.bucket, tmp_path) for xref in metadata.xrefs\n ]\n except AttributeError:\n log.warning(\"Building locally will ignore xrefs in the metadata.\")\n\n with open(tmp_path.joinpath(\"docfx.json\"), \"w\") as f:\n f.write(format_docfx_json(metadata))\n log.info(\"Wrote docfx.json\")\n\n # TODO: remove this once _toc.yaml is no longer created.\n if pathlib.Path(api_path.joinpath(\"_toc.yaml\")).is_file():\n shutil.move(api_path.joinpath(\"_toc.yaml\"), api_path.joinpath(\"toc.yml\"))\n\n return metadata_path, metadata\n\n\ndef build_and_format(blob, is_bucket, devsite_template):\n tmp_path = pathlib.Path(tempfile.TemporaryDirectory(prefix=\"doc-pipeline.\").name)\n\n api_path = decompress_path = tmp_path.joinpath(\"obj/api\")\n\n api_path.mkdir(parents=True, exist_ok=True)\n\n # If building blobs on a bucket, use setup_bucket_docfx\n # Else, use setup_local_docfx\n if is_bucket:\n metadata_path, metadata = setup_bucket_docfx(\n tmp_path, api_path, decompress_path, blob\n )\n blob_name = blob.name\n else:\n metadata_path, metadata = setup_local_docfx(\n tmp_path, api_path, decompress_path, blob\n )\n blob_name = metadata.name\n\n site_path = tmp_path.joinpath(\"site\")\n\n log.info(f\"Running `docfx build` for {blob_name}...\")\n shell.run(\n [\"docfx\", \"build\", \"-t\", f\"{devsite_template.absolute()}\"],\n cwd=tmp_path,\n hide_output=False,\n )\n\n # Rename the output TOC file to be _toc.yaml to match the expected\n # format. As well, support both toc.html and toc.yaml\n try:\n shutil.move(site_path.joinpath(\"toc.yaml\"), site_path.joinpath(\"_toc.yaml\"))\n except FileNotFoundError:\n shutil.move(site_path.joinpath(\"toc.html\"), site_path.joinpath(\"_toc.yaml\"))\n\n html_files = list(site_path.glob(\"**/*.html\"))\n if len(html_files) == 0:\n raise ValueError(\"Did not generate any HTML files.\")\n\n # Remove the manifest.json file.\n site_path.joinpath(\"manifest.json\").unlink()\n\n # Add the prettyprint class to code snippets\n prepare.add_prettyprint(site_path)\n\n log.success(f\"Done building HTML for {blob_name}. Starting upload...\")\n\n # Reuse the same docs.metadata file. The original docfx- prefix is an\n # command line option when uploading, not part of docs.metadata.\n shutil.copy(metadata_path, site_path)\n\n return tmp_path, metadata, site_path\n\n\ndef get_base_url(language, name):\n # The baseUrl must start with a scheme and domain. With no scheme, docfx\n # assumes it's a file:// link.\n base_url = f\"https://cloud.google.com/{language}/docs/reference/\" + f\"{name}/\"\n # Help packages should not include the version in the URL.\n if name != \"help\":\n base_url += \"latest/\"\n return base_url\n\n\ndef process_blob(blob, devsite_template):\n is_bucket = True\n tmp_path, metadata, site_path = build_and_format(blob, is_bucket, devsite_template)\n\n # Use the input blob name as the name of the xref file to avoid collisions.\n # The input blob has a \"docfx-\" prefix; make sure to remove it.\n xrefmap = site_path.joinpath(\"xrefmap.yml\")\n xrefmap_lines = xrefmap.read_text().splitlines()\n base_url = f\"baseUrl: {get_base_url(metadata.language, metadata.name)}\"\n\n # Insert base_url after the YamlMime first line.\n xrefmap_lines.insert(1, base_url)\n xrefmap.write_text(\"\\n\".join(xrefmap_lines))\n\n xref_blob_name_base = blob.name[len(\"docfx-\") :]\n xref_blob = blob.bucket.blob(f\"{XREFS_DIR_NAME}/{xref_blob_name_base}.yml\")\n xref_blob.upload_from_filename(filename=xrefmap)\n\n shell.run(\n [\n \"docuploader\",\n \"upload\",\n \".\",\n f\"--staging-bucket={blob.bucket.name}\",\n ],\n cwd=site_path,\n hide_output=False,\n )\n\n shutil.rmtree(tmp_path)\n\n log.success(f\"Done with {blob.name}!\")\n\n\ndef get_xref(xref, bucket, dir):\n if not xref.startswith(DEVSITE_SCHEME):\n return xref\n\n d_xref = xref[len(DEVSITE_SCHEME) :]\n lang, pkg = d_xref.split(\"/\", 1)\n version = \"latest\"\n if \"@\" in pkg:\n pkg, version = pkg.rsplit(\"@\", 1)\n if version == \"latest\":\n # List all blobs, sort by semver, and pick the latest.\n prefix = f\"{XREFS_DIR_NAME}/{lang}-{pkg}-\"\n blobs = bucket.list_blobs(prefix=prefix)\n versions = []\n for blob in blobs:\n # Be sure to trim the suffix extension.\n version = blob.name[len(prefix) : -len(\".tar.gz.yml\")]\n # Skip if version is not a valid version, like when some other package\n # has prefix as a prefix (...foo-1.0.0\" and \"...foo-beta1-1.0.0\").\n try:\n version_sort(version)\n versions.append(version)\n except ValueError:\n pass # Ignore.\n if len(versions) == 0:\n # There are no versions, so there is no latest version.\n log.error(f\"Could not find {xref} in gs://{bucket.name}. Skipping.\")\n return \"\"\n versions = sorted(versions, key=version_sort)\n version = versions[-1]\n\n d_xref = f\"{XREFS_DIR_NAME}/{lang}-{pkg}-{version}.tar.gz.yml\"\n\n blob = bucket.blob(d_xref)\n if not blob.exists():\n # Log warning. Dependency may not be generated yet.\n log.error(f\"Could not find gs://{bucket.name}/{d_xref}. Skipping.\")\n return \"\"\n d_xref_path = dir.joinpath(d_xref).absolute()\n d_xref_path.parent.mkdir(parents=True, exist_ok=True)\n blob.download_to_filename(d_xref_path)\n return str(d_xref_path)\n\n\ndef version_sort(v):\n if v[0] == \"v\": # Remove v prefix, if any.\n v = v[1:]\n return semver.VersionInfo.parse(v)\n\n\ndef build_blobs(blobs):\n num = len(blobs)\n if num == 0:\n log.success(\"No blobs to process!\")\n return\n\n log.info(\"Let's build some docs!\")\n\n blobs_str = \"\\n\".join(map(lambda blob: blob.name, blobs))\n log.info(f\"Processing {num} blob{'' if num == 1 else 's'}:\\n{blobs_str}\")\n\n # Clone doc-templates.\n templates_dir, devsite_template = setup_templates()\n\n # Process every blob.\n failures = []\n for i, blob in enumerate(blobs):\n try:\n log.info(f\"Processing {i+1} of {len(blobs)}: {blob.name}...\")\n if not blob.name.startswith(\"docfx\"):\n raise ValueError(\n (\n f\"{blob.name} does not start with docfx,\"\n f\"did you mean docfx-{blob.name}?\"\n )\n )\n process_blob(blob, devsite_template)\n except Exception as e:\n # Keep processing the other files if an error occurs.\n log.error(f\"Error processing {blob.name}:\\n\\n{e}\")\n failures.append(blob.name)\n\n shutil.rmtree(templates_dir)\n\n if len(failures) > 0:\n failure_str = \"\\n\".join(failures)\n raise Exception(\n f\"Got errors while processing the following archives:\\n{failure_str}\"\n )\n\n log.success(\"Done!\")\n\n\ndef build_all_docs(bucket_name, storage_client):\n all_blobs = storage_client.list_blobs(bucket_name)\n docfx_blobs = [blob for blob in all_blobs if blob.name.startswith(DOCFX_PREFIX)]\n build_blobs(docfx_blobs)\n\n\ndef build_one_doc(bucket_name, object_name, storage_client):\n blob = storage_client.bucket(bucket_name).get_blob(object_name)\n if blob is None:\n raise Exception(f\"Could not find gs://{bucket_name}/{object_name}!\")\n build_blobs([blob])\n\n\ndef build_new_docs(bucket_name, storage_client):\n all_blobs = list(storage_client.list_blobs(bucket_name))\n docfx_blobs = [blob for blob in all_blobs if blob.name.startswith(DOCFX_PREFIX)]\n other_blobs = {b.name: b for b in all_blobs if not b.name.startswith(DOCFX_PREFIX)}\n\n new_blobs = []\n for blob in docfx_blobs:\n new_name = blob.name[len(DOCFX_PREFIX) :]\n if new_name not in other_blobs:\n new_blobs.append(blob)\n else:\n # For existing blobs, re-build the docs if the YAML blob is newer\n # than the existing HTML blob\n yaml_last_updated = blob.updated\n\n html_blob = other_blobs[new_name]\n html_last_updated = html_blob.updated\n\n if yaml_last_updated > html_last_updated:\n new_blobs.append(blob)\n\n build_blobs(new_blobs)\n\n\ndef build_language_docs(bucket_name, language, storage_client):\n all_blobs = storage_client.list_blobs(bucket_name)\n language_prefix = DOCFX_PREFIX + language + \"-\"\n docfx_blobs = [blob for blob in all_blobs if blob.name.startswith(language_prefix)]\n build_blobs(docfx_blobs)\n","sub_path":"docpipeline/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":13181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106466183","text":"# encoding: utf-8\n\nimport pymongo\nimport copy\nimport time\n\n\ndef connectToDB(port,DB,collection):\n\tclient=pymongo.MongoClient('127.0.0.1',port)\n\tdb=client[DB]\n\treturn db[collection]\n\ndef getDistance(index,index_copy):\n\titem=copy.deepcopy(index)\n\titem_copy=copy.deepcopy(index_copy)\n\titem.pop('_id')\n\titem_copy.pop('_id')\n\titem.pop('article_topics')\n\titem_copy.pop('article_topics')\n\tdistance=0\n\tfor x in item:\n\t\tif x not in item_copy.keys():\n\t\t\tdistance+=item[x]*item[x]\n\t\telse:\n\t\t\tdistance+=(item[x]-item_copy[x])*(item[x]-item_copy[x])\n\treturn distance\n\ndef getNearestNeighbor(index,large_train_copy,k):\n\tnearest_K_neighbor_topics=[]\n\tfor index_copy in large_train_copy:\n\t\titem=copy.deepcopy(index_copy)\n\t\tneighbor={}\n\t\tneighbor['distance']=getDistance(index,index_copy)\n\t\tneighbor['article_topics']=item['article_topics']\n\t\t# print(neighbor['distance'])\n\t\t# print(neighbor['article_topics'])\n\t\tif len(nearest_K_neighbor_topics)<=k:\n\t\t\tnearest_K_neighbor_topics.append(neighbor)\n\t\t\t# print(nearest_K_neighbor_topics)\n\t\telse:\n\t\t\tnearest_K_neighbor_topics=sorted(nearest_K_neighbor_topics,key=lambda x:x['distance'])\n\t\t\tmaxNeighbor=nearest_K_neighbor_topics[k]\n\t\t\tif neighbor['distance'] < maxNeighbor['distance']:\n\t\t\t\tnearest_K_neighbor_topics[k]['distance']=neighbor['distance']\n\t\t\t\tnearest_K_neighbor_topics[k]['article_topics']=neighbor['article_topics']\n\treturn nearest_K_neighbor_topics\n\n\n\n\nconnection_train=connectToDB(12345,'multiLabel','large_unify_train')\n\n\nsumOfArticles=connection_train.find().count()\n\nlarge_train = connection_train.find()\n\n# connection_test=connectToDB(12345,'multiLabel','large_test')\n# connection_train=connectToDB(12345,'multiLabel','large_train')\n# connection_train_copy=connectToDB(12345,'multiLabel','large_train_copy')\n\n# for index in connection_train.find():\n# \tconnection_train_copy.insert(index)\n\t\n\n\nlarge_multi_count=0\nlarge_topics={}\nfor index in large_train:\n\tif len(index['article_topics'])>1:\n\t\tlarge_multi_count+=1\n\tfor item in index['article_topics']:\n\t\tif item not in large_topics.keys():\n\t\t\tlarge_topics[item]=1 \n\t\telse:\n\t\t\tlarge_topics[item]+=1\n\n\nprint(sumOfArticles)\nprint(large_multi_count)\nprint(sum(large_topics.values()))\nprint(large_topics)\n\nprior_probabilities={}\n\nfor index in large_topics:\n\tprior_probabilities[index]=round(large_topics[index]/sumOfArticles,4)\n\nprint(prior_probabilities)\nprint(sum(prior_probabilities.values()))\n\nclassConditionProbability={}\nk=31\nc=[]\nlarge_train=connection_train.find()\nconnection_train_copy=connectToDB(12345,'multiLabel','large_unify_train_copy')\nstart=time.time()\n\nposterior_probabilities={}\n\nfor x in large_topics.keys():\n\tposterior_probabilities[x]=[0 for x in range(k+3)]\n\tposterior_probabilities['-'+x]=[0 for x in range(k+3)]\n\n\n# print(posterior_probabilities)\n\n\ncount=0\n\nfor index in large_train:\n\tlarge_train_copy=connection_train_copy.find()\n\tnearest_K_neighbor_topics = getNearestNeighbor(index,large_train_copy,k)\n\tnearest_K_neighbor_topics=nearest_K_neighbor_topics[1:k]\n\tprint(index['article_topics'])\n\tneighbor_topics={}\n\tfor x in nearest_K_neighbor_topics:\n\t\tfor y in x['article_topics']:\n\t\t\tif y not in neighbor_topics.keys():\n\t\t\t\tneighbor_topics[y]=1 \n\t\t\telse:\n\t\t\t\tneighbor_topics[y]+=1\n\t\tprint(x)\n\tprint(neighbor_topics)\n\n\tfor z in neighbor_topics:\n\t\tif z in index['article_topics']:\n\t\t\tposterior_probabilities[z][neighbor_topics[z]]+=1\n\t\telse:\n\t\t\tposterior_probabilities['-'+z][neighbor_topics[z]]+=1\n\n\tend=time.time()\n\tprint(end-start)\n\tcount=count+1\n\tprint(count)\n\nprint(prior_probabilities)\nprint(posterior_probabilities)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"largeArticleHandler.py","file_name":"largeArticleHandler.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372836971","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pydeck as pdk\r\nimport plotly.express as px\r\n\r\n# PS C:\\Users\\pablo\\Desktop> cd .\\WebApp\\\r\n# PS C:\\Users\\pablo\\Desktop\\WebApp> streamlit run .\\myWebApp.py\r\n\r\n# You can now view your Streamlit app in your browser. \r\n\r\n# Local URL: http://localhost:8501 \r\n# Network URL: http://192.168.1.35:8501\r\n\r\nurl = (\r\n\"C:/Users/pablo/Desktop/WebApp/debugged_singapore_airbnb.csv\"\r\n)\r\nst.title('Airbnb prices in Singapore 🛏🌏')\r\nst.subheader('AUTHOR: Pablo Benayas')\r\nst.markdown('This application is a Streamlit dashboard that can be used '\r\n'to analyze airbnb prices in Singapore')\r\n\r\ndata = pd.read_csv(url, parse_dates=['last_review']).iloc[:,1:]\r\ndata = data.loc[(data.price < 1050) & (data.price > 5),:]\r\n\r\n\r\n# part I\r\nst.header('Part I: Given a certain price range, where are airbnbs concentrated?')\r\n\r\nselect = st.selectbox('select option', ['low cost & medium price','high price'])\r\nif select == 'high price':\r\n filter = data.loc[data.price > 200,:]\r\nelse:\r\n filter = data.loc[data.price <= 200,:]\r\n\r\n\r\n\r\n# injured_people = st.slider('Select price range', 1, 6) \r\n\r\nselect1 = st.slider('Select price (SGD)', float(filter.price.min()), float(filter.price.max()))\r\nrange = st.slider('Interval (previous price plus and minus selected value)', min_value=10, max_value=50, step=10)\r\nst.map(filter.loc[(filter.price >= select1 - range) & (filter.price <= select1 + range),['latitude','longitude']].dropna(how='any')) \r\n# ‘any’ : If any NA values are present, drop that row or column.\r\n \r\n \r\n\r\nst.subheader('Raw Data') \r\nst.markdown('(Prices sorted by ascending order)')\r\nst.write(filter.loc[(filter.price >= select1 - range) & (filter.price <= select1 + range),\r\n['price','host_name','neighbourhood','room_type']]\\\r\n .sort_values(by='price', ascending=True)) \r\n\r\n\r\n# part II\r\nst.header('Part II: Given its room type, Where are the most expensive airbnb accomadations in Singapore?')\r\n \r\n\r\nroom_type_selected = st.selectbox('Select room type', data.room_type.unique()) \r\n# hour = st.sidebar.slider('Hour to look at', 0, 23) #same but with sidebar!! \r\n# separated by the difference of one\r\nfiltered_data = data.loc[data.room_type == room_type_selected,:] \r\n\r\npct = round(len(data.loc[data.room_type==room_type_selected,:]) / len(data) * 100, 3) \r\navg_price = round(filtered_data.price.median() ,3)\r\n\r\nst.markdown('{}% of the airbnbs are of type \"{}\". The median price is {} SGD. (I choose the median here because mean values are highly affected by outliers in this dataset.)'\\\r\n .format(pct, room_type_selected, avg_price)) \r\n\r\n\r\nmidpoint = (np.average(filtered_data.latitude), np.average(filtered_data.longitude)) \r\n\r\n\r\n\r\nst.subheader('Map of \"{}s\". Color and size of every observation is based on its price.'\\\r\n .format(room_type_selected)) \r\n\r\nst.write(pdk.Deck(\r\n map_style ='mapbox://styles/mapbox/light-v9',\r\n initial_view_state={\r\n 'latitude': midpoint[0],\r\n 'longitude': midpoint[1],\r\n 'zoom': 11,\r\n 'pitch': 50, # 3d parameter (either more vertical or horizontal degrees for visualization)\r\n },\r\n layers=[\r\n pdk.Layer(\r\n 'HexagonLayer',\r\n data=filtered_data.loc[:,['price','longitude','latitude']],\r\n get_position=['longitude','latitude'], #(x,y) dont reverse order\r\n radius=100,\r\n extruded=True, # This is arg creates the 3d effect\r\n pickable=True,\r\n elevation_scale=4,\r\n elevation_range=[0, 1000],\r\n ), \r\n ],\r\n))\r\n\r\n\r\n\r\n# # Part III: histogram\r\n\r\n# st.subheader('Breakdown by number of available months where \"{}\" airbnbs can be booked in one year.'.format(room_type_selected))\r\n# # filtered = data.loc[(data['date/time'].dt.hour >= hour) & (data['date/time'].dt.hour < hour+1),:]\r\n# i=0\r\n# # bins = [i for i in range(0,366,30)] It works on jupyter, but somehow not here\r\n# bins = [0,30,60,90,120,150,180,210,240,270,300,330,366]\r\n# # ['months: '+str(i) for i in range(1,13)]\r\n# labels = ['m1 (less than one month available)','m2','m3','m4','m5','m6','m7','m8','m9','m10','m11','m12 = 1year']\r\n# hist = pd.cut(filtered_data.availability_365 , bins=bins, labels=labels) \r\n# #we get the values with '[0]'\r\n\r\n# hist_data = hist.value_counts() \r\n\r\n# fig = px.bar(hist_data, x=hist_data.index, y=hist_data, height=400)\r\n# # reveal more information about a data point by moving their mouse cursor over \r\n# # the point and having a hover label appear.\r\n# st.write(fig)","sub_path":"singapore_airbnb_streamlit_Web_App.py","file_name":"singapore_airbnb_streamlit_Web_App.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"113629054","text":"import torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom sklearn.metrics import roc_auc_score\nfrom tqdm import tqdm as tqdm_base\ndef tqdm(*args, **kwargs):\n if hasattr(tqdm_base, '_instances'):\n for instance in list(tqdm_base._instances):\n tqdm_base._decr_instances(instance)\n return tqdm_base(*args, **kwargs)\n\nimport os, sys #; sys.path.append(\"../experiments-pause\")\nimport matplotlib.pyplot as plt; plt.ion()\nimport seaborn as sns; sns.set_style(\"white\")\nsns.set_palette(sns.color_palette(\"Set2\", 10))\ntorch.autograd.set_detect_anomaly(True)\n\nimport numpy as np\nln2pi = np.log(2*np.pi)\n\ndef fit_vae(model, Xtrain, Xval, Xtest, Ytrain, Yval, Ytest, **kwargs):\n # args\n do_cuda = kwargs.get(\"do_cuda\", torch.cuda.is_available())\n batch_size = kwargs.get(\"batch_size\", 1024)\n epochs = kwargs.get(\"epochs\", 40)\n output_dir = kwargs.get(\"output_dir\", \"./\")\n #discrim_model = kwargs.get(\"discrim_model\", None)\n cond_dim = kwargs.get(\"cond_dim\", 1)\n zu_dropout_p = kwargs.get(\"zu_dropout_p\", .2)\n log_interval = kwargs.get(\"log_interval\", None)\n run_validation_interval = kwargs.get(\"run_validation_interval\", 2)\n learning_rate = kwargs.get(\"lr\", 1e-3)\n lr_reduce_interval = kwargs.get(\"lr_reduce_interval\", 25)\n epoch_log_interval = kwargs.get(\"epoch_log_interval\", 1)\n plot_interval = kwargs.get(\"plot_interval\", 10)\n dataset = kwargs.get(\"dataset\", None)\n torch_seed = kwargs.get(\"torch_seed\", None)\n scale_down_image_loss = kwargs.get(\"scale_down_image_loss\", \n False)\n anneal_rate = kwargs.get(\"anneal_rate\", 0.005)\n num_zero_kl_epochs = kwargs.get(\"num_zero_kl_epochs\", 0)\n #data_dim = Xtrain.shape[1]\n print(\"-------------------\")\n print(\"fitting vae: \", kwargs)\n \n # set up a dataset object\n if dataset is not None:\n # torchxrayvision map-syle dataset\n print('dataset is xray.')\n train_size = int(0.8 * len(dataset))\n valid_size = len(dataset) - train_size\n torch.manual_seed(torch_seed)\n train_data, val_data = torch.utils.data.random_split(\n dataset, [train_size, valid_size])\n train_epoch_func = train_epoch_xraydata\n test_epoch_func = test_epoch_xraydata\n else: \n # andy's version - input data to func \n # in the form Xtrain, Xval, Xtest, Ytrain, Yval, Ytest\n train_data = torch.utils.data.TensorDataset(\n torch.FloatTensor(Xtrain), torch.FloatTensor(Ytrain[:,None]))\n val_data = torch.utils.data.TensorDataset(\n torch.FloatTensor(Xval), torch.FloatTensor(Yval[:,None]))\n train_epoch_func = train_epoch\n test_epoch_func = test_epoch\n # below applies for both\n train_loader = torch.utils.data.DataLoader(train_data, \n batch_size=batch_size, num_workers=16, pin_memory=True, \n drop_last=True, shuffle=True)\n val_loader = torch.utils.data.DataLoader(val_data,\n drop_last=True,\n batch_size=batch_size, num_workers=16, pin_memory=True, shuffle=True)\n\n # create model\n if do_cuda:\n print('doing cuda')\n model.cuda()\n model.is_cuda = True\n\n # set up optimizer\n plist = list(filter(lambda p: p.requires_grad, model.parameters()))\n print(\" training %d param groups\"%len(plist))\n optimizer = optim.Adam(plist, lr=learning_rate, weight_decay=1e-5)\n\n # main training loop\n best_val_loss, best_val_state = np.inf, None\n prev_val_loss = np.inf\n train_total_loss = []\n train_kl = []\n train_disc_loss = []\n train_neg_ll = []\n val_total_loss = []\n val_kl = []\n val_disc_loss = []\n val_neg_ll = [] # quantity that we're minimizing, propto MSE\n kl_beta_list = [] # kl beta, increases in the annealing procedure.\n print(\"{:10} {:10} {:10} {:10} {:10} {:10}\".format(\n \"Epoch\", \"train-loss\", \"val-loss\", \"train-rmse\", \"val-rmse\", \"train/val-p\"))\n \n # initialize early stopping class. note -- patience is a function of run_validation_interval. \n # if we're running validation every 5 epochs, than patience = 3 stops when there's no improvement in the last 15 \n # epochs. \n early_stopping = EarlyStopping(patience=3, verbose=True, output_dir=output_dir)\n\n for epoch in range(1, epochs + 1): \n \n # set beta for kl loss, start with 20 epochs with 0 loss, than gradually\n # add the KL term\n kl_beta = kl_schedule(epoch, num_zero_kl_epochs, anneal_rate) \n\n # train/val over entire dataset\n tloss, trmse, tprecon, t_kl_loss, t_disc_loss, t_neg_ll = train_epoch_func(epoch, model, train_loader,\n optimizer = optimizer,\n do_cuda = do_cuda,\n log_interval = log_interval,\n num_samples = 1,\n scale_down_image_loss=scale_down_image_loss,\n kl_beta = kl_beta,\n output_dir = output_dir)\n # # works copying and modifying below\n # print('Finished training epoch %i' % epoch)\n # print('Predicting validation dataset...')\n # vloss, vrmse, vprecon, v_kl_loss, v_disc_loss = test_epoch_func(epoch, model, \n # val_loader, do_cuda, \n # scale_down_image_loss=scale_down_image_loss,\n # kl_beta = kl_beta,\n # output_dir = output_dir)\n \n # print('Finished.')\n \n if epoch % run_validation_interval ==0:\n \n print('Finished training epoch %i' % epoch)\n print('Predicting validation dataset...')\n vloss, vrmse, vprecon, v_kl_loss, v_disc_loss, v_neg_ll = test_epoch_func(epoch, model, \n val_loader, do_cuda, \n scale_down_image_loss=scale_down_image_loss,\n kl_beta = kl_beta,\n output_dir = output_dir)\n \n print('Finished.')\n \n # keep track of best model by validation rmse\n # ToDo: currently implemented also in the Early_Stopping class. pick one.\n if vrmse < best_val_loss:\n best_val_loss, best_val_state = vrmse, model.state_dict()\n \n # track elbo values\n train_total_loss.append(tloss)\n train_kl.append(t_kl_loss)\n train_disc_loss.append(t_disc_loss)\n train_neg_ll.append(t_neg_ll)\n val_total_loss.append(vloss)\n val_kl.append(v_kl_loss)\n val_disc_loss.append(v_disc_loss)\n val_neg_ll.append(v_neg_ll)\n kl_beta_list.append(kl_beta)\n\n \n print(\"{:10} {:10} {:10} {:10} {:10} {:10}\".format(\n epoch, \"%2.4f\"%tloss, \"%2.4f\"%vloss, \n \"%2.4f\"%trmse, \"%2.4f\"%vrmse,\n \"%2.3f / %2.3f\"%(tprecon, vprecon)))\n \n if kl_beta>=1.0: # make sure we reached the full VAE loss.\n early_stopping(vloss, model)\n # early_stopping needs the validation loss to check if it has decresed, \n # and if it has, it will make a checkpoint of the current model\n \n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n \n # if epoch % epoch_log_interval == 0:\n\n # print(\"{:10} {:10} {:10} {:10} {:10} {:10}\".format(\n # epoch, \"%2.4f\"%tloss, \"%2.4f\"%vloss, \n # \"%2.4f\"%trmse, \"%2.4f\"%vrmse,\n # \"%2.3f / %2.3f\"%(tprecon, vprecon)))\n # print('logging losses.')\n\n # # track elbo values\n # train_elbo.append(tloss)\n # train_kl.append(t_kl_loss)\n # train_disc_loss.append(t_disc_loss)\n # val_elbo.append(vloss)\n # val_kl.append(v_kl_loss)\n # val_disc_loss.append(v_disc_loss)\n\n # # keep track of best model by validation rmse # works, just doing it every few epochs.\n # if vrmse < best_val_loss:\n # best_val_loss, best_val_state = vrmse, model.state_dict()\n\n # update learning rate if we're not doing better\n if epoch % lr_reduce_interval == 0: # 100 and vloss >= prev_val_loss:\n print(\"... reducing learning rate!\")\n for param_group in optimizer.param_groups:\n param_group['lr'] *= .5\n\n # visualize reconstruction\n if epoch % plot_interval == 0: # add back the saved reconstruction\n # save_reconstruction(model, train_data,\n # output_file = os.path.join(output_dir, \"train-recon-%d.png\"%epoch))\n # save_reconstruction(model, val_data,\n # output_file = os.path.join(output_dir, \"val-recon-%d.png\"%epoch))\n save_elbo_plots(train_total_loss, val_total_loss, output_dir)\n #torch.save({'train_elbo' : train_elbo,\n # 'val_elbo' : val_elbo,\n # 'state_dict' : model.state_dict(),\n # 'optimizer' : optimizer.state_dict()},\n # f=os.path.join(output_dir, model.name() + \".pth.tar\"))\n \n\n # load in best state by validation loss\n # ToDo: keep in mind that we now have the early stopping class.\n if best_val_state is not None:\n model.load_state_dict(best_val_state)\n model.eval()\n else: \n print('best_val_state is None. We cannot load_state_dict before exiting -- keeping the current state_dict')\n\n resdict = {'train_total_loss' : train_total_loss,\n 'train_kl' : train_kl,\n 'train_disc_loss': train_disc_loss,\n 'train_neg_ll': train_neg_ll,\n 'val_total_loss' : val_total_loss,\n 'val_kl' : val_kl,\n 'val_disc_loss': val_disc_loss,\n 'val_neg_ll': val_neg_ll,\n 'kl_beta': kl_beta_list,\n #'model_state' : model.state_dict(),\n #'data_dim' : data_dim,\n 'cond_dim' : cond_dim,\n 'discrim_model': None,\n #'latent_dim' : latent_dim,\n 'zu_dropout_p' : zu_dropout_p,\n 'output_dir' : output_dir,\n #'hdims' : hdims\n }\n return resdict\n\n################################################################\n# Training functions -- for xray #\n################################################################\n\ndef train_epoch_xraydata(epoch, model, train_loader,\n optimizer = None,\n do_cuda = True,\n log_interval = None,\n num_samples = 1,\n scale_down_image_loss = False,\n kl_beta = 1.0,\n output_dir = None):\n '''This function is identical to train_epoch except that it uses \n a map style dataset from torchxrayvision'''\n # set up train/eval mode\n do_train = False if optimizer is None else True\n if do_train: \n model.train()\n if hasattr(model, \"discrim_model\"): # set discrim_model to eval mode, even when training.\n model.discrim_model.eval()\n else:\n model.eval()\n \n # run thorugh batches in data loader\n train_loss = 0\n recon_rmse = 0.\n kl_loss = 0.\n discrim_loss = 0.\n image_neg_ll = 0.0\n recon_prob_sse, recon_z_sse = 0., 0.\n loss_list = [] # renewed every epoch for debugging\n latent_loss_list = []\n #trues, preds = [], []\n #t = tqdm(train_loader) # and also had t instead of train loader inside brackets.\n for batch_idx, samples in enumerate(train_loader):\n data = samples[\"img\"].float()\n target = samples[\"lab\"]\n\n if do_cuda:\n data, target = data.cuda(), target.cuda()\n\n if do_train:\n optimizer.zero_grad()\n\n # compute encoding distribution\n loss = 0\n # ToDo: num_samples currently not supported, loss isn't accumulated across samples\n for _ in range(num_samples): \n try:\n recon_batch, z, mu, logvar = model(data)\n except Exception as e:\n print('VAE Forward pass failed.') # ToDo: save tensors in each forward call.\n print(repr(e))\n\n # model computes its own loss. \n # loss is a tuple and we minimize its first element.\n try:\n loss_tuple = model.lossfun(\n data, recon_batch, \n target, mu, logvar,\n kl_beta,\n scale_down_image_loss)\n except Exception as e:\n print('Failed calculating loss in epoch %i batch %i with kl_beta = %.2f' \\\n % (epoch, batch_idx, kl_beta))\n print(repr(e))\n print('Saving critical tensors...')\n save_critical_tensors(data, recon_batch, \n mu, logvar, z, output_dir)\n print('Plotting batch stats...')\n plot_recon_batch(recon_batch, data, \n epoch, batch_idx, output_dir)\n plot_bottleneck_stats(mu, logvar, z, \n epoch, batch_idx, \n 100, output_dir)\n \n # checks:\n if do_train:\n with torch.no_grad():\n loss_list.append(loss_tuple[0].data.item()) # loss list within a an epoch.\n latent_loss_list.append(loss_tuple[2].data.item())\n if batch_idx>1:\n if np.abs(loss_list[-1]/loss_list[-2]) > 1000.00 or \\\n np.abs(latent_loss_list[-1]/latent_loss_list[-2]) > 1000.00:\n print('------batch loss just jumped!---------')\n plot_recon_batch(recon_batch, data, epoch, batch_idx)\n plot_bottleneck_stats(mu, logvar, z, epoch, batch_idx, bins = 100)\n print('Saving critical tensors...')\n save_critical_tensors(data, recon_batch, mu, logvar, z)\n loss_list = loss_list[-2:]\n latent_loss_list = latent_loss_list[-2:]\n\n if np.sum(np.isnan(data.detach().cpu().numpy().flatten())) !=0 or \\\n (data.view(data.shape[0],-1).sum(dim=1).detach().cpu().numpy() == 0).any() or \\\n np.sum(np.isnan(recon_batch.detach().cpu().numpy().flatten())) !=0 or \\\n np.sum(np.isnan(mu.detach().cpu().numpy().flatten())) !=0 or \\\n np.sum(np.isnan(logvar.detach().cpu().numpy().flatten())) !=0:\n \n print('------encountered nans or all zeros---------')\n plot_recon_batch(recon_batch, data, epoch, batch_idx)\n plot_bottleneck_stats(mu, logvar, z, epoch, batch_idx, bins = 100)\n save_critical_tensors(data, recon_batch, mu, logvar, z)\n\n\n if do_train:\n try: \n loss_tuple[0].backward() # minimize first element in the loss tuple - total loss.\n optimizer.step()\n except Exception as e:\n print('Failed calculating gradients and taking a step.')\n print(repr(e))\n print('Saving critical tensors...')\n save_critical_tensors(data, recon_batch, \n mu, logvar, z, output_dir)\n print('Saving diagnostic figures...')\n plot_recon_batch(recon_batch, data, epoch, \n batch_idx, output_dir)\n plot_bottleneck_stats(mu, logvar, z, \n epoch, batch_idx, 100,\n output_dir)\n \n # add errors from each batch to the total train_loss of epoch\n recon_rmse += torch.std(recon_batch-data).data.item()*data.shape[0]\n train_loss += loss_tuple[0].data.item()*data.shape[0]\n kl_loss += loss_tuple[2].data.item()*data.shape[0]\n image_neg_ll += loss_tuple[3].data.item()*data.shape[0]\n if model.discrim_beta != 0:\n discrim_loss += loss_tuple[4].data.item()*data.shape[0] # NOT weighted by beta\n else: \n discrim_loss += 0.0\n\n if (log_interval is not None) and (batch_idx % log_interval == 0):\n print(\n ' epoch: {epoch} [{n}/{N} ({per:.0f}%)]\\tLoss: {total_loss:.4f}, Beta * Disc. Loss: {discrim_loss:.4f}, Lat. Loss: {latent_loss:.4f}, Recon. Loss: {image_loss:.4f}'.format(\n epoch = epoch,\n n = batch_idx * train_loader.batch_size,\n N = len(train_loader.dataset),\n per = 100. * batch_idx / len(train_loader),\n total_loss = loss_tuple[0].data.item() / len(data),\n discrim_loss = loss_tuple[0].data.item() / len(data) - \n loss_tuple[1].data.item() / len(data), # DRVAE - VAE\n latent_loss = loss_tuple[2].data.item() / len(data),\n image_loss = loss_tuple[3].data.item() / len(data),\n ))\n \n\n # compute average loss\n N = len(train_loader.dataset)\n return train_loss/N, recon_rmse/N, np.sqrt(recon_prob_sse/N), kl_loss/N, discrim_loss/N, image_neg_ll/N\n\ndef test_epoch_xraydata(epoch, model, data_loader, \n do_cuda, scale_down_image_loss, \n kl_beta, output_dir):\n return train_epoch_xraydata(epoch, model, train_loader=data_loader,\n optimizer=None, do_cuda=do_cuda, \n scale_down_image_loss=scale_down_image_loss,\n kl_beta = kl_beta, output_dir = output_dir)\n\n\n\n################################################################\n# Training functions --- should work with both BeatVAE types #\n################################################################\ndef train_epoch(epoch, model, train_loader,\n optimizer = None,\n do_cuda = True,\n log_interval = None,\n num_samples = 1):\n\n # set up train/eval mode\n do_train = False if optimizer is None else True\n if do_train:\n model.train()\n else:\n model.eval()\n\n # run thorugh batches in data loader\n train_loss = 0\n recon_rmse = 0.\n recon_prob_sse, recon_z_sse = 0., 0.\n trues, preds = [], []\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = Variable(data), Variable(target)\n if do_cuda:\n data, target = data.cuda(), target.cuda()\n\n if do_train:\n optimizer.zero_grad()\n\n # compute encoding distribution\n loss = 0\n for _ in range(num_samples):\n recon_batch, z, mu, logvar = model(data)\n recon_batch = recon_batch.view_as(data)\n # model computes its own loss\n loss += model.lossfun(data, recon_batch, target, mu, logvar)\n\n if do_train:\n loss.backward()\n optimizer.step()\n\n # track pred probs\n recon_rmse += torch.std(recon_batch-data).data.item()*data.shape[0]\n train_loss += loss.data.item()*data.shape[0]\n\n # if we have a discrim model, track how well it's reconstructing probs\n if hasattr(model, \"discrim_model\"):\n zrec = model.discrim_model[0](recon_batch)\n zdat = model.discrim_model[0](data)\n prec = torch.sigmoid(zrec)\n pdat = torch.sigmoid(zdat)\n recon_z_sse += torch.var(zrec-zdat).data.item()*data.shape[0]\n recon_prob_sse += torch.var(prec-pdat).data.item()*data.shape[0]\n\n if (log_interval is not None) and (batch_idx % log_interval == 0):\n print(' epoch: {epoch} [{n}/{N} ({per:.0f}%)]\\tLoss: {loss:.6f}'.format(\n epoch = epoch,\n n = batch_idx * train_loader.batch_size,\n N = len(train_loader.dataset),\n per = 100. * batch_idx / len(train_loader),\n loss = loss.data.item() / len(data)))\n\n # compute average loss\n N = len(train_loader.dataset)\n return train_loss/N, recon_rmse/N, np.sqrt(recon_prob_sse/N)\n\n\ndef test_epoch(epoch, model, data_loader, do_cuda):\n return train_epoch(epoch, model, train_loader=data_loader,\n optimizer=None, do_cuda=do_cuda)\n\n#def batch_reconstruct(mod, X):\n# data = torch.utils.data.TensorDataset(\n# torch.FloatTensor(X), torch.FloatTensor(X))\n# loader = torch.utils.data.DataLoader(data,\n# batch_size=batch_size, shuffle=False, pin_memory=True)\n# batch_res = []\n# if torch.cuda.is_available():\n# mod.cuda()\n# do_cuda = True\n# for batch_idx, (data, target) in enumerate(pyprind.prog_bar(loader)):\n# data, target = Variable(data), Variable(target)\n# if do_cuda:\n# data, target = data.cuda(), target.cuda()\n# data, target = data.contiguous(), target.contiguous()\n#\n# recon_batch, z, mu, logvar = model(data)\n# \n# res = mod.forward(data)\n# batch_res.append(res.data.cpu())\n#\n# return torch.cat(batch_res, dim=0)\n#\n\ndef kl_schedule(epoch_num, n_epochs_with_zero, rate=0.001):\n \"\"\"\n Anneal the KL term in the VAE cost function\n\n With rate 0.001 and n_epochs_with_zero = 20, we need 1020 epochs to get\n kl_lambda = 1\n\n Args:\n epoch_num:\n n_epochs_with_zero:\n rate:\n\n Returns:\n float\n\n \"\"\"\n if epoch_num < n_epochs_with_zero:\n kl_lambda = 0.0\n else:\n kl_lambda = np.minimum((epoch_num - n_epochs_with_zero) * rate, 1)\n return kl_lambda\n\n\n#######################\n# plotting functions #\n#######################\n\ndef save_elbo_plots(train_elbo, val_elbo, output_dir):\n fig, ax = plt.figure(figsize=(8, 6)), plt.gca()\n ax.plot(-np.array(train_elbo), label=\"train elbo\")\n ax.plot(-np.array(val_elbo), label=\"val elbo\")\n ax.legend()\n fig.savefig(os.path.join(output_dir, \"elbo-by-epoch.png\"), bbox_inches='tight')\n plt.close(\"all\")\n\n# my version # to be adapted. \ndef save_reconstruction(model, dataset, output_file):\n model_is_cuda = next(model.parameters()).is_cuda\n\n # select random data\n data_tensor, _ = dataset.tensors\n n_data = data_tensor.shape[0]\n idx = np.random.permutation(n_data)[:10]\n\n # reconstruct data\n data_npy = data_tensor.numpy()[idx]\n data = Variable(torch.FloatTensor(data_npy)).contiguous()\n if model_is_cuda:\n data = data.cuda()\n recon_x, z, mu, logvar = model(data)\n\n # reshape data and recon\n #if len(data.shape) == 2:\n # data = data.view(-1, 3, n_dim//3)\n # recon_x = recon_x.view_as(data)\n\n # plot beat and save\n X = recon_x.detach()\n if model_is_cuda:\n X = X.cpu()\n X = X.numpy()\n fig, ax = plt.figure(figsize=(8,6)), plt.gca()\n plot_images(X[:10,:], ax=ax)\n\n fig.savefig(output_file, bbox_inches='tight')\n plt.close(\"all\")\n \n# # Andy's version below\n# def save_reconstruction(model, dataset, output_file):\n# model_is_cuda = next(model.parameters()).is_cuda\n\n# # select random data\n# data_tensor, _ = dataset.tensors\n# n_data = data_tensor.shape[0]\n# idx = np.random.permutation(n_data)[:10]\n\n# # reconstruct data\n# data_npy = data_tensor.numpy()[idx]\n# data = Variable(torch.FloatTensor(data_npy)).contiguous()\n# if model_is_cuda:\n# data = data.cuda()\n# recon_x, z, mu, logvar = model(data)\n\n# # reshape data and recon\n# #if len(data.shape) == 2:\n# # data = data.view(-1, 3, n_dim//3)\n# # recon_x = recon_x.view_as(data)\n\n# # plot beat and save\n# X = recon_x.detach()\n# if model_is_cuda:\n# X = X.cpu()\n# X = X.numpy()\n# fig, ax = plt.figure(figsize=(8,6)), plt.gca()\n# plot_images(X[:10,:], ax=ax)\n\n# fig.savefig(output_file, bbox_inches='tight')\n# plt.close(\"all\")\n\ndef plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),\n cmap=None, vmin=None, vmax=None):\n \"\"\"Images should be a (N_images x pixels) matrix.\"\"\"\n import matplotlib.cm\n import matplotlib.pyplot as plt; plt.ion()\n if cmap is None:\n cmap = matplotlib.cm.binary\n N_images = images.shape[0]\n N_rows = (N_images - 1) // ims_per_row + 1\n pad_value = np.min(images.ravel())\n concat_images = np.full(((digit_dimensions[0] + padding) * N_rows + padding,\n (digit_dimensions[1] + padding) * ims_per_row + padding), pad_value)\n for i in range(N_images):\n cur_image = np.reshape(images[i, :], digit_dimensions)\n row_ix = i // ims_per_row\n col_ix = i % ims_per_row\n row_start = padding + (padding + digit_dimensions[0]) * row_ix\n col_start = padding + (padding + digit_dimensions[1]) * col_ix\n concat_images[row_start: row_start + digit_dimensions[0],\n col_start: col_start + digit_dimensions[1]] = cur_image\n cax = ax.matshow(concat_images, cmap=cmap, vmin=vmin, vmax=vmax)\n plt.xticks(np.array([]))\n plt.yticks(np.array([]))\n\n #ax.figure.patch.set_visible(False)\n ax.patch.set_visible(False)\n return cax\n\ndef plot_beat(data, recon_x=None):\n # first, move everything to CPU\n if data.is_cuda:\n data = data.cpu()\n if recon_x is not None and recon_x.is_cuda:\n recon_x = recon_x.cpu()\n\n # plot a bunch of data\n ncol = int(data.shape[0] / 2)\n nrow = 2\n fig, axarr = plt.subplots(nrow, ncol, figsize=(4*ncol, 2*nrow))\n for i, ax in enumerate(axarr.flatten()):\n ax.plot(data[i, 0, :].data.numpy(), \"-o\", label=\"beat\")\n if recon_x is not None:\n ax.plot(recon_x[i, 0, :].data.numpy(), label=\"recon\")\n ax.legend()\n return fig, axarr\n\ndef plot_bottleneck_stats(mu, logvar, z, epoch, \n batch_idx, bins = 100,\n save_dir = os.getcwd()):\n mu_np = mu.detach().cpu().numpy().flatten()\n logvar_np = logvar.detach().cpu().numpy().flatten()\n z_np = z.detach().cpu().numpy().flatten()\n f, axarr = plt.subplots(1,3, figsize = (12,4))\n axarr[0].hist(mu_np, bins=100, density = True);\n axarr[0].set_title('mu [%.2f, %.2f]' % (np.min(mu_np), np.max(mu_np)));\n axarr[1].hist(logvar_np, bins=100, density = True);\n axarr[1].set_title('logvar [%.2f, %.2f]' % (np.min(logvar_np), np.max(logvar_np)));\n axarr[2].hist(z_np, bins=100, density = True);\n axarr[2].set_title('z [%.2f, %.2f]' % (np.min(z_np), np.max(z_np)));\n f.suptitle('Epoch %i, Batch %i stats' %(epoch, batch_idx))\n #f.tight_layout()\n plt.savefig('epoch_%i_batch_%i_latent_stats.png' % (epoch, batch_idx))\n plt.close(\"all\")\n \ndef plot_recon_batch(recon, data, epoch, \n batch_idx, save_dir = os.getcwd()):\n \"\"\"\"wrapper around plot_images.\"\"\"\n recon = recon.detach().cpu().numpy()\n data = data.detach().cpu().numpy()\n batch_size = data.shape[0]\n image_size = data.shape[-1] # squared images.\n f, axarr = plt.subplots(1,2, figsize = (20,17))\n axarr[0].set_title('recon.', fontsize = 24)\n axarr[1].set_title('data', fontsize = 24)\n plot_images(recon.squeeze(1).reshape(batch_size,-1), axarr[0], ims_per_row=5, \n padding=5, digit_dimensions=(image_size, image_size),\n cmap='gray', vmin=None, vmax=None)\n plot_images(data.squeeze(1).reshape(batch_size,-1), axarr[1], ims_per_row=5, \n padding=5, digit_dimensions=(image_size, image_size),\n cmap='gray', vmin=None, vmax=None)\n f.suptitle('recons: epoch %i batch %i' % (epoch, batch_idx), fontsize = 28)\n f.tight_layout()\n plt.savefig(os.path.join(save_dir,\n 'epoch_%i_batch_%i_recon_stats.png' % (epoch, batch_idx)))\n plt.close(\"all\")\n\ndef save_critical_tensors(data, recon_batch, mu, \n logvar, z, save_dir = os.getcwd()):\n \n torch.save(data, os.path.join(save_dir, 'data_batch.pt'))\n torch.save(recon_batch, os.path.join(save_dir,'recon_batch.pt'))\n torch.save(mu, os.path.join(save_dir, 'mu_batch.pt'))\n torch.save(logvar, os.path.join(save_dir,'logvar_batch.pt'))\n torch.save(z, os.path.join(save_dir, 'z_batch.pt'))\n \n print('Critical tensors saved in %s' % str(save_dir))\n \nclass EarlyStopping:\n \"\"\"https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py\n Early stops the training if validation loss doesn't improve after a given patience.\"\"\"\n def __init__(self, patience=7, verbose=False, delta=0, output_dir = None):\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved.\n Default: 7\n verbose (bool): If True, prints a message for each validation loss improvement. \n Default: False\n delta (float): Minimum change in the monitored quantity to qualify as an improvement.\n Default: 0\n \"\"\"\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_min = np.Inf\n self.delta = delta\n self.output_dir = output_dir\n\n def __call__(self, val_loss, model):\n\n score = -val_loss\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n elif score < self.best_score + self.delta:\n self.counter += 1\n print(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(val_loss, model)\n self.counter = 0\n\n def save_checkpoint(self, val_loss, model):\n '''Saves model when validation loss decrease.'''\n if self.verbose:\n print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n torch.save(model.state_dict(), os.path.join(self.output_dir, 'checkpoint.pt'))\n self.val_loss_min = val_loss\n \n## ==== some debugging prints\n \n# print('data is nan:')\n# print(np.sum(np.isnan(data.detach().cpu().numpy().flatten())))\n# print(np.min(data.detach().cpu().numpy().flatten()))\n# print(np.max(data.detach().cpu().numpy().flatten()))\n# print('data raw:')\n# print(data)\n# print('recon is nan:')\n# print(np.sum(np.isnan(recon_batch.detach().cpu().numpy().flatten())))\n# print(np.min(recon_batch.detach().cpu().numpy().flatten()))\n# print(np.max(recon_batch.detach().cpu().numpy().flatten()))\n# print('mu is nan:')\n# print(np.sum(np.isnan(mu.detach().cpu().numpy().flatten())))\n# print(mu.detach().cpu().numpy().flatten())\n# print(np.min(mu.detach().cpu().numpy().flatten()))\n# print(np.max(mu.detach().cpu().numpy().flatten()))\n# print('lnvar is nan:')\n# print(np.sum(np.isnan(logvar.detach().cpu().numpy().flatten())))\n# print(logvar.detach().cpu().numpy().flatten())\n# print(np.min(logvar.detach().cpu().numpy().flatten()))\n# print(np.max(logvar.detach().cpu().numpy().flatten()))\n\n","sub_path":"drvae/model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":31925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"541487062","text":"from django.urls import path\n\nfrom server_arrdelstest.api.views import *\n\nurlpatterns = [\n path('initdatabase/', create_all_objects ),\n path('visitsdatas/', RendAllVisitsAndBehavior.as_view()),\n path('recommandnbtimes/', RendNBRecommandationsForProjectsSingleUser.as_view() ),\n path('visitsdata/', RendVisitsAndBehaviorForSingleUser.as_view()),\n path('projects/', ProjectListView.as_view()),\n path('projectcreate/', create_project_object),\n path('communesvisits/', VisitsCommuneListView.as_view()),\n path('departementsvisits/', VisitsDepartementListView.as_view())\n]","sub_path":"backendtest_arrdel/server_arrdelstest/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279486342","text":"# %load q03_get_toss_win_count/build.py\n#Default Imports\nimport numpy as np\nipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=1, delimiter=',')\n\n\n#Your Solution\n\ndef get_toss_win_count(team):\n \n \n #team = team.encode() #to convert string into byte\n\n #list of unique matches\n unique_matches = np.unique(ipl_matches_array[:, [0,3,4,5]],axis = 0)\n \n \n #comparing team name with unique matches then select column which has data of team who win toss\n #count = len(unique_matches[unique_matches[:,3] == team][:,3])\n \n return len(unique_matches[unique_matches[:,3] == team][:,3])\n\n\nteam_name = b'Mumbai Indians'\nget_toss_win_count(team_name)\n\n\n\n","sub_path":"q03_get_toss_win_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526377650","text":"#!/usr/bin/python3 \n#\nimport sys\n#\nimport ADT\n#\ndef work(x):\n print(x)\n#\nbt = ADT.BinaryTree()\n#\nbt.insert(2)\nbt.insert(1)\nbt.insert(3)\n#\nprint(\"includes ... {0}\".format(bt.includes(2)))\n#\nbt.in_order(work)\nbt.pre_order(work)\nbt.post_order(work)\n#\nsys.exit(0);\n\n","sub_path":"books/programming_in_python_3/mine/ch8/bt_test.py","file_name":"bt_test.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568437580","text":"import sys\nfrom collections import defaultdict\nfrom heapq import heappush, heappop\n\ninf = sys.maxsize\n\ndef dijkstra(G, source, n):\n dist = [inf] * n\n visited = [False] * n\n dist[source] = 0\n\n Q = [(0, source)]\n while Q:\n w, u = heappop(Q)\n visited[u] = True\n\n for weight, v in G[u]:\n alt = dist[u] + weight\n if not visited[v] and alt < dist[v]:\n dist[v] = alt\n heappush(Q, (alt, v))\n\n return dist\n\n\ndef main():\n n, m, q, s = map(int, input().split())\n while True:\n\n # End of file\n if n == 0:\n break\n\n # construct graph\n graph = defaultdict(list)\n for _ in range(m):\n u, v, w = map(int, input().split())\n graph[u].append((w, v))\n\n # use dijkstra\n distances = dijkstra(graph, s, n)\n\n # answer queries\n for _ in range(q):\n q = int(input())\n cost = distances[q]\n if cost == inf:\n print(\"Impossible\")\n else:\n print(cost)\n\n n, m, q, s = map(int, input().split())\n\n if n == 0:\n break\n print()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/medium/SSS-path/non-neg/sss_path.py","file_name":"sss_path.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368424277","text":"import os\nfrom flask import Flask, session, redirect\nfrom functools import wraps\nimport sqlite3\n\n# Set templates and static directory\ntemplate_dir = os.path.abspath('./app/templates')\nstatic_dir = os.path.abspath('./app/static')\n\n# Configure app to run from this file\napp = Flask(__name__, template_folder=template_dir, static_folder=static_dir)\n\n# Sessions secret key\napp.secret_key=\"mykey123456\"\n\n# Makes a route unable to be visited unless logged in\ndef loginRequired(function):\n\t@wraps(function)\n\tdef decorated_function(*args, **kwargs):\n\t\t# If user is not authenticated\n\t\ttry:\n\t\t\t# If user is authenticated, proceed as per normal\n\t\t\tif session['isAuthenticated']:\n\t\t\t\tprint(\"User authenticated\")\n\t\t\t\tprint(session['userType'])\n\t\t\t\treturn function()\n\t\t\t\n\t\texcept KeyError as e:\n\t\t\t# if session['isAuthenticated'] is None or not session['isAuthenticated']:\n\t\t\tprint(e)\n\t\tprint(\"User not authenticated, Redirecting\")\n\t\treturn redirect('/login')\n\treturn decorated_function\n\nfrom .app import routes\n\n# Configure app to run if this file is executed\nif __name__ == '__main__':\n app.run(debug=False, use_reloader=True)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605996761","text":"import numpy as np\n\n\n# sigmoid function 0 ve 1 arasinda bir deyer alir hemishe, deriv=true tepe noqtesi 0 olan menfi ededlerdir /\\\ndef nonlin(x, deriv=False):\n if (deriv == True):\n return x * (1 - x)\n return 1 / (1 + np.exp(-x))\n\n\n# input dataset\nX = np.array([[0, 0, 1],\n [0, 1, 1],\n [1, 0, 1],\n [1, 1, 1]])\n\n# output dataset .T sertlerle sutunlarin yerini deyishir, burada bir setr yaradir sonra onu sutuna cevirir. Birbasha sutunda yaratmaq olar(array([[0], [0], [1], [1]]))\ny = np.array([[0, 0, 1, 1]]).T\n\n# seed random numbers to make calculation\n# deterministic (just a good practice), neticesi sadece null-dur\nnp.random.seed(1)\n\n# initialize weights randomly with mean 0, -1 ve 1 arasinda 3 eded 1 setrli matrix generate edir( np.random.random((3, 1))- 0-1 arasinda olan matrix) 2-ye vurub 1 cixdiqda deyer -1 ve 1 arasinda alinir\nsyn0 = 2 * np.random.random((3, 1)) - 1\n\nfor iter in range(10000):\n # forward propagation l0 girish matrixdir, l1 cixish. l0 ve generate olunmush -1 ve 1 arasinda olan martixsi bir-birine vurur ve alinan deyerleri 0-1 arasina cevirir\n l0 = X\n l1 = nonlin(np.dot(l0, syn0))\n\n # how much did we miss? dogru cavabdan biz tesadufi aldigimiz deyerleri cixir ve bizim sehvmizini tapiriq\n l1_error = y - l1\n\n # multiply how much we missed by the\n # slope of the sigmoid at the values in l1, sehvin deltasini tapiriq\n l1_delta = l1_error * nonlin(l1, True)\n\n # update weights, etdiyimiz sehv qeder dogruya yaxinlashiriq ve procedurur defelerle icra ederek dogruya yaxin netice almaga calishiriq\n syn0 += np.dot(l0.T, l1_delta)\n\nprint(\"Output After Training:\")\nprint(l1)","sub_path":"neuron_one_synapse.py","file_name":"neuron_one_synapse.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54956716","text":"__author__ = 'GoForBroke'\n\nfrom pip._vendor import requests\nimport sys\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport lxml.html\n\nprint(sys.argv)\n\nuser_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'\n\n\n# login_page_url = 'https://www.google.ru/'\nlogin_page_url = 'http://vk.com/login.php'\n\npage = None\ntry:\n req = urllib.request.Request(\n login_page_url,\n data=None,\n headers={\n # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n # 'Accept-Encoding': 'gzip, deflate, sdch',\n # 'Accept-Language': 'en-US,en;q=0.8,ru;q=0.6,uk;q=0.4',\n # 'Connection': 'keep-alive',\n # 'Cookie': 'remixlang=3; remixlhk=ddfa1885e3df1ea294; remixflash=20.0.0; remixscreen_depth=24; remixdt=0; remixtst=a942ea64',\n # 'Host': 'vk.com',\n # 'Referer': 'http://vk.com/login.php',\n # 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': user_agent,\n },\n origin_req_host=None,\n unverifiable=False\n )\n # page = urllib.request.urlopen(login_page_url)\n page = urllib.request.urlopen(req)\nexcept urllib.error.HTTPError as err:\n if err.code == 404:\n print(\"Url \\\"%s\\\" это несуществующая страница\" % login_page_url)\n exit()\n\n# print(page.read())\n# exit()\n\ndoc = lxml.html.document_fromstring(page.read())\n\n\n# form_1 = doc.cssselect('form input')\n# print(form_1)\n\ninput_ip_h = doc.cssselect('input[name=\"ip_h\"]')[0]\ninput_lg_h = doc.cssselect('input[name=\"lg_h\"]')[0]\n\nip_h_val = input_ip_h.attrib.get(\"value\")\nlg_h_val = input_lg_h.attrib.get(\"value\")\n\nprint(ip_h_val)\nprint(lg_h_val)\n\n# exit()\n\n\ndata = urllib.parse.urlencode({\n 'act': 'login',\n '_origin': 'http://vk.com',\n 'ip_h': ip_h_val,\n 'lg_h': lg_h_val,\n 'email': '+79810000000',\n 'pass': 'your_password',\n 'expire': '',\n})\nheaders = {'User-Agent': user_agent, 'Content-Type': 'application/json'}\nrequest = requests.post('https://login.vk.com/', data=data, headers=headers)\nprint(request.text)\n\n# print(r.status_code, r.reason)\n# print(response_login.read())\n\nrequest = requests.post('https://vk.com/feed')\nprint(request.text)\n\n\n# r = requests.post('https://vk.com', data={\n# '@action': '/feed'\n# }, auth=(\n# '+380990001005',\n# 'ihatethisfuckingworld665'\n# ))\n# print(r.status_code, r.reason)\n# print(r.text)\n","sub_path":"src/vk-dialog-images-collector.py","file_name":"vk-dialog-images-collector.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"101467813","text":"from warnings import warn\nimport numpy as np\nimport SimpleITK as sitk\nfrom wsireg.utils.tform_conversion import convert_to_itk\n\n\nclass RegTransform:\n def __init__(self, elastix_transform):\n self.elastix_transform = elastix_transform\n self.itk_transform = convert_to_itk(self.elastix_transform)\n\n self.output_spacing = [\n float(p) for p in self.elastix_transform.get(\"Spacing\")\n ]\n self.output_size = [int(p) for p in self.elastix_transform.get(\"Size\")]\n self.output_origin = [\n float(p) for p in self.elastix_transform.get(\"Origin\")\n ]\n self.output_direction = [\n float(p) for p in self.elastix_transform.get(\"Direction\")\n ]\n self.resample_interpolator = self.elastix_transform.get(\n \"ResampleInterpolator\"\n )[0]\n\n self.is_linear = self.itk_transform.IsLinear()\n\n if self.is_linear is True:\n self.inverse_transform = self.itk_transform.GetInverse()\n transform_name = self.itk_transform.GetName()\n if transform_name == \"Euler2DTransform\":\n self.inverse_transform = sitk.Euler2DTransform(\n self.inverse_transform\n )\n elif transform_name == \"AffineTransform\":\n self.inverse_transform = sitk.AffineTransform(\n self.inverse_transform\n )\n elif transform_name == \"Similarity2DTransform\":\n self.inverse_transform = sitk.Similarity2DTransform(\n self.inverse_transform\n )\n else:\n self.inverse_transform = None\n\n def compute_inverse_nonlinear(self):\n\n tform_to_dfield = sitk.TransformToDisplacementFieldFilter()\n tform_to_dfield.SetOutputSpacing(self.output_spacing)\n tform_to_dfield.SetOutputOrigin(self.output_origin)\n tform_to_dfield.SetOutputDirection(self.output_direction)\n tform_to_dfield.SetSize(self.output_size)\n\n displacement_field = tform_to_dfield.Execute(self.itk_transform)\n displacement_field = sitk.InvertDisplacementField(displacement_field)\n displacement_field = sitk.DisplacementFieldTransform(\n displacement_field\n )\n\n self.inverse_transform = displacement_field\n\n def as_np_matrix(\n self,\n use_np_ordering=False,\n n_dim=3,\n use_inverse=False,\n to_px_idx=False,\n ):\n if self.is_linear:\n if use_np_ordering is True:\n order = slice(None, None, -1)\n else:\n order = slice(None, None, 1)\n\n if use_inverse is True:\n transform = self.inverse_transform\n else:\n transform = self.itk_transform\n\n # pull transform values\n tmatrix = np.array(transform.GetMatrix()[order]).reshape(2, 2)\n center = np.array(transform.GetCenter()[order])\n translation = np.array(transform.GetTranslation()[order])\n\n if to_px_idx is True:\n phys_to_index = 1 / np.asarray(self.output_spacing).astype(\n np.float64\n )\n center *= phys_to_index\n translation *= phys_to_index\n\n # construct matrix\n full_matrix = np.eye(n_dim)\n full_matrix[0:2, 0:2] = tmatrix\n full_matrix[0:2, n_dim - 1] = (\n -np.dot(tmatrix, center) + translation + center\n )\n\n return full_matrix\n else:\n warn(\n \"Non-linear transformations can not be represented converted\"\n \"to homogenous matrix\"\n )\n return None\n","sub_path":"wsireg/reg_transform.py","file_name":"reg_transform.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433040135","text":"from datetime import datetime\n\n\nclass Job:\n DayOfWeek = 0\n StartTime = datetime.strptime(\"00:00\", \"%H:%M\").time()\n EndTime = datetime.strptime(\"00:00\", \"%H:%M\").time()\n WorkDescription = \"\"\n\n def __init__(self, day_of_week, start_time, end_time, work_desc):\n parsed_start_time = datetime.strptime(start_time, \"%H:%M\").time()\n parsed_end_time = datetime.strptime(end_time, \"%H:%M\").time()\n if parsed_end_time > parsed_start_time:\n self.DayOfWeek = day_of_week\n self.StartTime = parsed_start_time\n self.EndTime = parsed_end_time\n self.WorkDescription = work_desc\n else:\n raise ArithmeticError('End time must be greater than start time.')\n","sub_path":"src/models/Job.py","file_name":"Job.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"466332433","text":"from django import forms\nfrom .models import Module\n\nclass ModuleForm(forms.ModelForm):\n class Meta:\n model = Module\n fields = [\"Department_Name\", \"Department_ID\", \"Module_Name\", \"Module_ID\", \"Faculty\",\n \"Credit_Value\", \"Module_Lead\", \"Catalogue_Link\", \"Description\"]\n\n\nclass CheckBoxForm(forms.Form):\n Modules = forms.BooleanField()\n Publications = forms.BooleanField()\n","sub_path":"App/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"575641813","text":"'''\nCreated on 2013-2-2\n\n@author: Joseph\n'''\nfrom PySide.QtUiTools import QUiLoader\nfrom PySide.QtCore import QMetaObject\n\n\nclass MyQUiLoader(QUiLoader):\n def __init__(self, baseinstance):\n super(MyQUiLoader, self).__init__()\n self.baseinstance = baseinstance\n \n def createWidget(self, className, parent=None, name=\"\"):\n widget = QUiLoader.createWidget(self, className, parent, name)\n if parent is None:\n return self.baseinstance\n else:\n setattr(self.baseinstance, name, widget)\n return widget\n\ndef loadUi(uifile, baseinstance=None):\n loader = MyQUiLoader(baseinstance)\n ui = loader.load(uifile)\n QMetaObject.connectSlotsByName(ui)\n return ui\n\n\n\n","sub_path":"pyside/ui/loadui.py","file_name":"loadui.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279956999","text":"from time import sleep\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.select import Select\r\n\r\n# setwd\r\nimport os\r\nwd = \"C:\\\\Users\\\\Daniel\\\\Google Drive\\\\Projects\\\\2020.01 Yale's Most Popular Courses\\\\raw-data\"\r\nos.chdir(wd)\r\n\r\n# from selenium.webdriver.common.by import By\r\n# from selenium.webdriver.support.ui import WebDriverWait\r\n# from selenium.webdriver.support import expected_conditions as EC\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Set url here\r\nurl = 'https://ivy.yale.edu/course-stats/'\r\n\r\n# Set Chrome options\r\noptions = webdriver.ChromeOptions()\r\noptions.add_argument('--ignore-certificate-errors')\r\noptions.add_argument('--ignore-ssl-errors')\r\n\r\n# Open webdriver\r\ndriver = webdriver.Chrome(chrome_options = options)\r\ndriver.get(url)\r\n\r\n# GET LIST OF SUBJECTS\r\n\r\nsubjects_names = []\r\nsubjects_codes = []\r\nsubjects_elems = driver.find_elements_by_css_selector(\"#subjectCode option\")\r\n\r\nfor elem in subjects_elems[1:]: # first element is blank\r\n texts = elem.text.split(\" - \", 2)\r\n subjects_codes.append(texts[0])\r\n subjects_names.append(texts[1])\r\n\r\ndf_subjects = pd.DataFrame({'subject': subjects_codes, \r\n 'name': subjects_names})\r\ndf_subjects.to_csv('subjects.csv', index = False)\r\n# df_subjects.head(10)\r\n\r\n# GET LIST OF DATE\r\n\r\ndropdown = Select(driver.find_element_by_id(\"subjectCode\"))\r\ndropdown.select_by_value(\"AMTH\") # since AMTH definitely isn't a blank table\r\n\r\ndates_table = driver.find_element_by_css_selector(\"table table\").find_elements_by_css_selector(\"td\")\r\ndates_headers = []\r\nfor elem in dates_table:\r\n dates_headers.append(elem.text.strip())\r\n \r\n# np.array(dates_headers) # use nparray to show on one line\r\n\r\n# SCRAPE DEMAND\r\n\r\ncourses_ids = []\r\ncourses_codes = []\r\ncourses_names = []\r\n\r\ndemand_ids = []\r\ndemand_codes = []\r\ndemand_dates = []\r\ndemand_counts = []\r\n\r\ni = 1\r\n\r\nfor subject in subjects_codes:\r\n dropdown = Select(driver.find_element_by_id(\"subjectCode\"))\r\n dropdown.select_by_value(subject)\r\n sleep(2)\r\n\r\n courses = driver.find_elements_by_css_selector(\"div#content > div > table > tbody > tr\")\r\n \r\n for course in courses:\r\n code = course.find_element_by_css_selector(\"td a\").text.strip()\r\n name = course.find_element_by_css_selector(\"td span\").text.strip()\r\n\r\n full_strings_all = code.split(\"/\") # a list with each possible cross-listed code\r\n full_strings = [s for s in full_strings_all if s.split(\" \")[0] in subjects_codes]\r\n code_this_subject = [s for s in full_strings if subject in s][0]\r\n \r\n if full_strings.index(code_this_subject) == 0:\r\n for string in full_strings:\r\n courses_ids.append(i)\r\n courses_codes.append(string)\r\n courses_names.append(name)\r\n \r\n demands_containers = course.find_elements_by_css_selector(\"td.trendCell\")\r\n\r\n for j in range(len(dates_headers)):\r\n demand_ids.append(i)\r\n demand_codes.append(code_this_subject)\r\n demand_dates.append(dates_headers[j])\r\n demand_counts.append(demands_containers[j].text.strip())\r\n \r\n i += 1\r\n\r\n# WRITE TO CSV\r\n\r\ndf_courses = pd.DataFrame({'id': courses_ids, \r\n 'code': courses_codes, \r\n 'name': courses_names})\r\ndf_demand = pd.DataFrame({'id': demand_ids,\r\n 'date': demand_dates,\r\n 'count': demand_counts})\r\n\r\ndf_courses.to_csv('courses.csv', index = False)\r\ndf_demand.to_csv('demand.csv', index = False)","sub_path":"scripts/scrape_cds.py","file_name":"scrape_cds.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615581914","text":"#!/usr/bin/env python3\nimport os\nimport matplotlib\nif os.environ.get('DISPLAY','') == '':\n print('no display found. Using non-interactive Agg backend')\n matplotlib.use('Agg')\n\nimport collections\nimport ipaddress\nimport glob\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport re\nimport shlex\nimport subprocess\nimport sys\nimport time\n\n\n# Params\nN_SAMPLES = 50\nDEFAULT_BACKEND = '127.0.0.1:80'\nVARNISH_PORT = 9090\nN_CLIENTS = 100\nN_REQUESTS = 10000\n\n# Git constants\nCLEAN_COMMIT = 'a3696e6'\nDRR_COMMIT = 'b9ce232'\n\n# Hosts constants\nCLIENT_HOSTNAME = 'client'\nSERVER_HOSTNAME = 'server'\nCLIENT_SIDE_DEV = 'enp6s0f0'\nSERVER_SIDE_DEV = 'enp6s0f1'\nCLIENT_SIDE_IP1 = '192.168.1.1'\nCLIENT_SIDE_IP2 = '192.168.1.3'\nSERVER_SIDE_IP = '10.0.0.1'\n\n# Dirs\nFPATH = os.path.dirname(os.path.realpath(__file__))\nBASE_DIR = os.path.join(FPATH, '..')\nWIDGETS_DIR = os.path.join(BASE_DIR, 'widgets')\nLOGS_DIR = os.path.join(BASE_DIR, 'logs')\nGRAPHS_DIR = os.path.join(BASE_DIR, 'graphs')\nVARNISH_DIR = os.path.join(BASE_DIR, 'varnish-cache')\nCSV_FNAME = '{}_sample_{}.csv'\n\n\ndef call(cmd, err_msg):\n if subprocess.call(cmd, shell=True):\n print(err_msg)\n sys.exit(1)\n\n\ndef set_ip(ip, dev):\n cmd = 'sudo ip addr add {}/16 dev {} || true'\n cmd = cmd.format(ip, dev)\n call(cmd, 'Failed to set ip address')\n\n\ndef killall_varnishd():\n cmd = '(! pgrep varnishd) || (sudo killall -q varnishd && sleep 2)'\n call(cmd, 'Failed to killall varnishd')\n\n\ndef rebuild_varnishd(commit):\n cmd = 'cd {} && git checkout {}'\n cmd = cmd.format(VARNISH_DIR, commit)\n call(cmd, 'Failed to checkout commit in varnish dir')\n\n cmd = 'cd {} && ./install-varnish.sh'\n cmd = cmd.format(BASE_DIR)\n call(cmd, 'Failed to install varnish')\n\n \ndef start_varnishd():\n cmd = 'sudo varnishd -a :{} -b {} -p vcc_allow_inline_c=on -p thread_pool_min=20 -p thread_pool_max=100'\n cmd = cmd.format(VARNISH_PORT, DEFAULT_BACKEND)\n call(cmd, 'Failed to start varnishd')\n\n \ndef restart_varnishd():\n killall_varnishd()\n start_varnishd()\n\n \ndef parse_vcl_name(vcl_path):\n split = os.path.split(vcl_path)\n fn = split[1].split('.')[0]\n wtype = os.path.split(split[0])[1]\n return '{}_{}'.format(wtype, fn)\n\n\ndef install_vcl(vcl_path):\n vcl_path = os.path.abspath(vcl_path)\n vcl_name = parse_vcl_name(vcl_path)\n print(vcl_name)\n cmd = 'echo \"vcl.load {} {}\" | varnishadm'\n cmd = cmd.format(vcl_name, vcl_path)\n call(cmd, 'Failed to load vcl')\n \n cmd = 'echo \"vcl.use {}\" | varnishadm'\n cmd = cmd.format(vcl_name)\n call(cmd, 'Failed to install vcl')\n\n\ndef killall_remote_ab():\n cmd = \"ssh client '(sudo killall -q ab || true) && sleep 1'\"\n call(cmd, 'Failed to kill all remote apache bench')\n\n\ndef start_slow_client():\n cmd = \"ssh client 'ab -c {} -n {} -v 1 http://{}:{}/index.html'\"\n cmd = cmd.format(N_CLIENTS, N_REQUESTS, CLIENT_SIDE_IP1, VARNISH_PORT)\n\n slow_client = subprocess.Popen(shlex.split(cmd))\n\n return slow_client\n\n\ndef start_fast_client(csv_fname):\n cmd = \"ssh client 'ab -c {} -n {} -v 1 -e {} http://{}:{}/index.html'\"\n cmd = cmd.format(N_CLIENTS, N_REQUESTS, csv_fname, CLIENT_SIDE_IP2, VARNISH_PORT)\n\n fast_client = subprocess.Popen(shlex.split(cmd))\n\n return fast_client\n\n\ndef copy_csv(fname, dst):\n cmd = 'scp client:/root/{} {}'\n cmd = cmd.format(fname, dst)\n\n call(cmd, 'Failed to copy csv file from client')\n\n\ndef collect_latency_dists(fname_prefix):\n # Setup\n set_ip(CLIENT_SIDE_IP1, CLIENT_SIDE_DEV)\n set_ip(CLIENT_SIDE_IP2, CLIENT_SIDE_DEV)\n killall_remote_ab()\n\n for i in range(N_SAMPLES):\n restart_varnishd()\n install_vcl(os.path.join(FPATH, 'ab_latency_dists.vcl'))\n\n # Start slow client\n slow_client = start_slow_client()\n\n # Give slow client chance to saturate Varnish\n time.sleep(5)\n\n # Start fast client\n fast_client = start_fast_client(CSV_FNAME.format(fname_prefix, i))\n\n # Wait for fast client to finish and clean up slow client\n fast_client.wait()\n\n # Clean up\n slow_client.kill()\n killall_remote_ab()\n\n logs_dir = os.path.join(LOGS_DIR, 'collect_latency_dists')\n if not os.path.exists(logs_dir):\n os.makedirs(logs_dir)\n\n fname = CSV_FNAME.format(fname_prefix, '*')\n copy_csv(fname, logs_dir)\n\n return logs_dir\n\n\ndef parse_logs(logs_dir, fname_prefix):\n\n # Parse logs\n csv_fname = CSV_FNAME.format(fname_prefix, '*')\n fns = glob.glob(os.path.join(logs_dir, csv_fname))\n\n frames = [pd.read_csv(open(fn, 'r'), index_col=0) for fn in fns]\n return pd.concat(frames, axis=1)\n \n\ndef create_results_csv(base_results, drr_results):\n graphs_dir = os.path.join(GRAPHS_DIR, 'collect_latency_dists')\n if not os.path.exists(graphs_dir):\n os.makedirs(graphs_dir)\n\n base_avg = base_results.mean(axis=1)\n drr_avg = drr_results.mean(axis=1)\n\n results = pd.concat([base_avg, drr_avg], axis=1, keys=['base', 'drr'])\n results.to_csv(os.path.join(graphs_dir, 'results.csv'))\n\n \ndef run_exps():\n # # Profile base version\n # rebuild_varnishd(CLEAN_COMMIT)\n # logs_dir = collect_latency_dists('base')\n\n # # Profile updated version\n # rebuild_varnishd(DRR_COMMIT)\n # logs_dir = collect_latency_dists('drr')\n\n logs_dir = os.path.join(LOGS_DIR, 'collect_latency_dists')\n base_results = parse_logs(logs_dir, 'base')\n drr_results = parse_logs(logs_dir, 'drr')\n\n create_results_csv(base_results, drr_results)\n\n\ndef main(argc, argv):\n if os.geteuid() != 0:\n print('This experiment requires root permissions')\n sys.exit(1)\n \n if not os.path.exists(LOGS_DIR):\n os.makedirs(LOGS_DIR)\n\n if not os.path.exists(GRAPHS_DIR):\n os.makedirs(GRAPHS_DIR)\n \n run_exps()\n\nif __name__ == '__main__':\n main(len(sys.argv), sys.argv)\n\n","sub_path":"data-collection/ab_latency_dists.py","file_name":"ab_latency_dists.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274958226","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom lib import helpers\nfrom collections import Counter\n\nimport config, subprocess, json, re\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\n\n\n\n\n# КЛАСС ДЛЯ СОЗДАНИЯ ФИЛЬТРОВ ВИДЕО\nclass Video_filters_generator():\n\n\tdef __init__( self, FILE_NAME, media_info, processing_params ):\n\n\t\tself.media_info = media_info\n\n\t\tself.FILE_NAME = FILE_NAME\n\n\t\tself.processing_params\t= processing_params\n\t\t\n\n\n\tdef generate_filter_chain( self ):\n\n\n\t\tself.video_filters\t\t= []\t# Массив с фильрами\n\t\tself.actual_width \t\t= None\t# значение ширины после применения очередного фильтра\n\t\tself.actual_height \t\t= None\t# значение высоты -||-\n\n\t\tscale_filter \t\t\t= None\t# фильтр масштаба\n\t\tcrop_filter \t\t\t= None\t# фильтр для обрезки полей видео\n\t\tpadding_filter \t\t\t= None\t# фильтр добавления полей для достижения минимального размера\n\t\tadditional_scale\t\t= None\t# Фильтр масштаба, следующий после всех другиз фильтров\n\n\t\tvideo_stream_index \t\t= self.media_info.indexes['video']\n\n\n\t\tself.actual_width = self.media_info.streams[video_stream_index]['width']\t\n\t\tself.actual_height = self.media_info.streams[video_stream_index]['height']\n\n\n\t\tif self.processing_params['v_codec'] == 'copy' or \\\n\t\t\tself.processing_params['vn'] == True:\n\n\t\t\treturn\n\n\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА МАСШТАБИРОВАНИЯ\n\t\tscale_filter = self.scale_calculation()\n\n\t\tif scale_filter != None:\n\n\t\t\tself.video_filters.append( scale_filter )\n\t\t\tself.video_filters.append( 'setsar=sar=1/1' )\n\n\t\t\tlogging.debug( 'width after rescaling ' + scale_filter )\n\n\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА КРОПА\n\t\tcrop_filter = self.crop_calculation()\n\n\t\tif crop_filter != None:\n\n\t\t\tself.video_filters.append( crop_filter )\n\n\t\t\tlogging.debug( crop_filter )\n\n\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА ПАДДИНГА\n\t\tpadding_filter = self.padding_calculation()\n\n\t\tif padding_filter!= None:\n\n\t\t\tself.video_filters.append( padding_filter )\n\n\t\t\tlogging.debug( padding_filter )\n\n\t\t\n\n\t\t# МАСШТАБ ВИДЕО ПОСЛЕ ПРИМЕНЕНИЯ ВСЕХ ФИЛЬТРОВ\n\t\tadditional_scale = self.additional_scale()\n\n\t\tif additional_scale != None:\n\n\t\t\tself.video_filters.append( additional_scale )\n\t\t\tself.video_filters.append( 'setsar=sar=1/1' )\n\n\n\n\t\t# ОПРЕДЕЛЕНИЕ БИТРЕЙТА\n\t\tbitrate = self.bitrate_calculation()\n\n\t\tif bitrate != None:\n\n\t\t\tself.bitrate = bitrate\n\n\n\t\t# ОПРЕДЕЛЕНИЕ НАЗВАНИЯ КАЧЕСТВА (SHQ, HD720 И Т.Д.)\t\n\t\tself.quality = self.quality_calculation()\n\n\n\n\tdef bitrate_calculation( self ):\n\n\t\t\"\"\"Метод определяет битрейт на основе размера видео, \n\t\tполучаемого после всех манипуляций \n\n\t\tВозвращает:\n\t\tbitrate - str\n\t\t\"\"\"\n\n\t\tlogging.debug( 'calculate bitrate' )\n\n\n\t\tvideo_stream_index \t= self.media_info.indexes['video']\n\t\tbitrate \t\t\t= '12M'\n\n\t\ttry:\n\t\t\t\n\t\t\tself.orig_bitrate = int( self.media_info.streams[ video_stream_index ]['bit_rate'] ) / ( 1024 * 1024 )\n\n\t\texcept:\n\n\t\t\tself.orig_bitrate = None\n\n\n\n\t\t# Если пользователь установил битрейт, то используем его\n\t\tif self.processing_params['vb'] != None :\n\n\t\t\tbitrate = self.processing_params['vb']\n\n\t\telif self.actual_width >= 1280:\n\n\t\t\tbitrate = '12M'\n\n\t\telse: \n\n\t\t\tbitrate = '8M'\n\n\n\n\t\treturn bitrate\n\n\n\tdef quality_calculation( self ):\n\n\t\t\"\"\"Метод выбирает название качества видео\n\t\tв зависимости от размера.\n\n\t\tВозвращает:\n\t\tquality - str\n\t\t\"\"\"\n\n\t\tif self.actual_width == None:\n\n\t\t\treturn 'und'\n\n\n\t\tif self.actual_width >= 1900:\n\n\t\t\tquality = 'hd1080'\n\n\t\telif self.actual_width >= 1270:\n\n\t\t\tquality = 'hd720'\n\n\t\telse:\n\n\t\t\tquality = 'shq'\n\n\t\treturn quality\n\n\t\t\n\n\n\tdef scale_calculation( self ):\n\n\t\t\"\"\"Метод вычисляет значение фильтра scale, необходимое для\n\t\tкомпенсации изменения ширины,связанного с переводом\n\t\tнеквадратного пикселя в квадратный\n\n\t\tВозвращает:\n\t\tscale_filter - str\n\t\t\"\"\"\n\n\n\t\tvideo_stream_index\t= self.media_info.indexes['video']\n\t\tsar \t\t\t\t= self.media_info.streams[video_stream_index]['sample_aspect_ratio']\n\n\n\t\t# Фильтр scale требуется только в том случае, \n\t\t# Если видео анаморфное\n\t\tif sar == 1:\n\n\t\t\treturn None\n\n\n\t\torig_width\t\t= self.media_info.streams[video_stream_index]['width']\n\t\tscale_width\t\t= helpers.round_up_to_even( orig_width*sar )\n\n\t\tscale_filter \t= 'scale=' + str( scale_width ) + ':' + str( self.media_info.streams[video_stream_index]['height'] )\n\n\n\t\tself.actual_width = scale_width\n\n\t\t# Добавляем к массиву фильтров изменение масштаба\n\t\t# Так как sar не равен единице, то также добавляем \n\t\t# фильр setsar\n\t\treturn scale_filter\n\n\t\t\t\n\n\n\tdef additional_scale( self ):\n\n\t\t\"\"\"Метод проверяет, задал ли пользователь\n\t\tдополнительное масштабирование и проверяет\n\t\tправильно ли оно задано\n\n\t\tВозвращает:\n\t\tadditional_scale - str\n\t\t\"\"\"\n\n\n\t\tadditional_scale = None\n\n\n\t\tif self.processing_params['set_scale'] == None:\n\n\t\t\treturn None\n\n\t\tadditional_scale = self.processing_params['set_scale'].split(':')\n\n\n\t\tif len( additional_scale ) != 2:\n\n\t\t\timport sys\n\n\t\t\tlogging.debug('invalid scale value')\n\t\t\tsys.exit()\n\n\n\t\tself.actual_width = int( additional_scale[0] )\n\t\tself.actual_height = int( additional_scale[1] )\n\n\t\tadditional_scale = 'scale=' + self.processing_params['set_scale']\n\t\t\n\t\treturn additional_scale\n\n\t\t\n\n\n\n\tdef crop_calculation( self ):\n\n\t\t\"\"\"Метод для создания фильтра кропа.\n\t\tПоведение зависит от параметра processing_params['crop']\n\t\tЕсли праметр равен auto, то метод обращается\n\t\tк классу media_analisis для определенияи кропа. \n\t\tЕсди параметр содержит заданное пользователем значение\n\t\tкропа, то использует это значение.\n\n\t\tЕсли итоговый кроп равен оригинальному размеру видео, то\n\t\tФильтр не используется.\n\n\t\tВозвращает:\n\t\tcrop_filter - str\n\n\t\t\"\"\"\n\n\n\t\tif self.processing_params['crop'] != None:\n\n\n\t\t\tif self.processing_params['crop'] == 'auto':\n\n\t\t\t\tcrop = self.media_info.crop_detect()\n\n\t\t\telse:\n\n\t\t\t\tcrop = self.processing_params['crop']\n\n\t\t\t\n\t\telse:\n\n\t\t\treturn None\n\n\n\t\tif crop == None:\n\n\t\t\treturn None\n\t\t\n\n\t\tlogging.debug( 'crop_calculation')\n\n\n\t\t# Превращаем итоговую строку кропа в массив с числовыми значениями\n\t\t# Сохраняем его в self для последующего использования при определения паддинга\n\t\tcrop_filter_values = [ int(value) for value in crop.split(':') ]\n\n\n\n\t\t# В случае неквадратного пикселя нужно пересчитать параметры кропа ( width и координату x)\n\t\t# Если кроп был задан вручную, то не пересчитываем\n\t\tvideo_stream_index\t= self.media_info.indexes['video']\n\n\t\twidth = self.media_info.streams[video_stream_index]['width']\n\t\theight = self.media_info.streams[video_stream_index]['height']\n\t\tsar \t= self.media_info.streams[video_stream_index]['sample_aspect_ratio']\n\n\n\t\tif crop_filter_values[0] == width and crop_filter_values[1] == height:\n\n\t\t\tlogging.debug('crop width and height are equal original size. Skipping')\n\n\t\t\treturn None\n\n\n\t\tif sar != 1:\n\n\t\t\t# Умножаем ширину и координату X на значение SAR и округляем результат, проверяя его четность\n\t\t\tcrop_filter_values[0] = helpers.round_up_to_even ( crop_filter_values[0]*sar )\n\t\t\tcrop_filter_values[2] = helpers.round_up_to_even ( crop_filter_values[2]*sar )\n\n\n\n\t\tself.actual_width = crop_filter_values[0]\n\t\tself.actual_height = crop_filter_values[1]\n\n\n\t\t# Приводим все значения массива к строковому типу для последующего объединения\n\t\t# и приводим в необходимый вид\n\t\tcrop_filter = [ str(value) for value in crop_filter_values ]\n\n\t\tcrop_filter = 'crop=' + ':'.join( crop_filter )\n\n\t\treturn crop_filter\n\n\tdef padding_calculation( self ):\n\n\t\t\"\"\"Метод добавляет поля к видео. Это нужно для того, \n\t\tчтобы ра��мер видео не был меньше минимально необходиымх\n\t\tзначений \n\n\t\t720x304 - SHQ\n\t\t1270x560 - HD720\n\t\t1900\t - HD1080\n\n\t\tВозвращает:\n\t\tpadding_filter - str\n\n\t\t\"\"\"\n\n\t\tlogging.debug( 'video padding filter calculation')\n\n\t\t# Если пользватель в параметрах кодирования задал значение масштаба, \n\t\t# то автоматическое вычисление паддинга не требуется\n\t\tif self.processing_params['set_scale'] != None or self.processing_params['no_pad'] == True:\n\n\t\t\tlogging.debug('padding disabled')\n\n\t\t\treturn None\n\n\t\tif self.actual_width <= 720:\n\n\t\t\tif self.actual_height < 304:\n\t\t\t\tpad_Y\t= ( 304 - self.actual_height ) / 2\n\t\t\t\tpad_height = 304\n\n\t\t\telse:\n\t\t\t\tpad_Y = 0\n\t\t\t\tpad_height = self.actual_height\n\n\t\t\tif self.actual_width < 720:\n\t\t\t\tpad_X = ( 720 - self.actual_width ) / 2\n\t\t\t\tpad_width = 720\n\n\t\t\telse:\n\n\t\t\t\tpad_X = 0\n\t\t\t\tpad_width = self.actual_width\n\n\t\telif self.actual_width > 1270 and self.actual_width <= 1280:\n\n\t\t\tif self.actual_height < 560:\n\t\t\t\tpad_Y = ( 560 - self.actual_height ) / 2\n\t\t\t\tpad_height = 560\n\n\t\t\telse:\n\t\t\t\tpad_Y = 0\n\t\t\t\tpad_height = self.actual_height\n\n\t\t\tif self.actual_width < 1280:\n\t\t\t\tpad_X = ( 1280 - self.actual_width ) / 2\n\t\t\t\tpad_width = 1280\n\n\t\t\telse:\n\t\t\t\tpad_X = 0\n\t\t\t\tpad_width = self.actual_width\n\n\t\telif self.actual_width > 1280:\n\n\t\t\tif self.actual_height < 700:\n\t\t\t\tpad_Y = ( 700 - self.actual_height ) / 2\n\t\t\t\tpad_height = 700\n\n\t\t\telse:\n\t\t\t\tpad_Y = 0\n\t\t\t\tpad_height = self.actual_height\n\n\t\t\tif self.actual_width < 1900:\n\t\t\t\tpad_X = ( 1900 - self.actual_width ) / 2\n\t\t\t\tpad_width = 1900\n\n\t\t\telse:\n\t\t\t\tpad_X = 0\n\t\t\t\tpad_width = self.actual_width\n\n\t\telse:\n\n\t\t\tpad_X = 0\n\t\t\tpad_Y = 0\n\n\n\t\tpad_X = round(pad_X)\n\t\tpad_Y = round(pad_Y)\n\n\n\t\tif pad_X != 0 or pad_Y != 0:\n\n\t\t\tpadding_filter = 'pad=' + str( pad_width ) + ':' + str( pad_height ) + ':' + str( pad_X ) + ':' + str( pad_Y ) + ':black'\n\n\t\t\tself.actual_width = pad_width\n\t\t\tself.actual_height = pad_height\n\n\t\t\treturn padding_filter\n\n\t\telse:\n\n\t\t\tlogging.debug( 'where is no need in padding filter. Skip' ) \n\n\n\n\n\n# КЛАСС ДЛЯ СОЗДАНИЯ ФИЛТЬРОВ АУДИО\nclass Audio_filters_generator():\n\n\tdef __init__( self, FILE_NAME, media_info, processing_params ):\n\n\t\tlogging.debug('Audio filters generating')\n\n\t\tself.media_info \t\t= media_info\n\t\tself.processing_params\t= processing_params\n\t\tself.audio_filters \t\t= []\n\t\tself.audio_metadata\t\t= []\n\t\tself.audio_mapping\t\t= []\n\n\tdef generate_filter_chain( self ):\n\n\t\tif 'audio_streams' not in self.processing_params or \\\n\t\t\t\tself.processing_params['audio_streams'] is None:\n\n\t\t\treturn None\n\n\t\toutput_channel_count = 0\n\t\tstreams = self.processing_params['audio_streams']\n\n\n\n\t\t# Однажды настанет тот светлый день, когда мы будем \n\t\t# отдавать один файл с разными аудиодорожками.\n\t\t# В тот прекрасный, далёкий день\n\t\t# можно будет раскомменить эту команду\n\t\t# streams = self.filter_streams(streams)\n\n\t\tfor audio_stream in streams:\n\n\t\t\t# анализ выбранных каналов в модуле media_analisis\n\t\t\taudio_stream = self.media_info.analise_audio( audio_stream )\n\n\t\t\tif audio_stream is None:\n\t\t\t\tcontinue\n\n\t\t\tlanguage = audio_stream['language']\n\t\t\tchannels = audio_stream['channels']\n\n\t\t\t# Получаем цепочку фильтров для выбранной аудиодорожки\n\t\t\t# Если установлен codec copy, то тогда не добавляем фильтры\n\t\t\tif 'a_codec' in self.processing_params and self.processing_params['a_codec'] == 'copy' or \\\n\t\t\t\t'codec' in self.processing_params and self.processing_params['codec'] == 'copy':\n\n\t\t\t\tfinal_audio_filter = None\n\n\t\t\telse:\n\t\t\t\tfinal_audio_filter = self.create_audio_filter( audio_stream )\n\n\t\t\t# Если фильтры созданы, то добавляем очередной\n\t\t\t# набор фильтр для языка в общий массив с аудифильтрами\n\t\t\tif final_audio_filter != None:\n\n\t\t\t\tself.audio_filters.append( final_audio_filter )\n\n\t\t\t\tself.audio_mapping += [ '-map' , '[a_' + language + '_out]' ]\n\n\t\t\telse:\n\n\t\t\t\tself.audio_mapping += [ '-map' , '0:' + str( channels[0] )]\n\n\t\t\t# устанавливаем значение метаданных в зависимости от языка\t\n\t\t\tself.audio_metadata += [ '-metadata:s:a:' + str(output_channel_count) , 'language=' + language ]\n\n\t\t\toutput_channel_count += 1\n\n\t\tlogging.debug(self.audio_filters)\n\t\tlogging.debug(self.audio_metadata)\n\t\tlogging.debug(self.audio_mapping)\n\n\tdef filter_streams( self, streams ):\n\n\t\tfiltered_streams = []\n\n\t\tfor stream in streams:\n\n\t\t\tfiltered_streams.append(stream)\n\n\t\t\tif stream['downmix'] != 1:\n\n\t\t\t\tcontinue\n\n\t\t\tif len(stream['channels']) == 1:\n\n\t\t\t\tlayout = self.media_info.check_channel_layout( channels[0] )\n\n\t\t\t\tif layout != '5.1':\n\n\t\t\t\t\tcontinue\n\n\t\t\t\tstream = stream.copy()\n\n\t\t\t\tstream['downmix'] = 0\n\n\t\t\t\tfiltered_streams.append(stream)\n\n\t\t\tif len(stream['channels']) == 6:\n\n\t\t\t\tstream = stream.copy()\n\n\t\t\t\tstream['downmix'] = 0\n\n\t\t\t\tfiltered_streams.append(stream)\n\n\t\treturn filtered_streams\n\n\tdef volume_filter_calculation( self, audio_mapping ):\n\n\t\tvolume_filter \t= None # строка фильтра для ffmpeg\n\t\tvolume_level \t= None # величина изменения пиковой громкости\n\t\tmax_level \t\t= None # уровень пиковой громкости исходного файла\n\n\t\tif self.processing_params['vol'] == 0 and \\\n\t\t\tself.processing_params['norm'] == None:\n\n\t\t\treturn None\n\n\t\telif self.processing_params['vol'] == 0 and \\\n\t\t\tself.processing_params['norm'] != None:\n\n\t\t\tself.media_info.volume_detect( audio_mapping )\n\n\t\t\t# определение параметров громкости с помощью метода volume_info\n\t\t\t# Этот метод создаёт большой хэш с гистограммами громкости \n\t\t\t# (количество сэмплов на определенный уровень громкости),\n\t\t\t# максимальным и среднеквадратическим уровнем\n\t\t\tmax_level = self.media_info.volume_info['max_volume']\n\n\t\t\t#Если максимальная громкость не опеределна, прекращаем\n\t\t\tif max_level == None or max_level == '':\n\n\t\t\t\treturn None\n\n\t\t\t#Если максимальная громкость больше заданной, прекращаем\n\t\t\tif max_level >= self.processing_params['norm']:\n\n\t\t\t\tlogging.debug('leaving original volume level')\n\n\t\t\t\treturn None\n\n\t\t\t# сведение до заданного уровня\n\t\t\tvolume_level = str( -1 * max_level + self.processing_params['norm'] )\n\n\t\telif self.processing_params['vol'] != None:\n\n\t\t\tvolume_level = self.processing_params['vol']\n\n\t\telse:\n\n\t\t\tvolume_level = 0\n\n\t\tvolume_filter = 'volume=+' + str(volume_level) + 'dB'\n\n\t\treturn volume_filter\n\n\tdef fade_in_filter( self, fade_time ):\n\n\t\tif fade_time == None:\n\n\t\t\treturn None\n\n\t\tfade_time = str(fade_time)\n\n\n\t\tif fade_time.isdigit():\n\n\t\t\treturn 'afade=t=in:ss=0:d=' + fade_time \n\n\t\telse:\n\n\t\t\treturn None\n\n\tdef fade_out_filter( self, fade_time ):\n\n\t\tif fade_time == None:\n\n\t\t\treturn None\n\n\t\tfade_time = str(fade_time)\n\n\t\tif fade_time.isdigit():\n\n\t\t\tst = int( self.media_info.final_duration ) - int( fade_time )\n\n\t\t\tst = str( st )\n\n\t\t\treturn 'afade=t=out:st=' + st + ':d=' + fade_time\n\n\t\telse:\n\n\t\t\treturn None\n\n\tdef create_audio_filter( self, audio_stream ):\n\t\t\n\t\t# массив, в котором будут содержаться фильтры для одного\n\t\t# выбранного языка\n\t\tsingle_language_filters = []\n\n\t\t# определение параметров меппинга\n\t\taudio_mapping = self.media_info.audio_map_calculation(audio_stream['channels'], audio_stream['downmix'])\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА ГРОМКОСТИ\n\t\tvolume_filter = self.volume_filter_calculation(audio_mapping)\n\n\t\tif volume_filter is not None:\n\n\t\t\tsingle_language_filters.append( volume_filter )\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА ПЛАВНОГО УВЕЛИЧЕНИЯ ГРОМКОСТИ В НАЧАЛЕ\t\n\t\tfade_in_filter = self.fade_in_filter(self.processing_params['fade_in'])\n\n\t\tif fade_in_filter is not None:\n\n\t\t\tsingle_language_filters.append( fade_in_filter )\n\n\t\t# ОПРЕДЕЛЕНИЕ ФИЛЬТРА ПЛАВНОГО УМЕНЬШЕНИЯ ГРОМКОСТИ В КОНЦЕ\t\n\t\tfade_out_filter = self.fade_out_filter(self.processing_params['fade_out'])\n\n\t\tif fade_out_filter is not None:\n\n\t\t\tsingle_language_filters.append(fade_out_filter)\n\n\n\t\t# Если фильтров нет и звук имеет допустимый кодек\n\t\t# То кодирование звука не требуется\n\t\tif len( single_language_filters ) == 0 and \\\n\t\t\tlen( audio_stream['channels'] ) == 1 and 'anull' in audio_mapping:\n\n\t\t\tindex = int(audio_stream['channels'][0])\n\n\t\t\ta_codec = self.media_info.streams[ index ]['codec_name']\n\n\t\t\tif a_codec in config.SUITABLE_AUDIO_CODECS:\n\n\t\t\t\treturn None\n\n\n\n\t\tfinal_audio_filter_string = audio_mapping \n\n\t\ti = 1\n\n\t\t# формирование цепочки фильтров вида:\n\t\t# audio_filter_1[a_rus_1];[a_rus_1]audio_filter2 и так далее\n\t\tfor single_filter, has_more in helpers.lookahead( single_language_filters ):\n\n\t\t\tfinal_audio_filter_string += '[a_' + audio_stream['language'] + '_' + str(i) + '];'\n\t\t\tfinal_audio_filter_string += '[a_' + audio_stream['language'] + '_' + str(i) + ']'\n\n\t\t\tfinal_audio_filter_string += single_filter\n\n\t\t\ti+=1\n\n\t\tfinal_audio_filter_string += '[a_' + audio_stream['language'] + '_out]'\n\n\t\treturn final_audio_filter_string\n\n\n\n\n\n\n\ndef filter_chain_finalising( video_filters, audio_filters, media_info ):\n\n\t# Если фильров нет, то мы не используем -filter_complex вовсе\n\tif len( video_filters ) == 0 and len( audio_filters ) == 0:\n\n\t\treturn None\n\n\n\tfinal_filter_string = ''\n\n\t# Если есть фильтры для видео, то цепочка фильтров начинается с выбора актуальной видеодорожки\n\tif len( video_filters ) > 0:\n\n\t\tfinal_filter_string = '[0:%s]' % str( media_info.indexes['video'] )\n\n\t\t# Далее мы перебираем все элементы из массива video_filters и поочередно добавляем \n\t\t# их в финальную строку. Итератор i используется для формирования выхода/входа фильтров\n\t\t# [0:0]filter_1[v_1];[v_1]filter_2[v_2] ... [v_n]filter_n[v_out]\n\t\t# Выход v_out в конечном счёте подается в -map\n\n\t\t# Для перебора массива используется вспомогательная функция lookahead\n\t\t# Она позволяет отследить, есть ли после текущего элемента ещё один\n\t\t# Если нет, то к строке добаляется [v_out] и цикл прекращается\n\t\ti = 1\n\n\t\tfor video_filter, has_more in helpers.lookahead( video_filters ):\n\n\t\t\t\t\n\t\t\tfinal_filter_string += video_filter\n\n\t\t\tif has_more == True:\n\n\t\t\t\tfinal_filter_string += '[v_%s]' % i\n\t\t\t\tfinal_filter_string += ';[v_%s]' % i\n\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tfinal_filter_string += '[v_out]'\n\n\t\t\ti+=1\n\n\n\t# Добавляем аудиофильтры в случае, если они есть\n\tif len(audio_filters) > 0:\n\n\t\tif final_filter_string != '':\n\n\t\t\tfinal_filter_string += ';'\n\n\n\t\tfinal_filter_string += ';'.join(audio_filters )\n\n\t\n\treturn final_filter_string","sub_path":"lib/filters_generator.py","file_name":"filters_generator.py","file_ext":"py","file_size_in_byte":20704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626955114","text":"from __future__ import print_function\nfrom random import sample, choice\nfrom Levenshtein import distance\nfrom Bio import SeqIO\nimport sys\nimport string\nimport datetime as d\n\n\n#@jit\ndef all_edit():\n \n length_cutoff = int(sys.argv[1])\n edit_dis = int(sys.argv[2])\n seq_file = sys.argv[3]\n filename = sys.argv[4]\n\n repeat_file = open(\"all_repeats_1-6nt.txt\",\"r\")\n\n records = SeqIO.parse(seq_file,\"fasta\")\n\n\n repeats_out = dict()\n new_motifs = set()\n out_file = open(filename,\"w+\")\n \n motif_lengths = []\n\n for line in repeat_file:\n motif_dict = dict()\n \n L = line.strip().split('\\t')\n motif = L[0]\n motif_length = int(L[2])\n\n if motif_length not in motif_lengths:\n motif_lengths.append(motif_length)\n i=0\n input_seq_length = motif_length\n while i < motif_length and input_seq_length < length_cutoff:\n motif += motif[i]\n i += 1\n if i >= motif_length:\n i = 0\n input_seq_length = len(motif)\n \n motif_dict['class'] = L[1]\n motif_dict['motif_length'] = motif_length\n motif_dict['strand'] = L[3]\n repeats_out[motif] = motif_dict\n repeats_out['rep_lengths'] = [length_cutoff]\n new_motifs.add(motif) #consists of all the motifs of specified length\n\n \"\"\"\n accessing the newly formed motifs \n \"\"\"\n\n #alphabet = ['A','T','G','C']\n #i=-1\n\n repeat_lengths = repeats_out['rep_lengths'] # All possible length cutoffs\n \n for record in records:\n #dict_out = dict()\n \n input_seq = str(record.seq).upper()\n\n input_seq_length = len(input_seq)\n for length_cutoff in repeat_lengths:\n #fallback = length_cutoff - 1\n sub_start = 0 # substring start\n sub_stop = sub_start + repeat_lengths[-1] # substring stop\n while sub_stop <= input_seq_length:\n \n subseq = input_seq[sub_start:sub_stop]\n\n while subseq.find('N')!=-1:\n nu_pos = input_seq.find('A' or 'T' or 'C' or 'G',subseq.find('N')+sub_start)\n change_by = nu_pos - (sub_start + subseq.find('N'))\n sub_start += subseq.find('N') + change_by\n sub_stop = sub_start + length_cutoff\n subseq = input_seq[sub_start:sub_stop]\n\n if subseq not in new_motifs:\n dict_out = dict()\n for ext_rep in new_motifs:\n #i = i+1\n cal_edit_dis = distance(subseq, ext_rep)\n if(cal_edit_dis <= edit_dis):\n if cal_edit_dis not in dict_out.keys():\n dict_out[cal_edit_dis] = list()\n for s in range(0,2):\n dict_out[cal_edit_dis].append(set())\n dict_out[cal_edit_dis][0].add(repeats_out[ext_rep]['class'])\n dict_out[cal_edit_dis][1].add(repeats_out[ext_rep]['strand'])\n else: \n dict_out[cal_edit_dis][0].add(repeats_out[ext_rep]['class'])\n dict_out[cal_edit_dis][1].add(repeats_out[ext_rep]['strand'])\n #print('{:<20s} {:<20s} {:<20s} {:<20s} {:<20s} {:<10s} {:<10s}'.format(record.id,str(sub_start),str(sub_stop),subseq,ext_rep,repeats_out[ext_rep]['class'],str(cal_edit_dis)),file = out_file)\n #print(record.id,str(sub_start),str(sub_stop),subseq,ext_rep,repeats_out[ext_rep]['class'],str(cal_edit_dis),sep='\\t',file = out_file)\n \n if len(dict_out.keys()) != 0:\n l = list()\n for m in dict_out.keys():\n l.append(int(m))\n cls_out = min(l)\n \n #print('{:<20s} {:<20s} {:<20s} {:<20s} {:<20s} {:<10s} {:<10s}'.format(record.id,str(sub_start),str(sub_stop),subseq,str('NA'),str(cls_out),\":\".join(str(x) for x in dict_out[cls_out])),file = out_file)\n print(record.id,sub_start,sub_stop,len(subseq),subseq,str('NA'),cls_out,\":\".join(str(x) for x in dict_out[cls_out][1]),\":\".join(str(y) for y in dict_out[cls_out][0]),sep='\\t',file = out_file)\n sub_start += 1\n sub_stop = sub_start + length_cutoff\n\n else:\n sub_start += length_cutoff\n sub_stop = sub_start + length_cutoff\n\n\nst = d.datetime.now() \nall_edit()\nprint(d.datetime.now()-st)\n","sub_path":"Edit_opt/seq_lev_chan_out.py","file_name":"seq_lev_chan_out.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365967150","text":"from kfp import dsl\n\nfrom metaflow import FlowSpec, step, kfp, S3\n\n\ndef flip_coin_func(s3_root: str) -> str:\n \"\"\"\n returns heads or tails\n \"\"\"\n import random\n from metaflow import S3\n\n result = \"tails\" if random.randint(0, 2) == 0 else \"heads\"\n\n print(\"s3_root\", s3_root)\n print(\"result\", result)\n\n if result == \"tails\":\n with S3(s3root=s3_root) as s3:\n s3.put(\"my_result\", result)\n\n return result\n\n\n@dsl.graph_component\ndef my_recursive_component(s3_root):\n from kfp.components import func_to_container_op\n from kfp.dsl import ContainerOp\n\n flip_coin_op: ContainerOp = func_to_container_op( # pylint: disable=E1102\n func=flip_coin_func, packages_to_install=[\"metaflow==2.2.4\"]\n )(s3_root)\n\n with dsl.Condition(flip_coin_op.output == \"heads\"):\n my_recursive_component(s3_root)\n\n\nclass KfpGraphComponentFlow(FlowSpec):\n \"\"\"\n A Flow that decorates a Metaflow Step with a KFP graph_component\n \"\"\"\n\n @step\n def start(self):\n \"\"\"\n kfp.preceding_component_inputs [\"s3_root\"] is passed to the graph_component because\n graph_components cannot return KFP outputs, and hence we use S3 flow root as the data\n passing mechanism. See how the end step uses S3 to get the result.\n \"\"\"\n with S3(run=self) as s3:\n self.s3_root = s3._s3root\n print(\"self.s3_root\", self.s3_root)\n s3.put(\"start_key\", \"start_value\")\n\n self.next(self.end)\n\n @kfp(preceding_component=my_recursive_component, preceding_component_inputs=[\"s3_root\"])\n @step\n def end(self):\n \"\"\"\n S3 flow root path now has flip result in my_result\n \"\"\"\n with S3(run=self) as s3:\n ret = s3.get(\"my_result\")\n print(\"ret\", ret)\n print(\"ret.text\", ret.text)\n assert ret.text == \"tails\"\n assert s3.get(\"start_key\").text == \"start_value\"\n\n\nif __name__ == \"__main__\":\n KfpGraphComponentFlow()\n","sub_path":"metaflow/tutorials/09-hellokfp/kfp_graph_component_flow.py","file_name":"kfp_graph_component_flow.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"141055245","text":"# a binary search allows us to search for an element in a sorted array.\n# this is more efficient than a loop because the time complexity is O(logN) instead of O(N).\n\ndef search2(nums, value, lo, hi):\n if lo > hi:\n return None # not in list\n mid = (lo + hi) // 2\n if (nums[mid] < value): # look in upper half\n return search2(nums, value, mid + 1, hi)\n elif (nums[mid] > value): # look in lower half\n return search2(nums, value, lo, mid - 1)\n else: # if value == nums[mid]\n return mid\n\ndef binary_search(nums, value):\n lo = 0\n hi = len(nums) - 1\n return search2(nums, value, lo, hi)\n\n# >>> binary_search([1,2,3], 2)\n# 1\n","sub_path":"search-and-sort/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627031713","text":"import quicksnmp\nfrom pyconfig import *\nfrom pysnmp.smi.rfc1902 import rfc1902\nimport json\nimport os\nimport time\nfrom aai_requests import *\n\ndef set_nec_lldp_port(host_ip):\n nec_port_lldp_to_enable = []\n comp = 0\n statuts = quicksnmp.get_table(host_ip, nec_port_lldp_status,credentials)\n for stat in statuts:\n if stat[1].prettyPrint() != 'txAndRx' :\n comp +=1\n nec_port_lldp_to_enable.append(('.1.0.8802.1.1.2.1.1.6.1.2.'+str(stat[0][-1]),rfc1902.Integer32(3)))\n print('Port to Set : ', comp)\n if nec_port_lldp_to_enable != [] :\n lldp_on = quicksnmp.add_row_oids(host_ip,nec_port_lldp_to_enable,credentials)\n prinn('LLDP Set')\n\ndef set_hua_lldp_port(host_ip) :\n hua_port_lldp_to_enable = []\n comp = 0\n statuts = quicksnmp.get_table(host_ip, hua_port_lldp_status,credentials)\n for stat in statuts:\n if stat[1].prettyPrint() != 'txrx' :\n comp +=1\n hua_port_lldp_to_enable.append(('.1.3.6.1.4.1.2011.2.25.4.50.27.1.5.1.4.'+str(stat[0][-3])+'.'+str(stat[0][-2])+'.'+str(stat[0][-1]),rfc1902.Integer32(3)))\n print('Ports to Set : ', comp)\n if hua_port_lldp_to_enable != [] :\n lldp_on = quicksnmp.add_row_oids(host_ip,hua_port_lldp_to_enable,credentials)\n print('LLDP Set')\n\n\n\ndef set():\n \n cwd = os.getcwd()\n if cwd.split('/')[-1]!='snmp' : os.chdir(\"Scripts/python/snmp/\")\n\n try:\n f=open(\"inventory.json\",)\n devices=json.load(f)\n f.close()\n except:\n devices = dict()\n \"\"\"\n try :\n devices = get_request(URL_GET_DEVICES)[1]['device']\n except:\n devices = list()\n \"\"\"\n\n for ne in devices :\n print(\"---------- NE : \", ne[\"hostname\"], ' - IP : ',ne['address'], \" -----------\")\n if 'nec' in ne['vendor']:\n set_nec_lldp_port(ne['address'])\n \n if ne['vendor'] == 'huawei' :\n set_hua_lldp_port(ne['address'])\n\nset()\n\nprint(\"Wait LLDP communications\")\ntime.sleep(30)","sub_path":"Microwave_ONAP/Scripts/python/snmp/set_lldp_port_on.py","file_name":"set_lldp_port_on.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"274727421","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport pymysql\nimport os\nfrom whoosh.index import create_in\nfrom jieba.analyse import ChineseAnalyzer\nfrom decimal import Decimal\nfrom whoosh.fields import Schema, TEXT\nimport configparser\n\n\nanalyzer = ChineseAnalyzer()\n\n\nclass Config(object):\n \"\"\"\n # Config().get_content(\"user_information\")\n \"\"\"\n def __init__(self, config_filename=\"myProjectConfig.cnf\"):\n file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), config_filename)\n self.cf = configparser.ConfigParser()\n self.cf.read(file_path)\n\n def get_sections(self):\n return self.cf.sections()\n\n def get_options(self, section):\n return self.cf.options(section)\n\n def get_content(self, section):\n result = {}\n for option in self.get_options(section):\n value = self.cf.get(section, option)\n result[option] = int(value) if value.isdigit() else value\n return result\n\n\nclass base_pymysql(object):\n def __init__(self, host, port, user, password, db_name):\n self.db_host = host\n self.db_port = int(port)\n self.user = user\n self.password = str(password)\n self.db = db_name\n self.conn = None\n self.cursor = None\n\n def connect(self):\n self.conn = pymysql.connect(host=self.db_host, port=self.db_port, user=self.user,\n passwd=self.password, db=self.db, charset=\"utf8\")\n self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)\n\n\nclass MyPymysql(base_pymysql):\n \"\"\"\n Basic Usage:\n ret = My_Pymysql('test1')\n res = ret.selectone_sql(\"select * from aaa\")\n print(res)\n ret.close()\n Precautions:\n Config.__init__(self, config_filename=\"myProjectConfig.cnf\")\n \"\"\"\n\n def __init__(self, conf_name):\n # self.conf = Config().get_content(conf_name)\n self.conf = {\"host\": \"192.168.1.126\", \"port\": 3306, \"db_name\": \"db_metadata\", \"user\": \"root\", \"password\": \"python123\"}\n super(MyPymysql, self).__init__(**self.conf)\n self.connect()\n\n def idu_sql(self, sql):\n # adu: insert, delete, update的简写\n # 考虑到多语句循环, try就不写在这里了\n self.cursor.execute(sql)\n self.conn.commit()\n\n def insert_sql(self, sql, value=None):\n # adu: insert, delete, update的简写\n self.cursor.execute(sql, value)\n self.conn.commit()\n\n def selectone_sql(self, sql):\n self.cursor.execute(sql)\n self.conn.commit()\n return self.cursor.fetchone()\n\n def selectall_sql(self, sql):\n self.cursor.execute(sql)\n self.conn.commit()\n return self.cursor.fetchall()\n\n def close(self):\n self.conn.close()\n self.conn = None\n self.cursor = None\n\ndef parse_db(tables, conn, indexname, schema, indexdir, keys):\n table = tables\n sql = \"select * from %s;\" % table\n rows = conn.selectall_sql(sql)\n conn.close()\n # keys = rows[0].keys()\n s = \"Schema(\"\n for key in keys:\n s += key.replace('\\n', '').replace('/r', '').replace('\\t', '').replace(' ', '') + '=TEXT(stored=True, analyzer=analyzer), '\n s = s.rstrip(\", \")\n s += \")\"\n schema = eval(s)\n if not os.path.exists(indexdir):\n os.makedirs(indexdir)\n ix = create_in(indexdir, schema=schema, indexname=indexname)\n writer = ix.writer()\n for row in rows:\n docline = \"\"\"writer.add_document(\"\"\"\n for key in keys:\n val = row[key]\n if not val:\n val = \"\"\n elif isinstance(val, (Decimal,)):\n val = str(val)\n\n else:\n val = pymysql.escape_string(str(val))\n docline += key + '=\"' + val + '\", '\n docline = docline.rstrip(\", \")\n docline += \"\"\")\"\"\"\n exec(docline)\n writer.commit()\n\n\ndef escape(s, obj=\"’\"):\n ret = ''\n for x in s:\n if x == obj:\n ret += '\\\\'\n ret += x\n return ret\n\n\ndef app():\n\n tables = [\"meta_project\", \"meta_questionnaire\", \"meta_variable\"]\n # filepath = Config().get_content(\"indexFilePath\")[\"filepath\"]\n filepath = \"/data/index\" #指定路径,首先需要创建\n indexdir = \"indexdir\"\n filename = filepath + \"/\" + indexdir\n projKey = [\"ProjectID\", \"UserID\", \"ProjectName\", \"ProjectOrgan\", \"ProjectSubject\", \"SubjectField\", \"ProjectLevel\",\n \"ProjectSource\", \"FundsSource\", \"ProjectSummary\", \"CycleType\", \"CycleSpan\", \"TeamIntroduction\",\n \"ProjectPublic\", \"ProjectStatus\", \"EditUserID\", \"EditTime\", \"CreateTime\", \"StartTime\", \"EndTime\"]\n quesKey = [\"QuesID\", \"ProjectID\", \"QuesDataForm\", \"QuesTitle\", \"QuesSummary\", \"QuesKeywords\", \"QuesObject\",\n \"QuesDataChannel\", \"SamplePlan\", \"ResponseSituation\", \"DataTeam\", \"QuesDataTown\",\n \"MinimumGeographicUnit\",\n \"DataCoverageTime\", \"QuesStartTime\", \"QuesEndTime\", \"WeightDescription\", \"CreateTime\", \"QuesStatus\"]\n varKey = [\"VariableID\", \"DataTableID\", \"OrderNum\", \"VarName\", \"VarType\", \"VarWidth\", \"VarDecimals\", \"OriginFormats\",\n \"VarMeasure\", \"VarValues\", \"VarMissing\", \"VarTopic\", \"VarLabel\", \"OriginQuestion\", \"OtherLangLabel\",\n \"DataFrom\", \"DeriveFrom\", \"VarRole\", \"VarVersion\", \"ReviseFrom\", \"ReviseTime\", \"ReviseUserID\", \"VarNote\",\n \"VarStatus\"]\n docline = \"\"\"writer.add_document(\"\"\"\n\n for table in tables:\n if table == \"meta_project\":\n keys = projKey\n elif table == \"meta_questionnaire\":\n keys = quesKey\n elif table == \"meta_variable\":\n keys = varKey\n db_connect = MyPymysql(\"metadata\")\n name = table.split(\"_\")\n dbname = name[0] + name[1]\n parse_db(table, db_connect, indexname=dbname, schema=\"\", indexdir=filename, keys=keys)\n\n\nif __name__ == '__main__':\n # 1. 修改mypymysql的用户名密码\n # 2. 修改filepath的路径,前提是先创建\n\n app()\n","sub_path":"common/util/myCreateWhooshIndexFile.py","file_name":"myCreateWhooshIndexFile.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436123962","text":"#===DESCRIPTION=================================================================\n# A script to extract mitogenome stats from the INSDSeq XML output of NCBI \n# written by C. Jonathan Schmitt \n\nimport xml.etree.ElementTree as ET\nimport csv\n\n# read in xml file, in this case saved in same directory where you call this script from\ntree = ET.parse(\"mitogenomes_squamata.xml\")\nroot = tree.getroot()\n\n# open a file for writing\n\nmitogenome_data = open('/Users/schmitty/Documents/CJS/projects/bird_genome_review/mitogenomes_squamata.csv', 'w')\n\n# create the csv writer object\n\ncsvwriter = csv.writer(mitogenome_data)\nmitogenome_head = []\n\n# create the column names\ncol_names = ['accession', 'submission_date', 'sequence_length', 'organism', ]\ncsvwriter.writerow(col_names)\n\ncount = 0\nfor member in root.findall('INSDSeq'):\n\tmitogenome = []\n\tif count == 0:\n\t\taccession = member.find('INSDSeq_primary-accession').tag\n\t\tmitogenome_head.append(accession)\n\t\tsubmission_date = member.find('INSDSeq_create-date').tag\n\t\tmitogenome_head.append(submission_date)\n\t\tsequence_length = member.find('INSDSeq_length').tag\n\t\tmitogenome_head.append(sequence_length)\n\t\torganism = member.find('INSDSeq_organism').tag\n\t\tmitogenome_head.append(organism)\n\t\tcount = count + 1\n\t\t\n\taccession = member.find('INSDSeq_primary-accession').text\n\tmitogenome.append(accession)\n\tsubmission_date = member.find('INSDSeq_create-date').text\n\tmitogenome.append(submission_date)\n\tsequence_length = member.find('INSDSeq_length').text\n\tmitogenome.append(sequence_length)\n\torganism = member.find('INSDSeq_organism').text\n\tmitogenome.append(organism)\n\tcsvwriter.writerow(mitogenome)\nmitogenome_data.close()","sub_path":"genome_stats_figure/NCBI_xml_to_csv_squamata_mitogenome.py","file_name":"NCBI_xml_to_csv_squamata_mitogenome.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294340508","text":"# coding: utf8\nfrom __future__ import unicode_literals, print_function, division, absolute_import\nimport json\n\nfrom mock import Mock\n\nfrom clld.db.models.common import Parameter, Language\nfrom clld.tests.util import TestWithEnv, WithDbAndDataMixin\nfrom clld.web.adapters import geojson\nfrom clld.web.datatables.base import DataTable\n\ngeojson.pacific_centered()\n\n\nclass Tests(WithDbAndDataMixin, TestWithEnv):\n def test_GeoJson(self):\n adapter = geojson.GeoJson(None)\n self.assertEquals(len(list(adapter.feature_iterator(None, None))), 0)\n self.assertEquals(len(list(adapter.feature_iterator(Language(), None))), 1)\n self.assertEquals(\n len(list(adapter.feature_iterator(Mock(languages=[Language()]), None))), 1)\n\n def test_GeoJsonParameter(self):\n adapter = geojson.GeoJsonParameter(None)\n self.assertTrue(\n '{' in adapter.render(Parameter.get('no-domain'), self.env['request']))\n\n self.set_request_properties(params=dict(domainelement='de'))\n res = json.loads(adapter.render(Parameter.get('parameter'), self.env['request']))\n self.assertTrue(len(res['features']) > 0)\n self.assertIn('label', res['features'][0]['properties'])\n\n def test_GeoJsonParameterMultipleValueSets(self):\n adapter = geojson.GeoJsonParameterMultipleValueSets(None)\n self.assertTrue(\n '{' in adapter.render(Parameter.get('no-domain'), self.env['request']))\n\n def test_GeoJsonParameterFlatProperties(self):\n adapter = geojson.GeoJsonParameterFlatProperties(None)\n self.assertTrue(\n '{' in adapter.render(Parameter.get('no-domain'), self.env['request']))\n\n def test_GeoJsonLanguages(self):\n class MockLanguages(DataTable):\n def get_query(self, *args, **kw):\n return [Language.first()]\n\n adapter = geojson.GeoJsonLanguages(None)\n self.assertIn(\n 'Point',\n adapter.render(\n MockLanguages(self.env['request'], Language), self.env['request']))\n\n def test_get_lonlat(self):\n self.assertIsNone(geojson.get_lonlat(None))\n self.assertIsNone(geojson.get_lonlat((None, 5)))\n self.assertGreater(geojson.get_lonlat((-50, 1))[0], 0)\n self.assertAlmostEquals(geojson.get_lonlat(Mock(latitude=1, longitude=1)), (1, 1))\n\n def test_get_feature(self):\n l = Language.first()\n self.assertEquals(geojson.get_feature(l)['id'], l.id)\n self.assertEquals(geojson.get_feature(l)['properties']['name'], l.name)\n self.assertEquals(geojson.get_feature(l, name='geo')['properties']['name'], 'geo')\n","sub_path":"clld/tests/test_web_adapters_geojson.py","file_name":"test_web_adapters_geojson.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"365530207","text":"import torch\nimport os\nimport cv2\nimport glob\nimport numpy as np\nfrom skimage import io, transform\nfrom torchvision import transforms, utils\nfrom torch.utils.data import Dataset, DataLoader\nfrom random import shuffle\n\nclass AnimalsDataset(Dataset):\n def __init__(self, mode, size, samples, labels, transform=None):\n self.mode = mode\n self.root_dir = f'C:/DATASETS/CatsDogs/{mode}_{size}'\n self.transform = transform\n self.samples = samples\n self.labels = labels\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, index):\n sample_name = self.samples[index]\n lable = None\n if self.mode == 'train':\n lable = self.labels[sample_name]\n lable = np.array(lable)\n elif self.mode == 'test':\n lable = sample_name#no matters\n image = cv2.imread(f'{self.root_dir}/{sample_name}')\n sample = (image, lable)\n\n if self.transform:\n sample = self.transform(sample)\n \n return sample","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"339273812","text":"import random\r\nimport matplotlib.pyplot as plt\r\nfrom pacman import *\r\nimport ghostAgents\r\nimport layout\r\nimport textDisplay\r\nimport graphicsDisplay\r\nimport copy\r\nimport numpy as np\r\nfrom pprint import pprint\r\nimport sys\r\n\r\n## set up the parameters to newGame\r\nnumtraining = 0\r\ntimeout = 30\r\nbeQuiet = True\r\nlayout = layout.getLayout(\"mediumClassic\")\r\npacmanType = loadAgent(\"NumericThresholdAgent\", True)\r\nnumGhosts = 1\r\nghosts = [ghostAgents.RandomGhost(i + 1) for i in range(numGhosts)]\r\ncatchExceptions = True\r\n\r\n\r\ndef run(code):\r\n rules = ClassicGameRules(timeout)\r\n if beQuiet:\r\n gameDisplay = textDisplay.NullGraphics()\r\n rules.quiet = True\r\n else:\r\n timeInterval = 0.001\r\n textDisplay.SLEEP_TIME = timeInterval\r\n gameDisplay = graphicsDisplay.PacmanGraphics(1.0, timeInterval)\r\n rules.quiet = False\r\n thePacman = pacmanType()\r\n thePacman.setCode(code)\r\n game = rules.newGame(layout, thePacman, ghosts, gameDisplay, beQuiet, catchExceptions)\r\n game.run()\r\n return game.state.getScore()\r\n\r\n\r\n####### genetic algorithm\r\n\r\n\r\ndef cross(parent1, parent2):\r\n crossoverchild = np.empty((19, 10), dtype=object)\r\n # chossing a random crossover point\r\n crossoverx = random.randrange(19)\r\n crossovery = random.randrange(10)\r\n crossoverchild[0:crossoverx, 0:crossovery] = parent1[0:crossoverx, 0:crossovery]\r\n crossoverchild[0:crossoverx, crossovery:10] = parent2[0:crossoverx, crossovery:10]\r\n crossoverchild[crossoverx:19, 0:crossovery] = parent2[crossoverx:19, 0:crossovery]\r\n crossoverchild[crossoverx:19, crossovery:10] = parent1[crossoverx:19, crossovery:10]\r\n return crossoverchild\r\n\r\n\r\ndef mutate(parentp, numberOfMutations):\r\n mchild = copy.deepcopy(parentp)\r\n for _ in range(numberOfMutations):\r\n xx = random.randrange(19)\r\n yy = random.randrange(10)\r\n mchild[xx][yy] = random.uniform(0, 4)\r\n return mchild\r\n\r\n\r\ndef newmember():\r\n program = np.empty((19, 10), dtype=object)\r\n for xx in range(19):\r\n for yy in range(10):\r\n program[xx][yy] = random.uniform(0, 4)\r\n return program\r\n\r\n\r\ndef newpop(popSiz):\r\n population = []\r\n for _ in range(popSiz):\r\n program = newmember()\r\n population.append(program)\r\n return population\r\n\r\n\r\ndef evaluatePop(population):\r\n fitness = []\r\n for pp in range(0, len(population)):\r\n fitness.append(run(population[pp]))\r\n return fitness\r\n\r\n\r\ndef runGA(popSiz=20, timescale=400, tournamentSize=7, numberOfMutations=5):\r\n averages = []\r\n bests = []\r\n\r\n ## create random initial population\r\n population = newpop(popSiz)\r\n\r\n print(\"Beginning Evolution\")\r\n # start the generations\r\n for t in range(timescale):\r\n\r\n ## evaluate population\r\n fitness = evaluatePop(population)\r\n\r\n averages.append(1000 + sum(fitness) / popSiz)\r\n print(\"av \", 1000 + sum(fitness) / popSiz)\r\n bests.append(1000 + max(fitness))\r\n print(\"max \", 1000 + max(fitness))\r\n\r\n popFitPairs = list(zip(population, fitness))\r\n newPopulation = []\r\n\r\n halfPop = int(popSiz / 2)\r\n\r\n for i in range(halfPop):\r\n\r\n # select two parents using tournaments\r\n tournament1 = random.sample(popFitPairs, tournamentSize)\r\n parent1 = max(tournament1, key=lambda x: x[1])[0]\r\n\r\n tournament2 = random.sample(popFitPairs, tournamentSize)\r\n parent2 = max(tournament2, key=lambda x: x[1])[0]\r\n\r\n # crossover the selected parents\r\n crossover_child = cross(parent1, parent2)\r\n\r\n # mutate the child\r\n child = mutate(crossover_child, numberOfMutations)\r\n\r\n newPopulation.append(child)\r\n\r\n # add the best half of the population to the next generation\r\n newPopulation.append(sorted(popFitPairs, key=lambda x: x[1])[i][0])\r\n\r\n print(t)\r\n population = copy.deepcopy(newPopulation)\r\n\r\n ## ADD CODE TO PLOT averages AND bests\r\n\r\n print(averages)\r\n print(bests)\r\n plt.plot(averages)\r\n plt.plot(bests)\r\n plt.show()\r\n\r\nrunGA()\r\n","sub_path":"NumericGeneticExp2.py","file_name":"NumericGeneticExp2.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"517727725","text":"arr = []\r\nn = int(input(\"Number of integer inputs (elements) :\"))\r\nprint(\"please input numbers (elements) in array\")\r\nfor i in range(0,n,1):\r\n arr.append(int(input()))\r\nprint(arr)\r\ntar = int(input(\"Target value is :\"))\r\n\r\nk=1\r\nDict = {1: [1,2]}\r\nfor i in range(0,n,1):\r\n for j in range(0,n,1):\r\n if i!=j:\r\n if arr[i]+arr[j]==tar:\r\n Dict[k] = [i,j]\r\n k = k+1\r\nprint(Dict)\r\n \r\n","sub_path":"Pranay_ME20M036_Q2.py","file_name":"Pranay_ME20M036_Q2.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"495607228","text":"from discord.ext import commands\nimport os\nimport traceback\n\nbot = commands.Bot(command_prefix='/')\ntoken = os.environ['DISCORD_BOT_TOKEN']\nCHANNEL_ID = 710111629806927943\ndateTimeList = [\n'01:00',\n'05:00',\n'09:00',\n'13:00',\n'17:00',\n'21:00',\n'02:12',\n]\n\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n orig_error = getattr(error, \"original\", error)\n error_msg = ''.join(traceback.TracebackException.from_exception(orig_error).format())\n await ctx.send(error_msg)\n\n\n@bot.command()\nasync def pop(ctx):\n await ctx.send('pong')\n\n@bot.command()\nasync def 草蛇(ctx):\n await ctx.send('ジャローダ')\n\nbot.run(token)\n\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91360712","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom SimMultiTrans.bin.Network import *\nfrom SimMultiTrans.bin import *\nfrom SimMultiTrans import graph_file, vehicle_file\nfrom SimMultiTrans.utils import RESULTS\nimport numpy as np\nimport time\n\n\ndef main():\n start_time = time.time()\n lazy = 25\n range_ = 10\n p_name = 'None'\n r_name = 'simplex'\n step_len = 600\n time_hor = 10\n # create graph\n g = Graph()\n g.import_graph(file_name=graph_file)\n\n # setup simulator\n simu = Simulator(graph=g)\n simu.import_arrival_rate(unit=(1, 'sec'))\n simu.import_vehicle_attribute(file_name=vehicle_file)\n simu.set_running_time(start_time='08:00:00', time_horizon=time_hor, unit='hour')\n # simu.routing.set_routing_method(r_name)\n # simu.rebalance.set_parameters(lazy=lazy, v_range=range_)\n # simu.rebalance.set_policy(p_name)\n\n simu.initialize(seed=0)\n # action = np.random.random((len(g.get_all_nodes()), len(g.get_all_nodes())))\n action = np.eye(len(g.get_all_nodes()))\n # action = np.zeros((len(g.get_all_nodes()), len(g.get_all_nodes())))\n sim_action = dict()\n for idx, node in enumerate(g.get_all_nodes()):\n sim_action[node] = action[idx, :]/np.sum(action[idx, :]) if np.sum(action[idx, :]) != 0 else 0\n c_time = 0\n for idx in range(time_hor*3600//step_len):\n print(c_time)\n simu.step(action=sim_action,\n step_length=step_len,\n curr_time=c_time)\n c_time += step_len\n simu.finishing_touch(start_time)\n simu.save_result(path_name=RESULTS, unique_name=False)\n print(\"Time used:\", time.time() - start_time)\n\n plot = Plot(simu.graph, simu.time_horizon, simu.start_time)\n plot.import_results(path_name=RESULTS)\n plot.combination_queue_animation(mode='taxi', frames=100)\n plot.plot_passenger_queuelen_time(mode='taxi')\n plot.plot_passenger_waittime(mode='taxi')\n plot.plot_metrics(mode='taxi')\n\n\nif __name__ == \"__main__\":\n # import cProfile, pstats, io\n # from pstats import SortKey\n # pr = cProfile.Profile()\n # pr.enable()\n main()\n # pr.disable()\n # s = io.StringIO()\n # ps = pstats.Stats(pr, stream=s).sort_stats(SortKey.CUMULATIVE)\n # ps.print_stats()\n # print(s.getvalue())\n","sub_path":"SimMultiTrans/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325146182","text":"def test_migrate_up_to_specific_revision(alembic_runner, alembic_engine):\n alembic_runner.migrate_up_to(\"aaaaaaaaaaaa\")\n\n alembic_engine.execute(\"INSERT INTO foo (id) VALUES (100)\")\n\n alembic_runner.migrate_up_to('head')\n\n result = alembic_engine.execute(\"SELECT * FROM foo\").fetchall()\n assert len(result) == 1\n\n result = alembic_engine.execute(\"SELECT * FROM bar\").fetchall()\n assert len(result) == 0\n","sub_path":"examples/test_branched_history_with_mergepoint/test_migrations.py","file_name":"test_migrations.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"501349017","text":"\"\"\"\nGiven a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn the minimum cuts needed for a palindrome partitioning of s.\n\nExample:\n\nInput: \"aab\"\nOutput: 1\nExplanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n\"\"\"\n\n\nclass Solution:\n def minCut(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n import collections\n visited = {0, }\n queue = [(0, 0)]\n while queue:\n cut, idx = queue.pop(0)\n if s[idx:] == s[idx:][::-1]: return cut\n for i in range(idx + 1, len(s)):\n if i not in visited and s[idx: i] == s[idx: i][::-1]:\n visited.add(i)\n queue.append((cut + 1, i))\n","sub_path":"August_18/132. Palindrome Partitioning II.py","file_name":"132. Palindrome Partitioning II.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550402943","text":"import os\nfrom celery import Celery\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"projectshop.settings\")\napp = Celery(\n \"tasks\", broker=\"redis://127.0.0.1:6379/0\",\n backend=\"redis://127.0.0.1:6379/1\",\n)\napp.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")\napp.autodiscover_tasks()\n","sub_path":"projectshop/projectshop/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621316021","text":"import cv2 \nimport numpy as np\nimport pandas as pd\nfrom torchvision import datasets, transforms\nimport torch\nimport random\nfrom facenet_pytorch import MTCNN\nfrom PIL import Image\nfrom multiprocessing import cpu_count\nimport zipfile\n\nclass MTCNN_Model:\n def __init__(self, general_parameters,model_parameters,inference_parameters):\n \n #---------dataset_infos\n self.X = None\n self.input_images = None\n self.subfolders = None\n\n #--------general_parameters\n self.root_folder_name = general_parameters['root_folder_name']\n \n\n #---------model_parameters\n self.image_size = model_parameters['image_size']\n self.margin = model_parameters['margin']\n self.min_face_size = model_parameters['min_face_size']\n self.thresholds = model_parameters['thresholds']\n self.factor = model_parameters['factor']\n self.keep_all = model_parameters['keep_all']\n self.device = 'cuda:0' if (model_parameters['device']==\"cuda\" and torch.cuda.is_available()) else 'cpu'\n self.seed = model_parameters['seed']\n self.post_process = False\n \n #---------Inference_parameters\n self.inference_batch_size = inference_parameters['inference_batch_size']\n self.input_square_transformation_size = inference_parameters['input_square_transformation_size']\n\n #------- Other\n self.num_workers = cpu_count()\n\n #------- MTCNN\n self.mtcnn = MTCNN(image_size=self.image_size, \n margin=self.margin, \n min_face_size=self.min_face_size,\n thresholds=self.thresholds, \n factor=self.factor, \n post_process=self.post_process,\n keep_all=self.keep_all,\n device=self.device)\n\n #------- Reproducibility\n random.seed(self.seed)\n np.random.seed(self.seed)\n torch.random.manual_seed(self.seed)\n torch.cuda.manual_seed(self.seed)\n \n #------- Results\n self.df_result = None\n\n\n def predict(self,img_reference,step):\n if step == \"Experiment\":\n image_array = img_reference\n if step == \"Deployment\":\n img = img_reference\n image_array = Image.fromarray(img)\n\n boxes, probs = self.mtcnn.detect(image_array, landmarks=False)\n \n return (boxes, probs)\n\n def _construct_result_dataframe(self,step):\n boxes = []\n probs = []\n\n for i in range(0,len(self.X),self.inference_batch_size):\n img_reference = []\n batch = self.X[i:i+self.inference_batch_size]\n for row in batch:\n v_cap = cv2.VideoCapture(row[0])\n success, frame = v_cap.read()\n img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n img = cv2.resize(img, (self.input_square_transformation_size,self.input_square_transformation_size))\n img_reference.append(Image.fromarray(img))\n\n batch_result = self.predict(img_reference,step)\n\n if self.keep_all:\n for b,p in zip(batch_result[0],batch_result[1]):\n boxes.append(b)\n probs.append(p)\n \n else:\n for b,p in zip(batch_result[0],batch_result[1]):\n max_prob_position = np.argmax(p)\n boxes.append(b[max_prob_position])\n probs.append(np.max(p))\n\n self.df_result = pd.DataFrame({'Input_image':self.input_images,'Subfolder': self.subfolders ,'Bboxes(x1,y1,x2,y2)':boxes,'Probabilities':probs})\n\n\n def get_result_dataframe(self,X,step = 'Experiment'):\n\n self.X = X\n self.input_images = X[:,0]\n self.subfolders = X[:,1]\n self._construct_result_dataframe(step)\n return self.df_result","sub_path":"tasks/cv-mtcnn-face-detection/mtcnn.py","file_name":"mtcnn.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491566321","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom datetime import datetime\nfrom course.models import KnowledgeTopic, KnowledgePoint, Teacher\n\n\n# Create your models here.\n\n\nclass Exam(models.Model):\n name = models.CharField(max_length=30, verbose_name=u'测试名称')\n category = models.CharField(choices=(('zjl', u'章节测试'), ('txl', u'专题测试'),\n ('qzl', u'期中测试'), ('qml', u'期末测试'),\n ('yml', u'一模测试'), ('eml', u'二模测试'),\n ('gkl', u'高考真题'), ('khl', u'课后测试')\n ), verbose_name=u'测试类型')\n exam_time = models.IntegerField(verbose_name=u'测试时长')\n subject = models.CharField(choices=(('sx', u'数学'), ('wl', u'物理')), verbose_name=u'科目')\n # 版本:必修1,必修2等\n version = models.CharField(max_length=20, verbose_name='课程版本')\n grade = models.CharField(choices=(('gy', u'高一'), ('ge', u'高二'), ('gs', u'高三')), verbose_name=u'年级')\n\n desc = models.CharField(max_length=300, verbose_name=u'课程描述')\n # TextField 不限制输入长度\n click_nums = models.IntegerField(default=0, verbose_name=u'点击数')\n question_nums = models.IntegerField(default=5, verbose_name=u'测试题目个数')\n\n def get_all_questions(self):\n return self.questions\n\n\n# 问题解析视频,一个问题对应一个或多个解析视频,有些视频分成多段讲解\nclass ExamVideo(models.Model):\n name = models.CharField(max_length=100, verbose_name=u'视频名')\n url = models.URLField(max_length=200, verbose_name=u'访问地址', default='www.baidu.com')\n add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')\n price = models.FloatField(default=0, verbose_name=u'价格')\n author = models.ForeignKey(Teacher, verbose_name=u\"录制视频教师\")\n\n def __unicode__(self):\n return self.name\n\n\n# 测试的试题\nclass ExamQuestion(models.Model):\n exam = models.ForeignKey(Exam, verbose_name=u'测试')\n question = models.CharField(max_length=600)\n option1 = models.CharField(max_length=100)\n option2 = models.CharField(max_length=100)\n option3 = models.CharField(max_length=100)\n option4 = models.CharField(max_length=100)\n degree = models.FloatField(verbose_name=u'问题难度')\n score = models.PositiveIntegerField(verbose_name=u'问题分数')\n time = models.PositiveIntegerField(verbose_name=u'所用时间')\n add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')\n\n\n# 测试试题关联的知识点\nclass ExamPoint(models.Model):\n exam_question = models.ForeignKey(ExamQuestion, verbose_name=u'测试试题')\n knowledge_point = models.ForeignKey(KnowledgePoint, verbose_name=u'知识点')\n add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')\n\n\n# 测试试题关联的题型\nclass ExamTopic(models.Model):\n exam_question = models.ForeignKey(ExamQuestion, verbose_name=u'测试试题')\n knowledge_topic = models.ForeignKey(KnowledgeTopic, verbose_name=u'题型')\n add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')\n\n\n# 测试试题答案\nclass ExamAnswer(models.Model):\n course_question = models.ForeignKey(ExamQuestion, verbose_name=u'问题')\n add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')\n\n\n# 答案的每个点\nclass AnswerSheet(models.Model):\n answer = models.ForeignKey(ExamAnswer, verbose_name=u'答案')\n desc = models.TextField(verbose_name=u'答案描述')\n score = models.PositiveIntegerField(verbose_name=u\"分数\")\n knowledge_point = models.OneToOneField(KnowledgePoint, verbose_name=u'知识点')\n knowledge_topic = models.OneToOneField(KnowledgeTopic, verbose_name=u'题型')\n\n\nclass AnswerSheetDepedency(models.Model):\n source = models.ForeignKey(AnswerSheet, verbose_name=u'源知识点')\n target = models.ForeignKey(AnswerSheet, verbose_name=u'目标知识点')\n\n\n\n","sub_path":"jianda/oldapp/exam/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82078361","text":"import numpy as np\n\nA = np.array([[0.5377, -0.8622],\n [1.8339, 0.3188],\n [-2.2588, 1.3077]], np.float64)\n\nb_trans = np.array([-0.4336, 0.3426, 0.5163], np.float64)\nb = np.transpose(b_trans)\n\na = 0.01\nx_0 = np.transpose(np.array([0, 0]))\n\n\ndef main():\n x_1 = x_k_plus_one(x_0)\n x_2 = x_k_plus_one(x_1)\n x_3 = x_k_plus_one(x_2)\n\n print(\"x_1: \", x_1)\n print(\"x_2: \", x_2)\n print(\"x_3: \", x_3)\n\ndef x_k_plus_one(x_k):\n return P_x(x_k - a * grad_f(x_k))\n\ndef grad_f(x_k):\n C = np.matmul(A, x_k) - b\n return np.matmul(2*np.transpose(A), np.transpose(C))\n\ndef P_x(v):\n for j, i in enumerate(v):\n if i >= 0:\n continue\n else:\n v[j] = 0\n return v\n\nif __name__ == \"__main__\":\n main()","sub_path":"PGD.py","file_name":"PGD.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24022171","text":"import json\nimport re\nimport csv\nfrom datetime import datetime\nfrom neatrader.model import Security, Quote, Option, OptionChain\n\n\nclass EtradeImporter:\n def from_json(self, file_name):\n with open(file_name, 'r') as f:\n chain_json = json.load(f)\n security = Security(chain_json['quote']['symbol'])\n match = re.match(r\"\\d+:\\d+:\\d+ E.T (\\d+-\\d+-\\d+)\", chain_json['quote']['dateTime'])\n date = datetime.strptime(match.group(1), '%m-%d-%Y')\n quote = self._parse_quote(date, chain_json['quote'])\n security.add_quote(quote)\n del chain_json['quote']\n return self._parse_option_chain(security, date, chain_json)\n\n def _parse_quote(self, date, json):\n return Quote(json['lastTrade'], date)\n\n def _parse_option_chain(self, security, date, json):\n chain = OptionChain(security, date)\n for exp_dt, options in json.items():\n for option in options:\n chain.add_option(self._parse_option(security, exp_dt, option))\n return chain\n\n def _parse_option(self, security, exp_dt, json):\n type = json['optionType'].lower()\n strike = json['strikePrice']\n expiration = datetime.strptime(exp_dt, '%Y-%m-%d')\n option = Option(type, security, strike, expiration)\n option.delta = json['OptionGreeks']['delta']\n option.theta = json['OptionGreeks']['theta']\n option.vega = json['OptionGreeks']['vega']\n option.iv = json['OptionGreeks']['iv']\n option.price = json['lastPrice']\n return option\n\n\nclass CsvImporter:\n def chains(self, file_name):\n with open(file_name, 'r') as f:\n symbol = re.match(r'chains_(\\w+).csv', 'chains_TSLA.csv').group(1)\n security = Security(symbol)\n for row in csv.reader(f):\n date = datetime.strptime(row[0], '%y%m%d')\n quote = row[1]\n security.add_quote(Quote(quote, date))\n chain = self._parse_chain(date, security, row[2:])\n yield chain\n\n def _parse_chain(self, date, security, contracts):\n chain = OptionChain(security, date)\n for contract in contracts:\n fields = contract.split(' ')\n match = re.match(r'(\\d+)(c|p)(\\d+\\.\\d*)', fields[0])\n expiration = datetime.strptime(match[1], '%y%m%d')\n direction = 'call' if match[2] == 'c' else 'put'\n strike = float(match[3])\n price = float(fields[1])\n delta = float(fields[2])\n theta = float(fields[3])\n option = Option(direction, security, strike, expiration)\n option.price = price\n option.delta = delta\n option.theta = theta\n chain.add_option(option)\n return chain\n","sub_path":"neatrader/preprocess/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616614726","text":"from tastypie.resources import ModelResource,\\\n ALL, ALL_WITH_RELATIONS\nfrom tastypie import fields\nfrom app.models import Campaign, PhoneBook, ContactsList\nfrom tastypie.authorization import Authorization\n\nclass PhoneBookResource(ModelResource):\n class Meta:\n queryset = PhoneBook.objects.all()\n resource_name = 'phonebook'\n allowed_methods = ['get','post','put','delete','patch']\n detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']\n filtering = {\n 'id': ALL\n }\n\nclass CampaignResource(ModelResource):\n phonebook_choice = fields.ForeignKey(PhoneBookResource, 'phonebook_choice', full=True)\n class Meta:\n queryset = Campaign.objects.all()\n resource_name = 'campaign'\n allowed_methods = ['get','post','put','delete','patch']\n detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']\n authorization = Authorization()\n filtering = {\n 'phonebook_choice': ALL_WITH_RELATIONS,\n 'id': ALL,\n }\n\nclass ContactsListResource(ModelResource):\n phonebook = fields.ForeignKey(PhoneBookResource, 'phonebook')\n class Meta:\n queryset = ContactsList.objects.all()\n resource_name = 'contactslist'\n allowed_methods = ['get','post','put','delete','patch']\n detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']\n filtering = {\n 'phonebook': ALL_WITH_RELATIONS\n }","sub_path":"app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408680307","text":"import logging\nimport time\nfrom pydispatch import dispatcher\nimport random\nimport os\nimport binascii\nimport copy\nimport threading\nfrom threading import Timer\nfrom config import system_config\n\n\nACCOUNT_DELTA = 5\n\ndef new_hash():\n return binascii.hexlify(os.urandom(4)).decode('utf-8')\n\n# Account state record\nclass Account():\n def __init__(self, yes_dep, no_deps, balance):\n # This state is conditional on this dependency being CORRECT\n self.yes_dep = yes_dep\n # This state is conditional on these dependencies being INCORRECT\n self.no_deps = no_deps\n # Account balance\n self.balance = balance\n self.root_balance = balance\n\n def __repr__(self):\n return \"[yes_dep: %r, no_deps: %r, balance: %d]\" % (self.yes_dep, self.no_deps, self.balance)\n\n\nclass Transaction():\n def __init__(self, sender, receiver, balance):\n self.sender = sender\n self.receiver = receiver\n self.balance = balance\n def __repr__(self):\n return \"[sender: %r, receiver: %r, balance: %d]\" % (self.sender, self.receiver, self.balance)\n\n\nclass Block():\n def __init__(self, slot, root, transactions, state):\n self.slot = slot\n self.root = root\n self.transactions = transactions\n self.state = state\n\n\n# Global state\nclass State():\n def __init__(self):\n self.state = []\n\n def greedy_genesis_state(self):\n genesis_account = Account(None, [], 10000000)\n self.state.append(genesis_account)\n return self.state\n\n def generate_random_transactions(self):\n # need to decouple state transition function out of the state object... hacky for now\n transactions = []\n accounts_length = len(self.state)\n account_set = accounts_length + ACCOUNT_DELTA\n self.state = self.state + ([None] * ACCOUNT_DELTA)\n\n for i in range(ACCOUNT_DELTA):\n sender_idx = random.randint(0, accounts_length - 1)\n receiver_idx = random.randint(0, account_set - 1)\n if sender_idx != receiver_idx:\n sender = self.state[sender_idx]\n\n if not sender:\n continue\n\n transaction_amount = random.randint(1, sender.balance)\n transaction = Transaction(sender_idx, receiver_idx, transaction_amount)\n receiver = self.state[receiver_idx] or Account(None, [], 0) \n sender.balance -= transaction_amount\n receiver.balance += transaction_amount\n self.state[receiver_idx] = receiver\n transactions.append(transaction)\n return transactions\n\nclass Shard():\n def __init__(self, name):\n self.blocks = []\n self.state = State()\n self.name = name\n\n def run(self):\n # Initiate with genesis account\n self.state.greedy_genesis_state()\n\n # Listens for a broadcast from the beacon chain that it is the shard's turn to write its crosslink\n dispatcher.connect(self.submit_to_beacon, signal=f\"BEACON_TO_SHARD_{self.name}\")\n\n while True:\n transactions = self.state.generate_random_transactions()\n\n # deep copy state so history is kept (vs. mutating state array)\n block = Block(len(self.blocks) - 1, new_hash(), transactions, copy.deepcopy(self.state.state))\n self.blocks.append(block)\n\n # notify visualizer and prediction market that a block has been submitted\n dispatcher.send(signal=f\"SHARD_{self.name}\", message=block)\n logging.info(f\"dispatched {block}\")\n\n # wait slot period\n time.sleep(system_config[\"SHARD_SLOT_TIME\"])\n\n def submit_to_beacon(self):\n logging.info(f\"shard {self.name} dispatching to beacon chain\")\n block_roots = [block.root for block in self.blocks]\n dispatcher.send(signal=f\"SHARD_TO_BEACON_{self.name}\", blocks=block_roots, shard=self.name)\n","sub_path":"shard.py","file_name":"shard.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398707039","text":"import requests\nimport datetime\nimport pytz\nimport collections\nimport tqdm\n\n\ndef load_attempts():\n url = 'https://devman.org/api/challenges/solution_attempts/'\n page = 1\n while True:\n response = requests.get(url=url.format(page), params={'page': page}).json()\n yield response['records']\n number_of_pages = response['number_of_pages']\n page += 1\n if page > int(number_of_pages):\n break\n\n\ndef convert_data(data_list):\n converted_list = []\n for element in data_list:\n if not element['timestamp']:\n continue\n time = datetime.datetime.fromtimestamp(element['timestamp'], pytz.timezone(element['timezone']))\n converted_list.append((element['username'], time))\n return converted_list\n\n\ndef get_owls(data_list):\n return collections.Counter([user for user, time in data_list if 0 <= time.hour < 5])\n\n\ndef print_owls(users_counter):\n print('Following users send their solutions after midnight:')\n print('\\n'.join(['\"{}\" {} times'.format(name, count)\n for name, count in sorted(users_counter.items(), key=lambda x: x[1], reverse=True)]))\n\nif __name__ == '__main__':\n api_data = []\n [api_data.extend(x) for x in tqdm.tqdm(load_attempts(), desc='collecting data')]\n data_with_time = convert_data(api_data)\n owls = get_owls(data_with_time)\n print_owls(owls)\n","sub_path":"seek_dev_nighters.py","file_name":"seek_dev_nighters.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"352094802","text":" \n \nclass perf_parser(object):\n \n def __init__(self, from_log_name):\n self.f_log_name = from_log_name\n #t_log = to_log \n \n def parse_log(self):\n\n all_stats = ['approx. 95 percentile', 'total number of events', 'avg', 'read', 'write', 'other', 'transactions', 'deadlocks', 'total time',\n 'total', 'min', 'other operations', 'Number of threads', 'max', 'events (avg/stddev)', 'read/write requests', 'execution time (avg/stddev)']\n parse_per_sec = ['other operations', 'transactions', 'deadlocks', 'read/write requests']\n parse_avg_stddev = ['execution time (avg/stddev)', 'events (avg/stddev)']\n \n #csv = True\n f = open(self.f_log_name, 'r')\n d = {}\n stats_dict = {}\n for line in f:\n l = line.rstrip(\"\\n\")\n #l = line.split(\"run_command\")\n # if len(l) > 1:\n # l = l.pop(1)\n l = str(l)\n l = l.split(\":\")\n if len(l) == 2:\n d[l[0].strip()] = l[1].strip()\n #Iterate through all of the items\n for k, v in d.iteritems():\n if k in all_stats:\n v = v.rstrip('ms')\n #Iterate through the Per Second Data\n if k in parse_per_sec:\n pri = self.get_pri_cnt(v)\n per_sec = self.get_per_sec(v)\n stats_dict[k] = pri\n #to_log.log(k + \",\" + pri, csv = True)\n stats_dict[k + \" per sec\"] = per_sec\n #to_log.log(k + \" per sec,\" + per_sec, csv)\n #Iterate through the Avg StdDev data\n if k in parse_avg_stddev:\n avg = self.parse_avg_stddev(v, 'avg')\n stddev = self.parse_avg_stddev(v, 'stddev')\n title = self.parse_avg_stddev_name(k)\n stats_dict[title.strip() + \" avg\"] = avg\n #to_log.log(title.strip() + \" avg,\" + avg, csv)\n stats_dict[title.strip() + \" stddev\"] = stddev\n #to_log.log(title.strip() + \" stddev,\" + stddev, csv)\n #Handle anything that is left\n if (k not in parse_avg_stddev) and (k not in parse_per_sec):\n stats_dict[k] = v\n #to_log.log(k + \",\" + v, csv)\n #print stats_dict\n return stats_dict\n \n def get_per_sec(self, field):\n fl = field.split(\"(\")\n fl = fl[1]\n fl = fl.split(\" \")\n fl = fl[0]\n return fl\n \n def get_pri_cnt(self, field):\n fl = field.split(\"(\")\n fl = fl[0].strip()\n return fl\n \n def parse_avg_stddev(self, field, type):\n #print field\n if type == 'avg':\n i = 0\n elif type == 'stddev':\n i = 1\n fl = field.split(\"/\")\n return fl[i] \n \n def parse_avg_stddev_name(self, field):\n fl = field.split(\"(\")\n return fl[0]\n\n","sub_path":"test_repo/database/perf/perf_parser.py","file_name":"perf_parser.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356181030","text":"import turtle\r\nimport math\r\n\r\n\r\n## GUI INTERFACE\r\n\r\nwn = turtle.Screen()\r\nwn.bgcolor(\"black\")\r\nwn.title(\"Project J\")\r\n\r\n## TURTLE TED\r\n\r\nted = turtle.Turtle()\r\nted.color('darkgrey')\r\nted.pensize(0)\r\n\r\ntess = turtle.Turtle()\r\ntess.color('black')\r\ntess.pensize(0)\r\n\r\ntom = turtle.Turtle()\r\ntom.color('black')\r\ntom.pensize(0)\r\n\r\n\r\n#Screen Facts\r\n\r\n'''\r\nResolution = 795,945\r\nTop right corner = 470,400\r\nTop left corner = -475,400\r\nBot right corner = 470,-395\r\nBot left corner = -475,-395\r\n\r\n'''\r\n\r\n#Variable\r\n\r\nstate_num = 0\r\n\r\n#Functions\r\n\r\ndef draw_housing(Turtle):\r\n ''' Draw a nice housing that holds the traffic light'''\r\n Turtle.pensize(3)\r\n Turtle.color(\"black\", \"darkgrey\")\r\n Turtle.begin_fill()\r\n Turtle.forward(80)\r\n Turtle.left(90)\r\n Turtle.forward(200)\r\n Turtle.circle(40, 180)\r\n Turtle.forward(200)\r\n Turtle.left(90)\r\n Turtle.end_fill()\r\n\r\ndef Greenlight(Turtle):\r\n Turtle.pu()\r\n Turtle.shape(\"circle\")\r\n Turtle.shapesize(3)\r\n Turtle.fillcolor('darkgreen')\r\n Turtle.fd(40)\r\n Turtle.lt(90)\r\n Turtle.fd(40)\r\n \r\n \r\ndef Orangelight(Turtle):\r\n Turtle.pu()\r\n Turtle.shape(\"circle\")\r\n Turtle.shapesize(3)\r\n Turtle.fillcolor('darkorange')\r\n Turtle.fd(40)\r\n Turtle.lt(90)\r\n Turtle.fd(115)\r\n \r\n\r\ndef Redlight(Turtle):\r\n Turtle.pu()\r\n Turtle.shape(\"circle\")\r\n Turtle.shapesize(3)\r\n Turtle.fillcolor('brown')\r\n Turtle.fd(40)\r\n Turtle.lt(90)\r\n Turtle.fd(190)\r\n \r\n\r\n#Execution\r\n\r\ndraw_housing(ted)\r\n\r\nGreenlight(ted)\r\n\r\nOrangelight(tess)\r\n\r\nRedlight(tom)\r\n\r\n#Notes\r\n'''\r\nted = Green\r\n\r\ntess = Orange\r\n\r\ntom = Red\r\n\r\n'''\r\n## ETC.\r\nwn.ontimer(ted.color('lightgreen'), 3000)\r\nwn.ontimer(ted.color('darkgreen'), 2000)\r\n\r\nwn.ontimer(tess.color('yellow'), 1500)\r\nwn.ontimer(tess.color('darkorange'), 500)\r\n\r\nwn.ontimer(tom.color('red'), 1500)\r\nwn.ontimer(tom.color('darkred'), 500)\r\n\r\nwn.mainloop()\r\n","sub_path":"Hw_Ch10_#4.py","file_name":"Hw_Ch10_#4.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610822198","text":"from cloud_inquisitor.config import dbconfig\nfrom cloud_inquisitor.constants import NS_CINQ_TEST\nfrom tests.libs.util_cinq import aws_get_client, collect_resources\nfrom tests.libs.var_const import CINQ_TEST_ACCOUNT_NAME, CINQ_TEST_ACCOUNT_NO\n\n\ndef test_collect(cinq_test_service):\n \"\"\"\n\n :return:\n \"\"\"\n\n # Prep\n cinq_test_service.start_mocking_services('ec2')\n account = cinq_test_service.add_test_account(\n account_type='AWS',\n account_name=CINQ_TEST_ACCOUNT_NAME,\n contacts=[{'type': 'email', 'value': dbconfig.get('test_email', NS_CINQ_TEST)}],\n properties={\n 'account_number': CINQ_TEST_ACCOUNT_NO\n }\n )\n\n # Add resources\n client = aws_get_client('ec2')\n resource = client.run_instances(ImageId='i-10000', MinCount=1, MaxCount=1)\n\n # Start collector\n collect_resources(account=account, resource_types=['ec2'])\n\n # verify\n assert cinq_test_service.has_resource('non-exist-id') is False\n assert cinq_test_service.has_resource(resource['Instances'][0]['InstanceId']) is True\n","sub_path":"backend/tests/test_cinq-collector-aws.py","file_name":"test_cinq-collector-aws.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228110049","text":"from __future__ import print_function\nfrom fuzzywuzzy import fuzz\nfrom nltk.metrics import *\n\nimport time\n\n\ndef get_matches(list1, list2):\n return [x for x in list1 if x in list2]\n\n\ndef get_fuzzy_match(list1, list2, treshold):\n\n matches = []\n\n for i1 in list1:\n for i2 in list2:\n ratio = fuzz.ratio(i1, i2)\n #ratio = fuzz.partial_ratio(i1, i2)\n #ratio = fuzz.token_sort_ratio(i1, i2)\n #ratio = fuzz.token_set_ratio(i1, i2)\n #ratio = edit_distance(i1, i2)\n if ratio >= treshold:\n matches.append([i1, i2, ratio])\n\n return matches\n\n\ndef write_list_to_file(filename, list):\n f = open(filename, \"w\")\n\n for item in list:\n f.write(\"{}\\n\".format(item))\n\n\n\nif __name__ == \"__main__\":\n \n # officers.txt, downloaded and formatted from Officers.csv @\n organizations = list(open(\"panama/entities.txt\", \"r\", encoding=\"utf-8\"))\n\n\n # canada_suppliers.txt, downloaded and formatted from: fiscel-2016.csv @ http://open.canada.ca/data/en/dataset/53753f06-8b28-42d7-89f7-04cd014323b0\n contractors = list(open(\"canada/canada_suppliers.txt\", \"r\", encoding=\"utf-8\"))\n\n # Start timer for timing the matching function\n time0 = time.time()\n\n # Matchem and catchem. Remove \"[:100]'s\" to use full lists.\n matches = get_fuzzy_match(contractors[:100], organizations[:100], 0)\n\n # Stop timer for timing the matching function\n time1 = time.time()\n\n # test1 = [\"Lorem ipsum\", \"Lörem aspum\", \"IPSUM LOREM\", \"lo rem ip sum\", \"Iprem losum\"];\n # test2 = [\"Lorem ipsum\"]\n #\n #\n # matches = get_fuzzy_match(test1, test2, 75)\n\n write_list_to_file(\"matches.txt\", matches)\n\n print(time1 - time0)\n","sub_path":"catchem2.py","file_name":"catchem2.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476991930","text":"#!/usr/bin/python3\n\nimport time, subprocess, json, random, os, signal, sys, importlib, importlib.util, os.path\n\nscriptPath = os.path.dirname(os.path.realpath(__file__))\nparentPath = os.path.abspath(os.path.join(scriptPath, os.pardir))\npidPath = os.path.join(parentPath, 'off-timer/')\n\nconfigPath = os.path.join(parentPath, 'config.json')\n\nconfig = open(configPath).read()\nconfig = json.loads(config)\nlightsDict = config['lights']\ncolorDict = config['colors']\n\nlights = {}\n\ndef module_from_file(module_name, file_path):\n spec = importlib.util.spec_from_file_location(module_name, file_path)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n return module\n\nfor group in lightsDict:\n lightGroup = []\n for light in lightsDict[group]:\n \n module = module_from_file(light['brand'], os.path.join(parentPath, os.path.join('devices', light['brand'] + '.py')))\n if light['multizone']:\n lightGroup.append(module.Bulb(light['ip'], light['mac'], multizone=True))\n else:\n lightGroup.append(module.Bulb(light['ip'], light['mac']))\n lights[group] = lightGroup\n\ngroup = lights[(sys.argv[1].lower())]\nseconds = int(sys.argv[2])\n\npidFile = open(os.path.join(pidPath, sys.argv[1].lower() + '.pid'), 'w')\npid = os.getpid()\npidFile.write(str(pid))\npidFile.close()\n\nfor light in group:\n color = list(light.get_color())\n color[2] = 0 # lower to brightness=0\n light.set_color(color, duration=(seconds * 1000))\n\ntime.sleep(seconds + (seconds / 20)) # add that bit of time just to be safe\n\nif os.path.exists(os.path.join(pidPath, sys.argv[1].lower() + '.pid')):\n pidFile = open(os.path.join(pidPath, sys.argv[1].lower() + '.pid'))\n if pidFile.read() == str(os.getpid()):\n for light in group:\n light.set_power(False)\n\n os.remove(os.path.join(pidPath, sys.argv[1].lower() + '.pid'))\n\ntime.sleep(20) # juuust in case\nsys.exit()\n","sub_path":"off-timer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338254555","text":"\"\"\"\nunit tests for naive_bayes_structure_comparison.py\n\"\"\"\nimport unittest\n\nimport NaiveBayesStructure as NBS\nimport naive_bayes_structure_comparison as compare\n\n\nDEFAULT_VALUE = 0.6740331491712708\n\n\nclass TestComparison(unittest.TestCase):\n all_file = 'data/all.csv'\n\n @classmethod\n def setUpClass(cls):\n cls.all_struct = NBS.NaiveBayesStructure(cls.all_file)\n\n def test_compare_structure_base(self):\n \"\"\"\n The base comparison with the original testing and training data\n \"\"\"\n test = self.all_struct.contents[0:543]\n train = self.all_struct.contents[543:]\n test, train = compare.compare_structure(test, train)\n val = compare.predict_accuracy(test, train)\n\n self.assertEqual(val, DEFAULT_VALUE)\n","sub_path":"tests/test_naive_bayes_structure_comparison.py","file_name":"test_naive_bayes_structure_comparison.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579525830","text":"#!/usr/bin/env python3\n\"\"\"\nLoad a list of lat/lons from a CSV file and reverse-geocode them to GSP / GNode.\n\n- Jamie Taylor \n- Ethan Jones \n- First Authored: 2020-05-29\n\"\"\"\n\nimport sys\nimport argparse\nimport time as TIME\nfrom pathlib import Path\n\nimport pandas as pd\n\nfrom geocode import Geocoder\nfrom utilities import query_yes_no, GenericException\n\ndef parse_options():\n \"\"\"Parse command line options.\"\"\"\n parser = argparse.ArgumentParser(description=(\"This is a command line interface (CLI) for \"\n \"the latlons2gsp.py module\"),\n epilog=\"Jamie Taylor & Ethan Jones, 2020-05-29\")\n parser.add_argument(\"-f\", \"--input-file\", dest=\"infile\", action=\"store\", type=Path,\n required=True, metavar=\"\",\n help=\"Specify a CSV file containing a list of latitudes and longitudes to \"\n \"be reverse-geocoded. The file must contain the columns 'latitude' \"\n \"and 'longitude' (it can contain others, all of which will be kept).\")\n parser.add_argument(\"-o\", \"--output-file\", dest=\"outfile\", action=\"store\", type=Path,\n required=True, metavar=\"\", help=\"Specify an output file.\")\n options = parser.parse_args()\n if not options.infile.is_file():\n raise GenericException(f\"The input file '{options.infile}' does not exist.\")\n if options.outfile.is_file():\n check = query_yes_no(f\"The outfile '{options.outfile}' already exists, are you sure you \"\n \"wish to overwrite?\", \"no\")\n if not check:\n print(\"Quitting...\")\n sys.exit(0)\n return options\n\ndef main():\n timerstart = TIME.time()\n options = parse_options()\n with open(options.infile, \"r\") as fid:\n df = pd.read_csv(fid)\n with Geocoder() as geo:\n results_ = geo.reverse_geocode_gsp(df[[\"latitude\", \"longitude\"]].to_numpy())\n results_ = [(None, None) if gsp_pair is None else gsp_pair for gsp_pair in results_]\n gsps, gsp_groups = [x[0] for x in results_], [x[1] for x in results_]\n output = pd.DataFrame({'gsp': gsps, 'gsp_group': gsp_groups})\n output.to_csv(options.outfile, index=False)\n print(f\"Finished, time taken: {TIME.time() - timerstart:.1f} seconds\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"geocode/latlons2gsp.py","file_name":"latlons2gsp.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"150797397","text":"from unittest import TestCase\nfrom unittest.mock import patch\nimport tempfile\nfrom pathlib import Path\n\n\nfrom lineflow.download import get_cache_directory\nfrom lineflow.datasets import CnnDailymail\nfrom lineflow.datasets.cnn_dailymail import CNN_DAILYMAIL_URL\nfrom lineflow.datasets.cnn_dailymail import TRAIN_SOURCE_NAME, TRAIN_TARGET_NAME\nfrom lineflow.datasets.cnn_dailymail import VAL_SOURCE_NAME, VAL_TARGET_NAME\nfrom lineflow.datasets.cnn_dailymail import TEST_SOURCE_NAME, TEST_TARGET_NAME\n\n\nclass CnnDailymailTestCase(TestCase):\n\n def setUp(self):\n cache_fp = tempfile.NamedTemporaryFile()\n self.cache_fp = cache_fp\n\n cached_download_patcher = patch('lineflow.datasets.cnn_dailymail.cached_download')\n cached_download_mock = cached_download_patcher.start()\n cached_download_mock.side_effect = lambda url: cache_fp.name\n self.cached_download_patcher = cached_download_patcher\n self.cached_download_mock = cached_download_mock\n\n tarfile_patcher = patch('lineflow.datasets.cnn_dailymail.tarfile')\n tarfile_mock = tarfile_patcher.start()\n self.tarfile_patcher = tarfile_patcher\n self.tarfile_mock = tarfile_mock\n\n exists_patcher = patch('lineflow.datasets.cnn_dailymail.Path.exists')\n exists_mock = exists_patcher.start()\n exists_mock.return_value = True\n self.exists_patcher = exists_patcher\n self.exists_mock = exists_mock\n\n init_patcher = patch('lineflow.datasets.seq2seq.Seq2SeqDataset.__init__')\n init_mock = init_patcher.start()\n self.init_patcher = init_patcher\n self.init_mock = init_mock\n\n self.cache_dir = Path(get_cache_directory('cnndm'))\n\n def tearDown(self):\n self.cache_fp.close()\n self.cached_download_patcher.stop()\n self.tarfile_patcher.stop()\n self.exists_patcher.stop()\n self.init_patcher.stop()\n\n def test_returns_train_set(self):\n CnnDailymail(split='train')\n self.cached_download_mock.assert_called_once_with(CNN_DAILYMAIL_URL)\n self.init_mock.assert_called_once_with(\n source_file_path=str(self.cache_dir / TRAIN_SOURCE_NAME),\n target_file_path=str(self.cache_dir / TRAIN_TARGET_NAME))\n\n def test_returns_dev_set(self):\n CnnDailymail(split='dev')\n self.cached_download_mock.assert_called_once_with(CNN_DAILYMAIL_URL)\n self.init_mock.assert_called_once_with(\n source_file_path=str(self.cache_dir / VAL_SOURCE_NAME),\n target_file_path=str(self.cache_dir / VAL_TARGET_NAME))\n\n def test_returns_test_set(self):\n CnnDailymail(split='test')\n self.cached_download_mock.assert_called_once_with(CNN_DAILYMAIL_URL)\n self.init_mock.assert_called_once_with(\n source_file_path=str(self.cache_dir / TEST_SOURCE_NAME),\n target_file_path=str(self.cache_dir / TEST_TARGET_NAME))\n\n def test_raises_value_error_with_invalid_split(self):\n with self.assertRaises(ValueError):\n CnnDailymail(split='invalid_split')\n\n def test_expands_tarfile(self):\n self.exists_mock.return_value = False\n CnnDailymail(split='train')\n self.tarfile_mock.open.return_value.extractall.assert_called_once_with(self.cache_dir)\n","sub_path":"tests/datasets/test_cnn_dailymail.py","file_name":"test_cnn_dailymail.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"593486038","text":"#!/usr/bin/env python3\n# based on https://github.com/haraldh/iconsole from Harald Hoyer\n# SPDX-License-Identifier: MIT\nfrom binascii import hexlify\nimport logging\n\nfrom packets import *\n\nlogger = logging.getLogger(\"iconsole\")\n\ndef send_recv(sock, packet, expect=None, plen=0):\n packet = bytes(packet) + bytes([sum(packet) & 0xff]) # add checksum\n if expect == None:\n # if no expected response byte, expect it to be 0xbX where the request is 0xaX\n expect = 0xb0 | (packet[1] & 0xF)\n\n if plen == 0:\n # if no expected length, expect response to be the same length as request\n # (with checksum added)\n plen = len(packet)\n\n while True:\n sock.sendall(packet)\n got = b''\n while len(got) < plen:\n ret = sock.recv(plen - len(got), 1.0)\n if not ret:\n break\n got += ret\n\n if len(got) == plen and got[0] == packet[0] and got[1] == expect:\n # check and remove checksum\n if (sum(got[0:-1]) & 0xff) == got[-1]:\n return got[0:-1]\n logger.error(\"Checksum error\")\n elif len(got) < plen:\n logger.error(\"Timed out\")\n else:\n logger.error(\"Unexpected response %s\" % hexlify(got))\n\n logger.info(\"Retransmit\")\n\ndef send_level(sock, lvl):\n packet = bytearray(SET_LEVEL)\n packet[-1] = lvl + 1\n got = send_recv(sock, packet)\n return got\n\ndef init(sock):\n got = send_recv(sock, PING)\n logger.debug(\"ping done %s\" % (hexlify(got).decode()))\n\n got = send_recv(sock, INIT_A0, expect=0xb7, plen=6)\n logger.debug(\"A0 done %s\" % (hexlify(got).decode()))\n\n got = send_recv(sock, STATUS, plen=6)\n logger.debug(\"status done %s\" % (hexlify(got).decode()))\n\n got = send_recv(sock, INIT_A3)\n logger.debug(\"A3 done %s\" % (hexlify(got).decode()))\n\n got = send_recv(sock, INIT_A4)\n logger.debug(\"A4 done %s\" % (hexlify(got).decode()))\n\n got = send_recv(sock, START)\n logger.debug(\"START done %s\" % (hexlify(got).decode()))\n","sub_path":"iconsole.py","file_name":"iconsole.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"66465316","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n if head is None:\n return head\n\n cur = head\n while cur:\n while cur.next and cur.val == cur.next.val:\n cur.next = cur.next.next\n cur = cur.next\n\n return head\n\n\nif __name__ == '__main__':\n head = ListNode(1)\n head.next = ListNode(1)\n head.next.next = ListNode(2)\n head.next.next.next = ListNode(3)\n head.next.next.next.next = ListNode(3)\n\n res = Solution().deleteDuplicates(head)\n\n while res:\n print(res.val)\n res = res.next\n","sub_path":"Leetcode Python/83. Remove Duplicates from Sorted List.py","file_name":"83. Remove Duplicates from Sorted List.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23701484","text":"# -*- coding: utf-8 -*-\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\n\nfrom ..items import SunsiteItem\n\n\nclass SunSpider(CrawlSpider):\n name = 'sun'\n start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']\n link = LinkExtractor(allow=r'question/\\d+/\\d+.shtml')\n rules = (\n Rule(LinkExtractor(allow=r'type=4&page=\\d+'), callback='parse_item', follow=True),\n Rule(link, callback='parse_detail'),\n )\n\n def parse_item(self, response):\n item = {}\n tr_list = response.xpath('//*[@id=\"morelist\"]/div/table[2]//tr/td/table//tr')\n for tr in tr_list:\n title = tr.xpath('./td[2]/a[2]/@title').extract_first()\n url = tr.xpath('./td[2]/a[2]/@href').extract_first()\n # print(title, url)\n yield item\n\n def parse_detail(self, response):\n num = response.xpath('/html/body/div[9]/table[1]//tr/td[2]/span[2]/text()').extract_first()\n title = response.xpath('/html/body/div[9]/table[1]//tr/td[2]/span[1]/text()').extract_first()\n print(num)\n item = SunsiteItem()\n item['num'] = num\n item['title'] = title\n yield item\n","sub_path":"108 scrapy-last/sunSite/sunSite/spiders/sun.py","file_name":"sun.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625398456","text":"from nltk.tokenize import RegexpTokenizer\nfrom nltk.util import ngrams\nfrom collections import Counter\nimport requests\nfrom lxml.html.clean import Cleaner\nfrom bs4 import BeautifulSoup\n\ndef grab_words(url):\n cleaner = Cleaner()\n cleaner.javascript = True\n cleaner.style = True\n r = requests.get(url)\n cleaned_html = cleaner.clean_html(r.text)\n soup = BeautifulSoup(cleaned_html,'html.parser')\n body_text = soup.find('body').get_text()\n return body_text\n\n\ndef words_keywords(text):\n tokenizer = RegexpTokenizer(r'\\w+')\n tokens = tokenizer.tokenize(text)\n word_count = len(tokens)\n bigrams = ngrams(tokens,2)\n trigrams = ngrams(tokens,3)\n bi_list = []\n tri_list = []\n for item in bigrams:\n item = ' '.join(item)\n bi_list.append(item)\n for item in trigrams:\n item = ' '.join(item)\n tri_list.append(item)\n return word_count, bi_list, tri_list\n\ndef keyword_density(word_count, bi_list, tri_list, min_density):\n matches = []\n two_word_occurences = Counter(bi_list).most_common(5)\n #print(two_word_occurences)\n three_word_occurences = Counter(tri_list).most_common(5)\n #print(three_word_occurences)\n #print(word_count)\n for i in two_word_occurences:\n number_occ = i[1]\n if (number_occ / word_count) > min_density:\n percentage_score = (number_occ / word_count)\n keyword = i[0]\n d = [keyword, percentage_score]\n matches.append(d)\n for i in three_word_occurences:\n number_occ = i[1]\n if (number_occ / word_count) > min_density:\n percentage_score = (number_occ / word_count)\n keyword = i[0]\n d = [keyword, percentage_score]\n matches.append(d)\n return matches\n","sub_path":"keyword_desnity.py","file_name":"keyword_desnity.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567946537","text":"def quickSort(s):\n number = s[0]\n if len(s)<=1:\n return s\n else:\n less = [x for x in s if xnumber]\n equal = [x for x in s if x==number]\n return (quickSort(less) + equal + quickSort(greater))\n\nn=int(input())\ns=list(map(int,input().split()))\ns = quickSort(s)\n\nprint([x for x in s if x%2==0])\n\n","sub_path":"venv/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87580096","text":"from model.group import Group\nfrom data.add_group import testdata\nimport pytest\n\n\n@pytest.mark.parametrize(\"group\", testdata, ids=[str(x) for x in testdata])\ndef test_add_group(app, group):\n old_groups = app.group.get_group_list()\n app.group.create(group)\n assert len(old_groups) + 1 == app.group.count()\n new_groups = app.group.get_group_list()\n old_groups.append(group)\n assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)\n","sub_path":"test/test_add_group.py","file_name":"test_add_group.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323407650","text":"# Date 19-3-2021\r\n\r\n# In this tutorial we will learn about local and global variables in python\r\n\r\nx = 1 # An example of Global Variable\r\n\"\"\"\r\ndef func1():\r\n x+=1\r\n print(x)\r\n\r\nfunc1()\r\n\"\"\"\r\n\r\n# The upper syntax will surely give you an error because value of a global variable cannot be changed in a function\r\n\r\n\r\n# To change the value of a global variable in a function use the below syntax\r\n\r\ndef func2():\r\n global x # Asking permission to change the value of x\r\n x += 1\r\n print(x, \"Is a Global Variable, but global function has asked permission from Python to change it's value \")\r\n\r\n\r\nfunc2()\r\n\r\n","sub_path":"tutorial 33.py","file_name":"tutorial 33.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112711293","text":"'''\ndeposit public class or function\ndata:2020-3-20\n@author antony weijiang\n'''\nimport can\nimport time\nimport sys\nimport os\nfrom log import logger as loger\n\nlogger = loger.Current_Module()\n# from Common import Signal_List as SL\n\n\nclass PCAN(object):\n def __enter__(self):\n return self\n\n def __init__(self):\n self.bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)\n\n def send(self, id, data):\n id = int(id, 16)\n data = list(map(lambda i: int(i), data))\n # print(id, list(data))\n msg = can.Message(arbitration_id=id, dlc=8, data=data, extended_id=False)\n try:\n self.bus.send(msg)\n logger.log_debug(\"Message sent on {0},id:{1},data:{2}\".format(self.bus.channel_info,id,data), \\\n sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,\n sys._getframe().f_lineno)\n # print(\"Message sent on {0},id:{1},data:{2}\".format(self.bus.channel_info,id,data))\n except can.CanError as e:\n logger.log_error(\"%s\" %(e), \\\n sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name,\n sys._getframe().f_lineno)\n\n def send_arry(self, arry_list=[]):\n for i in arry_list:\n self.send(i['id'], i['data'])\n time.sleep(0.2)\n\n def clean(self):\n self.bus.shutdown()\n\n\n\n\n\n","sub_path":"venv/Common/Signal_Common.py","file_name":"Signal_Common.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500359714","text":"import glob;\r\nimport codecs;\r\nimport random;\r\n\r\nfiles = glob.glob(\"*.tsv\");\r\noutputs = [];\r\n\r\nfor file in files:\r\n print(\"collecting: \" + file);\r\n with codecs.open(file, 'r', 'utf-8') as fin:\r\n for line in fin:\r\n line = line.strip();\r\n if not line:\r\n continue;\r\n array = line.split('\\t');\r\n if len(array) < 5:\r\n print(\"error:\" + line);\r\n outputs.append(line);\r\n\r\nprint('shuffling');\r\nrandom.seed(0.1);\r\nrandom.shuffle(outputs);\r\n\r\noutputs = ['\\t'.join(['id', 'query', 'intent', 'domain', 'QueryXml', 'id', '0'])] + outputs;\r\n\r\nwith codecs.open('Teams_Slot_Training.tsv', 'w', 'utf-8') as fout:\r\n for item in outputs:\r\n fout.write(item + '\\r\\n');\r\n","sub_path":"baseline_data/collect_all_features.py","file_name":"collect_all_features.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454203778","text":"# -*- coding: utf-8 -*-\nfrom PyQt4 import QtCore, QtGui, uic\nfrom PyQt4.Qt import Qt\nimport metrocss\n\nInputWindow = \"datainput.ui\"\nUi_InputWindow, QtBaseClass = uic.loadUiType(InputWindow)\n\n\nclass UserData(QtGui.QMainWindow, Ui_InputWindow):\n def __init__(self, user_data_signal, parent=None):\n \n super(UserData, self).__init__(parent)\n Ui_InputWindow.__init__(self)\n\n self.setupUi(self)\n self.setWindowModality(QtCore.Qt.WindowModal)\n self.setWindowFlags(Qt.FramelessWindowHint)\n\n self.signal=user_data_signal\n self.label1='Температура'\n self.label2='Выдержка'\n self.tempisset=0\n self.timeisset=0\n self.T=0\n self.t=0\n self.label.setText(metrocss.SetLabelText(self.label1))\n \n \n self.b1.pressed.connect(self.setData)\n self.b2.pressed.connect(self.setData)\n self.b3.pressed.connect(self.setData)\n self.b4.pressed.connect(self.setData)\n self.b5.pressed.connect(self.setData)\n self.b6.pressed.connect(self.setData)\n self.b7.pressed.connect(self.setData)\n self.b8.pressed.connect(self.setData)\n self.b9.pressed.connect(self.setData)\n self.b0.pressed.connect(self.setData)\n self.bdel.pressed.connect(self.setData)\n self.bok.pressed.connect(self.setData)\n\n self.b1.released.connect(self.Clear)\n self.b2.released.connect(self.Clear)\n self.b3.released.connect(self.Clear)\n self.b4.released.connect(self.Clear)\n self.b5.released.connect(self.Clear)\n self.b6.released.connect(self.Clear)\n self.b7.released.connect(self.Clear)\n self.b8.released.connect(self.Clear)\n self.b9.released.connect(self.Clear)\n self.b0.released.connect(self.Clear)\n self.bdel.released.connect(self.Clear)\n self.bok.released.connect(self.Clear)\n\n def setData(self):\n sender = self.sender()\n name = sender.objectName()\n if name[1] in ('1','2','3','4','5','6','7','8','9','0') :\n point=name[1]\n point=int(point)\n sender.setStyleSheet(metrocss.data_active)\n data=self.UserData.toPlainText()\n data=int(data)\n if data==0:\n data=point\n self.UserData.setHtml(metrocss.Show_Main_Temp(data))\n else:\n data=data*10+point\n if self.tempisset==0:\n if data>0 and data<211:\n self.UserData.setHtml(metrocss.Show_Main_Temp(data))\n else:\n if data>0 and data<31:\n self.UserData.setHtml(metrocss.Show_Main_Temp(data))\n\n if sender==self.bdel:\n sender.setStyleSheet(metrocss.data_active)\n data=self.UserData.toPlainText()\n data=int(data)\n if data==0:\n pass\n else:\n data=data//10\n self.UserData.setHtml(metrocss.Show_Main_Temp(data))\n\n if sender==self.bok:\n sender.setStyleSheet(metrocss.data_active)\n if self.tempisset==0:\n self.tempisset=1\n data=self.UserData.toPlainText()\n self.T=int(data)\n self.label.setText(metrocss.SetLabelText(self.label2))\n self.UserData.setHtml(metrocss.Show_Main_Temp(0)) \n else:\n self.timeisset=1\n data=self.UserData.toPlainText()\n self.t=int(data) \n \n def Clear(self):\n sender = self.sender()\n sender.setStyleSheet(metrocss.data_passive)\n if sender==self.bok and self.tempisset==1 and self.timeisset==1:\n self.signal.emit(self.T,self.t)\n self.close()\n","sub_path":"UserData.py","file_name":"UserData.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507389687","text":"__author__ = 'vaibhavsuri'\n\nimport util\nimport json\nimport getDynamoDB as db\nimport db_table_key_names as keys\nimport response_format\n\n###############################\n######## GLOBAL VARS #########\nTOP_SIZE = 5 #number of top posts to send for feed\n\n###############################\n\n#returns a list containing the top posts for a user's feed\ndef get_top_posts(post_ids):\n\ttop_posts = []\n\ttop_post_ids = post_ids[0:(TOP_SIZE+1)] #slicing the list based on TOP_SIZE\n\tfor post_id in top_post_ids:\n\t\tpost_file = db.get_post_item(post_id)\n\t\tcreator_name = db.get_user_name(post_file[keys.post_creator])\n\t\tsingle_post = response_format.get_feed_post(post_id, creator_name, post_file)\n\t\ttop_posts.append(single_post)\t\n\treturn top_posts\n\n#returns the feed for a user\ndef send_feed(user_id):\n\tuser_item = db.get_user_item(user_id)\n\tunvoted_post_ids = user_item[keys.users_unvoted_posts] #feed only contains posts which are currently not voted on by the user\n\tif (unvoted_post_ids is None):\n\t\ttop_posts = []\n\telse: \n\t\ttop_posts = get_top_posts(unvoted_post_ids)\n\tfeed = {\"posts\": top_posts}\n\tfeed_json = json.dumps(feed)\n\treturn feed_json\n\n","sub_path":"service/ThisOrThat/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475052809","text":"# -*- coding: utf-8 -*-\n'''\nImplements a correlated topic model, similar to that described by Blei\nbut using the Bouchard product of sigmoid bounds instead of Laplace\napproximation.\n\nCreated on 17 Jan 2014\n\n@author: bryanfeeney\n'''\n\nfrom math import log\nfrom math import pi\nfrom math import e\n\nimport time\n\nfrom collections import namedtuple\nimport numpy as np\nimport scipy.linalg as la\nimport scipy.sparse as ssp\nimport scipy.special as fns\nimport numpy.random as rd\n\nfrom sidetopics.util.array_utils import normalizerows_ip\nfrom sidetopics.util.sigmoid_utils import rowwise_softmax, scaledSelfSoftDot\nfrom sidetopics.util.sparse_elementwise import sparseScalarQuotientOfDot, \\\n sparseScalarProductOfSafeLnDot\nfrom sidetopics.util.misc import printStderr, static_var\nfrom sidetopics.util.overflow_safe import safe_log_det\nfrom sidetopics.model.evals import perplexity_from_like\nfrom sidetopics.model.common import DataSet\n\nfrom math import isnan\n\n \n# ==============================================================\n# CONSTANTS\n# ==============================================================\n\nDTYPE=np.float32 # A default, generally we should specify this in the model setup\n\nLN_OF_2_PI = log(2 * pi)\nLN_OF_2_PI_E = log(2 * pi * e)\n\nUSE_NIW_PRIOR=False\nNIW_PSI=0.1 # isotropic prior\nNIW_PSEUDO_OBS_MEAN=+2 # set to NIW_NU = K + NIW_NU_STEP # this is called kappa in the code, go figure\nNIW_PSEUDO_OBS_VAR=+2 # related to K\nNIW_MU=0\n\nVocabPrior = 1.1\n\nDEBUG=False\n\nMODEL_NAME=\"ctm/bohning\"\n\n# ==============================================================\n# TUPLES\n# ==============================================================\n\nTrainPlan = namedtuple ( \\\n 'TrainPlan',\n 'iterations epsilon logFrequency fastButInaccurate debug') \n\nQueryState = namedtuple ( \\\n 'QueryState', \\\n 'means expMeans varcs docLens'\\\n)\n\nModelState = namedtuple ( \\\n 'ModelState', \\\n 'K topicMean sigT vocab vocabPrior A dtype name'\n)\n\n# ==============================================================\n# PUBLIC API\n# ==============================================================\n\ndef wordDists(model):\n return model.vocab\n\ndef topicDists(query):\n result = np.exp(query.topicMean - query.topicMean.sum(axis=1))\n result /= result.sum(axis=1)\n return result\n\ndef newModelFromExisting(model):\n '''\n Creates a _deep_ copy of the given model\n '''\n return ModelState(model.K, model.topicMean.copy(), model.sigT.copy(), model.vocab.copy(), model.vocabPrior, model.A.copy(), model.dtype, model.name)\n\ndef newModelAtRandom(data, K, vocabPrior=VocabPrior, dtype=DTYPE):\n '''\n Creates a new CtmModelState for the given training set and\n the given number of topics. Everything is instantiated purely\n at random. This contains all parameters independent of of\n the dataset (e.g. learnt priors)\n \n Param:\n data - the dataset of words, features and links of which only words are used in this model\n K - the number of topics\n \n Return:\n A CtmModelState object\n '''\n assert K > 1, \"There must be at least two topics\"\n \n _,T = data.words.shape\n\n # Pick some random documents as the vocabulary\n vocab = np.ones((K,T), dtype=dtype)\n for k in range(1, K):\n docLenSum = 0\n while docLenSum < 1000:\n randomDoc = rd.randint(0, data.doc_count, size=1)\n sample_doc = data.words[randomDoc, :]\n vocab[k, sample_doc.indices] += sample_doc.data\n docLenSum += sample_doc.sum()\n vocab[k,:] /= vocab[k,:].sum()\n\n # stop-word vocab\n vocab[0,:] = data.words.sum(axis=0)\n vocab[0,:] /= vocab[0,:].sum()\n\n topicMean = rd.random((K,)).astype(dtype)\n topicMean /= np.sum(topicMean)\n \n# isigT = np.eye(K)\n# sigT = la.inv(isigT)\n sigT = np.eye(K, dtype=dtype)\n \n A = 0.5 * (np.eye(K, dtype=dtype) - 1./(K+1))\n \n return ModelState(K, topicMean, sigT, vocab, vocabPrior, A, dtype, MODEL_NAME)\n\ndef newQueryState(data, modelState):\n '''\n Creates a new CTM Query state object. This contains all\n parameters and random variables tied to individual\n datapoints.\n \n Param:\n data - the dataset of words, features and links of which only words are used in this model\n modelState - the model state object\n \n REturn:\n A CtmQueryState object\n '''\n K, vocab, dtype = modelState.K, modelState.vocab, modelState.dtype\n \n D,T = data.words.shape\n assert T == vocab.shape[1], \"The number of terms in the document-term matrix (\" + str(T) + \") differs from that in the model-states vocabulary parameter \" + str(vocab.shape[1])\n docLens = np.squeeze(np.asarray(data.words.sum(axis=1)))\n\n base = normalizerows_ip(rd.random((D,K*2)).astype(dtype))\n means = base[:,:K]\n expMeans = base[:,K:]\n varcs = np.ones((D,K), dtype=dtype)\n \n return QueryState(means, expMeans, varcs, docLens)\n\n\ndef newTrainPlan(iterations=100, epsilon=2, logFrequency=10, fastButInaccurate=False, debug=DEBUG):\n '''\n Create a training plan determining how many iterations we\n process, how often we plot the results, how often we log\n the variational bound, etc.\n '''\n return TrainPlan(iterations, epsilon, logFrequency, fastButInaccurate, debug)\n\ndef train (data, modelState, queryState, trainPlan):\n '''\n Infers the topic distributions in general, and specifically for\n each individual datapoint.\n \n Params:\n W - the DxT document-term matrix\n X - The DxF document-feature matrix, which is IGNORED in this case\n modelState - the actual CTM model\n queryState - the query results - essentially all the \"local\" variables\n matched to the given observations\n trainPlan - how to execute the training process (e.g. iterations,\n log-interval etc.)\n \n Return:\n A new model object with the updated model (note parameters are\n updated in place, so make a defensive copy if you want itr)\n A new query object with the update query parameters\n '''\n W = data.words\n D,_ = W.shape\n \n # Unpack the the structs, for ease of access and efficiency\n iterations, epsilon, logFrequency, diagonalPriorCov, debug = trainPlan.iterations, trainPlan.epsilon, trainPlan.logFrequency, trainPlan.fastButInaccurate, trainPlan.debug\n means, expMeans, varcs, docLens = queryState.means, queryState.expMeans, queryState.varcs, queryState.docLens\n K, topicMean, sigT, vocab, vocabPrior, H, dtype = modelState.K, modelState.topicMean, modelState.sigT, modelState.vocab, modelState.vocabPrior, modelState.A, modelState.dtype\n \n # Book-keeping for logs\n boundIters, boundValues, likelyValues = [], [], []\n \n debugFn = _debug_with_bound if debug else _debug_with_nothing\n \n # Initialize some working variables\n isigT = la.inv(sigT)\n R = W.copy()\n \n pseudoObsMeans = K + NIW_PSEUDO_OBS_MEAN\n pseudoObsVar = K + NIW_PSEUDO_OBS_VAR\n priorSigT_diag = np.ndarray(shape=(K,), dtype=dtype)\n priorSigT_diag.fill (NIW_PSI)\n\n rhs = means.copy()\n\n # Iterate over parameters\n for itr in range(iterations):\n \n # We start with the M-Step, so the parameters are consistent with our\n # initialisation of the RVs when we do the E-Step\n \n # Update the mean and covariance of the prior\n topicMean = means.sum(axis = 0) / (D + pseudoObsMeans) \\\n if USE_NIW_PRIOR \\\n else means.mean(axis=0)\n debugFn (itr, topicMean, \"topicMean\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, H, docLens)\n \n if USE_NIW_PRIOR:\n diff = means - topicMean[np.newaxis,:]\n sigT = diff.T.dot(diff) \\\n + pseudoObsVar * np.outer(topicMean, topicMean)\n sigT += np.diag(varcs.mean(axis=0) + priorSigT_diag)\n sigT /= (D + pseudoObsVar - K)\n else:\n sigT = np.cov(means.T) if sigT.dtype == np.float64 else np.cov(means.T).astype(dtype)\n sigT += np.diag(varcs.mean(axis=0))\n \n if diagonalPriorCov:\n diag = np.diag(sigT)\n sigT = np.diag(diag)\n isigT = np.diag(1./ diag)\n else:\n isigT = la.inv(sigT)\n\n # FIXME Undo debug\n sigT = np.eye(K)\n isigT = la.inv(sigT)\n \n debugFn (itr, sigT, \"sigT\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, H, docLens)\n# print(\" sigT.det = \" + str(la.det(sigT)))\n \n \n # Building Blocks - temporarily replaces means with exp(means)\n expMeans = np.exp(means - means.max(axis=1)[:,np.newaxis], out=expMeans)\n R = sparseScalarQuotientOfDot(W, expMeans, vocab, out=R)\n \n # Update the vocabulary\n vocab *= (R.T.dot(expMeans)).T # Awkward order to maintain sparsity (R is sparse, expMeans is dense)\n vocab += vocabPrior\n vocab = normalizerows_ip(vocab)\n \n # Reset the means to their original form, and log effect of vocab update\n R = sparseScalarQuotientOfDot(W, expMeans, vocab, out=R)\n V = expMeans * R.dot(vocab.T)\n\n debugFn (itr, vocab, \"vocab\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, H, docLens)\n \n # And now this is the E-Step, though itr's followed by updates for the\n # parameters also that handle the log-sum-exp approximation.\n \n # Update the Variances: var_d = (2 N_d * A + isigT)^{-1}\n varcs = np.reciprocal(docLens[:,np.newaxis] * (K-1.)/K + np.diagonal(sigT))\n debugFn (itr, varcs, \"varcs\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, H, docLens)\n \n # Update the Means\n rhs[:,:] = V.copy()\n rhs += docLens[:,np.newaxis] * means.dot(H) + isigT.dot(topicMean)\n rhs -= docLens[:,np.newaxis] * rowwise_softmax(means, out=means)\n\n\n if diagonalPriorCov:\n means = varcs * rhs\n else:\n means = isigT.dot(rhs)\n rhsSum = rhs.sum(axis=1)\n\n\n for d in range(D):\n means[d, :] = la.inv(isigT + docLens[d] * H).dot(rhs[d, :])\n \n# means -= (means[:,0])[:,np.newaxis]\n \n debugFn (itr, means, \"means\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, H, docLens)\n \n if logFrequency > 0 and itr % logFrequency == 0:\n modelState = ModelState(K, topicMean, sigT, vocab, vocabPrior, H, dtype, MODEL_NAME)\n queryState = QueryState(means, expMeans, varcs, docLens)\n \n boundValues.append(var_bound(data, modelState, queryState))\n likelyValues.append(log_likelihood(data, modelState, queryState))\n boundIters.append(itr)\n \n print (time.strftime('%X') + \" : Iteration %d: bound %f \\t Perplexity: %.2f\" % (itr, boundValues[-1], perplexity_from_like(likelyValues[-1], docLens.sum())))\n if len(boundValues) > 1:\n if boundValues[-2] > boundValues[-1]:\n if debug: printStderr (\"ERROR: bound degradation: %f > %f\" % (boundValues[-2], boundValues[-1]))\n \n # Check to see if the improvement in the bound has fallen below the threshold\n if itr > 100 and len(likelyValues) > 3 \\\n and abs(perplexity_from_like(likelyValues[-1], docLens.sum()) - perplexity_from_like(likelyValues[-2], docLens.sum())) < 1.0:\n break\n\n return \\\n ModelState(K, topicMean, sigT, vocab, vocabPrior, H, dtype, MODEL_NAME), \\\n QueryState(means, expMeans, varcs, docLens), \\\n (np.array(boundIters), np.array(boundValues), np.array(likelyValues))\n\ndef query(data, modelState, queryState, queryPlan):\n '''\n Given a _trained_ model, attempts to predict the topics for each of\n the inputs.\n \n Params:\n data - the dataset of words, features and links of which only words are used in this model\n modelState - the _trained_ model\n queryState - the query state generated for the query dataset\n queryPlan - used in this case as we need to tighten up the approx\n \n Returns:\n The model state and query state, in that order. The model state is\n unchanged, the query is.\n '''\n iterations, epsilon, logFrequency, diagonalPriorCov, debug = queryPlan.iterations, queryPlan.epsilon, queryPlan.logFrequency, queryPlan.fastButInaccurate, queryPlan.debug\n means, expMeans, varcs, n = queryState.means, queryState.expMeans, queryState.varcs, queryState.docLens\n K, topicMean, sigT, vocab, vocabPrior, A, dtype = modelState.K, modelState.topicMean, modelState.sigT, modelState.vocab, modelState.vocabPrior, modelState.A, modelState.dtype\n \n debugFn = _debug_with_bound if debug else _debug_with_nothing\n W = data.words\n D = W.shape[0]\n \n # Necessary temp variables (notably the count of topic to word assignments\n # per topic per doc)\n isigT = la.inv(sigT)\n \n # Update the Variances\n varcs = 1./((n * (K-1.)/K)[:,np.newaxis] + isigT.flat[::K+1])\n debugFn (0, varcs, \"varcs\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, A, n)\n \n lastPerp = 1E+300 if dtype is np.float64 else 1E+30\n R = W.copy()\n for itr in range(iterations):\n expMeans = np.exp(means - means.max(axis=1)[:,np.newaxis], out=expMeans)\n R = sparseScalarQuotientOfDot(W, expMeans, vocab, out=R)\n V = expMeans * R.dot(vocab.T)\n \n # Update the Means\n rhs = V.copy()\n rhs += n[:,np.newaxis] * means.dot(A) + isigT.dot(topicMean)\n rhs -= n[:,np.newaxis] * rowwise_softmax(means, out=means)\n if diagonalPriorCov:\n means = varcs * rhs\n else:\n for d in range(D):\n means[d,:] = la.inv(isigT + n[d] * A).dot(rhs[d,:])\n \n debugFn (itr, means, \"means\", W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, A, n)\n \n like = log_likelihood(data, modelState, QueryState(means, expMeans, varcs, n))\n perp = perplexity_from_like(like, data.word_count)\n if itr > 20 and lastPerp - perp < 1:\n break\n lastPerp = perp\n\n return modelState, queryState\n\n\ndef log_likelihood (data, modelState, queryState):\n ''' \n Return the log-likelihood of the given data W according to the model\n and the parameters inferred for the entries in W stored in the \n queryState object.\n '''\n return np.sum( \\\n sparseScalarProductOfSafeLnDot(\\\n data.words, \\\n rowwise_softmax(queryState.means), \\\n modelState.vocab \\\n ).data \\\n )\n \ndef var_bound(data, modelState, queryState):\n '''\n Determines the variational bounds. Values are mutated in place, but are\n reset afterwards to their initial values. So it's safe to call in a serial\n manner.\n '''\n \n # Unpack the the structs, for ease of access and efficiency\n W = data.words\n D,_ = W.shape\n means, expMeans, varcs, docLens = queryState.means, queryState.expMeans, queryState.varcs, queryState.docLens\n K, topicMean, sigT, vocab, vocabPrior, A = modelState.K, modelState.topicMean, modelState.sigT, modelState.vocab, modelState.vocabPrior, modelState.A\n \n # Calculate some implicit variables\n isigT = la.inv(sigT)\n \n bound = 0\n \n if USE_NIW_PRIOR:\n pseudoObsMeans = K + NIW_PSEUDO_OBS_MEAN\n pseudoObsVar = K + NIW_PSEUDO_OBS_VAR\n\n # distribution over topic covariance\n bound -= 0.5 * K * pseudoObsVar * log(NIW_PSI)\n bound -= 0.5 * K * pseudoObsVar * log(2)\n bound -= fns.multigammaln(pseudoObsVar / 2., K)\n bound -= 0.5 * (pseudoObsVar + K - 1) * safe_log_det(sigT)\n bound += 0.5 * NIW_PSI * np.trace(isigT)\n\n # and its entropy\n # is a constant which we skip\n \n # distribution over means\n bound -= 0.5 * K * log(1./pseudoObsMeans) * safe_log_det(sigT)\n bound -= 0.5 / pseudoObsMeans * (topicMean).T.dot(isigT).dot(topicMean)\n \n # and its entropy\n bound += 0.5 * safe_log_det(sigT) # + a constant\n \n \n # Distribution over document topics\n bound -= (D*K)/2. * LN_OF_2_PI\n bound -= D/2. * la.det(sigT)\n diff = means - topicMean[np.newaxis,:]\n bound -= 0.5 * np.sum (diff.dot(isigT) * diff)\n bound -= 0.5 * np.sum(varcs * np.diag(isigT)[np.newaxis,:]) # = -0.5 * sum_d tr(V_d \\Sigma^{-1}) when V_d is diagonal only.\n \n # And its entropy\n# bound += 0.5 * D * K * LN_OF_2_PI_E + 0.5 * np.sum(np.log(varcs)) \n \n # Distribution over word-topic assignments and words and the formers\n # entropy. This is somewhat jumbled to avoid repeatedly taking the\n # exp and log of the means\n expMeans = np.exp(means - means.max(axis=1)[:,np.newaxis], out=expMeans)\n R = sparseScalarQuotientOfDot(W, expMeans, vocab) # D x V [W / TB] is the quotient of the original over the reconstructed doc-term matrix\n V = expMeans * (R.dot(vocab.T)) # D x K\n \n bound += np.sum(docLens * np.log(np.sum(expMeans, axis=1)))\n bound += np.sum(sparseScalarProductOfSafeLnDot(W, expMeans, vocab).data)\n \n bound += np.sum(means * V)\n bound += np.sum(2 * ssp.diags(docLens,0) * means.dot(A) * means)\n bound -= 2. * scaledSelfSoftDot(means, docLens)\n bound -= 0.5 * np.sum(docLens[:,np.newaxis] * V * (np.diag(A))[np.newaxis,:])\n \n bound -= np.sum(means * V) \n \n \n return bound\n \n\n# ==============================================================\n# PUBLIC HELPERS\n# ==============================================================\n\n\n@static_var(\"old_bound\", 0)\ndef _debug_with_bound (itr, var_value, var_name, W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, A, n):\n if np.isnan(var_value).any():\n printStderr (\"WARNING: \" + var_name + \" contains NaNs\")\n if np.isinf(var_value).any():\n printStderr (\"WARNING: \" + var_name + \" contains INFs\")\n if var_value.dtype != dtype:\n printStderr (\"WARNING: dtype(\" + var_name + \") = \" + str(var_value.dtype))\n \n old_bound = _debug_with_bound.old_bound\n bound = var_bound(DataSet(W), ModelState(K, topicMean, sigT, vocab, vocabPrior, A, dtype, MODEL_NAME), QueryState(means, means.copy(), varcs, n))\n diff = \"\" if old_bound == 0 else \"%15.4f\" % (bound - old_bound)\n _debug_with_bound.old_bound = bound\n \n addendum = \"\"\n if var_name == \"sigT\":\n try:\n addendum = \"det(sigT) = %g\" % (la.det(sigT))\n except:\n addendum = \"det(sigT) = \"\n \n if isnan(bound):\n printStderr (\"Bound is NaN\")\n elif int(bound - old_bound) < 0:\n printStderr (\"Iter %3d Update %-15s Bound %22f (%15s) %s\" % (itr, var_name, bound, diff, addendum)) \n else:\n print (\"Iter %3d Update %-15s Bound %22f (%15s) %s\" % (itr, var_name, bound, diff, addendum)) \n\ndef _debug_with_nothing (itr, var_value, var_name, W, K, topicMean, sigT, vocab, vocabPrior, dtype, means, varcs, A, n):\n pass\n\n","sub_path":"sidetopics/model/ctm_bohning_fast.py","file_name":"ctm_bohning_fast.py","file_ext":"py","file_size_in_byte":19137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"52555738","text":"from __future__ import unicode_literals\nimport frappe\n\n\ndef execute(filters=None):\n\tcolumns, data = [], []\n\tcolumns = get_colums()\n\tdata = get_data(filters)\n\tvalidate_filters(filters)\n\n\treturn columns, data\n\ndef validate_filters(filters):\n\tif filters.from_date > filters.to_date:\n\t\tfrappe.throw(_(\"From Date must be before To Date\"))\n\n\ndef get_data(filters):\n\tquery=\"\"\"Select name, employee_name, company, user_id, date_of_joining, date_of_birth, gender, \n\t\tshift_type, shift_id, eligible_week_off_days, store, enroll_number, weekly_off_day1, weekly_off_day2\n\t from `tabEmployee` \"\"\"\n\t\n\tif filters.get(\"Store\"):\n\t\tquery += \"\"\" where store = '{0}' \n\t\t\t\"\"\".format(filters.get(\"Store\"))\n\t\n\tdl = frappe.db.sql(query,as_list=1,debug=1)\n\treturn dl\n\ndef get_colums():\n\tcolumns = [\"Emp Id:Data:100\"]+[\"Full Name:Data:100\"]+[\"Company:Data:100\"]+[\"User Id:Data:140\"]\\\n\t+[\"Date of Joining:Date:120\"]+[\"Date of Birth:Date:120\"]+[\"Gender:Data:100\"]+[\"Shift Type:Data:100\"]\\\n\t+[\"Shift Id:Data:100\"]+[\"Eligible Week Off Days:Data:100\"]+[\"Store:Data:100\"]+[\"Enroll Number:Data:100\"]\\\n\t+[\"Weekly Off Day1:Data:100\"]+[\"Weekly Off Day2:Data:100\"]\n\t\t\n\treturn columns\n\t\n\t\n\n","sub_path":"bnd/bnd/report/employee_details/employee_details.py","file_name":"employee_details.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"272329013","text":"from django.conf.urls import url\nfrom . import views\n\n\napp_name = 'home'\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^register/(?P\\w+)/$', views.RegisterView.as_view(), name='register'),\n url(r'^verify$', views.VerifyView.as_view(), name='verify'),\n url(r'^updateinfo/(?P\\w+)/$', views.ChangeUserInfo.as_view(), name='updateinfo'),\n url(r'^logout$', views.LogoutView.as_view(), name='logout'),\n\n]","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432786768","text":"# Copyright (c) 2018 UAVCAN Consortium\n# This software is distributed under the terms of the MIT License.\n# Author: Pavel Kirienko \n\nimport abc\nimport math\nimport typing\nimport itertools\nfrom .. import _expression\nfrom .. import _port_id_ranges\nfrom .._bit_length_set import BitLengthSet\nfrom ._serializable import SerializableType, TypeParameterError\nfrom ._attribute import Attribute, Field, PaddingField, Constant\nfrom ._name import check_name, InvalidNameError\nfrom ._void import VoidType\nfrom ._primitive import PrimitiveType, UnsignedIntegerType\n\n\nVersion = typing.NamedTuple(\"Version\", [(\"major\", int), (\"minor\", int)])\n\n\nclass InvalidVersionError(TypeParameterError):\n pass\n\n\nclass AttributeNameCollisionError(TypeParameterError):\n pass\n\n\nclass InvalidExtentError(TypeParameterError):\n pass\n\n\nclass InvalidFixedPortIDError(TypeParameterError):\n pass\n\n\nclass MalformedUnionError(TypeParameterError):\n pass\n\n\nclass DeprecatedDependencyError(TypeParameterError):\n pass\n\n\nclass CompositeType(SerializableType):\n \"\"\"\n This is the most interesting type in the library because it represents an actual DSDL definition upon its\n interpretation.\n This is an abstract class with several specializations.\n \"\"\"\n\n MAX_NAME_LENGTH = 255\n MAX_VERSION_NUMBER = 255\n NAME_COMPONENT_SEPARATOR = \".\"\n\n def __init__( # pylint: disable=too-many-arguments\n self,\n name: str,\n version: Version,\n attributes: typing.Iterable[Attribute],\n deprecated: bool,\n fixed_port_id: typing.Optional[int],\n source_file_path: str,\n has_parent_service: bool,\n doc: str = \"\",\n ):\n super().__init__()\n\n self._name = str(name).strip()\n self._version = version\n self._attributes = list(attributes)\n self._attributes_by_name = {a.name: a for a in self._attributes if not isinstance(a, PaddingField)}\n self._deprecated = bool(deprecated)\n self._fixed_port_id = None if fixed_port_id is None else int(fixed_port_id)\n self._source_file_path = str(source_file_path)\n self._has_parent_service = bool(has_parent_service)\n\n self._doc = doc\n\n # Name check\n if not self._name:\n raise InvalidNameError(\"Composite type name cannot be empty\")\n\n if self.NAME_COMPONENT_SEPARATOR not in self._name:\n raise InvalidNameError(\"Root namespace is not specified\")\n\n if len(self._name) > self.MAX_NAME_LENGTH:\n # TODO\n # Notice that per the Specification, service request/response types are unnamed,\n # but we actually name them the same as the parent service plus the \".Request\"/\".Response\" suffix.\n # This may trigger a name length error for long-named service types where per the Specification\n # no such error may occur. We expect the Specification to catch up with this behavior in a later\n # revision where the names for the request and response parts are actually properly specified.\n raise InvalidNameError(\n \"Name is too long: %r is longer than %d characters\" % (self._name, self.MAX_NAME_LENGTH)\n )\n\n for component in self._name.split(self.NAME_COMPONENT_SEPARATOR):\n check_name(component)\n\n # Version check\n version_valid = (\n (0 <= self._version.major <= self.MAX_VERSION_NUMBER)\n and (0 <= self._version.minor <= self.MAX_VERSION_NUMBER)\n and ((self._version.major + self._version.minor) > 0)\n )\n\n if not version_valid:\n raise InvalidVersionError(\"Invalid version numbers: %s.%s\" % (self._version.major, self._version.minor))\n\n # Attribute check\n used_names = set() # type: typing.Set[str]\n for a in self._attributes:\n if a.name and a.name in used_names:\n raise AttributeNameCollisionError(\"Multiple attributes under the same name: %r\" % a.name)\n used_names.add(a.name)\n\n # Port ID check\n port_id = self._fixed_port_id\n if port_id is not None:\n assert port_id is not None\n if isinstance(self, ServiceType):\n if not (0 <= port_id <= _port_id_ranges.MAX_SERVICE_ID):\n raise InvalidFixedPortIDError(\"Fixed service ID %r is not valid\" % port_id)\n else:\n if not (0 <= port_id <= _port_id_ranges.MAX_SUBJECT_ID):\n raise InvalidFixedPortIDError(\"Fixed subject ID %r is not valid\" % port_id)\n\n # Consistent deprecation check.\n # A non-deprecated type cannot be dependent on deprecated types.\n # A deprecated type can be dependent on anything.\n if not self.deprecated:\n for a in self._attributes:\n t = a.data_type\n if isinstance(t, CompositeType):\n if t.deprecated:\n raise DeprecatedDependencyError(\n \"A type cannot depend on deprecated types \" \"unless it is also deprecated.\"\n )\n\n @property\n def full_name(self) -> str:\n \"\"\"The full name, e.g., ``uavcan.node.Heartbeat``.\"\"\"\n return self._name\n\n @property\n def name_components(self) -> typing.List[str]:\n \"\"\"Components of the full name as a list, e.g., ``['uavcan', 'node', 'Heartbeat']``.\"\"\"\n return self._name.split(CompositeType.NAME_COMPONENT_SEPARATOR)\n\n @property\n def short_name(self) -> str:\n \"\"\"The last component of the full name, e.g., ``Heartbeat`` of ``uavcan.node.Heartbeat``.\"\"\"\n return self.name_components[-1]\n\n @property\n def doc(self) -> str:\n \"\"\"The DSDL header comment provided for this data type without the leading #.\"\"\"\n return self._doc\n\n @property\n def full_namespace(self) -> str:\n \"\"\"The full name without the short name, e.g., ``uavcan.node`` for ``uavcan.node.Heartbeat``.\"\"\"\n return str(CompositeType.NAME_COMPONENT_SEPARATOR.join(self.name_components[:-1]))\n\n @property\n def root_namespace(self) -> str:\n \"\"\"The first component of the full name, e.g., ``uavcan`` of ``uavcan.node.Heartbeat``.\"\"\"\n return self.name_components[0]\n\n @property\n def version(self) -> Version:\n \"\"\"The version numbers of the type, e.g., ``(1, 0)`` of ``uavcan.node.Heartbeat.1.0``.\"\"\"\n return self._version\n\n @property\n def extent(self) -> int:\n \"\"\"\n The amount of memory, in bits, that needs to be allocated in order to store a serialized representation of\n this type or any of its minor versions under the same major version.\n This value is always at least as large as the sum of maximum bit lengths of all fields padded to one byte.\n If the type is sealed, its extent equals ``bit_length_set.max``.\n \"\"\"\n return self.bit_length_set.max\n\n @property\n def bit_length_set(self) -> BitLengthSet:\n \"\"\"\n The bit length set of a composite is always aligned at :attr:`alignment_requirement`.\n For a sealed type this is the true bit length set computed by aggregating the fields and\n padding the result to :attr:`alignment_requirement`.\n That is, sealed types expose their internal structure; for example, a type that contains a single field\n of type ``uint32[2]`` would have a single entry in the bit length set: ``{64}``.\n \"\"\"\n raise NotImplementedError\n\n @property\n def deprecated(self) -> bool:\n \"\"\"Whether the definition is marked ``@deprecated``.\"\"\"\n return self._deprecated\n\n @property\n def attributes(self) -> typing.List[Attribute]:\n return self._attributes[:] # Return copy to prevent mutation\n\n @property\n def fields(self) -> typing.List[Field]:\n return [a for a in self.attributes if isinstance(a, Field)]\n\n @property\n def fields_except_padding(self) -> typing.List[Field]:\n return [a for a in self.attributes if isinstance(a, Field) and not isinstance(a, PaddingField)]\n\n @property\n def constants(self) -> typing.List[Constant]:\n return [a for a in self.attributes if isinstance(a, Constant)]\n\n @property\n def inner_type(self) -> \"CompositeType\":\n \"\"\"\n If the concrete type is a decorator over another Composite (such as :class:`DelimitedType`),\n this property provides access to the decorated instance.\n Otherwise, returns the current instance reference unchanged.\n This is intended for use in scenarios where the decoration is irrelevant and the user needs to know\n the concrete type of the decorated instance.\n \"\"\"\n return self\n\n @property\n def fixed_port_id(self) -> typing.Optional[int]:\n return self._fixed_port_id\n\n @property\n def has_fixed_port_id(self) -> bool:\n return self.fixed_port_id is not None\n\n @property\n def source_file_path(self) -> str:\n \"\"\"\n For synthesized types such as service request/response sections, this property is defined as an empty string.\n \"\"\"\n return self._source_file_path\n\n @property\n def alignment_requirement(self) -> int:\n # This is more general than required by the Specification, but it is done this way in case if we decided\n # to support greater alignment requirements in the future.\n return max([self.BITS_PER_BYTE] + [x.data_type.alignment_requirement for x in self.fields])\n\n @property\n def has_parent_service(self) -> bool:\n \"\"\"\n :class:`pydsdl.ServiceType` contains two special fields of this type: ``request`` and ``response``.\n This property is True if this type is a service request/response type.\n The version and deprecation status are shared with that of the parent service.\n The name of the parent service equals the full namespace name of this type.\n For example: ``ns.Service.Request.2.3`` --> ``ns.Service.2.3``.\n \"\"\"\n return self._has_parent_service\n\n @abc.abstractmethod\n def iterate_fields_with_offsets(\n self, base_offset: BitLengthSet = BitLengthSet(0)\n ) -> typing.Iterator[typing.Tuple[Field, BitLengthSet]]:\n \"\"\"\n Iterates over every field (not attribute -- constants are excluded) of the data type,\n yielding it together with its offset, where the offset is represented as :class:`pydsdl.BitLengthSet`.\n The offset of each field is added to the base offset, which may be specified by the caller;\n if not specified, the base offset is assumed to be ``{0}``.\n\n The objective of this method is to allow code generators to easily implement fully unrolled serialization and\n deserialization routines, where \"unrolled\" means that upon encountering another (nested) composite type, the\n serialization routine would not delegate its serialization to the serialization routine of the encountered type,\n but instead would serialize it in-place, as if the field of that type was replaced with its own fields in-place.\n The lack of delegation has very important performance implications: when the serialization routine does\n not delegate serialization of the nested types, it can perform infinitely deep field alignment analysis,\n thus being able to reliably statically determine whether each field of the type, including nested types\n at arbitrarily deep levels of nesting, is aligned relative to the origin of the serialized representation\n of the outermost type. As a result, the code generator will be able to avoid unnecessary reliance on slow\n bit-level copy routines replacing them instead with much faster byte-level copy (like ``memcpy()``) or even\n plain memory aliasing.\n\n When invoked on a tagged union type, the method yields the same offset for every field (since that's how\n tagged unions are serialized), where the offset equals the bit length of the implicit union tag (plus the\n base offset, of course, if provided).\n\n Please refer to the usage examples to see how this feature can be used.\n\n :param base_offset: Assume the specified base offset; assume zero offset if the parameter is not provided.\n The base offset will be implicitly padded out to :attr:`alignment_requirement`.\n\n :return: A generator of ``(Field, BitLengthSet)``.\n \"\"\"\n raise NotImplementedError\n\n def _attribute(self, name: _expression.String) -> _expression.Any:\n \"\"\"This is the handler for DSDL expressions like ``uavcan.node.Heartbeat.1.0.MODE_OPERATIONAL``.\"\"\"\n for c in self.constants:\n if c.name == name.native_value:\n assert isinstance(c.value, _expression.Any)\n return c.value\n\n if name.native_value == \"_extent_\": # Experimental non-standard extension\n return _expression.Rational(self.extent)\n\n return super()._attribute(name) # Hand over up the inheritance chain, this is important\n\n def __getitem__(self, attribute_name: str) -> Attribute:\n \"\"\"\n Allows the caller to retrieve an attribute by name.\n Padding fields are not accessible via this interface because they don't have names.\n Raises :class:`KeyError` if there is no such attribute.\n \"\"\"\n return self._attributes_by_name[attribute_name]\n\n def __str__(self) -> str:\n \"\"\"Returns a string like ``uavcan.node.Heartbeat.1.0``.\"\"\"\n return \"%s.%d.%d\" % (self.full_name, self.version.major, self.version.minor)\n\n def __repr__(self) -> str:\n return (\n \"%s(name=%r, version=%r, fields=%r, constants=%r, alignment_requirement=%r, \"\n \"deprecated=%r, fixed_port_id=%r)\"\n ) % (\n self.__class__.__name__,\n self.full_name,\n self.version,\n self.fields,\n self.constants,\n self.alignment_requirement,\n self.deprecated,\n self.fixed_port_id,\n )\n\n\nclass UnionType(CompositeType):\n \"\"\"\n A message type that is marked ``@union``.\n \"\"\"\n\n MIN_NUMBER_OF_VARIANTS = 2\n\n def __init__( # pylint: disable=too-many-arguments\n self,\n name: str,\n version: Version,\n attributes: typing.Iterable[Attribute],\n deprecated: bool,\n fixed_port_id: typing.Optional[int],\n source_file_path: str,\n has_parent_service: bool,\n doc: str = \"\",\n ):\n # Proxy all parameters directly to the base type - I wish we could do that\n # with kwargs while preserving the type information\n super().__init__(\n name=name,\n version=version,\n attributes=attributes,\n deprecated=deprecated,\n fixed_port_id=fixed_port_id,\n source_file_path=source_file_path,\n has_parent_service=has_parent_service,\n doc=doc,\n )\n\n if self.number_of_variants < self.MIN_NUMBER_OF_VARIANTS:\n raise MalformedUnionError(\n \"A tagged union cannot contain fewer than %d variants\" % self.MIN_NUMBER_OF_VARIANTS\n )\n\n for a in attributes:\n if isinstance(a, PaddingField) or not a.name or isinstance(a.data_type, VoidType):\n raise MalformedUnionError(\"Padding fields not allowed in unions\")\n\n self._tag_field_type = UnsignedIntegerType(\n self._compute_tag_bit_length([x.data_type for x in self.fields]), PrimitiveType.CastMode.TRUNCATED\n )\n\n self._bls = self.aggregate_bit_length_sets(\n [f.data_type for f in self.fields],\n ).pad_to_alignment(self.alignment_requirement)\n\n @property\n def bit_length_set(self) -> BitLengthSet:\n return self._bls\n\n @property\n def number_of_variants(self) -> int:\n return len(self.fields)\n\n @property\n def tag_field_type(self) -> UnsignedIntegerType:\n \"\"\"\n The unsigned integer type of the implicit union tag field.\n Note that the set of valid tag values is a subset of that of the returned type.\n \"\"\"\n return self._tag_field_type\n\n def iterate_fields_with_offsets(\n self, base_offset: BitLengthSet = BitLengthSet(0)\n ) -> typing.Iterator[typing.Tuple[Field, BitLengthSet]]:\n \"\"\"See the base class.\"\"\"\n offset = base_offset.pad_to_alignment(self.alignment_requirement) + self.tag_field_type.bit_length\n for f in self.fields: # Same offset for every field, because it's a tagged union, not a struct\n assert offset.is_aligned_at(f.data_type.alignment_requirement)\n yield f, offset\n\n @staticmethod\n def aggregate_bit_length_sets(field_types: typing.Sequence[SerializableType]) -> BitLengthSet:\n \"\"\"\n Computes the bit length set for a tagged union type given the type of each of its variants.\n The final padding is not applied.\n\n Unions are easy to handle because when serialized, a union is essentially just a single field prefixed with\n a fixed-length integer tag. So we just build a full set of combinations and then add the tag length\n to each element.\n\n Observe that unions are not defined for less than 2 elements;\n however, this function tries to be generic by properly handling those cases as well,\n even though they are not permitted by the specification.\n For zero fields, the function yields ``{0}``; for one field, the function yields the BLS of the field itself.\n \"\"\"\n ms = [x.bit_length_set for x in field_types]\n if len(ms) == 0:\n return BitLengthSet(0)\n if len(ms) == 1:\n return BitLengthSet(ms[0])\n\n tbl = UnionType._compute_tag_bit_length(field_types)\n return tbl + BitLengthSet.unite(ms)\n\n @staticmethod\n def _compute_tag_bit_length(field_types: typing.Sequence[SerializableType]) -> int:\n assert len(field_types) > 1, \"Internal API misuse\"\n unaligned_tag_bit_length = (len(field_types) - 1).bit_length()\n tag_bit_length = 2 ** math.ceil(math.log2(max(SerializableType.BITS_PER_BYTE, unaligned_tag_bit_length)))\n # This is to prevent the tag from breaking the alignment of the following variant.\n tag_bit_length = max([tag_bit_length] + [x.alignment_requirement for x in field_types])\n assert isinstance(tag_bit_length, int)\n assert tag_bit_length in {8, 16, 32, 64}\n return tag_bit_length\n\n\nclass StructureType(CompositeType):\n \"\"\"\n A message type that is NOT marked ``@union``.\n \"\"\"\n\n def __init__( # pylint: disable=too-many-arguments\n self,\n name: str,\n version: Version,\n attributes: typing.Iterable[Attribute],\n deprecated: bool,\n fixed_port_id: typing.Optional[int],\n source_file_path: str,\n has_parent_service: bool,\n doc: str = \"\",\n ):\n super().__init__(\n name=name,\n version=version,\n attributes=attributes,\n deprecated=deprecated,\n fixed_port_id=fixed_port_id,\n source_file_path=source_file_path,\n has_parent_service=has_parent_service,\n doc=doc,\n )\n self._bls = self.aggregate_bit_length_sets(\n [f.data_type for f in self.fields],\n ).pad_to_alignment(self.alignment_requirement)\n\n def iterate_fields_with_offsets(\n self, base_offset: BitLengthSet = BitLengthSet(0)\n ) -> typing.Iterator[typing.Tuple[Field, BitLengthSet]]:\n \"\"\"See the base class.\"\"\"\n offset = base_offset.pad_to_alignment(self.alignment_requirement)\n for f in self.fields:\n offset = offset.pad_to_alignment(f.data_type.alignment_requirement)\n yield f, offset\n offset = offset + f.data_type.bit_length_set\n\n @property\n def bit_length_set(self) -> BitLengthSet:\n return self._bls\n\n @staticmethod\n def aggregate_bit_length_sets(field_types: typing.Sequence[SerializableType]) -> BitLengthSet:\n \"\"\"\n Computes the bit length set for a structure type given the type of each of its fields.\n The final padding is not applied (but inter-field padding obviously is).\n \"\"\"\n bls = field_types[0].bit_length_set if len(field_types) > 0 else BitLengthSet(0)\n for t in field_types[1:]:\n bls = bls.pad_to_alignment(t.alignment_requirement) + t.bit_length_set\n return bls\n\n\nclass DelimitedType(CompositeType):\n \"\"\"\n Composites that are not sealed are wrapped into this container.\n It is a decorator over a composite type instance that injects the extent, bit length set, and field iteration\n logic that is specific to delimited (appendable, non-sealed) types.\n\n Most of the attributes are copied from the wrapped type (e.g., name, fixed port-ID, attributes, etc.),\n except for those that relate to the bit layout.\n\n Non-sealed composites are serialized into delimited opaque containers like ``uint8[<=(extent + 7) // 8]``,\n where the implicit length prefix is of type :attr:`delimiter_header_type`.\n Their bit length set is also computed as if it was an array as declared above,\n in order to prevent the containing definitions from making assumptions about the offsets of the following fields\n that might not survive the evolution of the type (e.g., version 1 may be 64 bits long, version 2 might be\n 56 bits long, then version 3 could grow to 96 bits, unpredictable).\n \"\"\"\n\n _DEFAULT_DELIMITER_HEADER_BIT_LENGTH = 32\n\n def __init__(self, inner: CompositeType, extent: int):\n self._inner = inner\n super().__init__(\n name=inner.full_name,\n version=inner.version,\n attributes=inner.attributes,\n deprecated=inner.deprecated,\n fixed_port_id=inner.fixed_port_id,\n source_file_path=inner.source_file_path,\n has_parent_service=inner.has_parent_service,\n doc=inner.doc,\n )\n self._extent = int(extent)\n if self._extent % self.alignment_requirement != 0:\n raise InvalidExtentError(\n \"The specified extent of %d bits is not a multiple of %d bits\"\n % (self._extent, self.alignment_requirement)\n )\n if self._extent < inner.extent:\n raise InvalidExtentError(\n \"The specified extent of %d bits is too small for this data type. \"\n \"Either compactify the data type or increase the extent at least to %d bits. \"\n \"Beware that the latter option may break wire compatibility.\" % (self._extent, inner.extent)\n )\n\n delimiter_header_bit_length = self._DEFAULT_DELIMITER_HEADER_BIT_LENGTH # This may be made configurable later.\n # This is to prevent the delimiter header from breaking the alignment of the following composite.\n delimiter_header_bit_length = max(delimiter_header_bit_length, self.alignment_requirement)\n self._delimiter_header_type = UnsignedIntegerType(\n delimiter_header_bit_length, UnsignedIntegerType.CastMode.TRUNCATED\n )\n\n self._bls = self.delimiter_header_type.bit_length + BitLengthSet(self.alignment_requirement).repeat_range(\n self._extent // self.alignment_requirement\n )\n\n assert self.extent % self.BITS_PER_BYTE == 0\n assert self.extent % self.alignment_requirement == 0\n assert self.extent >= self.inner_type.extent\n assert self.bit_length_set.is_aligned_at_byte()\n assert self.bit_length_set.is_aligned_at(self.alignment_requirement)\n assert self.extent >= (self.bit_length_set.max - self.delimiter_header_type.bit_length)\n assert self.has_parent_service == inner.has_parent_service\n\n @property\n def inner_type(self) -> CompositeType:\n \"\"\"\n The appendable type that is serialized inside this delimited container.\n Its bit length set, extent, and other layout-specific entities are computed as if it was a sealed type.\n \"\"\"\n return self._inner\n\n @property\n def extent(self) -> int:\n \"\"\"\n The extent of a delimited type is specified explicitly via ``@extent EXPRESSION``,\n where the expression shall yield an integer multiple of 8.\n\n Optional optimization hint: if the objective is to allocate buffer memory for constructing a new\n serialized representation locally, then it may be beneficial to use the extent of the inner type\n rather than this one because it may be smaller. This is not safe for deserialization, of course.\n \"\"\"\n return self._extent\n\n @property\n def bit_length_set(self) -> BitLengthSet:\n \"\"\"\n For a non-sealed type, not many guarantees about the bit length set can be provided,\n because the type may be mutated in the next minor revision.\n Therefore, a synthetic bit length set is constructed that is merely a list of all possible bit lengths\n plus the delimiter header.\n For example, a type that contains a single field of type ``uint32[2]`` would have the bit length set of\n ``{h, h+8, h+16, ..., h+56, h+64}`` where ``h`` is the length of the delimiter header.\n \"\"\"\n return self._bls\n\n @property\n def delimiter_header_type(self) -> UnsignedIntegerType:\n \"\"\"\n The type of the integer prefix field that encodes the size of the serialized representation [in bytes]\n of the :attr:`inner_type`.\n \"\"\"\n return self._delimiter_header_type\n\n def iterate_fields_with_offsets(\n self, base_offset: BitLengthSet = BitLengthSet(0)\n ) -> typing.Iterator[typing.Tuple[Field, BitLengthSet]]:\n \"\"\"\n Delegates the call to the inner type, but with the base offset increased by the size of the delimiter header.\n \"\"\"\n base_offset = base_offset + self.delimiter_header_type.bit_length_set\n return self.inner_type.iterate_fields_with_offsets(base_offset)\n\n def __repr__(self) -> str:\n return \"%s(inner=%r, extent=%r)\" % (self.__class__.__name__, self.inner_type, self.extent)\n\n\nclass ServiceType(CompositeType):\n \"\"\"\n A service (not message) type.\n Unlike message types, it can't be serialized directly.\n\n There are exactly two pseudo-fields: ``request`` and ``response``,\n which contain the request and the response structure of the service type, respectively.\n \"\"\"\n\n def __init__(self, request: CompositeType, response: CompositeType, fixed_port_id: typing.Optional[int]):\n name = request.full_namespace\n consistent = (\n request.full_name.startswith(name)\n and response.full_name.startswith(name)\n and request.version == response.version\n and not isinstance(request, ServiceType)\n and not isinstance(response, ServiceType)\n and request.deprecated == response.deprecated\n and request.source_file_path == response.source_file_path\n and request.fixed_port_id is None\n and response.fixed_port_id is None\n and request.has_parent_service\n and response.has_parent_service\n )\n if not consistent:\n raise ValueError(\"Internal error: service request/response type consistency error\")\n\n self._request_type = request\n self._response_type = response\n container_attributes = [\n Field(data_type=self._request_type, name=\"request\"),\n Field(data_type=self._response_type, name=\"response\"),\n ]\n super().__init__(\n name=name,\n version=request.version,\n attributes=container_attributes,\n deprecated=request.deprecated,\n fixed_port_id=fixed_port_id,\n source_file_path=request.source_file_path,\n has_parent_service=False,\n doc=request.doc,\n )\n\n @property\n def bit_length_set(self) -> BitLengthSet:\n raise TypeError(\"Service types are not directly serializable. Use either request or response.\")\n\n @property\n def request_type(self) -> CompositeType:\n assert self._request_type.has_parent_service\n return self._request_type\n\n @property\n def response_type(self) -> CompositeType:\n assert self._response_type.has_parent_service\n return self._response_type\n\n def iterate_fields_with_offsets(\n self, base_offset: BitLengthSet = BitLengthSet(0)\n ) -> typing.Iterator[typing.Tuple[Field, BitLengthSet]]:\n \"\"\"Always raises a :class:`TypeError`.\"\"\"\n raise TypeError(\"Service types do not have serializable fields. Use either request or response.\")\n\n\ndef _unittest_composite_types() -> None: # pylint: disable=too-many-statements\n from pytest import raises\n from ._primitive import SignedIntegerType, FloatType\n from ._array import FixedLengthArrayType, VariableLengthArrayType\n\n def try_name(name: str) -> CompositeType:\n return StructureType(\n name=name,\n version=Version(0, 1),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n with raises(InvalidNameError, match=\"(?i).*empty.*\"):\n try_name(\"\")\n\n with raises(InvalidNameError, match=\"(?i).*root namespace.*\"):\n try_name(\"T\")\n\n with raises(InvalidNameError, match=\"(?i).*long.*\"):\n try_name(\"namespace.another.deeper.\" * 10 + \"LongTypeName\")\n\n with raises(InvalidNameError, match=\"(?i).*component.*empty.*\"):\n try_name(\"namespace.ns..T\")\n\n with raises(InvalidNameError, match=\"(?i).*component.*empty.*\"):\n try_name(\".namespace.ns.T\")\n\n with raises(InvalidNameError, match=\"(?i).*cannot start with.*\"):\n try_name(\"namespace.0ns.T\")\n\n with raises(InvalidNameError, match=\"(?i).*cannot start with.*\"):\n try_name(\"namespace.ns.0T\")\n\n with raises(InvalidNameError, match=\"(?i).*cannot contain.*\"):\n try_name(\"namespace.n-s.T\")\n\n assert try_name(\"root.nested.T\").full_name == \"root.nested.T\"\n assert try_name(\"root.nested.T\").full_namespace == \"root.nested\"\n assert try_name(\"root.nested.T\").root_namespace == \"root\"\n assert try_name(\"root.nested.T\").short_name == \"T\"\n\n with raises(MalformedUnionError, match=\".*variants.*\"):\n UnionType(\n name=\"a.A\",\n version=Version(0, 1),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n with raises(MalformedUnionError, match=\"(?i).*padding.*\"):\n UnionType(\n name=\"a.A\",\n version=Version(0, 1),\n attributes=[\n Field(UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED), \"a\"),\n Field(SignedIntegerType(16, PrimitiveType.CastMode.SATURATED), \"b\"),\n PaddingField(VoidType(16)),\n ],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n u = UnionType(\n name=\"uavcan.node.Heartbeat\",\n version=Version(42, 123),\n attributes=[\n Field(UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED), \"a\"),\n Field(SignedIntegerType(16, PrimitiveType.CastMode.SATURATED), \"b\"),\n Constant(FloatType(32, PrimitiveType.CastMode.SATURATED), \"A\", _expression.Rational(123)),\n ],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n assert u[\"a\"].name == \"a\"\n assert u[\"b\"].name == \"b\"\n assert u[\"A\"].name == \"A\"\n assert u.fields == u.fields_except_padding\n with raises(KeyError):\n assert u[\"c\"]\n assert hash(u) == hash(u)\n assert not u.has_parent_service\n del u\n\n s = StructureType(\n name=\"a.A\",\n version=Version(0, 1),\n attributes=[\n PaddingField(VoidType(8)),\n Field(UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED), \"a\"),\n PaddingField(VoidType(64)),\n Field(SignedIntegerType(16, PrimitiveType.CastMode.SATURATED), \"b\"),\n PaddingField(VoidType(2)),\n Constant(FloatType(32, PrimitiveType.CastMode.SATURATED), \"A\", _expression.Rational(123)),\n ],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n assert s[\"a\"].name == \"a\"\n assert s[\"b\"].name == \"b\"\n assert s[\"A\"].name == \"A\"\n assert len(s.constants) == 1\n assert len(s.fields) == 5\n assert len(s.fields_except_padding) == 2\n with raises(KeyError):\n assert s[\"c\"]\n with raises(KeyError):\n assert s[\"\"] # Padding fields are not accessible\n assert hash(s) == hash(s)\n assert not s.has_parent_service\n assert s.inner_type is s\n assert s.inner_type.inner_type is s\n\n d = DelimitedType(s, 2048)\n assert d.inner_type is s\n assert d.inner_type.inner_type is s\n assert d.attributes == d.inner_type.attributes\n with raises(KeyError):\n assert d[\"c\"]\n assert hash(d) == hash(d)\n assert d.delimiter_header_type.bit_length == 32\n assert isinstance(d.delimiter_header_type, UnsignedIntegerType)\n assert d.delimiter_header_type.cast_mode == PrimitiveType.CastMode.TRUNCATED\n assert d.extent == 2048\n\n d = DelimitedType(s, 256)\n assert hash(d) == hash(d)\n assert d.delimiter_header_type.bit_length == 32\n assert isinstance(d.delimiter_header_type, UnsignedIntegerType)\n assert d.extent == 256\n\n d = DelimitedType(s, s.extent) # Minimal extent\n assert hash(d) == hash(d)\n assert d.delimiter_header_type.bit_length == 32\n assert isinstance(d.delimiter_header_type, UnsignedIntegerType)\n assert d.extent == s.extent == d.inner_type.extent\n\n with raises(InvalidExtentError):\n assert DelimitedType(s, 255) # Unaligned extent\n\n with raises(InvalidExtentError):\n assert DelimitedType(s, 8) # Extent too small\n\n def try_union_fields(field_types: typing.List[SerializableType]) -> UnionType:\n atr = []\n for i, t in enumerate(field_types):\n atr.append(Field(t, \"_%d\" % i))\n\n return UnionType(\n name=\"a.A\",\n version=Version(0, 1),\n attributes=atr,\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n u = try_union_fields(\n [\n UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED),\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n )\n assert u.inner_type is u\n assert u.inner_type.inner_type is u\n assert u.bit_length_set == {24}\n assert u.extent == 24\n assert DelimitedType(u, 40).extent == 40\n assert set(DelimitedType(u, 40).bit_length_set) == {32, 40, 48, 56, 64, 72}\n assert DelimitedType(u, 40).bit_length_set == {32, 40, 48, 56, 64, 72}\n assert DelimitedType(u, 24).extent == 24\n assert DelimitedType(u, 24).bit_length_set == {32, 40, 48, 56}\n assert DelimitedType(u, 32).extent == 32\n assert DelimitedType(u, 32).bit_length_set == {32, 40, 48, 56, 64}\n assert DelimitedType(u, 800).extent == 800\n assert DelimitedType(u, 800).inner_type is u\n assert DelimitedType(u, 800).inner_type.inner_type is u\n\n assert (\n try_union_fields(\n [\n UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED),\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n * 257\n ).bit_length_set\n == {16 + 16}\n )\n\n assert (\n try_union_fields(\n [\n UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED),\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n * 32769\n ).bit_length_set\n == {32 + 16}\n )\n\n # The reference values for the following test are explained in the array tests above\n tu8 = UnsignedIntegerType(8, cast_mode=PrimitiveType.CastMode.TRUNCATED)\n small = VariableLengthArrayType(tu8, 2)\n outer = FixedLengthArrayType(small, 2) # unpadded bit length values: {4, 12, 20, 28, 36}\n\n # Above plus one bit to each, plus 16-bit for the unsigned integer field\n assert (\n try_union_fields(\n [\n outer,\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n ).bit_length_set\n == {24, 32, 40, 48, 56}\n )\n\n def try_struct_fields(field_types: typing.List[SerializableType]) -> StructureType:\n atr = []\n for i, t in enumerate(field_types):\n atr.append(Field(t, \"_%d\" % i))\n\n return StructureType(\n name=\"a.A\",\n version=Version(0, 1),\n attributes=atr,\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n s = try_struct_fields(\n [\n UnsignedIntegerType(16, PrimitiveType.CastMode.TRUNCATED),\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n )\n assert s.bit_length_set == {32}\n assert s.extent == 32\n assert DelimitedType(s, 48).extent == 48\n assert DelimitedType(s, 48).bit_length_set == {32, 40, 48, 56, 64, 72, 80}\n assert DelimitedType(s, 32).extent == 32\n assert DelimitedType(s, 32).bit_length_set == {32, 40, 48, 56, 64}\n assert DelimitedType(s, 40).extent == 40\n assert DelimitedType(s, 40).bit_length_set == {32, 40, 48, 56, 64, 72}\n\n assert try_struct_fields([]).bit_length_set == {0} # Empty sets forbidden\n\n assert (\n try_struct_fields(\n [\n outer,\n SignedIntegerType(16, PrimitiveType.CastMode.SATURATED),\n ]\n ).bit_length_set\n == {16 + 16, 24 + 16, 32 + 16, 40 + 16, 48 + 16}\n )\n\n assert try_struct_fields([outer]).bit_length_set == {16, 24, 32, 40, 48}\n\n\ndef _unittest_field_iterators() -> None: # pylint: disable=too-many-locals\n from pytest import raises\n from ._primitive import BooleanType, FloatType\n from ._array import FixedLengthArrayType, VariableLengthArrayType\n\n saturated = PrimitiveType.CastMode.SATURATED\n _seq_no = 0\n\n def make_type(meta: typing.Type[CompositeType], attributes: typing.Iterable[Attribute]) -> CompositeType:\n nonlocal _seq_no\n _seq_no += 1\n return meta(\n \"ns.Type\" + str(_seq_no),\n version=Version(1, 0),\n attributes=attributes,\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n\n def validate_iterator(\n t: CompositeType,\n reference: typing.Iterable[typing.Tuple[str, typing.Set[int]]],\n base_offset: BitLengthSet = BitLengthSet(0),\n ) -> None:\n for (name, ref_set), (field, real_set) in itertools.zip_longest(\n reference, t.iterate_fields_with_offsets(base_offset)\n ):\n assert field.name == name\n assert real_set == ref_set, field.name + \": \" + str(real_set)\n\n a = make_type(\n StructureType,\n [\n Field(UnsignedIntegerType(10, saturated), \"a\"),\n Field(BooleanType(saturated), \"b\"),\n Field(VariableLengthArrayType(FloatType(32, saturated), 2), \"c\"),\n Field(FixedLengthArrayType(FloatType(32, saturated), 7), \"d\"),\n PaddingField(VoidType(3)),\n ],\n )\n\n validate_iterator(\n a,\n [\n (\"a\", {0}),\n (\"b\", {10}),\n (\"c\", {11}),\n (\n \"d\",\n {\n 11 + 8 + 32 * 0,\n 11 + 8 + 32 * 1,\n 11 + 8 + 32 * 2,\n },\n ),\n (\n \"\",\n {\n 11 + 8 + 32 * 0 + 32 * 7,\n 11 + 8 + 32 * 1 + 32 * 7,\n 11 + 8 + 32 * 2 + 32 * 7,\n },\n ),\n ],\n )\n\n d = DelimitedType(a, 472)\n validate_iterator(\n d,\n [\n (\"a\", {32 + 0}),\n (\"b\", {32 + 10}),\n (\"c\", {32 + 11}),\n (\n \"d\",\n {\n 32 + 11 + 8 + 32 * 0,\n 32 + 11 + 8 + 32 * 1,\n 32 + 11 + 8 + 32 * 2,\n },\n ),\n (\n \"\",\n {\n 32 + 11 + 8 + 32 * 0 + 32 * 7,\n 32 + 11 + 8 + 32 * 1 + 32 * 7,\n 32 + 11 + 8 + 32 * 2 + 32 * 7,\n },\n ),\n ],\n )\n print(\"d.bit_length_set\", d.bit_length_set)\n assert d.bit_length_set == BitLengthSet(\n {32 + x for x in range(((11 + 8 + 32 * 2 + 32 * 7) + 7) // 8 * 8 * 3 // 2 + 1)}\n ).pad_to_alignment(8)\n\n a_bls_options = [\n 11 + 8 + 32 * 0 + 32 * 7 + 3,\n 11 + 8 + 32 * 1 + 32 * 7 + 3,\n 11 + 8 + 32 * 2 + 32 * 7 + 3,\n ]\n assert a.bit_length_set == BitLengthSet(a_bls_options).pad_to_alignment(8)\n\n # Testing \"a\" again, this time with non-zero base offset.\n # The first base offset element is one, but it is padded to byte, so it becomes 8.\n validate_iterator(\n a,\n [\n (\"a\", {8, 16}),\n (\"b\", {8 + 10, 16 + 10}),\n (\"c\", {8 + 11, 16 + 11}),\n (\n \"d\",\n {\n 8 + 11 + 8 + 32 * 0,\n 8 + 11 + 8 + 32 * 1,\n 8 + 11 + 8 + 32 * 2,\n 16 + 11 + 8 + 32 * 0,\n 16 + 11 + 8 + 32 * 1,\n 16 + 11 + 8 + 32 * 2,\n },\n ),\n (\n \"\",\n {\n 8 + 11 + 8 + 32 * 0 + 32 * 7,\n 8 + 11 + 8 + 32 * 1 + 32 * 7,\n 8 + 11 + 8 + 32 * 2 + 32 * 7,\n 16 + 11 + 8 + 32 * 0 + 32 * 7,\n 16 + 11 + 8 + 32 * 1 + 32 * 7,\n 16 + 11 + 8 + 32 * 2 + 32 * 7,\n },\n ),\n ],\n BitLengthSet({1, 16}),\n ) # 1 becomes 8 due to padding.\n\n # Wrap the above into a delimited type with a manually specified extent.\n d = DelimitedType(a, 400)\n validate_iterator(\n d,\n [\n (\"a\", {32 + 8, 32 + 16}),\n (\"b\", {32 + 8 + 10, 32 + 16 + 10}),\n (\"c\", {32 + 8 + 11, 32 + 16 + 11}),\n (\n \"d\",\n {\n 32 + 8 + 11 + 8 + 32 * 0,\n 32 + 8 + 11 + 8 + 32 * 1,\n 32 + 8 + 11 + 8 + 32 * 2,\n 32 + 16 + 11 + 8 + 32 * 0,\n 32 + 16 + 11 + 8 + 32 * 1,\n 32 + 16 + 11 + 8 + 32 * 2,\n },\n ),\n (\n \"\",\n {\n 32 + 8 + 11 + 8 + 32 * 0 + 32 * 7,\n 32 + 8 + 11 + 8 + 32 * 1 + 32 * 7,\n 32 + 8 + 11 + 8 + 32 * 2 + 32 * 7,\n 32 + 16 + 11 + 8 + 32 * 0 + 32 * 7,\n 32 + 16 + 11 + 8 + 32 * 1 + 32 * 7,\n 32 + 16 + 11 + 8 + 32 * 2 + 32 * 7,\n },\n ),\n ],\n BitLengthSet({1, 16}),\n ) # 1 becomes 8 due to padding.\n assert d.bit_length_set == BitLengthSet({(32 + x + 7) // 8 * 8 for x in range(400 + 1)})\n\n b = make_type(\n StructureType,\n [\n Field(a, \"z\"),\n Field(VariableLengthArrayType(a, 2), \"y\"),\n Field(UnsignedIntegerType(6, saturated), \"x\"),\n ],\n )\n\n a_bls_padded = [((x + 7) // 8) * 8 for x in a_bls_options]\n validate_iterator(\n b,\n [\n (\"z\", {0}),\n (\n \"y\",\n {\n a_bls_padded[0],\n a_bls_padded[1],\n a_bls_padded[2],\n },\n ),\n (\n \"x\",\n { # The lone \"+8\" is for the variable-length array's implicit length field\n # First length option of z\n a_bls_padded[0] + 8 + a_bls_padded[0] * 0, # suka\n a_bls_padded[0] + 8 + a_bls_padded[1] * 0,\n a_bls_padded[0] + 8 + a_bls_padded[2] * 0,\n a_bls_padded[0] + 8 + a_bls_padded[0] * 1,\n a_bls_padded[0] + 8 + a_bls_padded[1] * 1,\n a_bls_padded[0] + 8 + a_bls_padded[2] * 1,\n a_bls_padded[0] + 8 + a_bls_padded[0] * 2,\n a_bls_padded[0] + 8 + a_bls_padded[1] * 2,\n a_bls_padded[0] + 8 + a_bls_padded[2] * 2,\n # Second length option of z\n a_bls_padded[1] + 8 + a_bls_padded[0] * 0,\n a_bls_padded[1] + 8 + a_bls_padded[1] * 0,\n a_bls_padded[1] + 8 + a_bls_padded[2] * 0,\n a_bls_padded[1] + 8 + a_bls_padded[0] * 1,\n a_bls_padded[1] + 8 + a_bls_padded[1] * 1,\n a_bls_padded[1] + 8 + a_bls_padded[2] * 1,\n a_bls_padded[1] + 8 + a_bls_padded[0] * 2,\n a_bls_padded[1] + 8 + a_bls_padded[1] * 2,\n a_bls_padded[1] + 8 + a_bls_padded[2] * 2,\n # Third length option of z\n a_bls_padded[2] + 8 + a_bls_padded[0] * 0,\n a_bls_padded[2] + 8 + a_bls_padded[1] * 0,\n a_bls_padded[2] + 8 + a_bls_padded[2] * 0,\n a_bls_padded[2] + 8 + a_bls_padded[0] * 1,\n a_bls_padded[2] + 8 + a_bls_padded[1] * 1,\n a_bls_padded[2] + 8 + a_bls_padded[2] * 1,\n a_bls_padded[2] + 8 + a_bls_padded[0] * 2,\n a_bls_padded[2] + 8 + a_bls_padded[1] * 2,\n a_bls_padded[2] + 8 + a_bls_padded[2] * 2,\n },\n ),\n ],\n )\n\n # Ensuring the equivalency between bit length and aligned bit offset\n b_offset = BitLengthSet(0)\n for f in b.fields:\n b_offset = b_offset + f.data_type.bit_length_set\n print(\"b_offset:\", b_offset)\n assert b_offset.pad_to_alignment(8) == b.bit_length_set\n assert not b_offset.is_aligned_at_byte()\n assert not b_offset.is_aligned_at(32)\n\n c = make_type(\n UnionType,\n [\n Field(a, \"foo\"),\n Field(b, \"bar\"),\n ],\n )\n\n validate_iterator(\n c,\n [\n (\"foo\", {8}), # The offset is the same because it's a union\n (\"bar\", {8}),\n ],\n )\n\n validate_iterator(\n c,\n [\n (\"foo\", {8 + 8}),\n (\"bar\", {8 + 8}),\n ],\n BitLengthSet(8),\n )\n\n validate_iterator(\n c,\n [\n (\"foo\", {0 + 8, 8 + 8}),\n (\"bar\", {0 + 8, 8 + 8}),\n ],\n BitLengthSet({0, 4, 8}),\n ) # The option 4 is eliminated due to padding to byte, so we're left with {0, 8}.\n\n with raises(TypeError, match=\".*request or response.*\"):\n ServiceType(\n request=StructureType(\n name=\"ns.S.Request\",\n version=Version(1, 0),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=True,\n ),\n response=StructureType(\n name=\"ns.S.Response\",\n version=Version(1, 0),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=True,\n ),\n fixed_port_id=None,\n ).iterate_fields_with_offsets()\n\n with raises(ValueError): # Request/response consistency error (internal failure)\n ServiceType(\n request=StructureType(\n name=\"ns.XX.Request\",\n version=Version(2, 0),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=True,\n ),\n response=StructureType(\n name=\"ns.YY.Response\",\n version=Version(3, 0),\n attributes=[],\n deprecated=True,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n ),\n fixed_port_id=None,\n )\n\n # Check the auto-padding logic.\n e = StructureType(\n name=\"e.E\",\n version=Version(0, 1),\n attributes=[],\n deprecated=False,\n fixed_port_id=None,\n source_file_path=\"\",\n has_parent_service=False,\n )\n validate_iterator(e, [])\n a = make_type(\n StructureType,\n [\n Field(UnsignedIntegerType(3, PrimitiveType.CastMode.TRUNCATED), \"x\"),\n Field(e, \"y\"),\n Field(UnsignedIntegerType(2, PrimitiveType.CastMode.TRUNCATED), \"z\"),\n ],\n )\n assert a.bit_length_set == {16}\n validate_iterator(\n a,\n [\n (\"x\", {0}),\n (\"y\", {8}), # Padded out!\n (\"z\", {8}),\n ],\n )\n","sub_path":"pydsdl/_serializable/_composite.py","file_name":"_composite.py","file_ext":"py","file_size_in_byte":49625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"432123197","text":"'''\nWrite a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. Go to the editor\nSample String : 'abc', 'xyz'\nExpected Result : 'xyc abz'\n'''\n\ns1 = 'abc'\ns2 = 'xyz'\nnew1 = s1[:2]\nnew2 = s2[:2]\nprint(new2 + s1[2::], new1 + s2[2::])\n","sub_path":"w3resource/string/swap.py","file_name":"swap.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207942172","text":"# from tflearn.data_augmentation import ImageAugmentation\n\nimport numpy as np\nimport tflearn\nimport itertools\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nfrom models import inception\nfrom models import resnet\nfrom models import vggnet\nfrom models import inception_resnet\n\nmodels_map = {'vggnet': vggnet,\n 'inception': inception,\n 'resnet': resnet,\n 'incep_resnet': inception_resnet}\n\n\ndef get_model(name):\n if name not in models_map:\n raise ValueError('==> %s not found! ' % name)\n\n return models_map[name]\n\n\ndef confusion_matrix(predictions, labels, num_class):\n \"\"\"Return the error rate and confusions.\"\"\"\n confusions = np.zeros([num_class, num_class], np.float32)\n bundled = zip(np.argmax(predictions, 1), np.argmax(labels, 1))\n for predicted, actual in bundled:\n confusions[predicted, actual] += 1\n\n return confusions\n\n\ndef plot_confusions(confusions, total, error, num_class, output):\n fig = plt.figure()\n fig.set_size_inches(4, 4, forward=True)\n # fig.suptitle('Confusion matrix')\n plt.title('Confusion matrix\\ntotal: %d images / error: %.2f%%' % (total, error))\n plt.xlabel('Actual')\n plt.ylabel('Predicted')\n plt.grid(False)\n plt.tight_layout()\n plt.xticks(np.arange(num_class))\n plt.yticks(np.arange(num_class))\n plt.imshow(confusions, cmap=plt.cm.jet, interpolation='nearest');\n\n for i, cas in enumerate(confusions):\n for j, count in enumerate(cas):\n if count > 0:\n xoff = .07 * len(str(count))\n x = j - xoff\n y = i + .2\n plt.text(x, y, int(count), fontsize=14, color='white')\n\n plt.savefig(output, dpi=100)\n # plt.show()\n\n\ndef plot_confusion_matrix(cm, num_class, output_fig,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig = plt.figure()\n fig.set_size_inches(4, 4, forward=True)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n # plt.xticks(np.arange(len(num_class)), num_class, rotation=45)\n # plt.yticks(np.arange(len(num_class)), num_class)\n plt.xticks(np.arange(num_class))\n plt.yticks(np.arange(num_class))\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n #print(cm)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n # plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(output_fig, dpi=100)\n # plt.show()\n\n\ndef compute_scores(global_step, predicts, labels):\n y_pred = np.argmax(predicts, 1)\n y_true = np.argmax(labels, 1)\n accuracy = np.mean(np.equal(y_pred, y_true))\n #print(\"Accuracy: %.4f\" % accuracy) # validation\n precision = metrics.precision_score(y_true, y_pred)\n #print(\"Precision: %.4f\" % precision)\n recall = metrics.recall_score(y_true, y_pred)\n #print(\"Recall: %.4f\" % recall)\n f1_score = metrics.f1_score(y_true, y_pred)\n #print(\"F1_score %.4f\" % f1_score)\n # confusions = metrics.confusion_matrix(y_true, y_pred)\n #print(\"Confusion_matrix: \", confusions)\n corrects = np.sum(y_pred == y_true)\n total = predicts.shape[0]\n\n error = 100.0 - (100 * float(corrects) / float(total))\n result = (\"%d,%.4f,%.4f,%.4f,%.4f,%.4f\\n\" % (global_step, accuracy, precision, recall, f1_score, error))\n #fpr, tpr, tresholds = metrics.roc_curve(y_true, y_pred)\n #return confusions, precision, recall, f1_score\n return result\n\n\ndef evaluate(dataset, network, global_step=0):\n model = tflearn.DNN(network)\n # load model from specific checkpoint or the latest one.\n model.load(dataset.checkpoint(global_step))\n\n images, labels = dataset.X, dataset.Y\n\n # To avoid OOM, slice dataset into multiple pieces and then predict it.\n n_pieces = 6\n sliced_size = int(np.shape(images)[0] / n_pieces)\n p = []\n for i in range((n_pieces + 1)):\n p.append(model.predict(images[sliced_size*i:sliced_size*(i+1)]))\n predicted = np.concatenate(p, axis=0)\n predicted = np.asarray(predicted)\n\n # Compute scores\n confusions = confusion_matrix(predicted, labels, dataset.number_classes())\n scores = compute_scores(global_step, predicted, labels)\n\n return predicted, scores","sub_path":"models/model_factory.py","file_name":"model_factory.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302244287","text":"# -*- coding: utf-8 -*-\n###########################################################################################\n#\n# module name for Qdodoo suifeng\n# Copyright (C) 2015 qdodoo Technology CO.,LTD. ().\n#\n###########################################################################################\n\nfrom openerp import fields, models, api\nfrom openerp.osv import osv\nfrom openerp.tools.translate import _\nfrom datetime import timedelta, datetime\nimport logging\n\n_logger = logging.getLogger(__name__)\n\nclass qdodoo_car_information(models.Model):\n \"\"\"\n 车辆档案\n \"\"\"\n _name = 'qdodoo.car.information'\n _rec_name = 'product_num'\n\n product_id = fields.Many2one('product.product',u'车辆型号')\n product_num = fields.Char(u'车架号')\n sale_contract = fields.Many2one('qdodoo.car.sale.contract',u'销售合同号')\n currency_raise = fields.Float(u'保证金汇率', related='sale_contract.currency_raise')\n deposit_rate = fields.Float(u'保证金比例(%)', related='sale_contract.deposit_rate')\n end_remove_date = fields.Date(u'应赎车日期')\n end_issuing_end_date = fields.Date(u'应交车日期')\n contract_all_money = fields.Float(u'合同总金额', related=\"sale_contract.amount_total\")\n contract_all_car_money = fields.Float(u'预收款合计',related=\"sale_contract.all_car_money\")\n contract_is_issuing = fields.Boolean(u'已收保证金',related=\"sale_contract.is_issuing\")\n contract_is_make_invoice = fields.Boolean(u'全部已开票',related=\"sale_contract.is_make_invoice\")\n contract_is_payment = fields.Boolean(u'全部已收提车款',related=\"sale_contract.is_payment\")\n contract_is_settlement = fields.Boolean(u'已结算',related=\"sale_contract.is_settlement\")\n partner_id = fields.Many2one('res.partner',u'客户', related=\"sale_contract.partner_id\")\n car_num = fields.Float(u'车辆数', related=\"sale_contract.car_number\")\n car_balance = fields.Float(u'车辆余额', compute='_get_car_balance')\n is_delivery = fields.Boolean(u'应交付', compute='_get_car_balance')\n price_unit = fields.Float(u'销售合同价格')\n sale_price_new = fields.Float(u'赎车裸车价', digits=(16,2), compute='_get_sale_price_new')\n tax_money = fields.Float(u'销售合同税费')\n pledge_money = fields.Float(u'销售合同保证金')\n all_car_money = fields.Float(u'预收款',compute=\"_get_all_car_money\")\n agent_money = fields.Float(u'平台费')\n purchase_id = fields.Many2one('qdodoo.car.purchase.contract',u'外贸合同号')\n purchase_partner_id = fields.Many2one('res.partner',u'供应商', related=\"purchase_id.partner_id\")\n negotiation_id = fields.Many2one('qdodoo.car.negotiation.manager',u'押汇协议号')\n currency_id = fields.Many2one('res.currency',u'开证币种')\n purchase_currency_id = fields.Many2one('res.currency',u'外贸合同币种')\n issuing_money = fields.Float(u'开证金额')\n negotiation_exchange_rate = fields.Float(u'购汇汇率(银行)', digits=(16,6))\n negotiation_date = fields.Date(u'押汇日期')\n negotiation_end_date = fields.Date(u'押汇截止日期')\n negotiation_rate = fields.Float(u'押汇利率%(银行)')\n negotiation_interest = fields.Float(u'押汇利息(银行)', digits=(16,2))\n issuing_type = fields.Selection([('near',u'即期'),('long',u'90天远期')],u'信用证类型')\n bill_id = fields.Many2one('qdodoo.car.bill.lading',u'提单号')\n sale_price = fields.Float(u'进口裸车价', digits=(16,2))\n inspection_price = fields.Float(u'监装费')\n in_tax = fields.Float(u'进口关税')\n in_sale_tax = fields.Float(u'进口消费税')\n commodity_money = fields.Float(u'商检费')\n commodity_money_all = fields.Float(u'商检费用',compute='_get_commodity_money_all')\n product_money = fields.Float(u'货代费')\n stock_money = fields.Float(u'仓储费')\n other_money = fields.Float(u'其他', compute='_get_other_money')\n three_issure = fields.Float(u'三包险')\n ship_issure = fields.Float(u'海运险')\n ship_issure_new = fields.Float(u'海运险', compute='_get_sale_price_new', digits=(16,2))\n one_total = fields.Float(u'小计', compute=\"_get_one_total\")\n issuing_cost = fields.Float(u'开证费用')\n no_tax_price = fields.Float(u'不含税开票金额',compute=\"get_no_tax_price\", digits=(16,2))\n forwarding_add_tax = fields.Float(u'货代增值税')\n sale_tax = fields.Float(u'销项税',compute=\"get_no_tax_price\")\n add_tax = fields.Float(u'进口增值税')\n all_total = fields.Float(u'合计金额', compute=\"_get_all_total\")\n purchase_price = fields.Float(u'外贸合同价格')\n negotiation_money = fields.Float(u'押汇金额',related=\"purchase_price\")\n make_invoice = fields.Many2one('qdodoo.car.make.invoice',u'开票申请')\n invoice_date = fields.Date(u'开票日期', related='make_invoice.date')\n contract_date = fields.Date(u'销售合同日期')\n purchase_date = fields.Date(u'外贸合同日期')\n issuing_date = fields.Date(u'开证日期')\n source_location = fields.Many2one('stock.location',u'源库位')\n dest_location = fields.Many2one('stock.location',u'现库位')\n out_ship = fields.Date(u'离港日期')\n in_ship = fields.Date(u'到港日期')\n open_box = fields.Date(u'拆箱日期')\n in_stock = fields.Date(u'入库日期')\n out_stock = fields.Date(u'出库日期')\n wait_take = fields.Date(u'调拨出库日期')\n move_in_date = fields.Date(u'调拨入库日期')\n pad_tax_date = fields.Date(u'垫税日期')\n pad_tax_end_date = fields.Date(u'垫税截止日期')\n tax_price = fields.Float(u'开票价格', digits=(16,2),compute=\"get_no_tax_price\")\n settle_price = fields.Float(u'结算价格')\n pad_agent = fields.Float(u'垫税代理费')\n issuing_id = fields.Many2one('qdodoo.car.issuing.manager',u'信用证编号')\n pad_id = fields.Many2one('qdodoo.car.pad.tax',u'垫税协议号')\n tax_id = fields.Char(u'税单号')\n pad_money = fields.Float(u'垫税金额')\n pad_rate = fields.Float(u'垫税利率%')\n pad_interest = fields.Float(u'垫税利息', digits=(16,2))\n margin_id = fields.Many2one('qdodoo.car.margin.money',u'展车保证金')\n carry_id = fields.Many2one('qdodoo.car.carry.money',u'提车款')\n carry_money = fields.Float(u'提车款金额', digits=(16,2), compute='_get_carry_money')\n margin_money = fields.Float(u'展车保证金金额')\n negotiation_sale_id = fields.Many2one('qdodoo.car.negotiation.manager.sale',u'客户押汇协议号')\n negotiation_sale_exchange_rate = fields.Float(u'购汇汇率(客户)' , digits=(16,6))\n negotiation_sale_rate = fields.Float(u'押汇利率%(客户)')\n negotiation_sale_interest = fields.Float(u'押汇利息(客户)', digits=(16,2))\n clearance_money = fields.Float(u'清关费用', compute=\"_get_clearance_money\", digits=(16,2))\n all_issure = fields.Float(u'保险费', compute=\"_get_all_issure\")\n bank_money = fields.Float(u'银行手续费')\n logistics_money = fields.Float(u'物流费用', compute=\"_get_logistics_money\")\n delayed_moeny = fields.Float(u'滞报金')\n disinfection_moeny = fields.Float(u'消毒费')\n in_issuing_money = fields.Float(u'海关保证金')\n invoice_issuing_money = fields.Float(u'开证保证金')\n negotiation_over = fields.Boolean(u'结汇完成')\n dalay_date = fields.Float(u'提车天数', default='90')\n dalay_rate = fields.Float(u'延期利率(%)外币', default='4.5')\n real_price = fields.Float(u'车价')\n add_tax_money = fields.Float(u'增值额税金',compute=\"get_no_tax_price\")\n carry_date = fields.Date(u'赎车日期')\n tt_price = fields.Float(u'tt付款单价')\n forward_money = fields.Float(u'结转金额')\n carry_end_date = fields.Date(u'赎车收款日期')\n in_car_date = fields.Date(u'交车日期', compute='get_in_car_date')\n balance_pay = fields.Float(u'差额补收')\n taxation_price = fields.Float(u'征税价格')\n invoice_expense = fields.Float(u'开票费')\n report_id = fields.Many2one('qdodoo.car.stock.report',u'打印需要')\n carry_expense = fields.Float(u'提车款')\n is_in_report = fields.Boolean(u'已打印')\n is_out_report = fields.Boolean(u'已打印')\n is_carry_money = fields.Boolean(u'提车款已到账')\n stock_partner_id = fields.Many2one('res.partner',u'承运商')\n other_place_money = fields.Float(u'异地交车保证金')\n margin_date = fields.Date(u'展车出库日期')\n stock_age = fields.Integer(u'库龄(天)', compute='_get_stock_age')\n land_money = fields.Float(u'陆运费')\n land_money_new = fields.Float(u'陆运费',compute='_get_land_money_new')\n bank_expense = fields.Float(u'银行费用', compute='_get_bank_expense', digits=(16,2))\n other_payments_money = fields.Float(u'其他预收款')\n other_payments_money_all = fields.Float(u'其他', compute='_get_bank_expense')\n pad_money_raise = fields.Float(u'垫税比例(%)')\n product_type = fields.Char(u'车型')\n\n # 计算陆运费\n def _get_land_money_new(self):\n for ids in self:\n if ids.land_money:\n ids.land_money_new = 1500\n else:\n ids.land_money_new = 0\n\n # 计算赎车裸车价\n def _get_sale_price_new(self):\n for ids in self:\n ids.sale_price_new = ids.price_unit * ids.negotiation_sale_exchange_rate\n ids.ship_issure_new = ids.price_unit * (ids.currency_raise + 0.2) * 1.1 * 0.0007\n\n # 计算提车款金额(增值税税金+开证保证金+开证费用+异地交车保证金+展车保证金+三税+其他预收款)\n def _get_carry_money(self):\n for ids in self:\n ids.carry_money = ids.tax_price - ids.invoice_issuing_money - ids.issuing_cost - ids.other_place_money - ids.margin_money - ids.other_payments_money_all\n\n # 计算银行费用\n def _get_bank_expense(self):\n for ids in self:\n if ids.partner_id.bank_expense:\n ids.bank_expense = ids.sale_price_new * 0.0018 + ids.partner_id.bank_expense\n else:\n if ids.issuing_id and ids.issuing_id.car_num:\n ids.bank_expense = ids.sale_price_new * 0.0018 + 600/ids.issuing_id.car_num\n else:\n ids.bank_expense = 0\n ids.other_payments_money_all = (ids.in_tax + ids.in_sale_tax) * (1 - ids.pad_money_raise/100) + ids.other_payments_money\n\n # 计算库龄\n def _get_stock_age(self):\n for ids in self:\n if ids.in_stock:\n ids.stock_age = (datetime.now().date() - datetime.strptime(ids.in_stock,'%Y-%m-%d').date()).days\n else:\n ids.stock_age = 0\n\n # 计算车辆余额\n def _get_car_balance(self):\n for ids in self:\n ids.car_balance = ids.price_unit * ids.sale_contract.currency_raise * (1-ids.sale_contract.deposit_rate/100)\n if ids.contract_date and (fields.date.today() - datetime.strptime(ids.contract_date,'%Y-%m-%d').date()).days > 84 and not ids.pad_tax_date:\n ids.is_delivery = True\n else:\n ids.is_delivery = False\n\n # 计算商检费用(商检费+消毒费)\n def _get_commodity_money_all(self):\n for ids in self:\n ids.commodity_money_all = ids.commodity_money + ids.disinfection_moeny\n\n # 计算其他项\n def _get_other_money(self):\n for ids in self:\n if ids.delayed_moeny:\n ids.other_money = ids.delayed_moeny\n\n # 计算交车日期\n def get_in_car_date(self):\n for ids in self:\n if ids.carry_end_date and ids.sale_contract:\n ids.in_car_date = datetime.strptime(ids.carry_end_date,'%Y-%m-%d') + timedelta(days=ids.sale_contract.carry_end_date)\n\n # 计算清关费用\n def _get_clearance_money(self):\n for ids in self:\n ids.clearance_money = ids.product_money + ids.commodity_money_all\n\n # 计算开票明细合计金额\n def _get_all_total(self):\n for ids in self:\n ids.all_total = ids.no_tax_price + ids.sale_tax\n\n # 计算不含税开票金额\n def get_no_tax_price(self):\n for ids in self:\n ids.no_tax_price = ids.invoice_expense/1.17 + ids.one_total + ids.agent_money/1.17 + ids.pad_interest + ids.negotiation_sale_interest + ids.bank_expense\n ids.sale_tax = ids.no_tax_price*0.17\n ids.add_tax_money = ids.sale_tax - ids.add_tax - ids.forwarding_add_tax\n ids.tax_price = ids.no_tax_price*1.17\n\n # 计算物流费用\n def _get_logistics_money(self):\n for ids in self:\n ids.logistics_money = ids.disinfection_moeny + ids.stock_money + ids.product_money + ids.inspection_price\n\n # 计算保险费(三包险、海运险)\n def _get_all_issure(self):\n for ids in self:\n ids.all_issure = ids.three_issure + ids.ship_issure\n\n # 预收款(保证金、二次保证金、提车款)\n def _get_all_car_money(self):\n for ids in self:\n if ids.carry_id and ids.carry_id.state =='done':\n ids.all_car_money = ids.pledge_money + ids.margin_money + ids.carry_money + ids.agent_money + ids.forward_money + ids.balance_pay\n else:\n ids.all_car_money = ids.pledge_money + ids.margin_money + ids.agent_money + ids.forward_money + ids.balance_pay\n\n # 获取垫税金额\n def _get_pad_money(self):\n for ids in self:\n ids.pad_money = ids.in_tax + ids.in_sale_tax + ids.add_tax\n\n # 获取小计\n def _get_one_total(self):\n for ids in self:\n ids.one_total = ids.sale_price_new+ids.inspection_price+ids.in_tax+ids.in_sale_tax+ids.commodity_money_all+ids.product_money+ids.stock_money+ids.land_money_new+ids.three_issure+ids.ship_issure_new\n\n _sql_constraints = [\n ('product_num_uniq', 'unique(product_num)',\n '车架号已存在!'),\n ]\n\n # 判断车架号位数\n @api.model\n def create(self, vals):\n if vals.get('product_num') and len(vals.get('product_num')) != 17:\n raise osv.except_osv(_(u'警告'),_(u'车架号必须为17位!'))\n return super(qdodoo_car_information, self).create(vals)\n\n @api.multi\n def write(self, vals):\n if vals.get('product_num') and len(vals.get('product_num')) != 17:\n raise osv.except_osv(_(u'警告'),_(u'车架号必须为17位!'))\n # 获取相同销售合同的车辆档案\n car_ids = self.search([('id','!=',self.id),('sale_contract','=',self.sale_contract.id)])\n # 更新销售订单的全部已收提车款\n if vals.get('carry_id'):\n # 判断所有的车辆档案时候都已收提车款\n log = True\n for line in car_ids:\n if not line.carry_id:\n log = False\n if log:\n self.sale_contract.write({'is_payment':True})\n # 更新销售订单的全部已开票\n if vals.get('make_invoice'):\n # 判断所有的车辆档案全部已开票\n log = True\n for line in car_ids:\n if not line.make_invoice:\n log = False\n if log:\n self.sale_contract.write({'is_make_invoice':True})\n # 更新销售订单的已结算\n if vals.get('settle_price'):\n # 判断所有的车辆档案全部已开票\n log = True\n for line in car_ids:\n if not line.settle_price:\n log = False\n if log:\n self.sale_contract.write({'is_settlement':True,'state':'done'})\n # 获取相同外贸合同的车辆档案\n car_purchase_ids = self.search([('id','!=',self.id),('purchase_id','=',self.purchase_id.id)])\n # 更新外贸合同的已垫税\n if vals.get('pad_id'):\n # 判断所有的车辆档案全部已开票\n log = True\n for line in car_purchase_ids:\n if not line.pad_id:\n log = False\n if log:\n self.purchase_id.write({'is_tax':True})\n # 更新外贸合同的已开票\n if vals.get('make_invoice'):\n log = True\n for line in car_purchase_ids:\n if not line.make_invoice:\n log = False\n if log:\n self.purchase_id.write({'is_make_invoice':True})\n # 更新外贸合同的已押汇\n if vals.get('negotiation_id'):\n # 判断所有的车辆档案全部已开票\n log = True\n for line in car_purchase_ids:\n if not line.negotiation_id:\n log = False\n if log:\n self.purchase_id.write({'is_negotiation':True})\n # 更新外贸合同的已结汇\n if vals.get('negotiation_id'):\n # 判断所有的车辆档案全部已结汇\n log = True\n for line in car_purchase_ids:\n if not line.negotiation_id:\n log = False\n if log:\n self.purchase_id.write({'is_negotiation':True})\n # 更新外贸合同的已收提单\n if vals.get('bill_id'):\n # 判断所有的车辆档案全部已收提单\n log = True\n for line in car_purchase_ids:\n if not line.bill_id:\n log = False\n if log:\n self.purchase_id.write({'is_bill':True})\n # 更新提单的已到港状态\n if vals.get('in_ship'):\n # 判断提单所有车辆是否已到港\n log = True\n for line in self.bill_id.order_line:\n if line.information_id.id != self.id:\n if not line.information_id.in_ship:\n log = False\n self.bill_id.write({'is_on_shop':log})\n # 更新外贸合同的已结算\n if vals.get('settle_price'):\n # 判断所有的车辆档案全部已结算\n log = True\n for line in car_purchase_ids:\n if not line.settle_price:\n log = False\n if log:\n self.purchase_id.write({'is_settlement':True,'state':'done'})\n # 更新所有该外贸合同的垫税申请\n tax_ids = self.env['qdodoo.car.pad.tax'].search([('state','=','doing'),('purchase_id','=',self.purchase_id.id)])\n for tax_id in tax_ids:\n log = True\n for line in tax_id.order_line:\n if not line.pad_tax_end_date:\n log = False\n if log:\n tax_id.write({'state':'done'})\n else:\n raise osv.except_osv(_(u'错误'),_(u'垫税申请明细中缺少垫税截止日期!'))\n # 更新所有该外贸合同的银行押汇、客户押汇\n manager_ids = self.env['qdodoo.car.negotiation.manager'].search([('state','=','doing'),('purchase_id','=',self.purchase_id.id)])\n for manager_id in manager_ids:\n log = True\n for line in manager_id.order_line:\n if not line.product_num.negotiation_over or not line.negotiation_end_date:\n log = False\n if log:\n manager_id.write({'state':'done'})\n else:\n raise osv.except_osv(_(u'错误'),_(u'银行押汇明细中缺少到期日期!'))\n sale_ids = self.env['qdodoo.car.negotiation.manager.sale'].search([('state','=','draft'),('purchase_id','=',self.purchase_id.id)])\n for sale_id in sale_ids:\n log = True\n for line in sale_id.order_line:\n if not line.negotiation_end_date:\n log = False\n if log:\n sale_id.write({'state':'done'})\n else:\n raise osv.except_osv(_(u'错误'),_(u'客户押汇明细中缺少到期日期!'))\n return super(qdodoo_car_information, self).write(vals)\n\nclass qdodoo_product_template_inherit(models.Model):\n \"\"\"\n 在产品信息中增加属性\n \"\"\"\n\n _inherit = 'product.template'\n\n product_name_tfs = fields.Char(u'品名')\n product_type_name = fields.Char(u'型号')","sub_path":"qdodoo_car_import_trade/models/qdodoo_car_information.py","file_name":"qdodoo_car_information.py","file_ext":"py","file_size_in_byte":20587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372973809","text":"class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n import collections\n memo=collections.defaultdict(list)\n def pre(node,i):\n if not node:\n return\n memo[i].append(node)\n pre(node.left,i+1)\n pre(node.right,i+1)\n pre(root,0)\n ans=[]\n for i in memo:\n if i%2==0:\n ans.append(memo[i])\n else:\n ans.append((memo[i][::-1]))\n return ans","sub_path":"103.py","file_name":"103.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105878806","text":"# -*- coding: latin-1 -*-\n\n\nfrom copy import copy as shallow_copy\nfrom functools import reduce\n\n\ndebug = 0\nnmax = 16\n\ndef set_nmax(n):\n \"\"\"Sets *nmax* to the value *i*.\n\n The value nmax determines the number of childs per group (which\n should be between nmax/2 and nmax for efficient trees).\n \"\"\"\n global nmax\n if n % 4:\n raise ValueError(\"nmax must be a multiple of 4.\") \n nmax = n\n\n \nEMPTYSTYLE = {}\nstyle_pool = {():EMPTYSTYLE}\n\ndef hash_style(style):\n return tuple(sorted(style.items()))\n\n\ndef as_style(d):\n global style_pool\n key = hash_style(d)\n try:\n return style_pool[key]\n except KeyError:\n style_pool[key] = d\n return d\n\n\n# ---- Tree objects ----\nclass Texel:\n is_single = 0\n is_container = 0\n is_group = 0\n is_text = 0\n is_endmark = 0\n weights = (0, 0, 0) # depth, length, lineno\n\n\nclass Single(Texel):\n is_single = 1\n weights = (0, 1, 0)\n style = EMPTYSTYLE\n text = '-'\n\n def __init__(self, style=None):\n if style:\n self.style = style\n\n def set_style(self, style):\n clone = shallow_copy(self)\n clone.style = style\n return clone\n\n def __setstate__(self, state):\n self.__dict__ = state.copy()\n self.style = as_style(self.style)\n\n\nclass Text(Texel):\n is_text = 1\n def __init__(self, text, style=EMPTYSTYLE):\n self.text = text\n self.style = style\n self.weights = (0, len(text), 0)\n\n def __repr__(self):\n return \"T(%s)\" % repr(self.text)\n\n def set_style(self, style):\n clone = shallow_copy(self)\n clone.style = style\n return clone\n \n def __setstate__(self, state):\n self.__dict__ = state.copy()\n self.style = as_style(self.style)\n\nT = Text\n\n\nclass _TexelWithChilds(Texel):\n def compute_weights(self):\n if len(self.childs): # for empty groups, we use the default weights\n w_list = zip(*[child.weights for child in self.childs])\n self.weights = [f(l) for (l, f) in zip(w_list, self.functions)]\n\n\n\nclass Group(_TexelWithChilds):\n is_group = 1\n functions = (\n lambda l:max(l)+1, \n sum, \n sum)\n\n def __init__(self, childs):\n # NOTE: childs are assumed to be lists and not to change!\n # Since violations of these requirements can lead to difficult\n # to find bugs, we are making a copy of the list here,\n # although strictly this should not be necessary.\n self.childs = list(childs[:])\n self.compute_weights()\n\n def __repr__(self):\n return 'G(%s)' % repr(list(self.childs))\nG = Group\n\n\n\nclass Container(_TexelWithChilds):\n is_container = 1\n functions = (\n lambda l:0,\n sum, \n sum)\n \n def set_childs(self, childs):\n clone = shallow_copy(self)\n clone.childs = list(childs[:])\n clone.compute_weights()\n return clone\n\n def __repr__(self):\n return 'C(%s)' % repr(list(self.childs))\n\n def get_mutability(self):\n return [i%2==1 for i in range(len(self.childs))]\n\n \n\nclass NewLine(Single):\n weights = (0, 1, 1)\n style = EMPTYSTYLE\n parstyle = EMPTYSTYLE\n text = u'\\n'\n\n def __repr__(self):\n return 'NL'\n\n def set_parstyle(self, style):\n clone = shallow_copy(self)\n clone.parstyle = style\n return clone\n\n def __setstate__(self, state):\n self.__dict__ = state.copy()\n self.style = as_style(self.style)\n self.parstyle = as_style(self.parstyle)\n\n\nclass Tabulator(Single):\n text = u'\\t'\n\n def __repr__(self):\n return 'TAB'\n\n\nclass Fraction(Container):\n # A simple math object for debugging\n def __init__(self, denominator, nominator):\n self.childs = [TAB, denominator, TAB, nominator, TAB]\n self.compute_weights()\n \n\nTAB = Tabulator()\nNL = NewLine()\nENDMARK = NewLine()\nENDMARK.is_endmark = 1\nNULL_TEXEL = T(u'')\n\n# ---- functions -----\ndef depth(texel):\n \"\"\"Returns the depth of an element.\n\n The depth can be definied as the number of generations of\n groups. By definition empty groups have depth 0.\n\n >>> depth(Text('abc'))\n 0\n\n >>> depth(G(Text('abc')))\n 1\n\n >>> depth(G()) # empty groups are ignored\n 0\n \"\"\"\n return texel.weights[0]\n\n\ndef length(texel):\n \"\"\"Returns the length of *texel* in index units.\"\"\"\n return texel.weights[1]\n\n\ndef spans(texel):\n r = []\n mutable = texel.get_mutability()\n k = -1 \n for i1, i2, child in iter_childs(texel):\n k += 1\n if mutable[k]:\n r.append((i1, i2))\n return r\n\n\ndef iter_childs(texel):\n assert texel.is_group or texel.is_container\n i1 = 0\n for child in texel.childs:\n i2 = i1+length(child)\n yield i1, i2, child\n i1 = i2 \n\n\ndef iter_d0(texel): # not needed, but might be useful in future\n \"\"\"Iterate through all depth-zero elements. \"\"\"\n l = [[texel]]\n i1 = 0\n while l:\n ll = l[-1]\n elem = ll[0]\n del ll[0]\n if elem.is_group:\n l.append(list(elem.childs))\n else:\n i2 = i1+length(elem)\n yield i1, i2, elem\n while l and not l[-1]:\n l.pop()\n\n\ndef iter_leaves(texel): # not needed, but might be useful in future\n \"\"\"Iterate through all leaf-elements \"\"\"\n l = [[texel]]\n i1 = 0\n while 1:\n while l and not l[-1]:\n l.pop()\n if not l:\n break\n ll = l[-1]\n elem = ll[0]\n del ll[0]\n if elem.is_group or elem.is_container:\n l.append(list(elem.childs))\n else:\n i2 = i1+length(elem)\n yield i1, i2, elem\n i1 = i2\n\n\ndef groups(l):\n \"\"\"Transform the list of texels *l* into a list of groups.\n\n If texels have depth d, groups will have depth d+1. All\n returned groups are efficient.\n\n pre:\n is_elementlist(l)\n is_list_efficient(l)\n is_clean(l)\n\n post[l]:\n is_homogeneous(__return__)\n calc_length(l) == calc_length(__return__)\n #out(\"groups check: ok\")\n #is_list_efficient(__return__) # XXX\n depth(__return__[0]) == depth(l[0])+1\n\n \"\"\"\n r = []\n N = len(l)\n if N == 0:\n return r\n\n assert nmax % 4 == 0 # nmax must be multiple of 4\n s = 3*(nmax // 4)\n \n n = N // s\n rest = N % s\n assert N == rest+n*s\n\n if rest > n*(nmax-s):\n n += 1\n\n elif s < 2*rest:\n n += 1\n\n m = N // n\n t = N % n\n assert N == n*m+t\n \n i1 = 0\n for i in range(n-t):\n i2 = i1+m\n r.append(Group(l[i1:i2]))\n i1 = i2\n\n for i in range(t):\n i2 = i1+m+1\n r.append(Group(l[i1:i2]))\n i1 = i2\n\n assert i2 == len(l)\n return r\n\n\ndef _join(l1, l2):\n \"\"\"\n pre:\n is_homogeneous(l1)\n is_homogeneous(l2)\n is_clean(l1)\n is_clean(l2)\n post:\n is_clean(__return__)\n calc_length(l1)+calc_length(l2) == calc_length(__return__)\n \"\"\"\n l1 = list(filter(length, l1)) # strip off empty elements\n l2 = list(filter(length, l2)) #\n if not l1:\n return l2\n if not l2:\n return l1\n t1 = l1[-1]\n t2 = l2[0]\n d1 = depth(t1)\n d2 = depth(t2)\n if d1 == d2:\n return l1+l2\n elif d1 > d2:\n return l1[:-1]+groups(_join(t1.childs, l2))\n # d1 < d2\n return groups(_join(l1, t2.childs))+l2[1:]\n\n\ndef join(*args):\n \"\"\"Join several homogeneous lists of elements.\n\n The returned list is homogeneous.\n\n pre:\n forall(args, is_elementlist)\n forall(args, is_list_efficient)\n post[args]:\n is_homogeneous(__return__)\n is_clean(__return__)\n sum([calc_length(x) for x in args]) == calc_length(__return__)\n #out(\"join check: ok\")\n \"\"\"\n return reduce(_join, args)\n\n\ndef _fuse(l1, l2):\n \"\"\"\n pre:\n is_homogeneous(l1)\n is_homogeneous(l2)\n is_clean(l1)\n is_clean(l2)\n post:\n is_clean(__return__)\n is_homogeneous(l2)\n calc_length(l1)+calc_length(l2) == calc_length(__return__)\n \"\"\"\n l1 = list(filter(length, l1)) # strip off empty elements\n l2 = list(filter(length, l2)) #\n if not l1:\n return l2\n if not l2:\n return l1\n t1 = l1[-1]\n t2 = l2[0]\n left = get_rightmost(t1)\n right = get_leftmost(t2)\n if can_merge(left, right):\n new = merge(left, right)\n l1.pop()\n l1.append(exchange_rightmost(t1, new))\n return join(l1, remove_leftmost(t2), l2[1:])\n return _join(l1, l2)\n \n\ndef fuse(*args):\n \"\"\"Like join(...) but also merge the arguments if possible.\n\n The returned list is homogeneous.\n\n pre:\n forall(args, is_elementlist)\n forall(args, is_homogeneous)\n\n post[args]:\n is_homogeneous(__return__)\n is_clean(__return__)\n sum([calc_length(x) for x in args]) == calc_length(__return__)\n #out(\"join check: ok\")\n \"\"\"\n return reduce(_fuse, args)\n\n\ndef insert(texel, i, stuff):\n \"\"\"Inserts the list *stuff* at position *i*.\n\n *Texel* must be root-efficient, *stuff* must be\n list-efficient. Note that insert can increase the texels\n depth. The returned list is always list efficient.\n\n pre:\n isinstance(texel, Texel)\n is_elementlist(stuff)\n is_list_efficient(stuff)\n\n post:\n calc_length(__return__) == length(texel)+calc_length(stuff)\n is_list_efficient(__return__)\n is_clean(__return__)\n \"\"\"\n if not 0 <= i <= length(texel):\n raise IndexError(i)\n if texel.is_group:\n k = -1\n for i1, i2, child in iter_childs(texel):\n k += 1\n if i1 <= i <= i2:\n l = insert(child, i-i1, stuff)\n r1 = texel.childs[:k]\n r2 = texel.childs[k+1:]\n return join(r1, l, r2)\n elif texel.is_container:\n mutable = texel.get_mutability()\n k = -1\n for i1, i2, child in iter_childs(texel):\n k += 1\n if (i1 < i < i2) or ((i1 <= i <= i2) and mutable[k]):\n l = insert(child, i-i1, stuff)\n r1 = texel.childs[:k]\n r2 = texel.childs[k+1:]\n return [texel.set_childs(r1+[grouped(l)]+r2)]\n if i == 0:\n return join(stuff, [texel])\n elif i == length(texel):\n return join([texel], stuff)\n assert False\n\n return fuse(copy(texel, 0, i), stuff, copy(texel, i, length(texel)))\n\n\ndef takeout(texel, i1, i2):\n \"\"\"Takes out all content between *i1* and *i2*.\n\n Returns the outer rest and the inner cut out piece, i.e. G([a, b,\n c]).takeout(1, 2) will return G([a, c]), b.\n\n *Texel* must be root efficient. Kernel and rest are guaranteed to\n be list efficient. Depths can change.\n\n pre:\n is_root_efficient(texel)\n #out(texel, i1, i2)\n\n post:\n is_elementlist(__return__[0])\n is_elementlist(__return__[1])\n is_homogeneous(__return__[0])\n is_homogeneous(__return__[1])\n calc_length(__return__[0])+i2-i1 == length(texel)\n calc_length(__return__[1]) == i2-i1\n #out(\"takeout\", texel, i1, i2)\n #out(__return__[0])\n #out(__return__[1])\n #dump_list(__return__[0])\n is_clean(__return__[0])\n is_clean(__return__[1])\n is_list_efficient(__return__[0])\n is_list_efficient(__return__[1])\n\n \"\"\"\n if not (0 <= i1 <= i2 <= length(texel)): \n raise IndexError([i1, i2])\n if not length(texel): # 1. empty texel\n return [], []\n if i1 == i2: # 2. empty interval\n return strip2list(texel), []\n if i1 <= 0 and i2 >= length(texel): # 3. fully contained\n return [], strip2list(texel)\n\n # Note that singles always fall under case 2 or 3. Beyond ths\n # point we only have G, C or T.\n\n if texel.is_group:\n r1 = []; r2 = []; r3 = []; r4 = [] # outer rest\n k1 = []; k2 = []; k3 = [] # inner kernel\n for j1, j2, child in iter_childs(texel):\n # formal prove of if-conditions in notebook 26.08.2020\n # collecting parts can still be simplified, see same entry\n if j2 <= i1:\n r1.append(child)\n elif j1 < i1:\n r, k = takeout(child, max(i1-j1, 0), min(i2-j1, length(child)))\n r2.extend(r)\n k1.extend(k)\n elif j2 <= i2:\n k2.append(child)\n elif j1 < i2:\n r, k = takeout(child, max(i1-j1, 0), min(i2-j1, length(child)))\n r3.extend(r)\n k3.extend(k)\n else:\n r4.append(child)\n # Note that we are returning a list of elements which have\n # been in the content before. So even if texel is only root\n # efficient, the elements muss be element efficient. Each of\n # the list r1, r2, r3, r4 and k1, k2, k3 is\n # homogeneous. Therefore join gives us list efficient return\n # values.\n\n if debug:\n if not is_clean(r2):\n dump_list(r2)\n if not is_clean(r3):\n dump_list(r3)\n\n tmp = fuse(r2, r3)\n return join(r1, tmp, r4), join(k1, k2, k3)\n \n elif texel.is_container:\n for k, (j1, j2, child) in enumerate(iter_childs(texel)):\n if i1 < j2 and j1 < i2: # test of overlap\n if not (j1 <= i1 and i2 <= j2):\n raise IndexError((i1, i2))\n childs = list(texel.childs) # this always creates a new list!\n tmp, kernel = takeout(\n child, max(0, i1-j1), min(length(texel), i2-j1))\n childs[k] = grouped(tmp)\n return [texel.set_childs(childs)], kernel\n raise IndexError((i1, i2))\n\n elif texel.is_text:\n r = texel.text[:i1]\n s = texel.text[i1:i2]\n t = texel.text[i2:] \n style = texel.style\n return [Text(r+t, style)], [Text(s, style)]\n\n assert False\n\n\n \ndef checked_takeout(takeout):\n def checked(texel, i1, i2):\n assert is_root_efficient(texel)\n __return__ = takeout(texel, i1, i2)\n outer, inner = __return__\n\n assert is_elementlist(__return__[0])\n assert is_elementlist(__return__[1])\n assert is_homogeneous(__return__[0])\n assert is_homogeneous(__return__[1])\n try:\n assert calc_length(__return__[0])+i2-i1 == length(texel)\n except:\n \n print(calc_length(__return__[0])+i2-i1, length(texel))\n print(\"in:\", texel, i1, i2)\n print(\"outer:\", outer)\n print(\"inner:\", inner) \n raise\n assert calc_length(__return__[1]) == i2-i1\n #out(\"takeout\", texel, i1, i2)\n #out(__return__[0])\n #out(__return__[1])\n #dump_list(__return__[0])\n assert is_clean(__return__[0])\n assert is_clean(__return__[1])\n assert is_list_efficient(__return__[0])\n assert is_list_efficient(__return__[1])\n return __return__\n return checked\n\nif debug:\n takeout = checked_takeout(takeout)\n\n \ndef copy(root, i1, i2):\n \"\"\"Copy all content of *root* between *i1* and *i2*.\n\n pre:\n isinstance(root, Texel)\n\n post:\n calc_length(__return__) == (i2-i1)\n \"\"\"\n return takeout(root, i1, i2)[1]\n\n\ndef grouped(stuff):\n \"\"\"Creates a single group from the list of texels *stuff*.\n\n If the number of texels exceeds nmax, subgroups are formed.\n Therefore, the depth can increase. \n\n pre:\n is_elementlist(stuff)\n is_homogeneous(stuff)\n is_clean(stuff) \n \n post:\n length(__return__) == calc_length(stuff)\n \"\"\"\n while len(stuff) > nmax:\n stuff = groups(stuff)\n g = Group(stuff)\n return strip(g)\n\n\ndef strip(element):\n \"\"\"Removes unnecessary Group-elements from the root.\"\"\"\n n = length(element)\n while element.is_group and len(element.childs) == 1:\n element = element.childs[0]\n assert n == length(element)\n return element\n\n\ndef strip2list(texel):\n \"\"\"Returns a list of texels which is list efficient. \n pre:\n is_root_efficient(texel)\n post:\n is_list_efficient(__return__)\n \"\"\"\n if texel.is_group:\n return texel.childs\n return [texel]\n\n\ndef provides_childs(texel):\n \"\"\"Returns True if *texel* provides the childs_interface.\"\"\"\n return texel.is_group or texel.is_container\n\n\ndef get_rightmost(element):\n if provides_childs(element):\n return get_rightmost(element.childs[-1])\n return element\n\n\ndef get_leftmost(element):\n if provides_childs(element):\n return get_leftmost(element.childs[0])\n return element\n\n\ndef exchange_rightmost(element, new):\n \"\"\"Replace the rightmost subelement of *element* by *new*.\n\n pre:\n depth(new) == 0\n post:\n depth(__return__) == depth(element)\n \"\"\"\n if provides_childs(element):\n l = exchange_rightmost(element.childs[-1], new)\n return Group(element.childs[:-1]+[l])\n return new\n\n\ndef remove_leftmost(element):\n \"\"\"Removes the leftmost subelement of *element*. Returns a list.\n\n Note that this function can change the depth. \n\n post:\n is_homogeneous(__return__)\n is_list_efficient(__return__)\n \"\"\"\n\n if length(element) == 0 or depth(element) == 0:\n return []\n\n l = remove_leftmost(element.childs[0])\n return join(l, element.childs[1:])\n\n\ndef can_merge(texel1, texel2):\n return texel1.is_text and texel2.is_text and \\\n texel1.style is texel2.style\n\n\ndef merge(texel1, texel2):\n \"\"\"Merge the rightmost child of *texel1* with the leftmost child of\n*texel2*.\n\n pre:\n isinstance(texel1, Texel)\n isinstance(texel2, Texel)\n can_merge(texel1, texel2)\n\n post:\n length(__return__) == length(texel1)+length(texel2)\n \"\"\"\n return Text(texel1.text+texel2.text, texel1.style)\n\n\ndef compute_hull(texel, i1, i2, i0=0):\n if texel.is_text or texel.is_single:\n return i1, i2\n elif texel.is_container:\n overlapp = False\n for j1, j2 in spans(texel):\n if j1+i0 <= i1 <= i2 <= j2+i0: # inside\n overlapp = True\n continue\n if i1 < j2+i0 and j1+i0 < i2: # overlapp but not inside\n overlapp = True\n i1 = min(i1, j1+i0)\n i2 = max(i2, j2+i0)\n if not overlapp:\n i1 = min(i0, i1)\n i2 = max(i0+length(texel), i1)\n\n for j1, j2, child in iter_childs(texel):\n if j1+i0 <= i1 <= i2 <= j2+i0:\n i1, i2 = compute_hull(child, i1, i2, i0+j1)\n return i1, i2\n\n\ndef get_text(texel):\n if texel.is_single or texel.is_text:\n return texel.text\n assert texel.is_group or texel.is_container\n return u''.join([get_text(x) for x in texel.childs])\n\n\n# ---- Debug Tools ---\n\ndef get_pieces(texel):\n \"\"\"For debugging: returns a list of text pieces in *texel*.\"\"\"\n if type(texel) == list:\n texel = grouped(texel)\n if provides_childs(texel):\n r = []\n for child in texel.childs:\n r.extend(get_pieces(child))\n return r\n if texel.is_text:\n return [texel.text]\n return [' '] # Glyph\n\n\ndef calc_length(l):\n \"\"\"Calculates the total length of all elements in list *l*.\"\"\"\n return sum([length(x) for x in l])\n\n\ndef is_clean(l):\n \"\"\"Returns True if no element in list *l* has zero length. \"\"\"\n for texel in l: \n if length(texel) == 0:\n return False\n if texel.is_group:\n if not is_clean(texel.childs):\n return False\n return True\n \n\ndef is_homogeneous(l):\n \"\"\"Returns True if the elements in list *l* are homogeneous.\n\n Elements are homogeneous if they have alle the same depth.\n \"\"\"\n return maxdepth(l) == mindepth(l)\n\n\ndef is_efficient(element):\n \"\"\"Returns True if *element* is efficient.\n\n An element is efficient, if it is not a group or otherwise if\n all of the following criteria are fulfilled:\n\n 1. if each descendant group has between nmax/2 and nmax childs\n 2. the depth of all childs is homogeneous\n\n In an efficient tree all groups (with the exception of the root\n node) must be element_efficient.\n\n Note: this function is very slow and should only be used for\n debugging.\n \"\"\"\n if not is_group(element):\n return True\n if not is_homogeneous(element.childs):\n return False\n if len(element.childs) < nmax/2 or len(element.childs) > nmax:\n return False\n if not is_list_efficient(element.childs):\n return False\n return True\n\n\ndef is_list_efficient(l):\n \"\"\"Returns True if each element in the list *l* is efficient.\n pre:\n isinstance(l, list)\n \"\"\"\n if not is_homogeneous(l):\n return False\n for element in l:\n if not is_efficient(element):\n return False\n return True\n\n\ndef is_root_efficient(root):\n \"\"\"Returns True if *root* is efficient.\n\n The tree spawned by *root* is efficient if it is either not a\n group or otherwise if it fulfills all of the following\n conditions:\n\n 1. all childs are efficient\n 2. the number of childs is <= nmax\n\n Note: this function is very slow and should only be used for\n debugging.\n \"\"\"\n if not is_group(root):\n return True\n if len(root.childs) > nmax:\n return False\n return is_list_efficient(root.childs)\n\n\ndef is_group(element):\n return element.is_group\n\n\ndef is_elementlist(l):\n \"\"\"Returns True if *l* is a list of Elements.\n \"\"\"\n if not type(l) in (tuple, list):\n print(\"not a list or tuple\", type(l), l.__class__) # XXX remove this\n return False\n return not False in [isinstance(x, Texel) for x in l]\n\n\ndef maxdepth(l):\n \"\"\"Computes the maximal depth of all elements in list *l*.\n \"\"\"\n m = [depth(x) for x in l if length(x)]\n if not m:\n return 0\n return max(m)\n\n\ndef mindepth(l):\n \"\"\"Computes the minimal depth of all elements in list *l*.\n \"\"\"\n m = [depth(x) for x in l if length(x)]\n if not m:\n return 0\n return min(m)\n\n\ndef out(*args):\n print(repr(args)[1:-1])\n return True\n\n\ndef dump(texel, i=0):\n print((\" \"*i)+str(texel.__class__.__name__), texel.weights, end=' ')\n if texel.is_text:\n print(repr(texel.text), texel.style)\n elif isinstance(texel, NewLine):\n print(texel.parstyle)\n else:\n print()\n if texel.is_group or texel.is_container:\n for i1, i2, child in iter_childs(texel):\n dump(child, i+2)\n return True\n\n\ndef dump_list(l):\n print(\"Dumping list (efficient: %s)\" % is_list_efficient(l))\n for i, element in enumerate(l):\n print (\"Dumping element no. %i\" % i, end=' ')\n print (\"(efficient: %s)\" % is_efficient(element))\n dump(element)\n return True\n\n\n# ---- Testing ----\n\nif 0 and debug: # enable contract checking\n import contract\n contract.checkmod(__name__)\n\n\ndef test_00():\n \"insert\"\n set_nmax(4)\n s = G([T('1'), T('2'), T('3')])\n element = G([s, s, s])\n\n tmp = grouped(insert(element, 3, [T('X'), T('Y')]))\n assert depth(tmp) == depth(element)\n assert get_pieces(tmp) == ['1', '2', '3X', 'Y', '1', '2', '3', '1', '2', '3']\n\n tmp = insert(element, 3, [G([T('X'), T('Y')])])\n assert depth(grouped(tmp)) == depth(element)\n assert get_pieces(tmp) == ['1', '2', '3X', 'Y', '1', '2', '3', '1', '2', '3']\n\n\ndef test_01():\n \"growth in insert\"\n set_nmax(4)\n g = Group([T(\"a\"), T(\"b\"), T(\"c\")])\n assert depth(g) == 1\n assert get_pieces(g) == ['a', 'b', 'c']\n n = grouped(insert(g, 0, [T(\"d\")]))\n assert get_pieces(n) == ['da', 'b', 'c']\n\n\ndef test_02():\n \"maintaining tree efficency in insert / takeout\"\n set_nmax(4)\n texel = Group([])\n import random\n for i in range(100):\n x = random.choice(\"abcdefghijklmnopqrstuvwxyz\")\n tmp = insert(texel, i, [Text(x)])\n assert is_list_efficient(tmp)\n texel = grouped(tmp)\n assert is_root_efficient(texel)\n #dump(texel)\n\n while length(texel):\n i1 = random.randrange(length(texel)+1)\n i2 = random.randrange(length(texel)+1)\n i1, i2 = sorted([i1, i2])\n r, k = takeout(texel, i1, i2)\n assert is_list_efficient(r)\n texel = grouped(r)\n assert is_root_efficient(texel)\n\n\ndef test_03():\n \"depth\"\n assert depth(Text('abc')) == 0\n assert depth(G([Text('abc')])) == 1\n assert depth(G([])) == 0\n element = G([G([G([T('1'), T('2')]), G([T('3')])])])\n assert depth(element) == 3\n\n\ndef test_04():\n \"fuse\"\n l1 = [T(\"01234\")]\n l2 = [T(\"56789\")]\n t = fuse([G(l1)], l2)\n assert get_pieces(t) == ['0123456789']\n\n t = fuse([G(l1)], [G(l2)])\n assert get_pieces(t) == ['0123456789']\n\n t = fuse(l1, [G(l2)])\n assert get_pieces(t) == ['0123456789']\n\n\ndef test_05():\n \"iter_d0\"\n t1 = T(\"012345678\")\n t2 = T(\"ABC\")\n t3 = T(\"xyz\")\n c = Container().set_childs((t2, t3))\n g = G((t1, c))\n #texeltree.dump(g)\n l = []\n for i1, i2, elem in iter_d0(g):\n l.append((i1, i2, elem))\n assert repr(l) == \"[(0, 9, T('012345678')), (0, 6, C([T('ABC'), T('xyz')]))]\"\n \n\ndef test_06():\n \"insert in container\"\n fraction = Fraction(T(\"Sin(alpha)\"), T(\"Cos(alpha)\"))\n t = T(\"X\") #, dict(color='red'))\n l = insert(fraction, 0, [t])\n assert get_pieces(grouped(l)) == ['X', ' ', 'Sin(alpha)', ' ', 'Cos(alpha)', ' ']\n l = insert(fraction, 1, [t])\n assert get_pieces(grouped(l)) == [' ', 'XSin(alpha)', ' ', 'Cos(alpha)', ' ']\n l = insert(fraction, 2, [t])\n assert get_pieces(grouped(l)) == [' ', 'SXin(alpha)', ' ', 'Cos(alpha)', ' ']\n l = insert(fraction, 11, [t])\n assert get_pieces(grouped(l)) == [' ', 'Sin(alpha)X', ' ', 'Cos(alpha)', ' ']\n l = insert(fraction, 12, [t])\n assert get_pieces(grouped(l)) == [' ', 'Sin(alpha)', ' ', 'XCos(alpha)', ' ']\n l = insert(fraction, 22, [t])\n assert get_pieces(grouped(l)) == [' ', 'Sin(alpha)', ' ', 'Cos(alpha)X', ' ']\n l = insert(fraction, 23, [t])\n assert get_pieces(grouped(l)) == [' ', 'Sin(alpha)', ' ', 'Cos(alpha)', ' ', 'X']\n\n elem = fraction\n text = \"0123456789\"\n for i in range(len(text)):\n tmp = insert(elem, 12, [T(text[i])])\n elem = grouped(tmp)\n assert get_pieces(elem) == [' ', 'Sin(alpha)', ' ', '9876543210Cos(alpha)', ' ']\n\n fraction = Fraction(T(\"\"), T(\"Cos(alpha)\"))\n l = insert(fraction, 0, [t])\n assert get_pieces(grouped(l)) == ['X', ' ', '', ' ', 'Cos(alpha)', ' ']\n\n l = insert(fraction, 1, [t])\n assert get_pieces(grouped(l)) == [' ', 'X', ' ', 'Cos(alpha)', ' ']\n\n l = insert(fraction, 2, [t])\n assert get_pieces(grouped(l)) == [' ', '', ' ', 'XCos(alpha)', ' ']\n\n\ndef test_07():\n \"compute_hull\"\n fraction = Fraction(T(\"Sin(alpha)\"), T(\"Cos(alpha)\"))\n n = length(fraction)\n assert compute_hull(fraction, 0, 1) == (0, n)\n assert compute_hull(fraction, 1, 2) == (1, 2)\n assert compute_hull(fraction, 2, 3) == (2, 3)\n assert compute_hull(fraction, 9, 11) == (9, 11)\n assert compute_hull(fraction, 11, 12) == (0, n)\n assert compute_hull(fraction, n-2, n-1) == (n-2, n-1)\n assert compute_hull(fraction, n-1, n) == (0, n)\n\n\ndef test_08():\n \"takeout\"\n s1 = as_style(dict(color='red'))\n s2 = as_style(dict(color='blue'))\n t1 = T(\"0123456789\", style=s1)\n t2 = T(\"ABC\", style=s2)\n g = G((t1, t2))\n r, k = takeout(g, 5, 12) \n assert get_text(grouped(r)) == \"01234C\"\n assert get_text(grouped(k)) == \"56789AB\"\n\n t1 = T(\"0123456789\")\n t2 = T(\"ABC\")\n g = G((t1, t2)) \n r, k = takeout(g, 5, 12)\n assert get_pieces(grouped(r)) == ['01234C']\n assert get_text(grouped(k)) == \"56789AB\"\n\n \ndef test_09():\n \"pickle\"\n s1 = as_style(dict(color='red'))\n s2 = as_style(dict(color='blue'))\n t1 = T(\"012345678\", style=s1)\n t2 = T(\"ABC\", style=s2)\n g = G((t1, t2))\n from pickle import dumps, loads \n t1_ = loads(dumps(t1))\n assert t1.style is t1_.style\n assert t1.text == t1_.text \n g_ = loads(dumps(g))\n t1_, t2_ = g_.childs\n assert not t1_ is t1\n assert not t2_ is t2\n assert t1.style is t1_.style\n assert t2.style is t2_.style\n assert t1.text == t1_.text \n assert t2.text == t2_.text \n\n\ndef test_10():\n \"set_style\"\n s1 = as_style(dict(color='red'))\n s2 = as_style(dict(color='blue'))\n t1 = T(\"012345678\", style=s1)\n t2 = t1.set_style(s2)\n assert t1.style == dict(color='red')\n assert t2.style == dict(color='blue')\n\n\ndef test_11():\n \"set_parstyle\"\n s1 = as_style(dict(base='h1'))\n s2 = as_style(dict(base='h2'))\n nl1 = NL.set_parstyle(s1)\n nl2 = NL.set_parstyle(s2)\n print(NL.parstyle)\n assert NL.parstyle == dict()\n assert nl1.parstyle == dict(base='h1')\n assert nl2.parstyle == dict(base='h2')\n\n\n","sub_path":"textmodel/textmodel/texeltree.py","file_name":"texeltree.py","file_ext":"py","file_size_in_byte":29304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112082104","text":"import unittest\n\nfrom learn.DB.MySqlResultInfo import PyResultDetail\nfrom learn.DB.PyResultDao import ResultInfoDao, ResultDetailDao\n\n\nclass TestResultDetailDao(unittest.TestCase):\n def setUp(self):\n self.resultDetailDao = ResultDetailDao(\"10.125.49.161\", \"dbtestdev\", \"Dbtestdev123\", \"dbtestdev\")\n print('setUp...')\n\n def tearDown(self):\n print('tearDown...')\n\n def test_insert(self):\n pyResultDetail = PyResultDetail()\n pyResultDetail.object_id = 2\n pyResultDetail.tool_name = 'archiveChecker'\n pyResultDetail.module_name = 'ctu'\n pyResultDetail.is_success = 'N'\n pyResultDetail.reason = 'failed because of module not merged.'\n\n dt = self.resultDetailDao.insert(pyResultDetail)\n result = self.resultDetailDao.get_result(pyResultDetail.object_id)\n print('-------------\\n', result)\n\n self.assertEqual(pyResultDetail.object_id, result.object_id)\n self.assertEqual(pyResultDetail.tool_name, result.tool_name)\n self.assertEqual(pyResultDetail.module_name, result.module_name)\n self.assertEqual(pyResultDetail.is_success, result.is_success)\n self.assertEqual(pyResultDetail.reason, result.reason)\n\n\n def test_update(self):\n info = PyResultDetail()\n info.object_id = 1\n info.tool_name = 'ArchiveChecker'\n info.module_name = 'ISERVER'\n info.is_success = 'N'\n info.reason = 'failed because of module not merged.'\n\n ID = 1\n result_before = self.resultDetailDao.get_result(ID)\n print('------result_before-------\\n', result_before)\n dt = self.resultDetailDao.update(ID, info)\n result_after = self.resultDetailDao.get_result(ID)\n print('------result_after-------\\n', result_after)\n\n self.assertIsNotNone(result_before)\n self.assertIsNotNone(result_after)\n\n self.assertEqual(info.object_id, result_after.object_id)\n self.assertEqual(info.tool_name, result_after.tool_name)\n self.assertEqual(info.module_name, result_after.module_name)\n self.assertEqual(info.is_success, result_after.is_success)\n self.assertEqual(info.reason, result_after.reason)\n\n\n\n def test_delete(self):\n info = PyResultDetail()\n info.object_id = 100\n info.tool_name = 'BranchChecker'\n info.module_name = 'cgw'\n info.is_success = 'N'\n info.reason = 'failed because of module not merged.'\n\n dt = self.resultDetailDao.insert(info)\n result_before = self.resultDetailDao.get_result(info.object_id)\n print('-------------\\n', result_before)\n self.assertIsNotNone(result_before)\n\n self.resultDetailDao.delete(info.object_id)\n result_after = self.resultDetailDao.get_result(info.object_id)\n self.assertIsNone(result_after)\n\n\n\n\n\n\n# 主运行入口\nif __name__ == '__main__':\n unittest.main()","sub_path":"learn/DB/ut/PyResultDetailDaoTest.py","file_name":"PyResultDetailDaoTest.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"277011809","text":"# -*- coding:utf-8 -*-\n\"\"\"\n实现添加目录,或者文件自动产生UUID和文件,保证xcode稳定运行\n\"\"\"\n\nimport os\nimport re\n\n# 1/* Begin PBXBuildFile section */ 下的.m 文件或者.png 4E8A9ADF2395FDC50067317C>4E8A9A4B2395FDC50067317C\nBASE_PBXBuildFile_SECTION = \"\t\t{uuid} /* {file_name} in {sources} */ = {{isa = PBXBuildFile; fileRef = \" \\\n \"{ref_uuid} /* {file_name} */; }};\\n\"\n\n# 2/* Begin PBXFileReference section */ 包含.png, .h, .m文件\n# 2.1 如果为图片:\n# 4E8A99E42395FDC50067317C /* FeeConsent@3x.png */ = {isa = PBXFileReference;\n# lastKnownFileType = image.png; path = \"FeeConsent@3x.png\"; sourceTree = \"\"; };\n\n# 4E8A99F72395FDC50067317C /* KWZQBaHeHeTool.h */ = {isa = PBXFileReference;\n# fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KWZQBaHeHeTool.h; sourceTree = \"\"; };\n\n# 4E8A99F82395FDC50067317C /* KWZQBaHeHeTool.m */ = {isa = PBXFileReference;\n# fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = KWZQBaHeHeTool.m; sourceTree = \"\"; };\n\nBASE_PBXFileReference_SECTION_PIC = '\t\t{ref_uuid} /* {file_name} */ = ' \\\n '{{isa = PBXFileReference; lastKnownFileType = image.png; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\n\nBASE_PBXFileReference_SECTION_H = '\t\t{ref_uuid} /* {file_name} */ = {{isa = PBXFileReference;' \\\n ' fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\n\nBASE_PBXFileReference_SECTION_M = '\t\t{ref_uuid} /* {file_name} */ = {{isa = PBXFileReference;' \\\n ' fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\n\nBASE_PBXFileReference_SECTION_XIB = '\t\t{ref_uuid} /* {file_name} */ = {{isa = PBXFileReference;' \\\n ' fileEncoding = 4; lastKnownFileType = file.xib; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\n\nBASE_PBXFileReference_SECTION_C = '\t\t{ref_uuid} /* {file_name} */ = {{isa = PBXFileReference;' \\\n ' fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\nBASE_PBXFileReference_SECTION_MM = '\t\t{ref_uuid} /* {file_name} */ = {{isa = PBXFileReference;' \\\n ' fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = \"{file_name}\"; ' \\\n 'sourceTree = \"\"; }};\\n'\n# 3. /* Begin PBXGroup section */\nBASE_PBXGroup_SECTION_ALONE = '\t\t\t\t{ref_uuid} /* {file_name} */,\\n'\nBASE_PBXGroup_SECTION_DIR = \"\"\"\n\t\t{dir_uuid} /* {dir_name} */ = {{\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t);\n\t\t\tpath = {dir_name_};\n\t\t\tsourceTree = \"\";\n\t\t}};\n\"\"\"\nBASE_PBXGroup_SECTION_PATTERN = re.compile(r'/\\* End PBXGroup section \\*/')\n\n# 4. /* Begin PBXSources|Resources BuildPhase section */ 该部分包括Sources(.m文件) 和 Resources(.xib,.png文件) 两部分资源\nBASE_PBXBuildPhase_SECTION = '\t\t\t\t{uuid} /* {file_name} in {source} */,\\n'\n\nBASE_PBXResourceBuildPhase_SECTION_PATTERN = re.compile(\n r'\\s*\\w+\\s*/\\* Resources \\*/ = {\\s*isa = PBXResourcesBuildPhase;.*?files = \\(.*?\\);', re.S)\n\nBASE_PBXSourceBuildPhase_SECTION_PATTERN = re.compile(\n r'\\s*\\w+\\s*/\\* Sources \\*/ = {\\s*isa = PBXSourcesBuildPhase;.*?files = \\(.*?\\);', re.S)\n\nNAME_ = 'project.pbxproj'\nBASE_PBXBuildFile_SECTION_PATTERN = re.compile(r'/\\* End PBXBuildFile section \\*/')\nBASE_PBXFileReference_SECTION_PATTERN = re.compile(r'/\\* End PBXFileReference section \\*/')\n\nSUFFIX_MAP = {\n '.png': BASE_PBXFileReference_SECTION_PIC,\n '.h': BASE_PBXFileReference_SECTION_H,\n '.m': BASE_PBXFileReference_SECTION_M,\n '.c': BASE_PBXFileReference_SECTION_C,\n '.xib': BASE_PBXFileReference_SECTION_XIB,\n '.mm': BASE_PBXFileReference_SECTION_MM\n}\nSOURCE_MAP = {\n '.png': 'Resources',\n '.xib': 'Resources',\n '.m': 'Sources',\n '.mm': 'Sources',\n '.c': 'Sources',\n}\n\n\ndef check_chinese(word):\n return re.compile(r'[\\u4e00-\\u9fa5]+').findall(word)\n\n\ndef get_uuid_and_dir(path, dir_, name):\n list_ = dir_.split('\\\\')\n usefull_list = None\n for i, v in enumerate(list_):\n if v == name:\n usefull_list = list_[i:]\n break\n with open(path, 'r', encoding='utf-8') as f:\n data = f.read()\n # 找到首个uuid\n uuid = ''\n # print('name:', name)\n\n for index, dir_name in enumerate(usefull_list):\n # print(\"dir_name:\", dir_name,\"index:\",index)\n if index == 1:\n # if index == 0:\n pattern_first = re.compile(\n r'\\s*(\\w+)\\s*/\\* {} \\*/ = {{\\s*isa = PBXGroup;\\s*children = \\(.*?\\);'.format(re.escape(dir_name)),\n re.S)\n # print(\"pattern_first:\", pattern_first)\n # uuid = pattern_first.findall(data)[0]\n res = pattern_first.findall(data)\n if res:\n uuid = res[0]\n # str_ = pattern_first.findall(data)[1]\n\n pattern_parent = re.compile(\n r'\\s*{uuid}\\s*/\\* {dir_name} \\*/ = {{\\s*isa = PBXGroup;\\s*children = \\((.*?)\\);'.format(uuid=uuid,\n dir_name=re.escape(\n dir_name)),\n re.S)\n print(\"pattern_parent:\", pattern_parent)\n str_ = pattern_parent.findall(data)[0]\n # print('str_:', str_)\n number = index + 1\n if number <= len(usefull_list) - 1:\n res = re.compile(\n r'(\\w+) /\\* {sub_name} \\*/,'.format(sub_name=re.escape(usefull_list[index + 1]))).findall(str_)\n if res:\n uuid = res[0]\n # print('uuid', uuid)\n return uuid\n\n\n# 获取工程中KWGameJTK.xcodeproj的KWGameJTK工程名\ndef get_parent_name(path):\n for parent, dirs, files in os.walk(path):\n for dir_ in dirs:\n name, ext = os.path.splitext(dir_)\n if '.xcodeproj' == ext:\n return name\ndef get_parent_path(path):\n for parent, dirs, files in os.walk(path):\n for dir_ in dirs:\n name, ext = os.path.splitext(dir_)\n if '.xcodeproj' == ext:\n return os.path.join(parent,name)\n\n# project.pbxproj 找到project.pbxproj的绝对路径\ndef get_project_pbxproj_path(path):\n for parent, _, files in os.walk(path):\n for file_name in files:\n if file_name == NAME_:\n return os.path.join(parent, file_name)\n\n\n# 生成create_BASE_PBXFileReference_SECTION\ndef create_BASE_PBXFileReference_SECTION(file_name, ref_uuid, model_str):\n return model_str.format(file_name=file_name, ref_uuid=ref_uuid)\n\n\nclass XcodeGenerator:\n\n def __init__(self, path):\n self.path = path\n self.project_path = get_project_pbxproj_path(path)\n self.parent_name = get_parent_name(path)\n self.set_ = None\n self.find_old_uuid()\n self.count = 0\n\n # 1.找到最大UUID(24位),找出其中需要修改的部分,每次经行+1生成新的UUID\n def uuid_generator(self):\n def dec_hex(str1): # 十转十六\n a = str(hex(eval(str1)))\n # print('十进制: %s 转换成 十六进制为:%s' % (str1, a))\n return a\n\n def hex_dec(str2): # 十六转十\n b = eval(str2)\n # print('十六进制: %s 转换成十进制为:%s:' % (str2, b))\n return b\n\n head_, ext_ = None, None\n for i, (k, v) in enumerate(zip(self.set_[-1], self.set_[-2])):\n if k != v:\n head_, ext_ = self.set_[-1][:i + 1], self.set_[-1][i + 1:]\n break\n one = int(hex_dec('0x{}'.format(head_))) + int(self.count + 1)\n self.count += 1\n hex_ = dec_hex(str(one)).upper()[2:] + ext_\n if len(hex_) != 24:\n hex_ = '0' + hex_\n return hex_\n\n # 找到工程中最大UUID值\n def find_old_uuid(self):\n pattern_ = re.compile(r'[A-Z0-9]{24}')\n # pattern_one = re.compile(r'/\\* Begin PBXBuildFile section \\*/(.*?)/\\* End PBXBuildFile section \\*/', re.S)\n # print(\"self.project_path:\", self.project_path)\n with open(self.project_path, 'r', encoding='utf-8') as f:\n data = f.read()\n res = pattern_.findall(data)\n if res:\n self.set_ = sorted(set(res))\n print('最大uuid:', self.set_[-1])\n return self.set_\n\n # ********************************功能*****************************************\n # 2. 在某个目录下添加文件(在工程和配置文件)\n def create_files(self, dir_path, fileNames):\n \"\"\"\n\n :param dir_path:要添加到工程的目录\n :param fileNames:上述dir_path下的文件\n :return:\n \"\"\"\n if not os.path.exists(dir_path):\n raise IOError('No such path, Can not insert files')\n _, dst_pbxgroup = os.path.split(dir_path)\n # print('dst_pbxgroup:', dst_pbxgroup)\n uuid = get_uuid_and_dir(self.project_path, dir_path, self.parent_name)\n all_str = {}\n BASE_PBXBuildFile_SECTION_STR = ''\n BASE_PBXFileReference_SECTION_STR = ''\n BASE_PBXGroup_SECTION_ALONE_STR = ''\n BASE_PBXSourceBuildPhase_SECTION_STR = ''\n BASE_PBXResourceBuildPhase_SECTION_STR = ''\n BASE_PBXGroup_SECTION_ALONE_PATTERN = re.compile(\n r'\\s*%s\\s*/\\* %s \\*/ = {\\s*isa = PBXGroup;\\s*children = \\(.*?\\);' % (uuid, re.escape(dst_pbxgroup)), re.S)\n\n for file_name in fileNames:\n name, f_type = os.path.splitext(file_name)\n ref_uuid = None\n uuid = None\n\n if f_type in ('.m', '.png', '.xib', '.c', '.mm'):\n PBXBuildFile_Str, uuid, ref_uuid = self.create_BASE_PBXBuildFile_SECTION(file_name, f_type)\n BASE_PBXBuildFile_SECTION_STR += PBXBuildFile_Str\n\n if f_type in SUFFIX_MAP: # 根据文件后缀选择相应模版\n if not ref_uuid:\n ref_uuid = self.uuid_generator()\n BASE_PBXFileReference_SECTION_STR += create_BASE_PBXFileReference_SECTION(file_name, ref_uuid,\n SUFFIX_MAP[f_type])\n\n # 插入Begin PBXGroup section 部分\n BASE_PBXGroup_SECTION_ALONE_STR += BASE_PBXGroup_SECTION_ALONE.format(ref_uuid=ref_uuid,\n file_name=file_name)\n # 插入 Begin PBXSources|Resources BuildPhase section 部分\n if f_type in SOURCE_MAP:\n\n # uuid = uuid if uuid else self.uuid_generator()\n if f_type in ('.png', '.xib'):\n BASE_PBXResourceBuildPhase_SECTION_STR += BASE_PBXBuildPhase_SECTION.format(\n uuid=uuid, file_name=file_name, source=SOURCE_MAP[f_type])\n else:\n # print('f_type:', f_type)\n BASE_PBXSourceBuildPhase_SECTION_STR += BASE_PBXBuildPhase_SECTION.format(\n uuid=uuid, file_name=file_name, source=SOURCE_MAP[f_type])\n\n if BASE_PBXResourceBuildPhase_SECTION_STR:\n self.write_source(BASE_PBXResourceBuildPhase_SECTION_PATTERN, BASE_PBXResourceBuildPhase_SECTION_STR)\n\n if BASE_PBXSourceBuildPhase_SECTION_STR:\n self.write_source(BASE_PBXSourceBuildPhase_SECTION_PATTERN, BASE_PBXSourceBuildPhase_SECTION_STR)\n\n if BASE_PBXGroup_SECTION_ALONE_STR:\n self.write_source(BASE_PBXGroup_SECTION_ALONE_PATTERN, BASE_PBXGroup_SECTION_ALONE_STR)\n\n all_str[BASE_PBXBuildFile_SECTION_STR] = BASE_PBXBuildFile_SECTION_PATTERN\n all_str[BASE_PBXFileReference_SECTION_STR] = BASE_PBXFileReference_SECTION_PATTERN\n for str_, pattern_ in all_str.items():\n self.insert_str_to_project(str_, pattern_)\n\n # 3. 在某个目录下插入文件夹\n def create_dir(self, dir_path):\n file_list = []\n dir_list = []\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n file_names = os.listdir(dir_path)\n\n # 父级的文件名\n father, name = os.path.split(dir_path)\n _, father_name = os.path.split(father)\n # 用uuid来匹配要插入的段落\n uuid = get_uuid_and_dir(self.project_path, father, self.parent_name)\n # print('father_name:', father_name, 'name:', name)\n\n BASE_PBXGroup_SECTION_DIR_PATTERN = re.compile(\n r'\\s*{uuid}\\s*/\\* {father_name} \\*/ = {{\\s*isa = PBXGroup;\\s*children = \\(.*?\\);'.format(\n uuid=uuid, father_name=father_name), re.S)\n # 在父级目录下插入子目录名,例如:4E8A9A502395FDC50067317C /* 单例 */,\n dir_uuid = self.uuid_generator()\n father_sub_str = BASE_PBXGroup_SECTION_ALONE.format(ref_uuid=dir_uuid, file_name=name)\n # print('father_sub_str:', father_sub_str)\n self.write_source(BASE_PBXGroup_SECTION_DIR_PATTERN, father_sub_str)\n\n # 实现子目录的PBXGroup部分\n # 判断是否是中文,如果是中文,path = \"\"\n dir_name_ = f'''\"{name}\"''' if check_chinese(name) else name\n BASE_PBXGroup_SECTION_DIR_STR = BASE_PBXGroup_SECTION_DIR.format(dir_uuid=dir_uuid, dir_name=name,\n dir_name_=dir_name_)\n self.insert_str_to_project(BASE_PBXGroup_SECTION_DIR_STR, BASE_PBXGroup_SECTION_PATTERN)\n for file_ in file_names:\n # 是文件还是文件夹\n if os.path.isfile(os.path.join(dir_path, file_)):\n file_list.append(file_)\n else:\n dir_list.append(file_)\n self.create_dir(os.path.join(dir_path, file_))\n\n self.create_files(dir_path, file_list)\n\n # 向project.pbproj文件中插入对应生成代码\n def insert_str_to_project(self, str_, pattern):\n with open(self.project_path, 'r+', encoding='utf-8') as f:\n file_data = ''\n for line in f:\n if pattern.findall(line):\n line = str_ + line\n file_data += line\n f.seek(0)\n f.truncate()\n f.write(file_data)\n\n # 生成BASE_PBXBuildFile_SECTION\n def create_BASE_PBXBuildFile_SECTION(self, file_name, f_type):\n ref_uuid = self.uuid_generator()\n uuid = self.uuid_generator()\n new_line = BASE_PBXBuildFile_SECTION.format(uuid=uuid, ref_uuid=ref_uuid,\n sources=SOURCE_MAP[f_type], file_name=file_name)\n return new_line, uuid, ref_uuid\n\n # 具体写入插入的字符串函数\n def write_source(self, pattern, new_str):\n with open(self.project_path, 'r+', encoding='utf-8') as f:\n data = f.read()\n res = pattern.findall(data)\n if res:\n line = res[0]\n # if '\\t\\t\\t\\t);' in line:\n data_ = line.replace('\\t\\t\\t);', '{}\t\t\t);'.format(new_str))\n\n # print('data_:', data_)\n data = data.replace(line, data_)\n f.seek(0)\n f.truncate()\n f.write(data)\n","sub_path":"src/xcode_helper.py","file_name":"xcode_helper.py","file_ext":"py","file_size_in_byte":15741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"40648862","text":"import json\n\nfrom django.conf import settings\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.db.models import Count\n\nfrom rest_framework import permissions, viewsets, status, views\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\n\nfrom .models import Account, Follow\nfrom .permissions import IsAccountOwner\nfrom .serializers import AccountSerializer, FollowSerializer\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\nclass LargeResultsSetPagination(PageNumberPagination):\n page_size = 3\n page_size_query_param = 'page_size'\n # max_page_size = 3\n\n\nclass AccountViewSet(viewsets.ModelViewSet):\n \"\"\"\n This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions.\n \"\"\"\n lookup_field = 'username'\n serializer_class = AccountSerializer\n # pagination_class = LargeResultsSetPagination\n\n def get_permissions(self):\n if self.request.method in permissions.SAFE_METHODS:\n return (permissions.AllowAny(), )\n\n if self.request.method == 'POST':\n return (permissions.AllowAny(), )\n\n return (permissions.IsAuthenticated(), IsAccountOwner(),)\n\n def get_queryset(self):\n \"\"\"\n get all users. if ?ex parameter is included - exclude request user\n no queryset attribute so needed to set base_name when registering this ViewSet\n \"\"\"\n query = self.request.query_params.get('q')\n if query:\n queryset = Account.objects.filter(username__startswith=query).\\\n annotate(snippet_count=Count('snippets')).order_by('-snippet_count')\n else:\n queryset = Account.objects.all().\\\n annotate(snippet_count=Count('snippets')).order_by('-snippet_count')\n exclude_requested_user = self.request.query_params.get('ex', None)\n if exclude_requested_user == '' and self.request.user.is_authenticated:\n return queryset.exclude(username=self.request.user.username)\n return queryset\n\n def create(self, request):\n serializer = self.serializer_class(data=request.data)\n\n if serializer.is_valid():\n Account.objects.create_user(**serializer.validated_data)\n return Response(serializer.validated_data, status=status.HTTP_201_CREATED)\n\n return Response({\n 'status': 'Bad request',\n 'message': 'Account could not be created with received data.'\n }, status=status.HTTP_400_BAD_REQUEST)\n\n @detail_route()\n def snippets(self, request, username):\n \"\"\"\n /api/v1/users//snippets\n Get public snippets created by user, for owner include private ones too.\n \"\"\"\n queryset = Snippet.objects.select_related('owner').filter(owner__username=username)\n requested_by_owner = request.user.username == username\n if not requested_by_owner:\n queryset = queryset.exclude(private=True)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = SnippetSerializer(page, many=True, context={'request': request})\n return self.get_paginated_response(serializer.data)\n\n serializer = SnippetSerializer(queryset, many=True, context={'request': request})\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @detail_route()\n def count(self, request, username):\n # todo\n # queryset = Snippet.objects.filter(owner__username=username).values('language').distinct()\n queryset = Snippet.objects.filter(owner__username=username).values('language').annotate(Count('language'))\n return Response()\n\n @detail_route(methods=['get', 'post'])\n def followed(self, request, username):\n \"\"\"\n /api/v1/users//followed\n Get followed users by user. Owner can follow and unfollow others.\n \"\"\"\n if request.method == 'POST':\n if not request.user.is_authenticated:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n followed = self.get_object()\n if followed is not None:\n if request.user == followed:\n return Response({'message': 'You can\\'t follow yourself'}, status=status.HTTP_401_UNAUTHORIZED)\n\n if request.method == 'POST':\n obj, created = Follow.objects.get_or_create(follower=request.user, followed=followed)\n message = 'You followed {}'.format(followed.username)\n if not created:\n obj.delete()\n message = 'You unfollowed {}'.format(followed.username)\n return Response({'message': message}, status=status.HTTP_200_OK)\n\n followed_ids = Follow.objects.filter(follower__username=username).values_list('followed', flat=True)\n followed_users = Account.objects.filter(pk__in=followed_ids)\n serializer = AccountSerializer(followed_users, many=True, context={'request': request})\n return Response(serializer.data)\n\n @list_route()\n def styles(self, request, format=None):\n \"\"\"\n /api/v1/users/styles\n Get all available highlighing styles snippets.\n \"\"\"\n styles = {\n 'dark': tuple({'value': value, 'style': style} for value, style in settings.STYLES['dark']),\n 'light': tuple({'value': value, 'style': style} for value, style in settings.STYLES['light']),\n }\n return Response(styles)\n\n\n# class FollowViewSet(viewsets.ModelViewSet):\n# lookup_field = 'follower__username'\n# queryset = Follow.objects.all()\n# serializer_class = FollowSerializer\n#\n# def get_permissions(self):\n# if self.request.method in permissions.SAFE_METHODS:\n# return (permissions.AllowAny(), )\n#\n# if self.request.method == 'POST':\n# return (IsAccountOwner(), )\n#\n# return (permissions.IsAuthenticated(), IsAccountOwner(),)\n\n\nclass LoginView(views.APIView):\n def post(self, request, format=None):\n body_unicode = request.body.decode('utf-8')\n data = json.loads(body_unicode)\n\n email = data.get('email', None)\n password = data.get('password', None)\n\n account = authenticate(email=email, password=password)\n if account:\n if account.is_active:\n login(request, account) # create a new session for this user.\n serialized = AccountSerializer(account, context={'request': request})\n return Response(serialized.data)\n else:\n return Response({\n 'status': 'Unauthorized',\n 'message': 'This account is not active'\n }, status=status.HTTP_401_UNAUTHORIZED)\n else:\n return Response({\n 'status': 'Unathorized',\n 'message': 'Invalid creditentials'\n }, status=status.HTTP_401_UNAUTHORIZED)\n\n\nclass LogoutView(views.APIView):\n # Only authenticated users should be able to hit this endpoint\n permission_classes = (permissions.IsAuthenticated, )\n\n def post(self, request, format=None):\n logout(request)\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n\n\ndef jwt_response_payload_handler(token, user=None, request=None):\n return {\n 'token': token,\n 'user': AccountSerializer(user, context={'request': request}).data\n }\n\n# don't need a generic activity like creating or updating an object,\n# we must start with something more basic\n# views.APIView are made specifically to handle AJAX requests\n# Unlike generic views, we must handle each HTTP verb ourselves\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131647837","text":"from WWTest.util.getTimeStr import GetTimeStr\nclass InputTapInputText(object):\n def inputtapinputtext(self,activebrowser,newaddid):\n timestr = GetTimeStr().getTimeStr()\n inputtext_list = []\n from testdatas.models import InputTapInputText\n inputtapinputtexts = InputTapInputText.objects.filter(newaddandcheck_id=int(newaddid))\n if str(inputtapinputtexts) != \"\":\n activebrowser.outPutMyLog(\"找到依赖数据\")\n for inputtapinputtext in inputtapinputtexts:\n if inputtapinputtext.is_with_time:\n inputtextwithtimestr = \"%s%s\"%(inputtapinputtext.input_text,timestr)\n else:\n inputtextwithtimestr = inputtapinputtext.input_text\n\n activebrowser.findEleAndInputNum(0,inputtapinputtext.input_ele_find,\n inputtapinputtext.input_ele_find_value,inputtextwithtimestr)\n if inputtapinputtext.is_check:\n inputtext_list.append(inputtextwithtimestr)\n else:\n activebrowser.outPutErrorMyLog(\"没有找到依赖id[%s]对应的数据!\" % newaddid)\n\n return inputtext_list\n\n\n\ninputtapinputtext = InputTapInputText()","sub_path":"WWAPITest/autotest/config/suijing/depend/inputTapInputText.py","file_name":"inputTapInputText.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"146888722","text":"#--------------------------------------------------------------------------\r\n# Tool Name: CalcTypology\r\n# Description: Classifies regions as 'Urban', 'Intermediate' or 'Rural'\r\n# by urban population share for regions and urban population\r\n# Input: Region feature class layer\r\n# Region population field !assumed numerical field\r\n# Region urban population field !assumed numerical field\r\n# Modify: Field for typology !assumed text field\r\r\n#\r\n#--------------------------------------------------------------------------\r\nimport sys, arcpy.da\r\n\r\ntry:\r\n infc = arcpy.GetParameterAsText(0)\t\t # Input feature class\r\n datafld_regPop = arcpy.GetParameterAsText(1)\t# Input data field - Region population\r\n datafld_regUrbanPop = arcpy.GetParameterAsText(2)\t# Input data field - Region urban population\r\n outfld = arcpy.GetParameterAsText(3)\t # Modify result field\r\nexcept:\r\n arcpy.AddError(\"Cannot parse input arguments\")\r\n sys.exit(\"Error reading arguments!\")\r\n\r\narcpy.AddMessage(\"Computing typology...\")\r\n\r\ntry:\r\n # instantiate variable\r\n urbanPopShare = 0.0\r\n \r\n # use UpdateCursor to open as read/write\r\n # wrapping the cursor in a WITH statement,\r\n # opens and closes the row and cursor objects at the end of the code block\r\n with arcpy.da.UpdateCursor(infc, ['Population', 'Urban_Pop', outfld]) as rows:\r\n for row in rows:\r\n \r\n # check value is not null\r\n if (row[0] is None or row[1] is None):\r\n row[2] = None\r\n rows.updateRow(row)\r\n \r\n # check value is not negative \r\n if (row[0] > 0 and row[1] > 0):\r\n # compute the urban population share ratio as Urban_Pop/Population\r\n urbanPopShare = row[1]/row[0]\r\n \r\n # check share ratio >= 0.5\r\n if urbanPopShare >= 0.5:\r\n # check Urban Population\r\n if row[1] < 500000:\r\n # if Urban Population < 500 000\r\n row[2] = 'Intermediate'\r\n rows.updateRow(row)\r\n else:\r\n # if Urban Population > 500 000\r\n row[2] = 'Urban'\r\n rows.updateRow(row)\r\n \r\n # check share ratio < 0.5 AND share ratio >= 0.15\r\n elif (urbanPopShare < 0.5 and urbanPopShare >= 0.15):\r\n \r\n if row[1] < 500000:\r\n # if Urban Population < 500 000\r\n row[2] = 'Rural'\r\n rows.updateRow(row)\r\n \r\n else:\r\n # if Urban Population > 500 000\r\n row[2] = 'Intermediate'\r\n rows.updateRow(row)\r\n \r\n # check share ratio < 0.15\r\n else:\r\n row[2] = 'Rural'\r\n rows.updateRow(row)\r\n # when value is negative or out of range \r\n else:\r\n row[2] = None\r\n rows.updateRow(row)\r\n\r\n arcpy.SetParameterAsText(4,infc)\t\t# Set feature layer as output to support data flows\r\n arcpy.AddMessage(\"Completed\")\r\n\r\nexcept:\r\n errMsg = arcpy.GetMessages(2)\r\n arcpy.AddError(\"Unexpected error : \" + errMsg)\r\n","sub_path":"CalcTypology.py","file_name":"CalcTypology.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348942244","text":"import requests\r\nimport json\r\nimport pandas as pd\r\n\r\nclass GetInformationFromDiseaseGeneNet:\r\n\r\n def __init__(self):\r\n self.database='DiseaseGeneNet'\r\n self.url='https://disgenet.org/api/gda/'\r\n self.resp_status_code = None\r\n self.response_gene = None\r\n self.disease_association_gene = None\r\n\r\n def check_data_base_connection(self):\r\n resp = requests.get(self.url)\r\n if resp.status_code != 200:\r\n raise ApiErrpr('GET url'.format(resp.status_code))\r\n self.resp_status_code = resp.status_code\r\n\r\n def get_gene_information(self,gene_of_interest):\r\n if gene_of_interest.__len__()!=1:\r\n seperation_pattern = '%2C'\r\n gene_pattern_in_url = seperation_pattern.join(gene_of_interest)\r\n url_to_take = self.url+'gene/'+gene_pattern_in_url+'?source=CURATED'\r\n response_gene = requests.get(url_to_take)\r\n self.response_gene = response_gene\r\n else:\r\n url_to_take = self.url+'gene/'+gene_of_interest+'?source=CURATED'\r\n response_gene = requests.get(url_to_take)\r\n self.response_gene = response_gene\r\n\r\n def disease_information(self,disease_of_interest):\r\n if disease_of_interest.__len__() != 1:\r\n seperation_pattern = '%2C'\r\n disease_pattern_in_url=seperation_pattern.join(disease_of_interest)\r\n url_to_take=self.url+'disease/'+disease_pattern_in_url+'?source=CURATED'\r\n response_disease = requests.get(url_to_take)\r\n else:\r\n url_to_take = self.url+'disease/'+disease_of_interest+'?source=CURATED'\r\n response_disease = requests.get(url_to_take)\r\n self.response_disease = response_disease\r\n\r\n def format_information_to_gene_and_disease_only(self):\r\n keys_of_interest = ('gene_symbol','disease_name')\r\n dictionary_from_json = self.response_gene.json()\r\n dataframe_disease_gene = pd.DataFrame.from_dict(dictionary_from_json)\r\n dataframe_disease_gene = dataframe_disease_gene.loc[:,keys_of_interest]\r\n type_interaction_disease = pd.DataFrame({'Type':['Gene-Disease' for x in range(dataframe_disease_gene.shape[0])]})\r\n dataframe_disease_gene.reset_index(drop=True, inplace=True)\r\n type_interaction_disease.reset_index(drop=True, inplace=True)\r\n disease_association_gene_df = pd.concat([dataframe_disease_gene,type_interaction_disease],axis=1)\r\n self.disease_association_gene = disease_association_gene_df","sub_path":"APIforDiseaseGeneNet.py","file_name":"APIforDiseaseGeneNet.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591443017","text":"from django.conf.urls import url\nfrom first_app import views\n\n\nurlpatterns = [\n url(r'^$',views.index,name='index'),\n url('zeki',views.index2),\n url('indexview',views.indexView),\n url('form',views.formResponse),\n\n]\n","sub_path":"Django/MyDjangoStuff/first_project/first_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154984758","text":"from pathlib import Path\nimport pandas as pd\nfrom tqdm import tqdm\n'''\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\n# download dataset from link provided by\n# https://github.com/X-zhangyang/Real-World-Masked-Face-Dataset\ndatasetPath = Path('covid-mask-detector/data/mask.zip')\ngdd.download_file_from_google_drive(file_id='1UlOk6EtiaXTHylRUx2mySgvJX9ycoeBp',\n dest_path=str(datasetPath),\n unzip=True)\n# delete zip file\ndatasetPath.unlink()\n'''\n\nif __name__ == '__main__':\n datasetPath = Path('./self-built-masked-face-recognition-dataset')\n maskPath = datasetPath/'AFDB_masked_face_dataset'\n nonMaskPath = datasetPath/'AFDB_face_dataset'\n maskDF = pd.DataFrame()\n nonMaskDF = pd.DataFrame()\n\n for subject in tqdm(list(maskPath.iterdir()), desc='mask photos'):\n id = subject.stem\n for imgPath in subject.iterdir():\n maskDF = maskDF.append({\n 'target': str(imgPath),\n 'id_name': str(id)\n }, ignore_index=True)\n\n for subject in tqdm(list(nonMaskPath.iterdir()), desc='no masked photos'):\n id = subject.stem\n for imgPath in subject.iterdir():\n nonMaskDF = nonMaskDF.append({\n 'source': str(imgPath),\n 'id_name': str(id)\n }, ignore_index=True)\n \n merge = pd.merge(nonMaskDF,maskDF,on='id_name')\n\n #adding class numbers to id_names\n merge['id_name'] = merge['id_name'].astype('category')\n merge['id_class'] = merge['id_name'].cat.codes\n\n dfName = './dataframe.pickle'\n print(f'saving Dataframe to: {dfName}')\n merge.to_pickle(dfName)\n\n ","sub_path":"lib/data/create_rmfd_dataframe.py","file_name":"create_rmfd_dataframe.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"140718457","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 9 21:08:49 2018\n\n@author: MMOHTASHIM\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport quandl\nfrom statistics import mean\nimport numpy as np\nfrom IPython import get_ipython\napi_key=\"fwwt3dyY_pF8LyZqpNsa\"\ndef get_data_company(company_name):\n df=quandl.get(\"EURONEXT/\"+str(company_name),authtoken=api_key)\n df=pd.DataFrame(df[\"Last\"])\n df.rename(columns={\"Last\":\"Price\"},inplace=True)\n df_2=df.resample(\"M\").mean()\n return df_2\ndef get_data_euronext():\n df_2=pd.read_csv(\"EuroNext 100 Historical Data.csv\")\n df_2=df_2.loc[0:6, :]\n df_2=pd.DataFrame(df_2[[\"Date\",\"Price\"]])\n return df_2\ndef calculate_beta(company_name):\n df=get_data_euronext()\n df_2=get_data_company(company_name)\n xs=np.array((df[\"Price\"]))\n ys=np.array(df_2[\"Price\"])\n m = (((mean(xs)*mean(ys)) - mean(xs*ys)) /\n ((mean(xs)*mean(xs)) - mean(xs*xs)))\n \n b = mean(ys) - m*mean(xs)\n get_ipython().run_line_magic('matplotlib', 'qt')\n print(\"Your Beta is\"+ str(m))\n regression_line = [(m*x)+b for x in xs]\n plt.scatter(xs,ys,color='#003F72')\n plt.plot(xs, regression_line)\n plt.show()\n return m, b\n\n\n\n\n\n ","sub_path":"practice-pandas/.ipynb_checkpoints/CAPM MODEL-checkpoint.py","file_name":"CAPM MODEL-checkpoint.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127245996","text":"import pandas as pd\nimport numpy as np\n\ngroup=['x','y','z']\ndata=pd.DataFrame({\n \"id\":np.random.randint(900,1200,20),\n \"group\":[group[x] for x in np.random.randint(0,len(group),20)] ,\n \"order_id\":np.random.randint(5,50,20),\n \"age\":np.random.randint(15,50,20)\n })\n\nprint(f'SELECT * FROM data;\\n{data}')\n\nprint(f'SELECT * FROM data LIMIT 10;\\n{data.head(10)}')\n\nprint(f'SELECT id FROM data;\\n {data.id}')\n\nprint(f'SELECT id FROM data;\\n {data.id.size}')\n\nprint(f'SELECT id FROM data;\\n {data.id.size}')\n\ndf1=data.loc[(data['id']<1000) & (data['age']>30)]\nprint(f'SELECT * FROM data WHERE id<1000 AND age>30;\\n {df1}')\n\ndef func_duplicate(df):\n df['dup'] = df.drop_duplicates(['order_id'])\n return df\n\ndf2 = data.loc[15:,'order_id']=40\n\ndata.loc[15:,'id']=400\ndata.loc[:14,'id']=1400\n\nprint(f'SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;\\n')\ndata.groupby('id').groups\nfor a, b in data.groupby('id'):\n print(a)\n b['COUNT(DISTINCT order_id)'] = b.drop_duplicates(['order_id'])['order_id'].count()\n print(b.loc[:,['id','COUNT(DISTINCT order_id)']])\n\ndata2=pd.DataFrame({\n \"id\":np.random.randint(1,50,20),\n \"group\":[group[x] for x in np.random.randint(0,len(group),20)] ,\n \"order_id\":np.random.randint(5,50,20),\n \"age\":np.random.randint(15,50,20)\n })\n\n\ndata3 = pd.DataFrame({\n \"group\":[group[x] for x in np.random.randint(0,len(group),20)] ,\n \"salary\":np.random.randint(10,50,20)\n })\n\ndata_inner = pd.merge(data2,data3, on='group',how='inner')\nprint(f'SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id;\\n{data_inner}')\n\ndata_union = pd.concat([data2,data3])\nprint(f'SELECT * FROM table1 UNION SELECT * FROM table2;\\n{data_union}')\ndf2 = data2.drop(data2[data2.id ==10].index)\nprint(f'DELETE FROM table1 WHERE id=10;\\n{df2}')\ndf2 = data2.drop('age',axis=1)\nprint(f'ALTER TABLE table1 DROP COLUMN column_name;\\n{df2}')\n","sub_path":"week04/wk4_pd_oper.py","file_name":"wk4_pd_oper.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"28477303","text":"class Obstacle:\n \"\"\"Represents an obstacle\n Note: x1, y1, x2, y2 must represent upper left corner and lower right corner of the object\n \"\"\"\n\n def __init__(self, x1=0, y1=0, x2=10, y2=10, color=\"black\"):\n \"\"\"initialize the obstacle\n x1,y1 is the upper left hand position of the obstacle\n x2,y2 is the lower right hand position of the obstacle\n color is the color of the object\n \"\"\"\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n self.color = color\n","sub_path":"Obstacle.py","file_name":"Obstacle.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"482291331","text":"__author__ = \"Sudip Sinha\"\n\nfrom tr_crr import tr_underlying\nfrom tr_vanilla import vanilla_call\nfrom asian import asian_call_sp\nfrom tr_asian_singularpoints_old import sp_asian_call_old\n\n\n# http://www.goddardconsulting.ca/matlab-binomial-crr.html\n# http://www.hoadley.net/options/binomialtree.aspx?tree=B\n# http://www.mngt.waikato.ac.nz/kurt/frontpage/studentwork/danielchainov2003/bitree2.htm\n# http://www.fintools.com/resources/online-calculators/options-calcs/binomial/\n# http://www.optionspricevaluation.com/\n\n\ndef show_results(tree) -> None:\n\ts0 = 100.; k = 100.; sigma = 0.1; q = 0.; t = 0.25; r = 0.1; am = False; h = 1e-6\n\n\t# tree = tr_underlying(s0=s0, sigma=sigma, t=t, n=n)\n\t# eu = vanilla_call(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n)\n\t# sp = sp_asian_call_old(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=True, n=n)\n\n\t# print('n = {n}'.format(n=n))\n\n\t# print('\\n' + '-' * 16 + '\\tUnderlying tree \\t' + '-' * 16)\n\t# # Display the tree for the underlying.\n\t# for (i, ti) in enumerate(tree):\n\t# \tprint('N({i}): {ti}'.format(i=i, ti=ti))\n\n\t# print('\\n' + '-' * 16 + '\\tEuropean call \\t' + '-' * 16)\n\t# # Display the tree for the European call.\n\t# for (i, ti) in enumerate(eu):\n\t# \tprint('N({i}): {ti}'.format(i=i, ti=ti))\n\n\tdisplay = '\\n' + '-' * 16 + '\\tSingular points \\t' + '-' * 16 + '\\n'\n\t# Print the price of the Asian call.\n\tfor (i, ti) in enumerate(tree):\n\t\tfor (j, tj) in enumerate(ti):\n\t\t\tdisplay = 'N({i},{j}): {tj}\\n'.format(i=i, j=j, tj=tj) + display\n\t\tdisplay = '-' * 64 + '\\n' + display\n\tprint(display)\n\t# print('Price of the call = {prc}'.format(prc=sp[0][0][0][1]))\n\n\ndef run_asian_old(ns: list, d: int=6) -> None:\n\t\"\"\"Display short results for a list of 'n's.\"\"\"\n\n\ts0 = 100.; k = 90.; sigma = 0.2; q = 0.03; t = 1.; r = 0.1; am = True; h = 1e-6 # Table 1\n\n\tfor n in ns:\n\t\tupper = sp_asian_call_old(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n, h=h, ub=True)[0][0][0][1]\n\t\tlower = sp_asian_call_old(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n, h=h, ub=False)[0][0][0][1]\n\t\tif n < 25:\n\t\t\tactual = sp_asian_call_old(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n)[0][0][0][1]\n\t\t\tprint('n={n:3}: {lb:.{d}f} <= {ac:.{d}f} <= {ub:.{d}f}'.format(d=d, n=n, lb=lower, ac=actual, ub=upper))\n\t\telse:\n\t\t\tprint('n={n:3}: {lb:.{d}f} <= {ub:.{d}f}'.format(d=d, n=n, lb=lower, ub=upper))\n\n\ndef run_asian(ns: list, d: int=6) -> None:\n\t\"\"\"Display short results for a list of 'n's.\"\"\"\n\n\t# s0 = 100.; k = 100.; sigma = 0.1886; q = 0.; t = 0.25; r = 0.05; am = True; h = 1e-6 # Table 4\n\n\t# s0 = 100.; k = 90.; sigma = 0.2; q = 0.03; t = 1.; r = 0.1; am = True; h = 1e-6 # Table 1\n\t# s0 = 100.; k = 90.; sigma = 0.4; q = 0.03; t = 1.; r = 0.1; am = True; h = 1e-6 # Table 1\n\ts0 = 100.; k = 110.; sigma = 0.2; q = 0.03; t = 1.; r = 0.1; am = True; h = 1e-6 # Table 2\n\t# s0 = 100.; k = 110.; sigma = 0.2; q = 0.03; t = 1.; r = 0.1; am = True; h = 1e-6 # Table 2\n\n\tfor n in ns:\n\t\tupper = asian_call_sp(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n, h=h, ub=True)\n\t\tlower = asian_call_sp(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n, h=h, ub=False)\n\t\t# if n < 25:\n\t\t# \tactual = asian_call_sp(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n)\n\t\t# \tprint('n={n:3}: {lb:.{d}f} <= {ac:.{d}f} <= {ub:.{d}f}'.format(d=d, n=n, lb=lower, ac=actual, ub=upper))\n\t\t# else:\n\t\tprint('{n:3}: {lb:.{d}f} <= {ub:.{d}f}'.format(d=d, n=n, lb=lower, ub=upper))\n\t\t# actual = asian_call_sp(r=r, s0=s0, sigma=sigma, q=q, k=k, t=t, am=am, n=n)\n\t\t# print('n={n:3}: {ac}'.format(d=d, n=n, ac=actual))\n\n\nrun_asian([25])\nrun_asian_old([25])\n\n# run_asian([221], d=6)\n# run_asian([222], d=6)\n","sub_path":"MathMods/Thesis/code/runAsian.py","file_name":"runAsian.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378796150","text":"import re,os\nimport urllib.request, urllib.error\nfrom bs4 import BeautifulSoup\nfrom urllib import request\n\n# 477 550 697\n# 239 692 662 467\nNUM = 664\n\ndef askURL(url):\n html_ret = \"\"\n head = {\n # User-Agent必要 其他看情况\n # \"authority\": \"www.yalayi.com\",\n \"referer\": \"https://www.yalayi.com/user/mygallery/\",\n # \"if-modified-since\": \"Tue, 29 Jun 2021 06:36:01 GMT\",\n # \"sec-ch-ua-mobile\": \"?0\",\n # \"sec-fetch-dest\": \"document\",\n # \"sec-fetch-mode\": \"navigate\",\n # \"sec-fetch-site\": \"same-origin\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36\",\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n # \"Accept-Encoding\": \"gzip, deflate, br\",\n # \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n # \"Connection\": \"keep-alive\",\n # \"Cache-Control\": \"max-age=0\",\n \"Host\": \"www.yalayi.com\",\n # \"Sec-Fetch-Dest\": \"document\",\n # \"Sec-Fetch-Mode\": \"navigate\",\n # \"Sec-Fetch-Site\": \"none\",\n # \"Upgrade-Insecure-Requests\": \"1\",\n \"Cookie\": \"UM_distinctid=17a1896e5f5a55-087a424c171bb1-37607201-240000-17a1896e5f637b; ogmjxmlusername=18856425363; ogmjxmluserid=167138; ogmjxmlgroupid=3; ogmjxmlrnd=LmG8sQZ5fsGUlHL3co1H; ogmjxmlauth=d884a3835c9e405e5fbf3866e4f88a94; CNZZDATA1279092031=2145931356-1623905385-%7C1625031868\"\n }\n try:\n req = urllib.request.Request(url=url, headers=head)\n response = urllib.request.urlopen(req)\n htmlRet = response.read().decode(\"utf-8\")\n # print(htmlRet)\n html_ret = htmlRet\n\n # 创建空文件\n desktop_path = os.getcwd() + \"/美女/\" # 新创建的txt文件的存放路径\n\n full_path = desktop_path + \"{}\".format(NUM) + '.html' # 也可以创建一个.doc的word文档\n print(full_path)\n file = open(full_path, 'w') # w 的含义为可进行读写\n file.write(html_ret) # file.write()为写入指令\n file.close()\n\n\n\n\n\n # 因为多次请求会被403 所以模拟加载本地html文本\n # f = open(\"/Users/udc/Desktop/日常学习/Python3/美女/550.html\", 'r')\n # html_ret = f.read()\n # print(html_ret)\n\n except urllib.error.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n return html_ret\n\ndef creat_dir(path):\n \"\"\"\n 创建文件夹\n :param path:文件夹路径\n :return:文件夹\n \"\"\"\n if not os.path.exists(path):\n os.mkdir(path) #默认在当前项目下创建\n\nif __name__ == '__main__':\n # askURL(\"https://www.yalayi.com/gallery/664.html\")\n# # 打开文件\n# fo = open(\"849.html\", \"rw+\")\n# print(\"文件名: \", fo.name)\n\n creat_dir(\"{}\".format(NUM))\n\n\n\n\n f = open((os.getcwd() + '/美女/{}.html').format(NUM), 'r') #没有就新建\n html_ret = f.read()\n # print(html_ret)\n soup = BeautifulSoup(html_ret, \"html.parser\") # 使用html.parser解析器来解析html\n data = []\n\n findImgSrc = re.compile(r'\n#\n# softrig is free software; you can redistribute and/or modify it\n# under the terms of that license as published by the Free Software\n# Foundation; either version 2 of the License, or (at your option)\n# any later version.\n#\n# softrig is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with softrig; see the file COPYING. If not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA, or see http://www.gnu.org/.\n\nimport softriglib.display as display\nimport softriglib.dttsp as dttsp\nimport urwid\nfrom urwid import AttrMap, Text, Pile, Columns, Padding, WidgetWrap\n\nbody_map = {\n\t\"heading\": \"heading\",\n\t\"editable\": \"editable\",\n\t\"edit-info\": \"edit-info\",\n\t\"edit-chosen\": \"edit-chosen\",\n\t\"read-only\": \"read-only\",\n\tNone: \"body\",\n\t}\n\nbody_focus_map = {\n\t\"heading\": \"heading focus\",\n\t\"editable\": \"editable focus\",\n\t\"edit-info\": \"edit-info focus\",\n\t\"edit-chosen\": \"edit-chosen focus\",\n\t\"read-only\": \"read-only focus\",\n\tNone: \"body focus\",\n\t}\n\ndef new_frontend(obj):\n\t\"\"\"Start a new frontend.\n\tobj may be a Frontend or a Device.\"\"\"\n\n\tif hasattr(obj, \"device\"):\n\t\t# A frontend -- we need the device.\n\t\tobj = obj.device\n\n\tobj.rig.defer(lambda: obj.add_new_frontend())\n\ndef remove_frontend(obj):\n\t\"\"\"Remove a frontend.\n\tobj may be a Frontend or a Device.\"\"\"\n\n\tif not hasattr(obj, \"device\"):\n\t\t# Not a frontend -- nothing to do.\n\t\treturn\n\n\tobj.device.rig.defer(lambda: obj.shutdown())\n\ndef connect_frontend(obj, app):\n\t\"\"\"Connect a frontend to an application.\"\"\"\n\n\tif not hasattr(obj, \"device\"):\n\t\t# Not a frontend -- nothing to do.\n\t\treturn\n\n\tobj.device.rig.defer(lambda: obj.connect_to(app))\n\nclass ControlHeading(Text):\n\t\"\"\"Base class for a Widget representing a RigObject.\"\"\"\n\n\tdef __init__(self, obj):\n\t\tself.obj = obj\n\t\tsuper(ControlHeading, self).__init__([\n\t\t\t(\"heading\", obj.label),\n\t\t\t])\n\n\tdef selectable(self):\n\t\treturn True\n\n\tdef keypress(self, size, key):\n\t\tif key == \"N\":\n\t\t\tnew_frontend(self.obj)\n\t\telif key == \"R\":\n\t\t\tremove_frontend(self.obj)\n\t\telif key == \"n\":\n\t\t\tconnect_frontend(self.obj, \"nothing\")\n\t\telif key == \"a\":\n\t\t\tconnect_frontend(self.obj, \"audio\")\n\t\telif key == \"f\":\n\t\t\tconnect_frontend(self.obj, \"fldigi\")\n\t\telif key == \"l\":\n\t\t\tconnect_frontend(self.obj, \"fldigi+listen\")\n\t\telse:\n\t\t\treturn key\n\t\treturn None\n\nclass Control(Text):\n\t\"\"\"Base class for a Widget representing a RigObject parameter.\"\"\"\n\n\tdef __init__(self, param, label, editable=True):\n\t\tsuper(Control, self).__init__(\"\")\n\n\t\tself.param = param\n\t\tself.label = label\n\t\tself.editable = editable\n\t\tself.value = None\n\n\t\t# RigWalker will set this later.\n\t\tself.obj = None\n\n\t\tself.new_value = None\n\n\tdef receive_param(self, value):\n\t\tself.value = value\n\t\tself.update_content()\n\n\tdef update_content(self):\n\t\tmarkup = [self.label + \": \"]\n\t\tif self.new_value is not None:\n\t\t\tmarkup.append((\"editing\", self.new_value))\n\t\telif self.editable:\n\t\t\tmarkup.append((\"editable\", self.format_value(self.value)))\n\t\telse:\n\t\t\tmarkup.append((\"read-only\", self.format_value(self.value)))\n\t\tedit_info = self.get_edit_info()\n\t\tif edit_info is not None:\n\t\t\tmarkup.append((\"edit-info\", \" \"))\n\t\t\tmarkup += self.get_edit_info()\n\t\tself.set_text(markup)\n\n\tdef send_param(self, value):\n\t\t\"\"\"Change the value of the parameter this object represents.\n\t\tThis doesn't update the widget directly; receive_param will be\n\t\tcalled once (if!) the new value has been accepted.\"\"\"\n\t\tself.obj.set_param(self.param, value)\n\n\tdef selectable(self):\n\t\treturn self.editable\n\n\tdef keypress(self, size, key):\n\t\tif key == \"N\":\n\t\t\tnew_frontend(self.obj)\n\t\telif key == \"R\":\n\t\t\tremove_frontend(self.obj)\n\t\telif key == \"n\":\n\t\t\tconnect_frontend(self.obj, \"nothing\")\n\t\telif key == \"a\":\n\t\t\tconnect_frontend(self.obj, \"audio\")\n\t\telif key == \"f\":\n\t\t\tconnect_frontend(self.obj, \"fldigi\")\n\t\telif key == \"l\":\n\t\t\tconnect_frontend(self.obj, \"fldigi+listen\")\n\t\telse:\n\t\t\treturn key\n\t\treturn None\n\n\tdef get_edit_info(self):\n\t\t\"\"\"Return additional markup for this control, or None.\"\"\"\n\t\treturn None\n\nclass NumericControl(Control):\n\t\"\"\"Control for a floating-point number.\"\"\"\n\n\tunit = \"\"\n\tscale = 1.0 # divide real value by this to get displayed value\n\tformat = \"%f\"\n\tinit_step = 1.0 # in terms of real value; should be a power of 10\n\ttypeable = \"01234567890.-\"\n\n\tdef __init__(self, *args):\n\t\tsuper(NumericControl, self).__init__(*args)\n\t\tself.step = self.init_step\n\n\tdef format_value(self, value):\n\t\treturn (self.format + \" \" + self.unit) % (value / self.scale)\n\n\tdef keypress(self, size, key):\n\t\tif key == \"left\":\n\t\t\tself.send_param(self.value - self.step)\n\t\telif key == \"right\":\n\t\t\tself.send_param(self.value + self.step)\n\t\telif key == \"[\":\n\t\t\tself.step *= 0.1\n\t\t\tself.update_content()\n\t\telif key == \"]\":\n\t\t\tself.step *= 10.0\n\t\t\tself.update_content()\n\t\telif key in self.typeable:\n\t\t\tif self.new_value is None:\n\t\t\t\tself.new_value = \"\"\n\t\t\tself.new_value += key\n\t\t\tself.update_content()\n\t\telif key == \"backspace\" and self.new_value is not None:\n\t\t\tself.new_value = self.new_value[:-1]\n\t\t\tif self.new_value == \"\":\n\t\t\t\tself.new_value = None\n\t\t\tself.update_content()\n\t\telif key == \"enter\" and self.new_value is not None:\n\t\t\ttry:\n\t\t\t\tself.send_param(float(self.new_value) * self.scale)\n\t\t\texcept ValueError:\n\t\t\t\tpass\n\t\t\texcept TypeError:\n\t\t\t\tpass\n\t\t\tself.new_value = None\n\t\t\tself.update_content()\n\t\telse:\n\t\t\treturn super(NumericControl, self).keypress(size, key)\n\t\treturn None\n\n\tdef get_edit_info(self):\n\t\treturn [(\"edit-info\", \"(step %s)\" % self.format_value(self. step))]\n\nclass ChoiceControl(Control):\n\t\"\"\"Control with a list of possible values.\"\"\"\n\n\t# A list of (display value, real value) pairs.\n\toptions = None\n\n\tdef find_option(self, value):\n\t\tfor i in range(len(self.options)):\n\t\t\tif self.options[i][1] == value:\n\t\t\t\treturn i\n\t\traise ValueError(\"Could not find option for value: \" + str(value))\n\n\tdef format_value(self, value):\n\t\treturn self.options[self.find_option(value)][0]\n\n\tdef keypress(self, size, key):\n\t\tif key == \"left\":\n\t\t\tself.step_param(-1)\n\t\telif key == \"right\":\n\t\t\tself.step_param(1)\n\t\telse:\n\t\t\treturn super(ChoiceControl, self).keypress(size, key)\n\t\treturn None\n\n\tdef step_param(self, dir):\n\t\tpos = self.find_option(self.value) + dir\n\t\tif pos < 0:\n\t\t\tpos = 0\n\t\telif pos >= len(self.options):\n\t\t\tpos = len(self.options) - 1\n\t\tself.send_param(self.options[pos][1])\n\n\tdef get_edit_info(self):\n\t\tmarkup = [(\"edit-info\", \"(\")]\n\n\t\tfirst = True\n\t\tfor option in self.options:\n\t\t\tif not first:\n\t\t\t\tmarkup.append((\"edit-info\", \" \"))\n\t\t\tfirst = False\n\n\t\t\tattr = \"edit-info\"\n\t\t\tif option[1] == self.value:\n\t\t\t\tattr = \"edit-chosen\"\n\t\t\tmarkup.append((attr, option[0]))\n\n\t\tmarkup.append((\"edit-info\", \")\"))\n\t\treturn markup\n\nclass TuningControl(NumericControl):\n\tformat = \"%.3f\"\n\tunit = \"kHz\"\n\tscale = 1000.0\n\tinit_step = 1000.0\n\ndef make_dttsp_choice(dict):\n\t\"\"\"Given one of the DTTSP constant dictionaries, return a list of\n\toptions for ChoiceControl, ordered by the constant values.\"\"\"\n\treturn [(name, name)\n\t for name, value\n\t in sorted(dict.items(), key=lambda pair: pair[1])]\n\nclass ModeControl(ChoiceControl):\n\toptions = make_dttsp_choice(dttsp.MODE)\n\nclass TransmitControl(ChoiceControl):\n\toptions = [\n\t\t(\"Off\", False),\n\t\t(\"On\", True),\n\t\t]\n\n\tdef receive_param(self, value):\n\t\t# For Devices, the \"transmitting\" param is None or a Frontend.\n\t\t# Convert this to True/False when it's received.\n\t\tif value not in (True, False):\n\t\t\tvalue = (value is not None)\n\t\tsuper(TransmitControl, self).receive_param(value)\n\nclass FilterControl(NumericControl):\n\tformat = \"%.0f\"\n\tunit = \"Hz\"\n\tinit_step = 100.0\n\nclass AGCControl(ChoiceControl):\n\toptions = make_dttsp_choice(dttsp.AGC_TYPE)\n\nclass GainControl(NumericControl):\n\tformat = \"%.1f\"\n\tunit = \"dB\"\n\tinit_step = 0.1\n\nclass IQControl(NumericControl):\n\tformat = \"%.0f\"\n\tunit = \"\"\n\tinit_step = 10.0\n\nclass RigWalker(urwid.SimpleListWalker):\n\t\"\"\"ListWalker class that walks over all the parameters in the Rig.\"\"\"\n\n\tdef __init__(self, rig):\n\t\tself.rig = rig\n\t\tsuper(RigWalker, self).__init__([])\n\n\t\tself.rebuild_list()\n\n\tdef rebuild_list(self):\n\t\t\"\"\"Rebuild the list of widgets in the listbox.\"\"\"\n\n\t\t# Clear the list.\n\t\tself[:] = []\n\t\tself.subscriptions = {}\n\n\t\tfor device in self.rig.get_devices():\n\t\t\tself.build_device(device)\n\t\t\tfor frontend in device.get_frontends():\n\t\t\t\tself.build_frontend(frontend)\n\n\tdef build_device(self, device):\n\t\tself.build_controls(device, [\n\t\t\tTuningControl(\"freq\", \"Frequency\", False),\n\t\t\tTransmitControl(\"transmitting\", \"Transmit\", False),\n\t\t\t])\n\n\tdef build_frontend(self, frontend):\n\t\tdef pad(widget):\n\t\t\treturn Padding(widget, \"right\", (\"relative\", 95))\n\n\t\tself.build_controls(frontend, [\n\t\t\tTuningControl(\"freq\", \"Frequency\"),\n\t\t\tModeControl(\"mode\", \"Mode\"),\n\t\t\tTransmitControl(\"transmit\", \"Transmit\"),\n\t\t\tFilterControl(\"filter_l\", \"Filter L\"),\n\t\t\tFilterControl(\"filter_h\", \"Filter H\"),\n\t\t\tAGCControl(\"rx_agc\", \"AGC Type\"),\n\t\t\tGainControl(\"rx_rf_gain\", \"RX RF Gain\"),\n\t\t\tGainControl(\"rx_af_gain\", \"RX AF Gain\"),\n\t\t\tGainControl(\"tx_af_gain\", \"TX AF Gain\"),\n\t\t\tGainControl(\"tx_rf_gain\", \"TX RF Gain\"),\n\t\t\tIQControl(\"tx_iq_phase\", \"TX I-Q Phase\"),\n\t\t\tIQControl(\"tx_iq_gain\", \"TX I-Q Gain\"),\n\t\t\tIQControl(\"rx_iq_phase\", \"RX I-Q Phase\"),\n\t\t\tIQControl(\"rx_iq_gain\", \"RX I-Q Gain\"),\n\t\t\t], pad)\n\n\tdef build_controls(self, obj, controls, wrap=lambda x: x):\n\t\tdef amap(widget):\n\t\t\treturn AttrMap(widget, body_map, body_focus_map)\n\n\t\tself.append(Pile([Text(\"\"),\n\t\t wrap(amap(ControlHeading(obj)))]))\n\n\t\tsubscriptions = {}\n\t\tfor control in controls:\n\t\t\tparam = control.param\n\t\t\tsubscriptions[param] = control\n\t\t\tcontrol.obj = obj\n\t\t\tcontrol.receive_param(obj.get_param(param))\n\n\t\t\tself.append(wrap(amap(control)))\n\t\tobj.set_param(\"widget_subscriptions\", subscriptions)\n\nclass LogText(Text):\n\tsize = 8\n\n\tdef __init__(self):\n\t\tsuper(LogText, self).__init__(\"\")\n\t\tself.set_wrap_mode(\"clip\")\n\n\t\tself.lines = [\"\"] * self.size\n\t\tself.add(\"\")\n\n\tdef add(self, line):\n\t\t\"\"\"Append a line to the log.\"\"\"\n\n\t\tself.lines.append(line)\n\t\tself.lines = self.lines[-self.size:]\n\t\tself.set_text(\"\\n\".join(self.lines))\n\ndef hkey(text):\n\treturn (\"header key\", text)\n\nclass UrwidDisplay(display.Display):\n\tpoll_period = 0.05 # s\n\n\tpalette = [\n\t\t(\"header title\", \"white\", \"black\"),\n\t\t(\"header key\", \"yellow\", \"black\"),\n\t\t(\"header\", \"light gray\", \"black\"),\n\n\t\t(\"heading\", \"yellow\", \"black\"),\n\t\t(\"heading focus\", \"yellow\", \"dark blue\"),\n\t\t(\"body\", \"white\", \"black\"),\n\t\t(\"body focus\", \"white\", \"dark blue\"),\n\t\t(\"editable\", \"light cyan\", \"black\"),\n\t\t(\"editable focus\", \"light cyan\", \"dark blue\"),\n\t\t(\"editing\", \"white\", \"dark red\"),\n\t\t(\"edit-info\", \"black\", \"black\"),\n\t\t(\"edit-info focus\", \"light gray\", \"dark blue\"),\n\t\t(\"edit-chosen\", \"black\", \"black\"),\n\t\t(\"edit-chosen focus\", \"light cyan\", \"dark blue\"),\n\t\t(\"read-only\", \"light gray\", \"black\"),\n\t\t(\"read-only focus\", \"light gray\", \"dark blue\"),\n\n\t\t(\"log\", \"light gray\", \"black\"),\n\t\t]\n\n\theader_markup = [\n\t\t(\"header title\", \"softrig\\n\"),\n\t\thkey(\"q\"), \"uit \",\n\t\thkey(\"N\"), \"ew frontend \",\n\t\thkey(\"R\"), \"emove frontend\\n\",\n\t\t\"Connect to: \",\n\t\thkey(\"n\"), \"othing \",\n\t\thkey(\"a\"), \"udio \",\n\t\thkey(\"f\"), \"ldigi \",\n\t\t\"fldigi+\", hkey(\"l\"), \"isten\\n\",\n\t\thkey(\"Left\"), \"/\", hkey(\"Right\"), \": step value \",\n\t\thkey(\"[\"), \"/\", hkey(\"]\"), \": change step size\\n\",\n\t\thkey(\"0\"), \"..\", hkey(\"9\"), \", \", hkey(\"-\"), \", \", hkey(\".\"), \", \",\n\t\thkey(\"Backspace\"), \": type new value then \", hkey(\"Enter\"),\n\t\t]\n\n\tdef __init__(self, *args):\n\t\tsuper(UrwidDisplay, self).__init__(*args)\n\n\tdef run(self):\n\t\ttry:\n\t\t\tmain_loop = urwid.MainLoop(self.build_ui(), self.palette,\n\t\t\t unhandled_input=self.handle_input)\n\t\t\tmain_loop.set_alarm_in(self.poll_period, self.poll_callback)\n\t\t\tmain_loop.run()\n\t\tfinally:\n\t\t\tself.rig.defer(None)\n\n\tdef handle_input(self, input):\n\t\t\"\"\"Handle otherwise-unhandled input events.\"\"\"\n\t\tif input == \"q\":\n\t\t\traise urwid.ExitMainLoop()\n\n\tdef handle_message(self, msg):\n\t\tif msg[0] == \"log\":\n\t\t\tself.logtext.add(msg[1])\n\t\telif msg[0] == \"set_param\":\n\t\t\tsubscriptions = msg[1].get_param(\"widget_subscriptions\")\n\t\t\tif subscriptions is not None:\n\t\t\t\twidget = subscriptions.get(msg[2])\n\t\t\t\tif widget is not None:\n\t\t\t\t\twidget.receive_param(msg[3])\n\t\telif msg[0] in (\"add_frontend\", \"remove_frontend\"):\n\t\t\tself.listwalker.rebuild_list()\n\n\tdef poll_callback(self, main_loop, user_data):\n\t\t\"\"\"Callback that runs every poll_period (more or less).\"\"\"\n\n\t\tif self.process_input_queue():\n\t\t\traise urwid.ExitMainLoop()\n\n\t\tmain_loop.set_alarm_in(self.poll_period, self.poll_callback)\n\n\tdef build_ui(self):\n\t\t\"\"\"Construct the UI, returning the top-level widget.\"\"\"\n\n\t\tself.listwalker = RigWalker(self.rig)\n\t\tself.listbox = urwid.ListBox(self.listwalker)\n\n\t\tself.logtext = LogText()\n\n\t\ttop = AttrMap(Text(self.header_markup), \"header\")\n\t\tbottom = AttrMap(self.logtext, \"log\")\n\t\tframe = urwid.Frame(self.listbox, header=top, footer=bottom)\n\t\treturn frame\n","sub_path":"softriglib/urwiddisplay.py","file_name":"urwiddisplay.py","file_ext":"py","file_size_in_byte":13078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573295249","text":"from bokeh.core.properties import value\nfrom bokeh.io import show, output_file\nfrom bokeh.plotting import figure\nfrom bokeh.models import Legend\nimport pandas\n\nread_data = pandas.read_csv(open('data/us-population-by-age.csv', 'r'), delimiter=\",\")\n\nissue = read_data['Year'].values\nvote = ['Under 5', '5 to 19', '20 to 44','45 to 64','65+']\ncolors = [\"#66c2a5\", \"#e84d60\", \"#bdbdbd\",\"#EA340D\",\"#68CC74\"]\nyearlist = []\nfor i in range(len(issue)):\n yearlist.insert(i, str(issue[i]))\n print(i, issue[i])\n\noutput_file(\"stacked.html\")\n\np = figure(x_range=yearlist, height=350, title=\"Approval ratings for Barack Obama in 2010\",\n toolbar_location=\"right\", tools=\"hover,tap, save\", tooltips=\"$name: @$name\")\n\nv = p.vbar_stack(vote, x='Year', width=0.9, color=colors, source=read_data)\n\np.y_range.start = 0\np.yaxis[0].axis_label = 'Percentage (%)'\np.x_range.range_padding = 0.1\np.xaxis.major_label_orientation = 1\np.xgrid.grid_line_color = None\np.axis.minor_tick_line_color = None\np.outline_line_color = None\n# p.legend.location = \"top_right\"\n# p.legend.orientation = \"vertical\"\n\nlegend = Legend(items=[\n (\"Approve\", [v[0]]),\n (\"Disapprove\", [v[1]]),\n (\"None\", [v[2]]),\n ], location=(0, 100))\n\np.add_layout(legend, 'right')\n\nshow(p)\n\n","sub_path":"Lab-ch06-20200213/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"19726511","text":"from django.contrib import admin\nfrom django.urls import path\nfrom main import views\n\nurlpatterns = [\n path('ocupaciones_usuarios/',views.mostrar_ocupaciones),\n path('puntuaciones_usuario/',views.mostrar_puntuaciones_usuario),\n path('mejores_peliculas/',views.mostrar_mejores_peliculas),\n path('busqueda_peliculas/',views.mostrar_peliculas_year),\n path('',views.index),\n path('index.html/', views.index),\n path('populate/', views.populateDatabase),\n path('ingresar/', views.ingresar), \n path('admin/',admin.site.urls),\n ]\n","sub_path":"EjercicioDjangoPractica1Solucion/EjercicioDjango/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137129329","text":"#!/usr/local/bin/python3\n\nclass Node:\n def __init__(self, val):\n self.left = None\n self.right = None\n self.val = val\n \n def __repr__(self): \n return f\"({self.val})\"\n\n\nclass Tree:\n def __init__(self, root, limit):\n self.root = Node(root)\n self.limit = limit\n \n def __repr__(self):\n return f\"[{self.root.left} <-- {self.root} --> {self.root.right}]\"\n \ndef make(): \n r = Node(0)\n r.left = Node(1)\n r.right = Node(2)\n r.left.left = Node(3)\n r.left.right = Node(4)\n r.right.left = Node(5)\n r.right.right = Node(6)\n return r\n\n\"\"\"\nmake() gives us the following tree:\n 0\n 1 2\n 3 4 5 6\n\"\"\"\n\ndef inOrder(node):\n if node:\n inOrder(node.left)\n print(node.val)\n inOrder(node.right)\n\ndef preOrder(node):\n if node:\n print(node.val)\n preOrder(node.left)\n preOrder(node.right)\n\ndef postOrder(node):\n if node:\n postOrder(node.left)\n postOrder(node.right)\n print(node.val)\n\n\"\"\"\n>>> from tree import * \n>>> t = make()\n>>> inOrder(t)\n3\n1\n4\n0\n5\n2\n6\n>>> preOrder(t)\n0\n1\n3\n4\n2\n5\n6\n>>> postOrder(t) \n3\n4\n1\n5\n6\n2\n0\n\"\"\"\n\nfrom queue import Queue\nfrom typing import Dict\n\ndef bfs(node):\n # for each node in our tree, visit its children, and their children, and so on\n visited = Queue()\n visited.put(node)\n seen: Dict[Node, bool] = {node: True}\n while not visited.empty():\n n = visited.get()\n print(n)\n for node in [n.left, n.right]:\n if node is None:\n continue\n if not seen.get(node):\n visited.put(node)\n\n\n\"\"\"\n>>> bfs(t)\n(0)\n(1)\n(2)\n(3)\n(4)\n(5)\n(6)\n\"\"\"","sub_path":"practice/trees/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"608617919","text":"from . import admin\r\nfrom app import db\r\nfrom flask import render_template, flash, redirect, url_for\r\nfrom app.models import Product\r\nfrom app.templates.database.forms import ProductDataForm\r\nfrom flask_login import login_required\r\n\r\n\r\n@admin.route('/product_list/', methods=[\"GET\"])\r\n# @login_required\r\ndef product_list(page):\r\n if page is None:\r\n page = 1\r\n page_data = Product.query.order_by(\r\n Product.id.asc()\r\n ).paginate(page=page, per_page=5)\r\n return render_template('product_list.html', page_data=page_data)\r\n\r\n\r\n@admin.route('/product_edit', methods=[\"GET\", \"POST\"])\r\n# @login_required\r\ndef product_edit():\r\n form = ProductDataForm()\r\n return render_template('edit/product_edit.html', form=form)\r\n\r\n\r\n@admin.route('/product_add', methods=['GET', 'POST'])\r\n# @login_required\r\ndef product_add():\r\n form = ProductDataForm()\r\n if form.validate_on_submit():\r\n name = form.name.data\r\n product_id = form.product_id.data\r\n node = form.node.data\r\n is_gateway = form.is_gateway.data\r\n networking = form.networking.data\r\n data_format = form.data_format.data\r\n is_authen = form.is_authen.data\r\n authen_id = form.authen_id.data\r\n description = form.description.data\r\n\r\n product = Product(name=name,\r\n product_id=product_id,\r\n node=node,\r\n is_gateway=is_gateway,\r\n networking=networking,\r\n data_format=data_format,\r\n is_authen=is_authen,\r\n authen_id=authen_id,\r\n description=description)\r\n\r\n db.session.add(product)\r\n db.session.commit()\r\n flash('Product数据添加成功!', 'ok')\r\n return redirect(url_for('admin.product_add'))\r\n return render_template('database/product_add.html', form=form)\r\n","sub_path":"app/admin/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"85705650","text":"import random\n\n\nclass OTService:\n def __init__(self, transfer_protocol):\n self.transfer_protocol = transfer_protocol\n\n def receiverOT(self, A, B, w, m):\n for i in range(w):\n A_column = []\n B_column = []\n for line in range(m):\n A_column.append(A[line][i])\n B_column.append(B[line][i])\n data = {\"A\": A_column, \"B\": B_column}\n self.transfer_protocol.send_OT(data)\n\n def receiver_randomOT(self, A, B, w, m):\n for i in range(w):\n A_column = []\n B_column = []\n for line in range(m):\n A_column.append(A[line][i])\n B_column.append(B[line][i])\n r_i1 = [random.randint(0, 1) for c in range(m)]\n delta_i = [int(bool(r_i1[i]) ^ bool(B_column[i])) for i in range(m)]\n data = {\"r_0\": A_column, \"r_1\": r_i1, \"delta\": delta_i}\n self.transfer_protocol.send_OT(data)\n\n def senderOT(self, s, w, m):\n C = [[0 for c in range(w)] for l in range(m)]\n for it in range(w):\n data = self.transfer_protocol.receiveOT()\n #print(data)\n if s[it] == \"0\":\n selected = data[\"A\"]\n else:\n selected = data[\"B\"]\n for l in range(m):\n C[l][it] = selected[l]\n return C\n\n def sender_randomOT(self, s, w, m):\n C = [[0 for c in range(w)] for l in range(m)]\n for it in range(w):\n data = self.transfer_protocol.receiveOT()\n #print(data)\n if s[it] == \"0\":\n selected = data[\"r_0\"]\n else:\n selected = [int(bool(data[\"r_1\"][i]) ^ bool(data[\"delta\"][i])) for i in range(m)]\n for l in range(m):\n C[l][it] = selected[l]\n return C\n","sub_path":"Entities/OTService.py","file_name":"OTService.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279714403","text":"# -*- coding: utf-8 -*-\n# this is basic configuration used by django project on local developer machine\n# this file should be symlinked to the directory of your project ->module, where standard settins.py lies.\n# Copy only if you need to fine tune it.\n# In docker\nDEBUG = True\nSASS_DEBUG = DEBUG\n# COMPRESS_ENABLED = True\nADMINS = ()\nimport os\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'DB',\n 'USER': 'root',\n 'PASSWORD': 'root',\n 'HOST': 'db',\n 'PORT': '3306',\n 'ATOMIC_REQUESTS': True\n },\n}\n# # Celery in docker\nBROKER_URL = 'amqp://rabbitmq:rabbitmq@rabbitmq:5672/'\nCELERY_ALWAYS_EAGER = False\n\n# Redis in docker\nWS4REDIS_CONNECTION = {\n 'host': 'redis',\n 'port': 6379,\n}\n\n# Haystack in docker\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',\n 'URL': 'http://elasticsearch:9200/',\n 'INDEX_NAME': 'local-docker',\n 'TIMEOUT': 120,\n },\n}\n# use along with haystack\nELASTICSEARCH_URL = \"elasticsearch:9200\"\n\nINTERNAL_IPS = (\n \"127.0.0.1\",\n \"testserver\",\n \"localhost\",\n)\nALLOWED_HOSTS = INTERNAL_IPS\nDIET_COMPRESS_STATIC_IMAGES = False\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211'\n }\n}\n\n# if SASS_DEBUG:\n# COMPRESS_PRECOMPILERS = (\n# # ('text/x-scss', 'sass --scss --debug-info {infile} {outfile}'),\n# ('text/x-scss', 'sass --scss --compass --debug-info {infile} {outfile}'),\n# )\n# else:\n# COMPRESS_PRECOMPILERS = (\n# ('text/x-scss', 'sass --scss --compass {infile} {outfile}'),\n# )\n# disable on local\nRAVEN_CONFIG = {\n 'dsn': '',\n}\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n# uncomment the settings below to see all db queries on console\n#\n# LOGGING = {\n# 'disable_existing_loggers': False,\n# 'version': 1,\n# 'handlers': {\n# 'console': {\n# # logging handler that outputs log messages to terminal\n# 'class': 'logging.StreamHandler',\n# 'level': 'DEBUG', # message level to be written to console\n# },\n# },\n# 'loggers': {\n# '': {\n# # this sets root level logger to log debug and higher level\n# # logs to console. All other loggers inherit settings from\n# # root level logger.\n# 'handlers': ['console'],\n# 'level': 'DEBUG',\n# 'propagate': False, # this tells logger to send logging message\n# # to its parent (will send if set to True)\n# },\n# 'django.db': {\n# # django also has database level logging\n# },\n# },\n# }\n\n# if you need django debug toolbar only for local (watch out for tests):\nUSE_DEBUG_TOOLBAR = False\n# USE_DEBUG_TOOLBAR = True\n\nif USE_DEBUG_TOOLBAR:\n from django.conf import settings\n\n MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware'] + list(settings.MIDDLEWARE)\n import django.VERSION\n if django.VERSION < (1, 10):\n MIDDLEWARE_CLASSES = ['debug_toolbar.middleware.DebugToolbarMiddleware'] + list(settings.MIDDLEWARE_CLASSES)\n\n INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['debug_toolbar']\n DEBUG_TOOLBAR_PATCH_SETTINGS = True\n\n REST_FRAMEWORK = settings.REST_FRAMEWORK\n\n REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = list(\n REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']) + ['rest_framework.authentication.SessionAuthentication']\n\n\n# update test server with counting number of queries\nUSE_QUERIES_NUMBER_IN_TEST_SERVER = True\nif USE_QUERIES_NUMBER_IN_TEST_SERVER:\n from django.conf import settings\n project = lambda: os.path.basename(os.path.dirname(os.path.realpath(__file__)))\n QUERIES_NUMBER_WARN = 7\n QUERIES_ERR_NUMBER = 15\n INSTALLED_APPS = list(settings.INSTALLED_APPS) + [str(project()) + '.utils.hacks']\n\n\n# intercom\nINTERCOM_ID_PREFIX = 'local'\n","sub_path":"devel/pycommon/docker_local_settings.py","file_name":"docker_local_settings.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68487567","text":"\n# coding: utf-8\n\n# ## Imports\n\n# In[1]:\n\nimport os\nimport datetime\nimport math\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nget_ipython().magic('matplotlib inline')\n\n\n# ## Read Data\n\n# In[4]:\n\nfolder = 'C:\\\\Users\\\\levay_b\\\\Work\\\\XRF_Data\\\\Model_Tests\\\\Standards_Fittings\\\\ReducedMinDiff'\n\nXRF1_datapath = os.path.join(folder, 'XRF1_Standards_wFit.csv')\nXRF2_datapath = os.path.join(folder, 'XRF2_Standards_wFit.csv')\n\nXRF1_data = pd.read_csv(XRF1_datapath)\nXRF2_data = pd.read_csv(XRF2_datapath)\n\n\n# ## Filter Bad Data\n\n# In[5]:\n\nXRF1_locations = XRF1_data[XRF1_data['Sample'].isin([50,100,150])]\nXRF2_locations = XRF2_data[XRF2_data['Sample'].isin([50,100,150])]\n\nXRF1_counts = XRF1_locations[XRF1_locations['Throughput'] > 10000]\nXRF2_counts = XRF2_locations[XRF2_locations['Throughput'] > 10000]\n\nXRF1_filtered = XRF1_counts[XRF1_counts['Ar-Ka Area'] < -1000]\nXRF2_filtered = XRF2_counts[XRF2_counts['Ar-Ka Area'] < -1000]\n\nXRF2_filtered = XRF2_filtered[XRF2_filtered['Noise Val'] > 0.00]\nXRF2_filtered = XRF2_filtered[XRF2_filtered['Noise Val'] < 0.12]\nXRF2_filtered = XRF2_filtered[XRF2_filtered['Fano Val'] < 0.14]\n\n\n# ## Create Date Column For Plotting\n\n# In[6]:\n\ndef create_datetime(row):\n timepts = row['Acquisition time'].split(\":\")\n return datetime.datetime(row['Year'], row['Month'], row['Day'], \n int(timepts[0]), int(timepts[1]), int(timepts[2]))\n\n\n# In[7]:\n\nXRF1_datetime = XRF1_filtered.apply(create_datetime, axis=1)\nXRF2_datetime = XRF2_filtered.apply(create_datetime, axis=1)\n\nXRF1_df = XRF1_filtered.copy()\nXRF2_df = XRF2_filtered.copy()\n\nXRF1_df['Datetime'] = XRF1_datetime\nXRF2_df['Datetime'] = XRF2_datetime\n\n\n# In[8]:\n\nXRF1_df.columns\n\n\n# ## Plot Data\n\n# In[9]:\n\ndef plot_data(df, cols, width, height, title):\n df_50 = df[df['Sample'] == 50]\n df_100 = df[df['Sample'] == 100]\n df_150 = df[df['Sample'] == 150]\n \n n_subs = len(cols)\n fig_width = width\n fig_height = n_subs * height\n \n fig = plt.figure(figsize=(fig_width,fig_height))\n for i, col in enumerate(cols):\n ax = fig.add_subplot(n_subs, 1, (i+1))\n ax.plot_date(df_50['Datetime'], df_50[col], label='50mm')\n ax.plot_date(df_100['Datetime'], df_100[col], label='100mm')\n ax.plot_date(df_150['Datetime'], df_150[col], label='150mm')\n ax.set_xlabel('Date')\n ax.set_ylabel('Value')\n ax.set_title(title + \" \" + col)\n ax.legend()\n\n plt.tight_layout()\n plt.show()\n\n\n# In[10]:\n\ncols = ['Throughput', 'Oveall Chi2', 'Zero Val', 'Gain Val', 'Noise Val', 'Fano Val']\n\nplot_data(XRF1_df, cols, 15.0, 7.5, \"XRF1\")\n\n\n# In[11]:\n\nplot_data(XRF2_df, cols, 15.0, 7.5, \"XRF2\")\n\n\n# ## Sensitivity to Gain and Offset\n\n# In[12]:\n\nXRF1_ch = XRF1_df.copy()\n\nXRF1_ch['Gain Mean'] = XRF1_ch['Gain Val'].mean()\nXRF1_ch['Zero Ref'] = 0.0\n\n\n# In[13]:\n\ndef channel(energy, gain, zero):\n return round((energy - zero) / gain)\n\n\n# In[14]:\n\ndef channel_diffs(df, peaks, gain_ref, zero_ref):\n bins_ch = [-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5]\n n_rows = int(math.ceil(len(peaks)/2))\n n_cols = 2\n \n fig_width = n_cols * 8\n fig_height = n_rows * 7\n fig = plt.figure(figsize=(fig_width,fig_height))\n \n for i, (peak, energy) in enumerate(peaks.items()):\n col_name = peak + \" DelCh\"\n df[col_name] = (df.apply(lambda x: channel(energy, x[gain_ref], x[zero_ref]), axis=1) - \n df.apply(lambda x: channel(energy, x['Gain Val'], x['Zero Val']), axis=1))\n\n ax = fig.add_subplot(3, 2, (i+1))\n ax.hist(df[col_name], bins=bins_ch)\n ax.set_title(col_name)\n\n plt.tight_layout()\n plt.show()\n\n\n# In[ ]:\n\n# Si Ka = 1.74 keV\n# Ca Ka = 3.692 keV\n# Fe Ka = 6.404 keV\n# Sr Ka = 14.166 keV\n# Ag Ka = 22.163 keV\n# Ba Ka = 32.194 keV\n\npeaks = {'Si-Ka': 1.74, 'Ca-Ka': 3.692, 'Fe-Ka': 6.404, 'Sr-Ka': 14.166, 'Ag-Ka': 22.163, 'Ba-Ka': 32.194}\n\nchannel_diffs(XRF1_ch, peaks, 'Gain Val', 'Zero Ref')\n\n","sub_path":"axml_processing/view_fitting.py","file_name":"view_fitting.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629429195","text":"import os\r\n\r\n\r\nimport pandas as pd\r\nimport openpyxl\r\nfrom openpyxl.styles import PatternFill\r\nfrom openpyxl.styles import Font\r\n\r\nfrom main_windows import Ui_Form\r\n\r\n\r\n# from statement import Statement\r\n\r\n###获取筛选项并整理到一个excel###\r\n\r\nclass GetFilter(object):\r\n\r\n def __init__(self):\r\n self.path_list = []\r\n self.bace_path = r'D:\\杨伟强\\工作\\可口可乐数据处理\\table' #获取所有路径下的文件\r\n\r\n def get_bybanner_city(self):\r\n \"\"\"获取bybanner city(测试去重excel.xlsx)\"\"\"\r\n lins_df = pd.read_excel('pop.xlsx')\r\n lins_df['tag'] = lins_df['BG'] + lins_df['OU'] + lins_df['City']\r\n new_lins_df = lins_df[['BG', 'OU', 'City', 'tag']]\r\n print(new_lins_df)\r\n new_lins_df.drop_duplicates(subset='tag', keep='first', inplace=True)\r\n new_lins_df.sort_values(by=[\"BG\", \"OU\", \"City\"], inplace=True)\r\n b = new_lins_df.iloc[:, :3]\r\n b.index = b.index + 1 # shifting index\r\n df = pd.DataFrame(data=[[\"Total\", \"Total\", \"Total\"]], columns=[\"BG\", \"OU\", \"City\"])\r\n com_db = df.append(b)\r\n # b.loc[-1] = [\"Total\", \"Total\", \"Total\"]\r\n # b = b.sort_index()\r\n print(com_db)\r\n com_db.to_excel('测试去重excel.xlsx', sheet_name='测试', index=False)\r\n\r\n def get_allfile_path(self, sPath):\r\n \"\"\"列出当前路径下的所有文件夹和文件 并进行遍历\"\"\"\r\n for schild in os.listdir(sPath):\r\n # 拼接地址\r\n sChildPath = os.path.join(sPath, schild)\r\n # 判断当前遍历到的是文件还是文件夹\r\n if os.path.isdir(sChildPath):\r\n # 再次递归调用\r\n self.get_allfile_path(sChildPath)\r\n else:\r\n if '%' in sChildPath or '~$' in sChildPath: # 除去不需要的\r\n pass\r\n else:\r\n sChildPath_list = sChildPath.rsplit(\"\\\\\", 1)\r\n sChildPath_list.append(sChildPath)\r\n self.path_list.append(sChildPath_list)\r\n\r\n def save(self):\r\n \"\"\"获取所有路径下的文件(测试路径总和.xlsx)\"\"\"\r\n bace_path = self.bace_path\r\n self.get_allfile_path(bace_path)\r\n # writer = pd.ExcelWriter(\"测试路径总和.xlsx\")\r\n df = pd.DataFrame(data=self.path_list, columns=[\"PathName\", \"FileName\", \"all_path\"])\r\n df.sort_values(by=[\"PathName\", \"FileName\"], inplace=True)\r\n print(df)\r\n # df.to_excel(writer, index=False, sheet_name=\"Dirs\")\r\n df.to_excel('测试路径总和.xlsx', sheet_name='测试', index=False)\r\n # writer.save()\r\n # writer.close()\r\n\r\n def get_bybanner_ou_No(self):\r\n \"\"\"获取bybanner_No 和 ou_No(测试banner_ou总和.xlsx)\"\"\"\r\n lins_df = pd.read_excel('测试路径总和.xlsx')\r\n banner_df = pd.read_excel('fiter_bybanner.xlsx', sheet_name='fiterbybanner')\r\n ou_df = pd.read_excel('fiter_byou.xlsx', sheet_name='fiterbyou')\r\n # print(lins_df)\r\n writer = pd.ExcelWriter(\"测试banner_ou总和.xlsx\")\r\n banner_list = []\r\n ou_list = []\r\n # banner_no = 1\r\n # ou_no = 1\r\n # 处理 fiter_bybanner 数据\r\n banner_fit_name = list(banner_df['Combination'])\r\n banner_fit_No = list(banner_df['FilterNo'])\r\n # 处理 fiter_ou 数据\r\n ou_fit_name = list(ou_df['Combination'])\r\n ou_fit_No = list(ou_df['FilterNo'])\r\n # print(banner_fit_name)\r\n print(ou_fit_name)\r\n for one in lins_df.iterrows():\r\n if \"by banner\" in one[1]['PathName']: # 为bybanner的路径\r\n type = one[1]['FileName'].replace('可乐-Banner-', '').replace('(Abs).xlsx', '')\r\n lins_list = []\r\n lins_list.append(one[1][\"all_path\"]) # 文件路径\r\n if 'base=BG' in one[1]['PathName']: # BG 分类的\r\n lins_list.append(type)\r\n lins_list.append('Total')\r\n lins_list.append('Total')\r\n elif 'base=City' in one[1]['PathName']: # City 分类的\r\n lins_list.append('Total')\r\n lins_list.append('Total')\r\n lins_list.append(type)\r\n else: # OU 分类的\r\n lins_list.append('Total')\r\n lins_list.append(type)\r\n lins_list.append('Total')\r\n # print(''.join(lins_list[1:]))\r\n if ''.join(lins_list[1:]) in banner_fit_name:\r\n index_ = banner_fit_name.index(''.join(lins_list[1:]))\r\n lins_list.append(banner_fit_No[index_])\r\n else:\r\n continue\r\n # lins_list.append(banner_no)\r\n bacontinue_flag = False\r\n for i in banner_list: # 已存在就不加入了\r\n if i[-1] == lins_list[-1]:\r\n bacontinue_flag = True\r\n break\r\n if bacontinue_flag:\r\n continue\r\n banner_list.append(lins_list)\r\n # banner_no += 1\r\n elif \"by bottler\" in one[1]['PathName']:\r\n lins_list = []\r\n lins_list.append(one[1][\"all_path\"]) # 文��路径\r\n if 'base=Channel' in one[1]['PathName']: # BG 分类的\r\n type = one[1]['FileName'].replace('可乐-BG&OU-', '').replace('(Abs).xlsx', '')\r\n if type == 'H S':\r\n type = 'H/S'\r\n lins_list.append(type)\r\n lins_list.append('Total')\r\n\r\n elif 'base=Banner' in one[1]['PathName']: # City 分类的\r\n type = one[1]['FileName'].replace('可乐-BG&OU-', '').replace('(Abs).xlsx', '').split('_')\r\n if type[0] == 'H S':\r\n type[0] = 'H/S'\r\n lins_list.append(type[0])\r\n lins_list.append(type[1])\r\n print(''.join(lins_list[1:]))\r\n if ''.join(lins_list[1:]) in ou_fit_name:\r\n index_ = ou_fit_name.index(''.join(lins_list[1:]))\r\n lins_list.append(ou_fit_No[index_])\r\n else:\r\n continue\r\n # lins_list.append(ou_no)\r\n continue_flag = False\r\n for i in ou_list: # 已存在就不加入了\r\n if i[-1] == lins_list[-1]:\r\n continue_flag = True\r\n break\r\n if continue_flag:\r\n continue\r\n ou_list.append(lins_list)\r\n # ou_no += 1\r\n\r\n df_banner = pd.DataFrame(data=banner_list, columns=[\"Source File\", \"BG\", \"OU\", \"City\", \"NO.\"])\r\n df_banner.sort_values(by=[\"NO.\"], inplace=True)\r\n df_banner.to_excel(writer, index=False, sheet_name=\"bybanner\")\r\n df_ou = pd.DataFrame(data=ou_list, columns=[\"Source File\", \"Channel\", \"Banner\", \"NO.\"])\r\n df_ou.sort_values(by=[\"NO.\"], inplace=True)\r\n df_ou.to_excel(writer, index=False, sheet_name=\"byou\")\r\n writer.save()\r\n writer.close()\r\n # df.sort_values(by=[\"Source File\"], inplace=True)\r\n # print(df_banner)\r\n\r\n def get_bybanner_fiter_no(self):\r\n \"\"\"获取bybanner_fiter No.(测试fiter_bybanner.xlsx)\"\"\"\r\n lins_df = pd.read_excel('测试去重excel.xlsx')\r\n all_list = []\r\n for one_df in lins_df.iterrows():\r\n now_list = [one_df[1][\"BG\"], one_df[1][\"OU\"], one_df[1][\"City\"]]\r\n # print(now_list)\r\n all_list.append(now_list)\r\n j = 2\r\n ouNo = 1\r\n a_ouNo = 1\r\n maxFltNo = 1\r\n all_fit_list = []\r\n print(len(all_list))\r\n for i in range(len(all_list)):\r\n lins_list = ['Total', 'Total', all_list[i][2]]\r\n com_name = 'Total' + 'Total' + all_list[i][2]\r\n lins_list.append(com_name)\r\n lins_list.append(maxFltNo)\r\n city_flt = maxFltNo\r\n all_fit_list.append(lins_list)\r\n j += 1\r\n\r\n if city_flt > 1:\r\n lins_list = ['Total', all_list[i][1]]\r\n print(i)\r\n if all_list[i - 1][1] != all_list[i][1]:\r\n lins_list.append('Total')\r\n com_name = 'Total' + all_list[i][1] + 'Total'\r\n lins_list.append(com_name)\r\n try:\r\n if all_list[i + 1][1] == all_list[i][1]:\r\n maxFltNo += 1\r\n except:\r\n pass\r\n lins_list.append(maxFltNo)\r\n all_fit_list.append(lins_list)\r\n a_ouNo = maxFltNo\r\n ouNo += 1\r\n j += 1\r\n lins_list = ['Total', all_list[i][1], all_list[i][2]]\r\n com_name = 'Total' + all_list[i][1] + all_list[i][2]\r\n lins_list.append(com_name)\r\n lins_list.append(city_flt)\r\n all_fit_list.append(lins_list)\r\n else:\r\n lins_list.append(all_list[i][2])\r\n com_name = 'Total' + all_list[i][1] + all_list[i][2]\r\n lins_list.append(com_name)\r\n lins_list.append(city_flt)\r\n all_fit_list.append(lins_list)\r\n j += 1\r\n if all_list[i - 1][0] != all_list[i][0]:\r\n lins_list = [all_list[i][0], 'Total', 'Total']\r\n com_name = all_list[i][0] + 'Total' + 'Total'\r\n lins_list.append(com_name)\r\n try:\r\n if all_list[i + 1][0] == all_list[i][0]:\r\n maxFltNo += 1\r\n except:\r\n pass\r\n lins_list.append(maxFltNo)\r\n all_fit_list.append(lins_list)\r\n j += 1\r\n if all_list[i - 1][1] != all_list[i][1]:\r\n lins_list = [all_list[i][0], all_list[i][1], 'Total']\r\n com_name = all_list[i][0] + all_list[i][1] + 'Total'\r\n lins_list.append(com_name)\r\n try:\r\n if all_list[i + 1][1] == all_list[i][1]:\r\n lins_list.append(a_ouNo)\r\n else:\r\n lins_list.append(city_flt)\r\n except:\r\n lins_list.append(city_flt)\r\n all_fit_list.append(lins_list)\r\n j += 1\r\n lins_list = [all_list[i][0], all_list[i][1], all_list[i][2]]\r\n com_name = all_list[i][0] + all_list[i][1] + all_list[i][2]\r\n lins_list.append(com_name)\r\n lins_list.append(city_flt)\r\n all_fit_list.append(lins_list)\r\n else:\r\n lins_list = [all_list[i][0], all_list[i][1], all_list[i][2]]\r\n com_name = all_list[i][0] + all_list[i][1] + all_list[i][2]\r\n lins_list.append(com_name)\r\n lins_list.append(city_flt)\r\n all_fit_list.append(lins_list)\r\n maxFltNo += 1\r\n print(all_fit_list)\r\n df_ou = pd.DataFrame(data=all_fit_list, columns=['BG', 'OU', 'City', 'Combination', 'FilterNo'])\r\n df_ou.to_excel('fiter_bybanner.xlsx', index=False, sheet_name='fiterbybanner')\r\n\r\n def get_byou_fiter_no(self):\r\n \"\"\"待整理逻辑\"\"\"\r\n # 获取各类超市的规模\r\n all_market_df = pd.read_excel('pop.xlsx')\r\n market_type = ['Hyper', 'Super', 'Mini']\r\n lins_df = all_market_df[['Channel', 'Banner']]\r\n select_groupby = lins_df.groupby(['Banner', 'Channel'])\r\n all_name = []\r\n all_dict = dict() # 归类统计\r\n for name, data in select_groupby:\r\n lins_list = [0, 0, 0]\r\n if name[1] != 'Hyper' and name[1] != 'Super' and name[1] != 'MINI': # 剔除不要的\r\n continue\r\n if name[0] not in all_name:\r\n all_name.append(name[0])\r\n if name[1] == 'Hyper':\r\n lins_list[0] = len(data)\r\n elif name[1] == 'Super':\r\n lins_list[1] = len(data)\r\n else:\r\n lins_list[2] = len(data)\r\n lins_list.insert(0, lins_list[0] + lins_list[1])\r\n lins_list.insert(0, lins_list[1] + lins_list[2] + lins_list[3])\r\n all_dict.update({name[0]: lins_list})\r\n else:\r\n ard_list = all_dict[name[0]]\r\n if name[1] == 'Hyper':\r\n ard_list[2] = len(data)\r\n elif name[1] == 'Super':\r\n ard_list[3] = len(data)\r\n else:\r\n ard_list[4] = len(data)\r\n ard_list[1] = ard_list[2] + ard_list[3]\r\n ard_list[0] = ard_list[2] + ard_list[3] + ard_list[4]\r\n all_dict[name[0]] = ard_list\r\n # 生成fiter ou\r\n channel_banner_df = pd.read_excel('pop.xlsx')\r\n channel_df = channel_banner_df.iloc[:, 11].dropna(0)\r\n channel_list = list(channel_df)\r\n print(channel_list)\r\n banner_df = channel_banner_df.iloc[:, 22].dropna(0)\r\n banner_list = list(banner_df)\r\n banner_list.insert(0, \"Total\")\r\n print(banner_list)\r\n count = 0\r\n all_data = []\r\n for j, one_channel in enumerate(channel_list):\r\n next_count = ''\r\n for one_banner in banner_list:\r\n if j == 0:\r\n count += 1\r\n next_count = count\r\n else: # 'Total' 'H/S' 'Hyper', 'Super', 'Mini'\r\n if one_banner == \"Total\":\r\n count += 1\r\n next_count = count\r\n else:\r\n channel_type = all_dict[one_banner] # 获取各个超市对应的数据\r\n if one_channel == 'H/S': # 如果名为“H/S”\r\n if channel_type[1] == 0:\r\n continue\r\n if channel_type[1] != channel_type[0]:\r\n count += 1\r\n next_count = count\r\n else:\r\n for one_data in all_data:\r\n if one_data[0] == 'Total' and one_data[1] == one_banner:\r\n next_count = one_data[-1]\r\n break\r\n elif one_channel == 'Hyper':\r\n if channel_type[2] == 0:\r\n continue\r\n if channel_type[2] != channel_type[1]:\r\n count += 1\r\n next_count = count\r\n else:\r\n for one_data in all_data:\r\n if one_data[0] == 'H/S' and one_data[1] == one_banner:\r\n next_count = one_data[-1]\r\n break\r\n elif one_channel == 'Super':\r\n\r\n if channel_type[3] == 0:\r\n continue\r\n if channel_type[3] != channel_type[1]:\r\n count += 1\r\n next_count = count\r\n else:\r\n for one_data in all_data:\r\n if one_data[0] == 'H/S' and one_data[1] == one_banner:\r\n next_count = one_data[-1]\r\n break\r\n elif one_channel == 'Mini':\r\n if channel_type[4] == 0:\r\n continue\r\n if channel_type[4] != channel_type[0]:\r\n count += 1\r\n next_count = count\r\n else:\r\n for one_data in all_data:\r\n if one_data[0] == 'Mini' and one_data[1] == one_banner:\r\n next_count = one_data[-1]\r\n break\r\n else:\r\n count += 1\r\n next_count = count\r\n lins_list = []\r\n lins_list.append(one_channel)\r\n lins_list.append(one_banner)\r\n tag = one_channel + one_banner\r\n lins_list.append(tag)\r\n lins_list.append(next_count)\r\n all_data.append(lins_list)\r\n df_ou = pd.DataFrame(data=all_data, columns=[\"Channel\", \"Banner\", \"Combination\", \"FilterNo\"])\r\n df_ou.to_excel('fiter_byou.xlsx', index=False, sheet_name='fiterbyou')\r\n\r\n def summary_all_file(self):\r\n \"\"\"把所有子表整理成一张表\"\"\"\r\n\r\n bybanner_df = pd.read_excel('测试banner_ou总和.xlsx', sheet_name='bybanner') # 读取 测试路径总和.xlsx 生成的\r\n byou_df = pd.read_excel('测试banner_ou总和.xlsx', sheet_name='byou') # 读取 测试路径总和.xlsx 生成的\r\n fitbanner_df = pd.read_excel('fiter_bybanner.xlsx',\r\n sheet_name='fiterbybanner') # 读取 pop.xlsx 生成 测试去重excel.xlsx 生成的\r\n fitou_df = pd.read_excel('fiter_byou.xlsx', sheet_name='fiterbyou') # 读取 pop.xlsx 生成的\r\n allpath_df = pd.read_excel('测试路径总和.xlsx', sheet_name='测试') # 读取所有文件生产的\r\n pop_df = pd.read_excel('pop.xlsx') # pop 文件\r\n\r\n # tablecopy_df = pd.read_excel('测试汇总设置表.xlsx',sheet_name='TableCopy')\r\n writer = pd.ExcelWriter(\"测试设置表.xlsx\")\r\n bybanner_df.to_excel(writer, index=False, sheet_name='bybanner')\r\n byou_df.to_excel(writer, index=False, sheet_name='byou')\r\n fitbanner_df.to_excel(writer, index=False, sheet_name='fiterbybanner')\r\n fitou_df.to_excel(writer, index=False, sheet_name='fiterbyou')\r\n allpath_df.to_excel(writer, index=False, sheet_name='Dirs')\r\n pop_df.to_excel(writer, index=False, sheet_name='pop')\r\n # tablecopy_df.to_excel(writer,index=False,sheet_name=\"TableCopy\")\r\n writer.save()\r\n writer.close()\r\n self.write_fiterline_table() # 存筛选表\r\n\r\n # wb = openpyxl.load_workbook(name)\r\n\r\n def write_fiterline_table(self):\r\n \"\"\"整合设计表\"\"\"\r\n\r\n colors = ['EEE5DE', 'FFE1FF', 'C1FFC1', 'C6E2FF', 'FAEBD7'] # 颜色编码\r\n font = Font('宋体', bold=True, color='FFFFFF')\r\n wb = openpyxl.load_workbook('测试汇总设置表.xlsx')\r\n ws = wb['TableCopy']\r\n # sheets1=wb.sheetnames()#获取sheet页\r\n rows = ws.rows\r\n all_data_list = []\r\n for i in rows:\r\n lins_list = []\r\n for one_i in i:\r\n lins_list.append(one_i.value)\r\n # print(lins_list)\r\n all_data_list.append(lins_list)\r\n # print(i)\r\n wb = openpyxl.load_workbook('测试设置表.xlsx')\r\n wb.create_sheet('TableCopy') # 新建一个sheet\r\n ws = wb['TableCopy']\r\n for i in all_data_list:\r\n ws.append(i)\r\n fill = PatternFill(\"solid\", fgColor=\"36648B\") # 标题\r\n zm = ['A', 'B', 'C', 'D', 'E', 'F']\r\n for one_zm in zm:\r\n ws['{}1'.format(one_zm)].fill = fill\r\n ws['{}1'.format(one_zm)].font = font\r\n color = colors[0]\r\n color_id = 0\r\n for i in range(2, len(all_data_list)):\r\n # print(colors[color_id])\r\n fill = PatternFill(\"solid\", fgColor=colors[color_id])\r\n # print(fill)\r\n ws['A{}'.format(i)].fill = fill\r\n ws['B{}'.format(i)].fill = fill\r\n ws['C{}'.format(i)].fill = fill\r\n ws['D{}'.format(i)].fill = fill\r\n ws['E{}'.format(i)].fill = fill\r\n ws['F{}'.format(i)].fill = fill\r\n if ws['A{}'.format(i)].value != ws['A{}'.format(i + 1)].value:\r\n color_id += 1\r\n if color_id == 5:\r\n color_id = 1\r\n wb.save('{}.xlsx'.format('测试设置表'))\r\n\r\n def run(self):\r\n self.get_bybanner_city()\r\n self.get_bybanner_fiter_no()\r\n self.get_byou_fiter_no()\r\n self.get_bybanner_ou_No()\r\n self.summary_all_file()\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n a = GetFilter()\r\n a.run()\r\n # a = SaveInSql()\r\n # a.run()\r\n ###\r\n\r\n # a.get_bybanner_city()\r\n # a.get_bybanner_fiter_no()\r\n # a.get_byou_fiter_no()\r\n # a.get_bybanner_ou_No()\r\n # a.summary_all_file()\r\n # VisitMain()\r\n # a = Text()\r\n # a.get_fitter_list()\r\n","sub_path":"项目模块/可口可乐数据处理/get_all_filterNo.py","file_name":"get_all_filterNo.py","file_ext":"py","file_size_in_byte":21253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476015282","text":"# Copyright (C) 2019-2020 Zilliz. All rights reserved.\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\n__all__ = [\n \"ST_Point_UDF\",\n \"ST_Intersection_UDF\",\n \"ST_IsValid_UDF\",\n \"ST_PrecisionReduce_UDF\",\n \"ST_Equals_UDF\",\n \"ST_Touches_UDF\",\n \"ST_Overlaps_UDF\",\n \"ST_Crosses_UDF\",\n \"ST_IsSimple_UDF\",\n \"ST_GeometryType_UDF\",\n \"ST_MakeValid_UDF\",\n \"ST_SimplifyPreserveTopology_UDF\",\n \"ST_PolygonFromEnvelope_UDF\",\n \"ST_Contains_UDF\",\n \"ST_Intersects_UDF\",\n \"ST_Within_UDF\",\n \"ST_Distance_UDF\",\n \"ST_Area_UDF\",\n \"ST_Centroid_UDF\",\n \"ST_Length_UDF\",\n \"ST_HausdorffDistance_UDF\",\n \"ST_ConvexHull_UDF\",\n \"ST_NPoints_UDF\",\n \"ST_Envelope_UDF\",\n \"ST_Buffer_UDF\",\n \"ST_Union_Aggr_UDF\",\n \"ST_Envelope_Aggr_UDF\",\n \"ST_Transform_UDF\",\n \"ST_CurveToLine_UDF\",\n \"ST_GeomFromGeoJSON_UDF\",\n \"ST_PointFromText_UDF\",\n \"ST_PolygonFromText_UDF\",\n \"ST_LineStringFromText_UDF\",\n \"ST_GeomFromText_UDF\",\n \"ST_GeomFromWKT_UDF\",\n \"ST_AsText_UDF\",\n \"my_plot\" # or point_map\n]\n\nimport pyarrow as pa\nfrom pyspark.sql.functions import pandas_udf, PandasUDFType\n\ndef toArrow(parameter):\n return pa.array(parameter)\n\n@pandas_udf(\"string\", PandasUDFType.GROUPED_AGG)\ndef my_plot(x, y):\n arr_x = pa.array(x, type='uint32')\n arr_y = pa.array(y, type='uint32')\n from arctern_gis import point_map\n curve_z = point_map(arr_x, arr_y)\n curve_z_copy = curve_z\n curve_z = curve_z.buffers()[1].to_pybytes()\n return curve_z_copy.buffers()[1].hex()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_PointFromText_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_PolygonFromText_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_LineStringFromText_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_GeomFromWKT_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_GeomFromText_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_AsText_UDF(geo):\n return geo\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Point_UDF(x, y):\n arr_x = pa.array(x, type='double')\n arr_y = pa.array(y, type='double')\n from arctern_gis import ST_Point\n rs = ST_Point(arr_x, arr_y)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_GeomFromGeoJSON_UDF(json):\n geo = pa.array(json,type='string')\n from arctern_gis import ST_GeomFromGeoJSON\n rs = ST_GeomFromGeoJSON(geo)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Intersection_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Intersection\n rs = ST_Intersection(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_IsValid_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_IsValid\n rs = ST_IsValid(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_PrecisionReduce_UDF(geos, precision):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_PrecisionReduce\n rs = ST_PrecisionReduce(arr_geos, precision)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Equals_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Equals\n rs = ST_Equals(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Touches_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Touches\n rs = ST_Touches(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Overlaps_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Overlaps\n rs = ST_Overlaps(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Crosses_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Crosses\n rs = ST_Crosses(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_IsSimple_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_IsSimple\n rs = ST_IsSimple(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_GeometryType_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_GeometryType\n rs = ST_GeometryType(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_MakeValid_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_MakeValid\n rs = ST_MakeValid(arr_geos)\n return rs.to_pandas()\n\n# TODO: ST_SimplifyPreserveTopology\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_SimplifyPreserveTopology_UDF(geos, distance_tolerance):\n arr_geos = pa.array(geos, type='string')\n dis_tol = distance_tolerance[0]\n from arctern_gis import ST_SimplifyPreserveTopology\n rs = ST_SimplifyPreserveTopology(arr_geos, dis_tol)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_PolygonFromEnvelope_UDF(min_x, min_y, max_x, max_y):\n arr_min_x = pa.array(min_x, type='double')\n arr_min_y = pa.array(min_y, type='double')\n arr_max_x = pa.array(max_x, type='double')\n arr_max_y = pa.array(max_y, type='double')\n from arctern_gis import ST_PolygonFromEnvelope\n rs = ST_PolygonFromEnvelope(arr_min_x, arr_min_y, arr_max_x, arr_max_y)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Contains_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Contains\n rs = ST_Contains(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Intersects_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Intersects\n rs = ST_Intersects(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"boolean\", PandasUDFType.SCALAR)\ndef ST_Within_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Within\n rs = ST_Within(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"double\", PandasUDFType.SCALAR)\ndef ST_Distance_UDF(left, right):\n arr_left = pa.array(left, type='string')\n arr_right = pa.array(right, type='string')\n from arctern_gis import ST_Distance\n rs = ST_Distance(arr_left, arr_right)\n return rs.to_pandas()\n\n@pandas_udf(\"double\", PandasUDFType.SCALAR)\ndef ST_Area_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Area\n rs = ST_Area(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Centroid_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Centroid\n rs = ST_Centroid(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"double\", PandasUDFType.SCALAR)\ndef ST_Length_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Length\n rs = ST_Length(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"double\", PandasUDFType.SCALAR)\ndef ST_HausdorffDistance_UDF(geo1, geo2):\n arr1 = pa.array(geo1, type='string')\n arr2 = pa.array(geo2, type='string')\n from arctern_gis import ST_HausdorffDistance\n rs = ST_HausdorffDistance(arr1, arr2)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_ConvexHull_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_ConvexHull\n rs = ST_ConvexHull(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"int\", PandasUDFType.SCALAR)\ndef ST_NPoints_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_NPoints\n rs = ST_NPoints(arr_geos)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Envelope_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Envelope\n rs = ST_Envelope(arr_geos)\n return rs.to_pandas()\n\n# TODO: ST_Buffer, how to polymorphicly define the behaviour of spark udf\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Buffer_UDF(geos, dfDist):\n arr_geos = pa.array(geos, type='string')\n distance = dfDist[0]\n from arctern_gis import ST_Buffer\n rs = ST_Buffer(arr_geos, distance)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.GROUPED_AGG)\ndef ST_Union_Aggr_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Union_Aggr\n rs = ST_Union_Aggr(arr_geos)\n return str(rs[0])\n\n@pandas_udf(\"string\", PandasUDFType.GROUPED_AGG)\ndef ST_Envelope_Aggr_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Envelope_Aggr\n rs = ST_Envelope_Aggr(arr_geos)\n return str(rs[0])\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_Transform_UDF(geos, src_rs, dst_rs):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_Transform\n src_rs1 = bytes(src_rs[0], encoding=\"utf8\")\n dst_rs1 = bytes(dst_rs[0], encoding=\"utf8\")\n rs = ST_Transform(arr_geos, src_rs1, dst_rs1)\n return rs.to_pandas()\n\n@pandas_udf(\"string\", PandasUDFType.SCALAR)\ndef ST_CurveToLine_UDF(geos):\n arr_geos = pa.array(geos, type='string')\n from arctern_gis import ST_CurveToLine\n rs = ST_CurveToLine(arr_geos)\n return rs.to_pandas()\n","sub_path":"spark/pyspark/arctern_pyspark/_wrapper_func.py","file_name":"_wrapper_func.py","file_ext":"py","file_size_in_byte":10396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595849981","text":"from collections import defaultdict\n\ndef isPalindrome(word):\n if len(word) <= 1:\n return True\n return word[0] == word[-1] and isPalindrome(word[1:-1])\n\nclass Solution(object):\n def palindromePairs(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[List[int]]\n \"\"\"\n\n '''\n The trie has a next which goes to the next char.\n The end trie is such that it holds not char, just that it is a left and the index.\n palindromesBelow tells is for a certain node, what indicies are below it such that the parts below of these indicies are palindromes. \n For example if we have a word abcdc with index 5 the node with b in it will have palindromesBelow having 5 in it and the node after c will be just having index = 5 in it, and empty other fields. \n '''\n \n class Trie(object):\n \n def __init__(self):\n self.next = defaultdict(Trie)\n self.index = -1\n self.palindromesBelow = []\n \n def addWord(self, word, index):\n \n trie = self\n \n for i,c in enumerate(reversed(word)):\n if isPalindrome(word[0:len(word)-i]):\n trie.palindromesBelow.append(index)\n trie = trie.next[c]\n trie.index = index\n \n pairs = []\n \n trie = Trie()\n for index, word in enumerate(words):\n trie.addWord(word, index)\n \n def getCandidates(trie, word, index):\n candidates = []\n \n while word:\n \n # Palindrome of the form A B where |A| > |B|.\n if trie.index >= 0:\n if isPalindrome(word):\n candidates.append(trie.index)\n # The trie ended. Either this node will be the end of some reversed word.\n if word[0] not in trie.next:\n return candidates\n else:\n trie = trie.next[word[0]]\n \n word = word[1:]\n\n # Here, the trie has been traversed fully.\n \n # Palindrome A B where |A| = |B|. \n if trie.index >= 0:\n candidates.append(trie.index)\n \n # Palindrome A B where |B| > |A|.\n candidates.extend(trie.palindromesBelow)\n \n return candidates\n \n output = []\n for i, word in enumerate(words):\n candidates = getCandidates(trie, word, i)\n output.extend([[i, c] for c in candidates if i != c])\n return output\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"palindromePairs.py","file_name":"palindromePairs.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"560753119","text":"\"\"\"\r\n\r\nplt\r\n\r\n\r\nfigure 建立畫布\r\naxes 劃出矩形\r\nset_title 標題\r\nset_xlabel x軸說明\r\nset_ylabel y軸說明\r\nsavefig('image.jpg') 儲存圖 需引入pip install pillow\r\n\"\"\"\r\n\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nfig = plt.figure(figsize=(16,6))\r\n\r\np = plt.axes((0.1, 0.2, 0.3, 0.4), facecolor='w')\r\np.set_title(\"title\")\r\np.set_xlabel(\"xlabel\")\r\np.set_ylabel(\"ylabel\")\r\nplt.savefig('image.jpg')\r\nplt.show()","sub_path":"codenote/matplot/plt.axes.py","file_name":"plt.axes.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"339878888","text":"import random\n\ndef _try_composite(a, d, n, s):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2**i * d, n) == n-1:\n return False\n return True # n is definitely composite\n \n_known_primes = [2, 3]\n\ndef isPrime(n, _precision_for_huge_n=16):\n if n in _known_primes:\n return True\n if any((n % p) == 0 for p in _known_primes) or n in (0, 1):\n return False\n d, s = n - 1, 0\n while not d % 2:\n d, s = d >> 1, s + 1\n # Returns exact according to http://primes.utm.edu/prove/prove2_3.html\n if n < 1373653: \n return not any(_try_composite(a, d, n, s) for a in (2, 3))\n if n < 25326001: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))\n if n < 118670087467: \n if n == 3215031751: \n return False\n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7))\n if n < 2152302898747: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11))\n if n < 3474749660383: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13))\n if n < 341550071728321: \n return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17))\n # otherwise\n return not any(_try_composite(a, d, n, s) \n for a in _known_primes[:_precision_for_huge_n])\n\n\ndef totient(number): \n if(isPrime(number, 3)):\n return number-1\n else:\n return False\n\n\n# it isnt the best method to compute prime numbers\ndef prime(n): # check if the number is prime\n if (n <= 1):\n return False\n if (n <= 3):\n return True\n\n if (n%2 == 0 or n%3 == 0):\n return False\n\n i = 5\n while(i * i <= n):\n if (n%i == 0 or n%(i+2) == 0):\n return False\n i+=6\n return True\n\n\ndef generate_E(num): \n def mdc(n1,n2):\n rest = 1\n while(n2 != 0):\n rest = n1%n2\n n1 = n2\n n2 = rest\n return n1\n\n while True:\n e = random.randrange(2,num) \n if(mdc(num,e) == 1):\n return e\n\n\ndef generate_prime(): # generate the prime number - p e q\n while True: # 2**2048 is the RSA standart keys\n x=random.randrange(1,100) # define the range of the primes\n if(isPrime(x, 3)==True):\n return x\n\n\ndef mod(a,b): # mod function\n if(a(.*?)', html)\nif title is not None:\n print('Title : '+title.group(1))\n \n# Search and print video thumbnail url\nthum_url = re.search('.thumbnailUrl.:\"(.*?)\"', html)\nif thum_url is not None:\n print('Thumbnail Url : '+thum_url.group(1).replace(\"\\/\",\"/\"))\n\n# Search and print SD video url\nsd_url = re.search('sd_src:\"(.*?)\",', html)\nif sd_url is not None:\n print('SD : '+sd_url.group(1))\n\n# Search and print HD video url\nhd_url = re.search('hd_src:\"(.*?)\",', html)\nif hd_url is not None:\n print('HD : '+hd_url.group(1))\n\n# Search and print audio url (Download video as audio)\naudio_url = re.search('audio:..url:\"(.*?)\"', html)\nif audio_url is not None:\n print('audio : '+audio_url.group(1))\n \n# Search and print 144p video url (Without audio)\nv_144 = re.search('144p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_144 is not None:\n print('144p : '+v_144.group(1).replace(\"&\",\"&\"))\n\n# Search and print 240p video url (Without audio)\nv_240 = re.search('240p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_240 is not None:\n print('240p : '+v_240.group(1).replace(\"&\",\"&\"))\n \n# Search and print 360p video url (Without audio)\nv_360 = re.search('360p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_360 is not None:\n print('360p : '+v_360.group(1).replace(\"&\",\"&\"))\n\n# Search and print 480p video url (Without audio)\nv_480 = re.search('480p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_480 is not None:\n print('480p : '+v_480.group(1).replace(\"&\",\"&\"))\n\n# Search and print 720p video url (Without audio)\nv_720 = re.search('720p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_720 is not None:\n print('720p : '+v_720.group(1).replace(\"&\",\"&\"))\n\n# Search and print 1080p video url (Without audio)\nv_1080 = re.search('1080p.*?>.x3CBaseURL>(.*?).x3C/', html)\nif v_1080 is not None:\n print('1080p : '+v_1080.group(1).replace(\"&\",\"&\"))\n\n# Hope this code is useful and clear\n","sub_path":"fvideotool.py","file_name":"fvideotool.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"344205595","text":"import PySimpleGUI as sg\nfrom PlotHandler import *\nfrom UtililityFunctions import *\nfrom Neuron import Neuron\n\npoints = [[], [], []]\n\n\n# Validate data\ndef is_valid():\n for i, val in enumerate(values):\n if (type(values[val]) is str or type(values[val]) is int) and not val == 'activation':\n # Check if values are not empty\n if len(str(values[val])) == 0:\n window[val].Update('')\n sg.popup_error('Invalid values!', 'Value of ' + column1[i - 1][0].DisplayText + ' is invalid')\n return False\n # Check if values are numbers\n if not is_number(values[val]):\n window[val].Update('')\n sg.popup_error('Invalid values!', 'Value of ' + column1[i - 1][0].DisplayText + ' is invalid')\n return False\n # Check deviations\n if 'Deviation' in val and float(values[val]) < 0:\n window[val].Update('')\n sg.popup_error('Invalid values!',\n 'Value of ' + column1[i - 1][0].DisplayText + ' can\\'t be lower than 0')\n return False\n if float(values['minDeviation']) > float(values['maxDeviation']):\n sg.popup_error('Invalid values!', 'Min std deviation can\\'t be greater than max std deviation')\n return False\n # Check number of clusters\n if int(values['clustersNum']) <= 0 or int(values['clustersNum']) > 7:\n sg.popup_error('Invalid values!', 'Clusters number can\\'t be lower than 1 and greater than 7')\n return False\n # Check size\n if int(values['clustersNum']) > int(values['size']):\n sg.popup_error('Invalid values!', 'Size can\\'t be lower than number of clusters')\n return False\n # Check learning rate\n if float(values['learningRate']) <= 0 or float(values['learningRate']) > 1:\n sg.popup_error('Invalid values!', 'Learning rate can\\'t be lower/equal to 0 and greater than 1')\n return False\n return True\n\n\n# GUI\ncolumn1 = [\n [sg.Text('Min mean value')],\n [sg.Text('Max mean value')],\n [sg.Text('Min std deviation')],\n [sg.Text('Max std deviation')],\n [sg.Text('Number of values to generate per cluster')],\n [sg.Text('Number of clusters')],\n [sg.Text('Activation function')],\n [sg.Text('Number of epochs')],\n [sg.Text('Learning rate')],\n [sg.Button('Generate inputs', size=(15, 1)), sg.Button('Draw', size=(15, 1), disabled=True)]\n]\n\ncolumn2 = [\n [sg.In(default_text='-10.0', key='minVal', size=(4, 1))],\n [sg.In(default_text='10.0', key='maxVal', size=(4, 1))],\n [sg.In(default_text='0.5', key='minDeviation', size=(4, 1))],\n [sg.In(default_text='2.0', key='maxDeviation', size=(4, 1))],\n [sg.Spin([i for i in range(100, 100000, 100)], initial_value=100, key='size', size=(5, 1))],\n [sg.Spin([i for i in range(1, 8)], initial_value=2, key='clustersNum', size=(1, 1))],\n [sg.InputCombo(('heaviside', 'sigmoid', 'sin', 'cos', 'tanh', 'sign', 'ReLu', 'leaky ReLu'),\n default_value='heaviside', size=(10, 1), key='activation')],\n [sg.Spin([i for i in range(10, 100000, 10)], initial_value=1000, key='epochs', size=(5, 1))],\n [sg.In(default_text='0.01', key='learningRate', size=(4, 1))],\n [sg.Exit(size=(8, 1))]\n]\n\nlayout = [\n [sg.Canvas(size=(1, 1), key='canvas')],\n [sg.Column(column1), sg.Column(column2)]\n]\n\n# Create the Window\nwindow = sg.Window('Single neuron', layout).Finalize()\n\n# Event Loop to process \"events\" and get the \"values\" of the inputs\nwhile True:\n event, values = window.read()\n if event in (None, 'Exit'): # if user closes window or clicks cancel\n print('Close')\n plt.close('all')\n break\n\n if event == 'Generate inputs':\n if is_valid():\n points = calculate_gaussian(int(values['size']), int(values['clustersNum']), float(values['minVal']),\n float(values['maxVal']), float(values['minDeviation']),\n float(values['maxDeviation']))\n window.Element('Draw').Update(disabled=False)\n\n if event == 'Draw':\n if is_valid():\n inputs = []\n outputs = []\n for i in range(len(points[0])):\n inputs.append([1.0, points[0][i], points[1][i]])\n if points[2][i] is 'r':\n outputs.append(0)\n else:\n outputs.append(1)\n neuron = Neuron(values['activation'].lower().replace(' ', '_'),\n float(values['learningRate']))\n neuron.train(np.asarray(inputs), np.asarray(outputs), int(values['epochs']))\n\n if 'fig_canvas_agg' in globals(): # Update if plot already exists\n plt.clf()\n plt.scatter(points[0], points[1], c=points[2])\n draw_decision_surface(neuron, np.amin(points[0]), np.amax(points[0]), np.amin(points[1]),\n np.amax(points[1]))\n fig_canvas_agg.draw()\n else: # Generate new plot\n fig = generate_plot(points)\n draw_decision_surface(neuron, np.amin(points[0]), np.amax(points[0]), np.amin(points[1]),\n np.amax(points[1]))\n fig_canvas_agg = draw_figure(window['canvas'].TKCanvas, fig)\n\nwindow.close()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342846212","text":"from __future__ import absolute_import\nimport logging\nfrom polyglot.downloader import downloader\n\nfrom aleph.core import celery, db\nfrom aleph.ext import get_analyzers\nfrom aleph.model import Document\nfrom aleph.index import index_document\nfrom aleph.search import scan_iter\n\n\nlog = logging.getLogger(__name__)\n\n\ndef install_analyzers():\n # ['pos2', 'ner2', 'morph2', 'tsne2', 'counts2', 'embeddings2',\n # 'sentiment2', 'sgns2', 'transliteration2']\n for task in ['embeddings2', 'ner2']:\n log.info(\"Downloading linguistic resources: %r...\", task)\n downloader.download('TASK:%s' % task, quiet=True)\n\n\n@celery.task()\ndef analyze_source(source_id):\n query = {'term': {'source_id': source_id}}\n query = {'query': query, '_source': False}\n for row in scan_iter(query):\n analyze_document.delay(row.get('_id'))\n\n\n@celery.task()\ndef analyze_document(document_id):\n document = Document.by_id(document_id)\n if document is None:\n log.info(\"Could not find document: %r\", document_id)\n return\n log.info(\"Analyze document: %r\", document)\n analyzers = []\n meta = document.meta\n for cls in get_analyzers():\n try:\n analyzer = cls(document, meta)\n analyzer.prepare()\n analyzers.append(analyzer)\n except Exception as ex:\n log.exception(ex)\n\n if document.type == Document.TYPE_TEXT:\n for page in document.pages:\n for analyzer in analyzers:\n analyzer.on_page(page)\n for text in page.text_parts():\n for analyzer in analyzers:\n analyzer.on_text(text)\n\n if document.type == Document.TYPE_TABULAR:\n for record in document.records:\n for analyzer in analyzers:\n analyzer.on_record(record)\n for text in record.text_parts():\n for analyzer in analyzers:\n analyzer.on_text(text)\n\n for analyzer in analyzers:\n try:\n analyzer.finalize()\n except Exception as ex:\n log.exception(ex)\n document.meta = meta\n db.session.add(document)\n db.session.commit()\n index_document(document_id)\n","sub_path":"aleph/analyze/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458363085","text":"# 质数(Prime number),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个正因数的数)。\n# 大于1的自然数若不是素数,则称之为合数(也称为合成数)。\n# 算术基本定理确立了素数于数论里的核心地位:任何大于1的整数均可被表示成一串唯一素数之乘积。\n# 为了确保该定理的唯一性,1被定义为不是素数,因为在因式分解中可以有任意多个1(如3、1×3、1×1×3等都是3的有效约数分解)。\n# import time\n# abc = time.time()\n# flag = False\n# jh = [2,3]\n# for i in range(4,10001):\n# if i % 2 == 0 or i % 3 == 0 or i % 5 == 0 or i % 10 == 0:\n# continue\n# for j in range(2, 10001):\n# if i % j == 0:\n# continue\n# else:\n# jh.append(i)\n# print(jh, \"花费时间:{}\".format(time.time() - abc))\nimport time\nt = time.time()\ncount = 1\nabc = [2]\nfor i in range(3, 100001, 2):\n if i > 5 and i % 10 == 5:\n continue\n for j in range(3, int(i ** 0.5)+1, 2):\n if i % j == 0:\n break\n else:\n count += 1\n abc.append(i)\nprint(\"使用时长:{}\".format(time.time()-t))\nprint(abc)\nprint(\"素数个数:{}\".format(count))","sub_path":"求10万内的所有素数.py","file_name":"求10万内的所有素数.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"42860681","text":"string = 'aldous huxley was born in 1894.'\nnewstring = ''\n\n# This program capitalizes the first two words in the given string.\n# It may potentially be modified to capitalize any words that are considered a name value\n# which were found in a list/container of names.\n\n\nstring = string.capitalize()\n\nc = 0\n\nfor i, char in enumerate(string):\n\tif char == ' ':\n\t\tc += 1\n\t\tnewstring = ''\n\t\tnewstring += string[i+1:].capitalize()\n\t\tif c == 1:\n\t\t\tstring = string[:i]\n\t\t\tstring += ' ' + newstring\n\nprint(string)\nprint('#capitalizes the first two words in given string by enumerating and capitalizing both the original and the slice for the second word')\n\n","sub_path":"IntroToProgramming/ch6questions_stringmanipulation/cap_first_new.py","file_name":"cap_first_new.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412129110","text":"class node:\n def __init__(self, n):\n self.n = n\n self.left = None\n self.right = None\n\n def addValue(self, n):\n if n < self.n:\n if self.left:\n self.left.addValue(n)\n else:\n self.left = node(n)\n elif n > self.n:\n if self.right:\n self.right.addValue(n)\n else:\n self.right = node(n)\n\n def visit(self):\n l = []\n if self.left:\n l += self.left.visit()\n l.append(self.n)\n if self.right:\n l += self.right.visit()\n return l\n\n def search(self, n):\n if self.n is n:\n return True\n elif self.n < n and self.right:\n return self.right.search(n)\n elif self.left:\n return self.left.search(n)\n else:\n return False\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"45566244","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/jmusilek/github/django-fido/django_fido/forms.py\n# Compiled at: 2020-02-24 10:41:19\n# Size of source mod 2**32: 5699 bytes\n\"\"\"Forms for FIDO 2 registration and login.\"\"\"\nfrom __future__ import unicode_literals\nimport base64\nfrom django import forms\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.core.exceptions import ValidationError\nfrom django.http import HttpRequest\nimport django.utils.translation as _\nfrom fido2.client import ClientData\nfrom fido2.ctap2 import AttestationObject, AuthenticatorData\nfrom fido2.server import Fido2Server\n\nclass Fido2RegistrationForm(forms.Form):\n __doc__ = 'Form for FIDO 2 registration responses.'\n client_data = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n attestation = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n label = forms.CharField(required=False, max_length=255, label=(_('Label')))\n\n class Media:\n __doc__ = 'Add FIDO 2 related JS.'\n js = ('django_fido/js/fido2.js', )\n\n def clean_client_data(self) -> ClientData:\n \"\"\"Return decoded client data.\"\"\"\n value = self.cleaned_data['client_data']\n try:\n return ClientData(base64.b64decode(value))\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n def clean_attestation(self) -> AttestationObject:\n \"\"\"Return decoded attestation object.\"\"\"\n value = self.cleaned_data['attestation']\n try:\n return AttestationObject(base64.b64decode(value))\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n\nclass Fido2AuthenticationForm(forms.Form):\n __doc__ = 'Form for FIDO 2 authentication responses.'\n client_data = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n credential_id = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n authenticator_data = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n signature = forms.CharField(error_messages={'required': _(\"Operation wasn't completed.\")}, widget=(forms.HiddenInput))\n\n class Media:\n __doc__ = 'Add FIDO 2 related JS.'\n js = ('django_fido/js/fido2.js', )\n\n def clean_client_data(self) -> ClientData:\n \"\"\"Return decoded client data.\"\"\"\n value = self.cleaned_data['client_data']\n try:\n return ClientData(base64.b64decode(value))\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n def clean_credential_id(self) -> bytes:\n \"\"\"Return decoded credential ID.\"\"\"\n value = self.cleaned_data['credential_id']\n try:\n return base64.b64decode(value)\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n def clean_authenticator_data(self) -> AuthenticatorData:\n \"\"\"Return decoded authenticator data.\"\"\"\n value = self.cleaned_data['authenticator_data']\n try:\n return AuthenticatorData(base64.b64decode(value))\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n def clean_signature(self) -> bytes:\n \"\"\"Return decoded signature.\"\"\"\n value = self.cleaned_data['signature']\n try:\n return base64.b64decode(value)\n except ValueError:\n raise ValidationError((_('FIDO 2 response is malformed.')), code='invalid')\n\n\nclass Fido2ModelAuthenticationForm(AuthenticationForm, Fido2AuthenticationForm):\n __doc__ = 'Authentication form with username, password and FIDO 2 credentials.'\n\n def __init__(self, request, fido2_server, session_key, *args, **kwargs):\n \"\"\"Initialize form.\"\"\"\n (super().__init__)(request, *args, **kwargs)\n self.fido2_server = fido2_server\n self.session_key = session_key\n self.error_messages['invalid_login'] = _('Please enter a correct %(username)s and password and use valid FIDO2 security key.')\n\n def clean(self):\n \"\"\"Authenticate user.\"\"\"\n username = self.cleaned_data.get('username')\n password = self.cleaned_data.get('password')\n state = self.request.session.pop(self.session_key, None)\n if state is None:\n raise ValidationError((_('Authentication request not found.')), code='missing')\n else:\n self.user_cache = authenticate((self.request),\n username=username,\n password=password,\n fido2_server=(self.fido2_server),\n fido2_state=state,\n fido2_response=(self.cleaned_data))\n if self.user_cache is None:\n raise self.get_invalid_login_error()\n else:\n self.confirm_login_allowed(self.user_cache)\n return self.cleaned_data\n\n def get_invalid_login_error(self):\n \"\"\"Get invalid login error.\"\"\"\n return forms.ValidationError((self.error_messages['invalid_login']),\n code='invalid_login',\n params={'username': self.username_field.verbose_name})","sub_path":"pycfiles/django_fido-0.22-py3-none-any/forms.cpython-37.py","file_name":"forms.cpython-37.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525051570","text":"\"\"\"Utilities for manipulating BED files.\n\"\"\"\nimport os\nimport shutil\nimport sys\n\nimport toolz as tz\n\nfrom bcbio import utils\nfrom bcbio.distributed.transaction import file_transaction\nfrom bcbio.pipeline import config_utils\nfrom bcbio.provenance import do\nfrom bcbio.variation import vcfutils\n\ndef clean_file(in_file, data, prefix=\"\", bedprep_dir=None):\n \"\"\"Prepare a clean sorted input BED file without headers\n \"\"\"\n if in_file:\n if not bedprep_dir:\n bedprep_dir = utils.safe_makedir(os.path.join(data[\"dirs\"][\"work\"], \"bedprep\"))\n out_file = os.path.join(bedprep_dir, \"%s%s\" % (prefix, os.path.basename(in_file))).replace(\".gz\", \"\")\n if not utils.file_exists(out_file):\n with file_transaction(data, out_file) as tx_out_file:\n py_cl = os.path.join(os.path.dirname(sys.executable), \"py\")\n cat_cmd = \"zcat\" if in_file.endswith(\".gz\") else \"cat\"\n cmd = (\"{cat_cmd} {in_file} | grep -v ^track | grep -v ^browser | \"\n \"{py_cl} -x 'bcbio.variation.bedutils.remove_bad(x)' | \"\n \"sort -k1,1 -k2,2n > {tx_out_file}\")\n do.run(cmd.format(**locals()), \"Prepare cleaned BED file\", data)\n vcfutils.bgzip_and_index(out_file, data[\"config\"], remove_orig=False)\n return out_file\n\ndef remove_bad(line):\n \"\"\"Remove non-increasing BED lines which will cause variant callers to choke.\n \"\"\"\n parts = line.strip().split(\"\\t\")\n if int(parts[2]) > int(parts[1]):\n return line\n else:\n return None\n\ndef merge_overlaps(in_file, data):\n \"\"\"Merge bed file intervals to avoid overlapping regions.\n\n Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes\n that don't collapse BEDs prior to using them.\n \"\"\"\n if in_file:\n bedtools = config_utils.get_program(\"bedtools\", data[\"config\"])\n work_dir = tz.get_in([\"dirs\", \"work\"], data)\n if work_dir:\n bedprep_dir = utils.safe_makedir(os.path.join(work_dir, \"bedprep\"))\n else:\n bedprep_dir = os.path.dirname(in_file)\n out_file = os.path.join(bedprep_dir, \"%s-merged.bed\" % (utils.splitext_plus(os.path.basename(in_file))[0]))\n if not utils.file_exists(out_file):\n with file_transaction(data, out_file) as tx_out_file:\n cmd = \"{bedtools} merge -i {in_file} > {tx_out_file}\"\n do.run(cmd.format(**locals()), \"Prepare merged BED file\", data)\n vcfutils.bgzip_and_index(out_file, data[\"config\"], remove_orig=False)\n return out_file\n\ndef clean_inputs(data):\n \"\"\"Clean BED input files to avoid overlapping segments that cause downstream issues.\n\n Per-merges inputs to avoid needing to call multiple times during later parallel steps.\n \"\"\"\n clean_vr = clean_file(utils.get_in(data, (\"config\", \"algorithm\", \"variant_regions\")), data)\n merge_overlaps(clean_vr, data)\n data[\"config\"][\"algorithm\"][\"variant_regions\"] = clean_vr\n return data\n\ndef combine(in_files, out_file, config):\n \"\"\"Combine multiple BED files into a single output.\n \"\"\"\n if not utils.file_exists(out_file):\n with file_transaction(config, out_file) as tx_out_file:\n with open(tx_out_file, \"w\") as out_handle:\n for in_file in in_files:\n with open(in_file) as in_handle:\n shutil.copyfileobj(in_handle, out_handle)\n return out_file\n","sub_path":"bcbio/variation/bedutils.py","file_name":"bedutils.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"185447180","text":"from botInfo import version, channel\n\n\nstart_message = '/help'\nhelp_message = f'这个bot可以:抓取和转发新闻到 @DragaliaNews\\n' \\\n f'获取轻松龙约 /life\\n' \\\n f'获取NGA论坛链接详情。\\n' \\\n f'欢迎加入群组 @dragaliazh\\n\\n/English /Japanese\\n' \\\n f'Ver.: {version} ({channel})'\nhelp_en = f'Read Dragalia Life: /life\\n' \\\n f'Welcome to the player group @dragaliazh (in Chinese)\\n\\n' \\\n f'Ver.: {version} ({channel})'\nhelp_ja = f'「ゆるがりあ」を読む /life\\n' \\\n f'中国語グループ @dragaliazh へようこそ\\n\\n' \\\n f'Ver.: {version} ({channel})'\nunavailable_cmd = '这个功能不可用。为什么不试试 /life 呢'\ndefault_reply = '嗯'\nunknown = 'I can\\'t understand your message or command. You may try /help.'\n","sub_path":"botDB.py","file_name":"botDB.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"164648471","text":"# Runs GEMC using the gcard, on LUND file produced by generator\r\n#\r\n#\r\n# N is set to to the number requested by the user, with a max of 10K set by the portal\r\n\r\ndef C_runGemc(scard, **kwargs):\r\n\r\n\tgemcInputOptions = \"\"\" -INPUT_GEN_FILE=\"lund, {0}\" \"\"\".format(scard.genOutput)\r\n\r\n\tc12f_home = \"/cvmfs/oasis.opensciencegrid.org/jlab/hallb/clas12/soft/noarch/clas12-config/dev/\"\r\n\tgcard = c12f_home + \"gemc/\" + scard.gemcv + \"/\" + scard.configuration + \".gcard\"\r\n\r\n\tif scard.genExecutable == 'gemc':\r\n\t\tgemcInputOptions = scard.genOptions\r\n\r\n\ttorusField = \"\"\" -SCALE_FIELD=\"binary_torus, {0}\" \"\"\".format(scard.torus)\r\n\tsolenField = \"\"\" -SCALE_FIELD=\"binary_solenoid, {0}\" \"\"\".format(scard.solenoid)\r\n\r\n\toutput = \"\"\" -OUTPUT=\"hipo, gemc.hipo\" \"\"\"\r\n\tall_vertex_options = \"\"\" \"\"\"\r\n\r\n\tif scard.gemcv == '4.4.2':\r\n\t\toutput = \"\"\" -OUTPUT=\"evio, gemc.evio\" \"\"\"\r\n\t\ttorusField = \"\"\" -SCALE_FIELD=\"TorusSymmetric, {0}\" \"\"\".format(scard.torus)\r\n\t\tsolenField = \"\"\" -SCALE_FIELD=\"clas12-newSolenoid, {0}\" \"\"\".format(scard.solenoid)\r\n\telse:\r\n\t\tvertex_z = \"\"\" -RANDOMIZE_LUND_VZ=\"{0}\" \"\"\".format(scard.vertex_z_to_gemc)\r\n\t\tbeamspot = \"\"\" -BEAM_SPOT=\"{0}\" \"\"\".format(scard.beamspot_to_gemc)\r\n\t\traster = \"\"\" -RASTER_VERTEX=\"{0}\" \"\"\".format(scard.raster_to_gemc)\r\n\t\tall_vertex_options = vertex_z + beamspot + raster\r\n\r\n\trunGemc = \"\"\"\r\n# Run GEMC\r\n# --------\r\n\r\necho GEMC START: `date +%s`\r\n\r\necho\r\necho GEMC executable: `which gemc`, gcard: {0}\r\n\r\ngemc -USE_GUI=0 -N={1} {0} {2} {3} {4} {5} {6} \r\nif ($? != 0) then\r\n\techo gemc failed\r\n\techo removing data files and exiting\r\n\trm -f *.hipo *.evio\r\n\texit 204\r\nendif\r\n# removing generated events file\r\nrm -f *.dat\r\n\r\necho\r\nprintf \"GEMC Completed on: \"; /bin/date\r\necho\r\necho \"Directory Content After GEMC:\"\r\nls -l\r\nif ($? != 0) then\r\n\techo ls failure\r\n\techo removing data files and exiting\r\n\trm -f *.hipo *.evio\r\n\texit 211\r\nendif\r\necho\r\n\r\necho GEMC END: `date +%s`\r\n\r\n# End of GEMC\r\n# -----------\r\n\r\n\"\"\".format(gcard, scard.nevents, gemcInputOptions, all_vertex_options, torusField, solenField, output)\r\n\r\n\treturn runGemc\r\n","sub_path":"submission_files/script_generators/type_1/runscript_generators/C_runGemc.py","file_name":"C_runGemc.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616575027","text":"# Class for the generic enemy class and the Zombie class\n\n# Import libraries\nfrom entity import Entity\nfrom constants import FPS\nimport math\n\n\nclass Enemy(Entity):\n # Load the damage from the xml file and call the super constructor\n def __init__(self, x, y, xml_data, driver, image = None):\n self.dmg = int(xml_data.get(\"dmg\"))\n Entity.__init__(self, x, y, xml_data, driver, image = image)\n\n # Initialize the player as their target\n self.player = driver.player\n\n # Stun-time, how long they are stunned on hit\n self.stun_time = 0\n\n # Deal damage to the player\n def deal_damage(self) -> None:\n self.player.take_damage(self.dmg)\n\n def tick(self) -> None:\n # Call the super method\n Entity.tick(self)\n\n # If they are stunned, do nothing\n self.stun_time -= 1\n if self.stun_time > 0:\n return\n\n # Otherwise, move towards the player\n dx = self.player.x - self.x\n dy = self.player.y - self.y\n hypot = math.hypot(dx, dy)\n\n x_move = dx / hypot\n y_move = dy / hypot\n self.move(x_move, y_move)\n\n # Take damage\n def take_damage(self, dmg : int) -> None:\n # Call the super method\n took_damage = Entity.take_damage(self, dmg)\n\n # Set a stunned timer if they take damage\n if took_damage:\n # Set a stunned timer\n self.stun_time = FPS // 3\n\n\n# Zombie enemy class\nclass Zombie(Enemy):\n def tick(self):\n Enemy.tick(self)\n # If they collide with the player, deal the player damage\n if self.collides(self.player):\n self.deal_damage()","sub_path":"enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292461427","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport torch\nfrom torch.jit import script, trace\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport random\nimport re\nimport os\nimport unicodedata\nfrom io import open\nimport itertools\nfrom gensim.models import KeyedVectors\n\nfrom parse import parse_file\n\nUSE_CUDA = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\n\ncorpus_name = \"cornell movie-dialogs corpus\"\ncorpus = os.path.join(\"data\", corpus_name)\nsave_dir = os.path.join(\"data\", \"save\")\ndatafile = os.path.join(corpus, \"formatted_movie_lines.txt\")\n\nif not datafile:\n parse_file(datafile, corpus)\n\n\n# Default word tokens\nPAD_token = 0 # Used for padding short sentences\nSOS_token = 1 # Start-of-sentence token\nEOS_token = 2 # End-of-sentence token\n\n# Relatively fixed parameters\nhidden_size = 300\nencoder_n_layers = 2\ndecoder_n_layers = 2\n\n\nclass Voc:\n def __init__(self, name):\n self.name = name\n self.trimmed = False\n self.word2index = {}\n self.word2count = {}\n self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\"}\n self.num_words = 3 # Count SOS, EOS, PAD\n\n def addSentence(self, sentence):\n for word in sentence.split(' '):\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.num_words\n self.word2count[word] = 1\n self.index2word[self.num_words] = word\n self.num_words += 1\n else:\n self.word2count[word] += 1\n \n def updateDict(self, dict_old):\n for word in self.word2index:\n if word not in dict_old[\"word2index\"]:\n word2index[word] = self.num_words\n self.word2count[word] = 1\n self.index2word[self.num_words] = word\n self.num_words += 1\n\n # Remove words below a certain count threshold\n def trim(self, min_count):\n if self.trimmed:\n return\n self.trimmed = True\n\n keep_words = []\n\n for k, v in self.word2count.items():\n if v >= min_count:\n keep_words.append(k)\n\n print('Keep_words {} / {} = {:.4f}'.format(\n len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n ))\n\n # Reinitialize dictionaries\n self.word2index = {}\n self.word2count = {}\n self.index2word = {PAD_token: \"PAD\", SOS_token: \"SOS\", EOS_token: \"EOS\"}\n self.num_words = 3 # Count default tokens\n\n for word in keep_words:\n self.addWord(word)\n\n\n# Turn a Unicode string to plain ASCII, thanks to\n# https://stackoverflow.com/a/518232/2809427\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n\n# Lowercase, trim, and remove non-letter characters\ndef normalizeString(s):\n s = unicodeToAscii(s.lower().strip())\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?']+\", r\" \", s)\n s = re.sub(r\"\\s+\", r\" \", s).strip()\n return s\n\n# Read query/response pairs and return a voc object\ndef readVocs(datafile, corpus_name):\n print(\"Reading lines...\")\n # Read the file and split into lines\n lines = open(datafile, encoding='utf-8'). read().strip().split('\\n')\n # Split every line into pairs and normalize\n pairs = [[normalizeString(s) for s in l.split('\\t')] for l in lines]\n voc = Voc(corpus_name)\n return voc, pairs\n\n# Returns True iff both sentences in a pair 'p' are under the MAX_LENGTH threshold\ndef filterPair(p, max_length):\n # Input sequences need to preserve the last word for EOS token\n return len(p[0].split(' ')) < max_length and len(p[1].split(' ')) < max_length\n\n# Filter pairs using filterPair condition\ndef filterPairs(pairs, max_length):\n return [pair for pair in pairs if filterPair(pair, max_length)]\n\n# Using the functions defined above, return a populated voc object and pairs list\ndef loadPrepareData(corpus, corpus_name, datafile, save_dir, max_length):\n print(\"Start preparing training data ...\")\n voc, pairs = readVocs(datafile, corpus_name)\n print(\"Read {!s} sentence pairs\".format(len(pairs)))\n pairs = filterPairs(pairs, max_length)\n print(\"Trimmed to {!s} sentence pairs\".format(len(pairs)))\n print(\"Counting words...\")\n for pair in pairs:\n voc.addSentence(pair[0])\n voc.addSentence(pair[1])\n print(\"Counted words:\", voc.num_words)\n return voc, pairs\n\n\ndef trimRareWords(voc, pairs, MIN_COUNT):\n # Trim words used under the MIN_COUNT from the voc\n voc.trim(MIN_COUNT)\n # Filter out pairs with trimmed words\n keep_pairs = []\n for pair in pairs:\n input_sentence = pair[0]\n output_sentence = pair[1]\n keep_input = True\n keep_output = True\n # Check input sentence\n for word in input_sentence.split(' '):\n if word not in voc.word2index:\n keep_input = False\n break\n # Check output sentence\n for word in output_sentence.split(' '):\n if word not in voc.word2index:\n keep_output = False\n break\n\n # Only keep pairs that do not contain trimmed word(s) in their input or output sentence\n if keep_input and keep_output:\n keep_pairs.append(pair)\n\n print(\"Trimmed from {} pairs to {}, {:.4f} of total\".format(len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))\n return keep_pairs\n\n\ndef indexesFromSentence(voc, sentence):\n return [voc.word2index[word] for word in sentence.split(' ')] + [EOS_token]\n\ndef zeroPadding(l, fillvalue=PAD_token):\n return list(itertools.zip_longest(*l, fillvalue=fillvalue))\n\ndef binaryMatrix(l, value=PAD_token):\n m = []\n for i, seq in enumerate(l):\n m.append([])\n for token in seq:\n if token == PAD_token:\n m[i].append(0)\n else:\n m[i].append(1)\n return m\n\n# Returns padded input sequence tensor and lengths\ndef inputVar(l, voc):\n indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\n lengths = torch.tensor([len(indexes) for indexes in indexes_batch])\n padList = zeroPadding(indexes_batch)\n padVar = torch.LongTensor(padList)\n return padVar, lengths\n\n# Returns padded target sequence tensor, padding mask, and max target length\ndef outputVar(l, voc):\n indexes_batch = [indexesFromSentence(voc, sentence) for sentence in l]\n max_target_len = max([len(indexes) for indexes in indexes_batch])\n padList = zeroPadding(indexes_batch)\n mask = binaryMatrix(padList)\n mask = torch.BoolTensor(mask)\n padVar = torch.LongTensor(padList)\n return padVar, mask, max_target_len\n\n# Returns all items for a given batch of pairs\ndef batch2TrainData(voc, pair_batch):\n pair_batch.sort(key=lambda x: len(x[0].split(\" \")), reverse=True)\n input_batch, output_batch = [], []\n for pair in pair_batch:\n input_batch.append(pair[0])\n output_batch.append(pair[1])\n inp, lengths = inputVar(input_batch, voc)\n output, mask, max_target_len = outputVar(output_batch, voc)\n return inp, lengths, output, mask, max_target_len\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, hidden_size, embedding, n_layers=1, dropout=0):\n super(EncoderRNN, self).__init__()\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.embedding = embedding\n\n # Initialize GRU; the input_size and hidden_size params are both set to 'hidden_size'\n # because our input size is a word embedding with number of features == hidden_size\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers,\n dropout=(0 if n_layers == 1 else dropout), bidirectional=True)\n\n def forward(self, input_seq, input_lengths, hidden=None):\n # Convert word indexes to embeddings\n embedded = self.embedding(input_seq)\n # Pack padded batch of sequences for RNN module\n packed = nn.utils.rnn.pack_padded_sequence(embedded, input_lengths)\n # Forward pass through GRU\n outputs, hidden = self.gru(packed, hidden)\n # Unpack padding\n outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs)\n # Sum bidirectional GRU outputs\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:]\n # Return output and final hidden state\n return outputs, hidden\n\n\n# Luong attention layer\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n self.method = method\n if self.method not in ['dot', 'general', 'concat']:\n raise ValueError(self.method, \"is not an appropriate attention method.\")\n self.hidden_size = hidden_size\n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(hidden_size))\n\n def dot_score(self, hidden, encoder_output):\n return torch.sum(hidden * encoder_output, dim=2)\n\n def general_score(self, hidden, encoder_output):\n energy = self.attn(encoder_output)\n return torch.sum(hidden * energy, dim=2)\n\n def concat_score(self, hidden, encoder_output):\n energy = self.attn(torch.cat((hidden.expand(encoder_output.size(0), -1, -1), encoder_output), 2)).tanh()\n return torch.sum(self.v * energy, dim=2)\n\n def forward(self, hidden, encoder_outputs):\n # Calculate the attention weights (energies) based on the given method\n if self.method == 'general':\n attn_energies = self.general_score(hidden, encoder_outputs)\n elif self.method == 'concat':\n attn_energies = self.concat_score(hidden, encoder_outputs)\n elif self.method == 'dot':\n attn_energies = self.dot_score(hidden, encoder_outputs)\n\n # Transpose max_length and batch_size dimensions\n attn_energies = attn_energies.t()\n\n # Return the softmax normalized probability scores (with added dimension)\n return F.softmax(attn_energies, dim=1).unsqueeze(1)\n\n\nclass LuongAttnDecoderRNN(nn.Module):\n def __init__(self, attn_model, embedding, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(LuongAttnDecoderRNN, self).__init__()\n\n # Keep for reference\n self.attn_model = attn_model\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n # Define layers\n self.embedding = embedding\n self.embedding_dropout = nn.Dropout(dropout)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=(0 if n_layers == 1 else dropout))\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n\n self.attn = Attn(attn_model, hidden_size)\n\n def forward(self, input_step, last_hidden, encoder_outputs):\n # Note: we run this one step (word) at a time\n # Get embedding of current input word\n embedded = self.embedding(input_step)\n embedded = self.embedding_dropout(embedded)\n # Forward through unidirectional GRU\n rnn_output, hidden = self.gru(embedded, last_hidden)\n # Calculate attention weights from the current GRU output\n attn_weights = self.attn(rnn_output, encoder_outputs)\n # Multiply attention weights to encoder outputs to get new \"weighted sum\" context vector\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1))\n # Concatenate weighted context vector and GRU output using Luong eq. 5\n rnn_output = rnn_output.squeeze(0)\n context = context.squeeze(1)\n concat_input = torch.cat((rnn_output, context), 1)\n concat_output = torch.tanh(self.concat(concat_input))\n # Predict next word using Luong eq. 6\n output = self.out(concat_output)\n output = F.softmax(output, dim=1)\n # Return output and final hidden state\n return output, hidden\n\n\ndef maskNLLLoss(inp, target, mask):\n nTotal = mask.sum()\n crossEntropy = -torch.log(torch.gather(inp, 1, target.view(-1, 1)).squeeze(1))\n loss = crossEntropy.masked_select(mask).mean()\n loss = loss.to(device)\n return loss, nTotal.item()\n\n\ndef train(input_variable, lengths, target_variable, mask, max_target_len, encoder, decoder, embedding,\n encoder_optimizer, decoder_optimizer, batch_size, clip, max_length, teacher_forcing_ratio):\n\n # Zero gradients\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n # Set device options\n input_variable = input_variable.to(device)\n lengths = lengths.to(device)\n target_variable = target_variable.to(device)\n mask = mask.to(device)\n\n # Initialize variables\n loss = 0\n print_losses = []\n n_totals = 0\n\n # Forward pass through encoder\n encoder_outputs, encoder_hidden = encoder(input_variable, lengths)\n\n # Create initial decoder input (start with SOS tokens for each sentence)\n decoder_input = torch.LongTensor([[SOS_token for _ in range(batch_size)]])\n decoder_input = decoder_input.to(device)\n\n # Set initial decoder hidden state to the encoder's final hidden state\n decoder_hidden = encoder_hidden[:decoder.n_layers]\n\n # Determine if we are using teacher forcing this iteration\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n # Forward batch of sequences through decoder one time step at a time\n if use_teacher_forcing:\n for t in range(max_target_len):\n decoder_output, decoder_hidden = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n # Teacher forcing: next input is current target\n decoder_input = target_variable[t].view(1, -1)\n # Calculate and accumulate loss\n mask_loss, nTotal = maskNLLLoss(decoder_output, target_variable[t], mask[t])\n loss += mask_loss\n print_losses.append(mask_loss.item() * nTotal)\n n_totals += nTotal\n else:\n for t in range(max_target_len):\n decoder_output, decoder_hidden = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n # No teacher forcing: next input is decoder's own current output\n _, topi = decoder_output.topk(1)\n decoder_input = torch.LongTensor([[topi[i][0] for i in range(batch_size)]])\n decoder_input = decoder_input.to(device)\n # Calculate and accumulate loss\n mask_loss, nTotal = maskNLLLoss(decoder_output, target_variable[t], mask[t])\n loss += mask_loss\n print_losses.append(mask_loss.item() * nTotal)\n n_totals += nTotal\n\n # Perform backpropatation\n loss.backward()\n\n # Clip gradients: gradients are modified in place\n _ = nn.utils.clip_grad_norm_(encoder.parameters(), clip)\n _ = nn.utils.clip_grad_norm_(decoder.parameters(), clip)\n\n # Adjust model weights\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return sum(print_losses) / n_totals\n\n\ndef trainIters(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer, \n embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size, \n print_every, save_every, clip, corpus_name, loadFilename, max_length, teacher_forcing_ratio, checkpoint):\n\n # Load batches for each iteration\n training_batches = [batch2TrainData(voc, [random.choice(pairs) for _ in range(batch_size)])\n for _ in range(n_iteration)]\n\n # Initializations\n print('Initializing ...')\n start_iteration = 0\n print_loss = 0\n if loadFilename:\n start_iteration = checkpoint['iteration']\n\n # Training loop\n print(\"Training...\")\n for iteration in range(1, n_iteration + 1):\n training_batch = training_batches[iteration - 1]\n # Extract fields from batch\n input_variable, lengths, target_variable, mask, max_target_len = training_batch\n\n # Run a training iteration with batch\n loss = train(input_variable, lengths, target_variable, mask, max_target_len, encoder,\n decoder, embedding, encoder_optimizer, decoder_optimizer, batch_size, clip, max_length, teacher_forcing_ratio)\n print_loss += loss\n\n # Print progress\n if iteration % print_every == 0:\n print_loss_avg = print_loss / print_every\n print(\"Iteration: {}; Percent complete: {:.1f}%; Average loss: {:.4f}\".format(iteration, iteration / n_iteration * 100, print_loss_avg))\n print_loss = 0\n\n # Save checkpoint\n if (iteration % save_every == 0):\n directory = os.path.join(save_dir, model_name, corpus_name, '{}-{}_{}'.format(encoder_n_layers, decoder_n_layers, hidden_size))\n if not os.path.exists(directory):\n os.makedirs(directory)\n torch.save({\n 'iteration': iteration+start_iteration,\n 'en': encoder.state_dict(),\n 'de': decoder.state_dict(),\n 'en_opt': encoder_optimizer.state_dict(),\n 'de_opt': decoder_optimizer.state_dict(),\n 'loss': loss,\n 'voc_dict': voc.__dict__,\n 'embedding': embedding.state_dict()\n }, os.path.join(directory, '{}_{}.tar'.format(iteration+start_iteration, 'checkpoint')))\n\n\ndef trainBot(attn_model, load_checkpoint, max_length, min_count, model_name, dropout, batch_size, clip, \n teacher_forcing_ratio, learning_rate, decoder_learning_ratio, n_iteration, print_every, save_every):\n \n # Clear GPU cache\n torch.cuda.empty_cache()\n \n # Load/Assemble voc and pairs\n voc, pairs = loadPrepareData(corpus, corpus_name, datafile, save_dir, max_length)\n pairs = trimRareWords(voc, pairs, min_count)\n\n if load_checkpoint:\n loadFilename = os.path.join(save_dir, model_name, corpus_name,\n '{}-{}_{}'.format(encoder_n_layers, decoder_n_layers, hidden_size),\n '{}_checkpoint.tar'.format(load_checkpoint))\n else:\n loadFilename = None\n checkpoint = None\n \n # Load model if a loadFilename is provided\n if loadFilename:\n # If loading on same machine the model was trained on\n checkpoint = torch.load(loadFilename)\n encoder_sd = checkpoint['en']\n decoder_sd = checkpoint['de']\n encoder_optimizer_sd = checkpoint['en_opt']\n decoder_optimizer_sd = checkpoint['de_opt']\n embedding_sd = checkpoint['embedding']\n voc__dict__ = checkpoint['voc_dict']\n# voc.updateDict(dict_old)\n\n print('Building encoder and decoder ...')\n # Initialize word embeddings\n if loadFilename:\n embedding = nn.Embedding(100000, 300) # Google word2vec has 3 million embeddings, each has a 300 dim vector\n embedding.load_state_dict(embedding_sd)\n else:\n embedding_model = KeyedVectors.load_word2vec_format('data\\GoogleNews-vectors-negative300.bin.gz', binary=True, limit=100000)\n embedding_weights = torch.FloatTensor(embedding_model.vectors)\n embedding = nn.Embedding.from_pretrained(embedding_weights)\n \n print(embedding(\"the\"))\n # Initialize encoder & decoder models\n encoder = EncoderRNN(hidden_size, embedding, encoder_n_layers, dropout)\n decoder = LuongAttnDecoderRNN(attn_model, embedding, hidden_size, voc.num_words, decoder_n_layers, dropout)\n if loadFilename:\n encoder.load_state_dict(encoder_sd)\n decoder.load_state_dict(decoder_sd)\n \n # Use appropriate device\n encoder = encoder.to(device)\n decoder = decoder.to(device)\n print('Models built and ready to go!')\n \n # Ensure dropout layers are in train mode\n encoder.train()\n decoder.train()\n\n # Initialize optimizers\n print('Building optimizers ...')\n encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate * decoder_learning_ratio)\n if loadFilename:\n encoder_optimizer.load_state_dict(encoder_optimizer_sd)\n decoder_optimizer.load_state_dict(decoder_optimizer_sd)\n\n # If you have cuda, configure cuda to call\n for state in encoder_optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.cuda()\n\n for state in decoder_optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.cuda()\n\n # Run training iterations\n print(\"Starting Training!\")\n trainIters(model_name, voc, pairs, encoder, decoder, encoder_optimizer, decoder_optimizer,\n embedding, encoder_n_layers, decoder_n_layers, save_dir, n_iteration, batch_size,\n print_every, save_every, clip, corpus_name, loadFilename, max_length, teacher_forcing_ratio, checkpoint)\n print(\"Training Ended!\")\n return encoder, decoder, voc\n\n\nembedding_model = KeyedVectors.load_word2vec_format('data\\GoogleNews-vectors-negative300.bin.gz', binary=True, limit=100000)\n\nembedding_weights = torch.FloatTensor(embedding_model.vectors)\nembedding = nn.Embedding.from_pretrained(embedding_weights)\n\n\n# input_tensor = torch.LongTensor([[1,2],[1,4]])\n# tensor = embedding(input_tensor)\n# print(tensor)\n# print(word)\n# print(tensor.shape)\n\nembedding_model[\"dog\"]\n\n# embedding_model.similar_by_vector(tensor, topn=10)\n\n","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":21928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408219035","text":"import os\nimport sys\nimport bs4\nimport shlex\nimport pickle\nimport requests\nimport readline\nimport argparse\nfrom getpass import getpass\nfrom datetime import datetime\nfrom prettytable import PrettyTable\nfrom inc.algorithms import validalgs\nfrom inc.header import header\n\n# Functions\n\n# Returns json of current jobs in escrow\ndef get_jobs(sortby = 'createdAt', algid = None, reverse = True):\n\turl = \"https://hashes.com/escrow/viewjson/\"\n\tjson = requests.get(url).json()\n\tif algid is not None:\n\t\tjson2 = []\n\t\tfor rows in json:\n\t\t\tif str(rows['algorithmId']) in algid:\n\t\t\t\tjson2.append(rows)\n\t\tjson = json2\n\tjson = sorted(json, key=lambda x : x[sortby], reverse=reverse)\n\treturn json\n\n# Downloads or prints jobs in escrow\ndef download(jobid, algid, file, printr):\n\turls = []\n\tjobs = get_jobs()\n\tif jobid is not None:\n\t\tif \",\" in str(jobid):\n\t\t\tjobid = jobid.split(\",\")\n\t\telse:\n\t\t\tjobid = [jobid]\n\t\tfor rows in jobs:\n\t\t\tif str(rows['id']) in jobid:\n\t\t\t\turls.append(rows['leftList'])\n\t\t\t\tjobid.remove(str(rows['id']))\n\t\tif jobid:\n\t\t\tprint (\",\".join(jobid) + \" not valid jobs\")\n\tif algid is not None:\n\t\tfor rows in jobs:\n\t\t\tif str(rows['algorithmId']) == algid:\n\t\t\t\turls.append(rows['leftList'])\n\t\tif not urls:\n\t\t\tprint (\"No jobs for \" + validalgs[algid])\n\tif urls:\n\t\tif printr:\n\t\t\tfor url in urls:\n\t\t\t\treq = requests.get(\"http://hashes.com\"+url).text.rstrip()\n\t\t\t\tprint(req)\n\t\tif file:\n\t\t\ttry:\n\t\t\t\twith open(file, \"ab+\") as outfile:\n\t\t\t\t\tfor url in urls:\n\t\t\t\t\t\treq = requests.get(\"http://hashes.com\"+url, stream=True)\n\t\t\t\t\t\tfor chunk in req.iter_content(1024):\n\t\t\t\t\t\t\toutfile.write(chunk)\n\t\t\t\t\tprint (\"Wrote hashes to: \"+file)\n\t\t\texcept OSError as e:\n\t\t\t\tprint(e)\n\n# Gets stats about hashes that are left in escrow\ndef get_stats(json):\n\tstats = {}\n\tfor rows in json:\n\t\talgid = rows['algorithmId']\n\t\tneededleft = float(rows['maxCracksNeeded']) - float(rows['foundHashes']) if rows['foundHashes'] > 0 else rows['maxCracksNeeded']\n\t\tif algid in stats:\n\t\t\tfound = stats[algid]['totalFound'] + rows['foundHashes']\n\t\t\tleft = stats[algid]['totalLeft'] + rows['leftHashes']\n\t\t\tusd = float(stats[algid]['totalUSD']) + float(rows['pricePerHashUsd']) * neededleft\n\t\t\tbtc = float(stats[algid]['totalBTC']) + float(rows['pricePerHash']) * neededleft\n\t\telse:\n\t\t\tfound = rows['foundHashes']\n\t\t\tleft = rows['leftHashes']\n\t\t\tusd = float(rows['pricePerHashUsd']) * neededleft\n\t\t\tbtc = float(rows['pricePerHash']) * neededleft\n\t\tstats[algid] = {\"totalFound\": found, \"totalLeft\": left, \"totalUSD\": \"{0:.3f}\".format(float(usd)), \"totalBTC\": \"{0:.7f}\".format(float(btc))}\n\ttable = PrettyTable()\n\ttable.field_names = [\"ID\", \"Algorithm\", \"Left\", \"Found\", \"Total Value\"]\n\ttable.align = \"l\"\n\tescrowleft = 0\n\tescrowfound = 0\n\tescrowbtcvalue = 0\n\tescrowusdvalue = 0\n\tfor aid in stats:\n\t\tvalue = \"₿\"+stats[aid]['totalBTC'] + \" / $\" + stats[aid]['totalUSD']\n\t\tescrowleft += stats[aid]['totalLeft']\n\t\tescrowfound += stats[aid]['totalFound']\n\t\tescrowbtcvalue += float(stats[aid]['totalBTC'])\n\t\tescrowusdvalue += float(stats[aid]['totalUSD'])\n\t\ttable.add_row([aid, validalgs[str(aid)], stats[aid]['totalLeft'], stats[aid]['totalFound'], value])\n\tprint(table)\n\tprint(\"Hashes left: \"+str(escrowleft))\n\tprint(\"Hashes found: \"+str(escrowfound))\n\tprint(\"Total value in escrow: ₿\"+\"{0:.7f}\".format(escrowbtcvalue)+\" / $\"+\"{0:.3f}\".format(escrowusdvalue))\n\n# Creates requests session for actions that require you to be logged into hashes.com\ndef login(email, password, rememberme):\n\tglobal session\n\tsession = requests.Session()\n\turl = \"https://hashes.com/en/login\"\n\tget = session.get(url).text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\tcsrf = bs.find('input', {'name': 'csrf_token'})['value']\n\tcaptchaid = bs.find('input', {'name': 'captchaIdentifier'})['value']\n\tcaptchaurl = bs.find(id=\"captcha\").get(\"src\")\n\tprint(\"Please open the following link and enter the captcha. https://hashes.com\"+captchaurl)\n\tcaptcha = input(\"Captcha Code: \")\n\tdata = {\"email\": email, \"password\": password, \"csrf_token\": csrf, \"captcha\": captcha, \"captchaIdentifier\": captchaid, \"ddos\": \"fi\", \"submitted\": \"1\"}\n\tpost = session.post(url, data=data).text\n\tbs2 = bs4.BeautifulSoup(post, features=\"html.parser\")\n\terror = bs2.find(\"div\", {\"class\": \"my-center alert alert-dismissible alert-danger\"})\n\terror2 = bs2.find('p', attrs={'class':'mb-0'})\n\tif error is not None:\n\t\tprint(\"\".join([t for t in error.contents if type(t)==bs4.element.NavigableString]).strip())\n\t\tsession = None\n\telif error2 is not None:\n\t\tprint(error2.text.strip())\n\t\tsession = None\n\telse:\n\t\tprint(\"Login successful.\")\n\t\tif rememberme:\n\t\t\twith open(\"session.txt\", \"wb+\") as sessionfile:\n\t\t\t\tpickle.dump(session.cookies, sessionfile)\n\t\t\tprint(\"Wrote session data to: session.txt\")\n\n# Gets paid recovery history from escrow\ndef get_escrow_history(reverse, limit):\n\tuploadurl = \"https://hashes.com/escrow/upload/\"\n\tget = session.get(uploadurl).text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\thistory = bs.find(\"table\", { \"id\" : \"paidRecovery\" })\n\ttable = PrettyTable()\n\ttable.field_names = [\"ID\", \"Created\", \"Algorithm\", \"Status\", \"Total Hashes\", \"Lines Processed\", \"Valid Finds\", \"Earned\"]\n\ttable.align = \"l\"\n\tfor row in history.findAll(\"tr\"):\n\t\tcells = row.findAll(\"td\")\n\t\tif cells != []:\n\t\t\tcid = cells[0].find(text=True)\n\t\t\tdate = cells[1].find(text=True)\n\t\t\talg = cells[2].find(text=True)\n\t\t\tstatus = cells[3].find(text=True)\n\t\t\ttotal = cells[4].find(text=True)\n\t\t\tlines = cells[5].find(text=True)\n\t\t\tfinds = cells[6].find(text=True)\n\t\t\tearned = cells[7].find(text=True)\n\t\t\ttable.add_row([str(cid), str(date), str(alg), str(status), str(total), str(lines), str(finds), str(earned)])\n\tif reverse:\n\t\ttable = table[::-1]\n\tif limit:\n\t\ttable = table[0:limit]\n\tprint(table)\n\n# Gets current balance in escrow\ndef get_escrow_balance():\n\tget = session.get(\"https://hashes.com/profile\").text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\thistory = bs.find(\"table\", { \"class\" : \"table text-center\" })\n\trows = history.findAll(\"td\")\n\tbalance = rows[4].find(text=True)\n\tprint(balance)\n\n\n# Upload found hashes to hashes.com\ndef upload(algid, file):\n\tuploadurl = \"https://hashes.com/en/escrow/upload\"\n\tget = session.get(uploadurl).text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\tcsrf = bs.find('input', {'name': 'csrf_token'})['value']\n\tdata = {\"csrf_token\": csrf, \"algo\": algid, \"submitted\": \"true\"}\n\tfile = {\"userfile\": open(file, \"rb\")}\n\tpost = session.post(uploadurl, files=file, data=data).text\n\tbs2 = bs4.BeautifulSoup(post, features=\"html.parser\")\n\tsuccess = bs2.find(\"div\", {\"class\": \"my-center alert alert-dismissible alert-success\"})\n\tif success is not None:\n\t\tprint(\"\".join([t for t in success.contents if type(t)==bs4.element.NavigableString]).strip())\n\t\tprint(\"Type 'history' to check progress.\")\n\telse:\n\t\tprint(\"Something happened while uploading file.\")\n\n# Withdraw funds from hashes.com to BTC address.\ndef withdraw():\n\turl = \"https://hashes.com/en/billing/withdraw\"\n\tget = session.get(url).text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\tcsrf = bs.find('input', {'name': 'csrf_token'})['value']\n\tmaxamount = bs.find('div', {'class': 'col'}).text.strip(\"\\n\")\n\tfee = \"0.0005\"\n\tbtcaddr = input(\"Bitcoin Address: \")\n\tamount = input(maxamount+\": \")\n\tif confirm(\"Are you sure you want to withdraw %s to %s? There will be a %s fee.\" % (amount, btcaddr, fee)):\n\t\tdata = {\"csrf_token\": csrf, \"address\": btcaddr, \"amount\": amount, \"submitted\": \"true\"}\n\t\tpost = session.post(url, data=data).text\n\t\tbs2 = bs4.BeautifulSoup(post, features=\"html.parser\")\n\t\terror = bs2.find('p', attrs={'class':'mb-0'})\n\t\terror2 = bs2.find(\"div\", {\"class\": \"my-center alert alert-dismissible alert-danger\"})\n\t\tsuccess = bs2.find(\"div\", {\"class\": \"my-center alert alert-dismissible alert-success\"})\n\t\tif error is not None:\n\t\t\tprint(error.text.strip())\n\t\telif error2 is not None:\n\t\t\ttext = error2.text.replace(\"Alert\", \"\").replace(\"×\", \"\")\n\t\t\tprint(text.strip())\n\t\telif success is not None:\n\t\t\ttext = success.text.replace(\"Alert\", \"\").replace(\"×\", \"\")\n\t\t\tprint(text.strip())\n\t\telse:\n\t\t\tprint(\"Something happened during withdraw request.\")\n\telse:\n\t\tprint(\"You have canceled your withdraw request.\")\n\n# Shows all withdraw requests\ndef withdraw_requests():\n\turl = \"https://hashes.com/en/billing/withdraw\"\n\tget = session.get(url).text\n\tbs = bs4.BeautifulSoup(get, features=\"html.parser\")\n\thistory = bs.find(\"table\", { \"id\" : \"paidRecovery\" })\n\ttable = PrettyTable()\n\ttable.field_names = [\"Created\", \"Address\", \"Status\", \"Amount\", \"Fee\", \"Final\", \"Transaction Hash\"]\n\ttable.align = \"l\"\n\tfor row in history.findAll(\"tr\"):\n\t\tcells = row.findAll(\"td\")\n\t\tif cells != []:\n\t\t\tdate = cells[0].find(text=True)\n\t\t\taddress = cells[1].find(text=True)\n\t\t\tstatus = cells[2].find(text=True)\n\t\t\tamount = cells[3].find(text=True)\n\t\t\tfee = cells[4].find(text=True)\n\t\t\tfinal = cells[5].find(text=True)\n\t\t\tthash = cells[6].find(text=True)\n\t\t\ttable.add_row([str(date), str(address), str(status), str(amount), str(fee), str(final), str(thash)])\n\tprint(table)\n\n# Confirm function\ndef confirm(message):\n c = input(message+\" [y/n] \")\n if c == \"y\":\n return True\n if c == \"n\":\n return False\n\n# Print header at start of script\nprint(header)\n\n# Check if there is an exisiting session saved\nif os.path.exists(\"session.txt\"):\n\tif confirm(\"Load saved session?\"):\n\t\tsession = requests.session()\n\t\twith open(\"session.txt\", \"rb\") as sessionfile:\n\t\t\tsession.cookies.update(pickle.load(sessionfile))\n\t\tprint(\"Loaded existing session from session.txt\")\n\telse:\n\t\tsession = None\nelse:\n\tsession = None\n\n# Start console\ntry:\n\twhile True:\n\t\tcmd = input(\"hashes.com:~$ \")\n\n\t\tif cmd[0:8] == \"get jobs\":\n\t\t\tif len(cmd) > 8:\n\t\t\t\targs = cmd[8:]\n\t\t\t\tvalidsort = {\"price\": \"pricePerHash\", \"total\": \"totalHashes\", \"left\": \"leftHashes\", \"found\": \"foundHashes\", \"lastcrack\": \"lastUpdate\", \"created\": \"createdAt\"}\n\t\t\t\tparser = argparse.ArgumentParser(description='Get escrow jobs from hashes.com', prog='get jobs')\n\t\t\t\tparser.add_argument(\"-sortby\", help='Parameter to sort jobs by.', default='created', choices=validsort)\n\t\t\t\tparser.add_argument(\"-algid\", help='Algorithm to filter jobs by. Multiple can be give e.g. 20,300,220', default=None)\n\t\t\t\tparser.add_argument(\"-r\", help='Reverse display order.', action='store_false')\n\t\t\t\ttry:\n\t\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\t\tif parsed.algid is not None:\n\t\t\t\t\t\tif \",\" in parsed.algid:\n\t\t\t\t\t\t\ts = set(parsed.algid.split(\",\"))\n\t\t\t\t\t\t\td = s.difference(validalgs)\n\t\t\t\t\t\t\ts.intersection_update(validalgs)\n\t\t\t\t\t\t\tif s is not None:\n\t\t\t\t\t\t\t\tif len(d) > 0:\n\t\t\t\t\t\t\t\t\tprint (\",\".join(d)+\" are not valid algorithm IDs.\")\n\t\t\t\t\t\t\t\tjobs = get_jobs(validsort[parsed.sortby], s, parsed.r)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tjobs = False\n\t\t\t\t\t\t\t\tprint (\",\".join(d)+ \" are not valid algorithm IDs.\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif parsed.algid not in validalgs:\n\t\t\t\t\t\t\t\tjobs = False\n\t\t\t\t\t\t\t\tprint (parsed.algid+\" not a valid algorithm ID.\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t \t\tjobs = get_jobs(validsort[parsed.sortby], [parsed.algid], parsed.r)\n\t\t\t\t\telse:\n\t\t\t\t\t\tjobs = get_jobs(validsort[parsed.sortby], parsed.algid, parsed.r)\n\t\t\t\texcept SystemExit:\n\t\t\t\t\tjobs = False\n\t\t\t\t\tNone\n\t\t\telse:\n\t\t\t\tjobs = get_jobs()\n\t\t\tif jobs:\n\t\t\t\ttable = PrettyTable()\n\t\t\t\ttable.field_names = [\"Created\", \"ID\", \"Algorithm\", \"Total\", \"Found\", \"Left\", \"Max\", \"Price Per Hash\"]\n\t\t\t\ttable.align = \"l\"\n\t\t\t\tfor rows in jobs:\n\t\t\t\t\tids = rows['id']\n\t\t\t\t\tcreated = datetime.strptime(rows['createdAt'], '%Y-%m-%d %H:%M:%S').strftime(\"%m/%d/%y\")\n\t\t\t\t\talgorithm = rows['algorithmName']\n\t\t\t\t\ttotal = rows['totalHashes']\n\t\t\t\t\tfound = rows['foundHashes']\n\t\t\t\t\tleft = rows['leftHashes']\n\t\t\t\t\tmaxcracks = rows['maxCracksNeeded']\n\t\t\t\t\tprice = \"₿\"+rows['pricePerHash'] + \" / $\" + rows['pricePerHashUsd']\n\t\t\t\t\ttable.add_row([created, ids, algorithm, total, found, left, maxcracks, price])\n\t\t\t\tprint(table)\n\t\t\telse:\n\t\t\t\tprint (\"No jobs found.\")\n\t\tif cmd[0:8] == \"download\":\n\t\t\t\targs = cmd[8:]\n\t\t\t\tparser = argparse.ArgumentParser(description='Download escrow jobs from hashes.com', prog='download')\n\t\t\t\tg1 = parser.add_mutually_exclusive_group(required=True)\n\t\t\t\tg1.add_argument(\"-jobid\", help='Job ID to download. Multiple IDs can be seperated with a comma. e.g. 3,4,5.')\n\t\t\t\tg1.add_argument(\"-algid\", help='Algorithm ID to download')\n\t\t\t\tg2 = parser.add_mutually_exclusive_group(required=True)\n\t\t\t\tg2.add_argument(\"-f\", help='Download to file.')\n\t\t\t\tg2.add_argument(\"-p\", help='Print to screen', action='store_true')\n\t\t\t\ttry:\n\t\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\t\tif parsed.algid is not None:\n\t\t\t\t\t\tif parsed.algid not in validalgs:\t\n\t\t\t\t\t\t\tprint(parsed.algid+\" is not a valid algorithm.\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdownload(parsed.jobid, parsed.algid, parsed.f, parsed.p)\n\t\t\t\t\telse:\n\t\t\t\t\t\tdownload(parsed.jobid, parsed.algid, parsed.f, parsed.p)\n\t\t\t\texcept SystemExit:\n\t\t\t\t\tNone\n\t\tif cmd[0:4] == \"help\":\n\t\t\ttable = PrettyTable()\n\t\t\ttable.field_names = [\"Command\", \"Description\", \"Flags\"]\n\t\t\ttable.align = \"l\"\n\t\t\ttable.add_row([\"get jobs\", \"Gets current jobs in escrow\", \"-algid, -sortby, -r, --help\"])\n\t\t\ttable.add_row([\"download\", \"Download or print jobs from escrow\", \"-jobid, -algid, -f, -p, --help\"])\n\t\t\ttable.add_row([\"stats\", \"Gets stats about hashes left in escrow\", \"-algid, --help\"])\n\t\t\ttable.add_row([\"upload\", \"Uploads founds to hashes.com. Must be logged in.\", \"-algid, -file, --help\"])\n\t\t\ttable.add_row([\"login\", \"Login to hashes.com for certain features\", \"-email, -rememberme\"])\n\t\t\ttable.add_row([\"history\", \"Show history of submitted cracks.\", \"-limit, -r\"])\n\t\t\ttable.add_row([\"withdraw\", \"Withdraw funds from hashes.com to BTC address.\", \"No flags\"])\n\t\t\ttable.add_row([\"withdrawals\", \"Shows all withdrawals requests\", \"No flags\"])\n\t\t\ttable.add_row([\"balance\", \"Show BTC balance.\", \"No flags\"])\n\t\t\ttable.add_row([\"algs\", \"Gets algorithms hashes.com currently supports\", \"No flags\"])\n\t\t\ttable.add_row([\"logout\", \"Clears logged in session\", \"No flags\"])\n\t\t\ttable.add_row([\"clear\", \"Clears console\", \"No flags\"])\n\t\t\ttable.add_row([\"exit\", \"Exits console\", \"No flags\"])\n\t\t\tprint(table)\n\t\tif cmd[0:5] == \"stats\":\n\t\t\targs = cmd[5:]\n\t\t\tparser = argparse.ArgumentParser(description='Get stats for hashes left in escrow from hashes.com', prog='stats')\n\t\t\tparser.add_argument(\"-algid\", help='Algorithm ID to sort stats by. Multiple can be give e.g. 20,300,220', default=None)\n\t\t\ttry:\n\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\tif parsed.algid is not None:\n\t\t\t\t\tif \",\" in parsed.algid:\n\t\t\t\t\t\ts = set(parsed.algid.split(\",\"))\n\t\t\t\t\t\td = s.difference(validalgs)\n\t\t\t\t\t\ts.intersection_update(validalgs)\n\t\t\t\t\t\tif s is not None:\n\t\t\t\t\t\t\tif len(d) > 0:\n\t\t\t\t\t\t\t\tprint (\",\".join(d)+\" are not valid algorithm IDs.\")\n\t\t\t\t\t\t\tget_stats(get_jobs(\"createdAt\", s))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint (\",\".join(d)+ \" are not valid algorithm IDs.\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tif parsed.algid not in validalgs:\n\t\t\t\t\t\t\tprint(parsed.algid+\" is not a vlaid algorithm.\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tget_stats(get_jobs(\"createdAt\", [parsed.algid]))\n\t\t\t\telse:\n\t\t\t\t\tget_stats(get_jobs())\n\t\t\texcept SystemExit:\n\t\t\t\tNone\n\t\tif cmd[0:4] == \"algs\":\n\t\t\tprint(\"List of algorithms hashes.com currently supports.\")\n\t\t\ttable = PrettyTable()\n\t\t\ttable.field_names = [\"ID\", \"Algorithm\"]\n\t\t\ttable.align = \"l\"\n\t\t\tfor aid, name in validalgs.items():\n\t\t\t\ttable.add_row([aid, name])\n\t\t\tprint(table)\n\t\tif cmd[0:5] == \"login\":\n\t\t\targs = cmd[5:]\n\t\t\tparser = argparse.ArgumentParser(description='Login to hashes.com', prog='login')\n\t\t\tparser.add_argument(\"-email\", help='Email to hashes.com account.', required=True)\n\t\t\tparser.add_argument(\"-rememberme\", help='Save session to reload after closing console.', action='store_true')\n\t\t\ttry:\n\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\temail = parsed.email\n\t\t\t\tpassword = getpass()\n\t\t\t\tlogin(email, password, parsed.rememberme)\n\t\t\texcept SystemExit:\n\t\t\t\tNone\n\t\tif cmd[0:6] == \"upload\":\n\t\t\tif session is not None:\n\t\t\t\tuploadurl = \"https://hashes.com/escrow/upload/\"\n\t\t\t\targs = cmd[6:]\n\t\t\t\tparser = argparse.ArgumentParser(description='Upload cracked hashes to hashes.com', prog='upload')\n\t\t\t\tparser.add_argument(\"-algid\", help='Algorithm ID of cracked hashes', required=True, default=None)\n\t\t\t\tparser.add_argument(\"-file\", help='File of cracked hashes', required=True, default=None)\n\t\t\t\ttry:\n\t\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\t\tif parsed.algid not in validalgs:\n\t\t\t\t\t\tprint (parsed.algid+\" is not a valid algorithm ID\")\n\t\t\t\t\telif os.path.exists(parsed.file) == False:\n\t\t\t\t\t\tprint (parsed.file+\" does not exist\")\n\t\t\t\t\telif not parsed.file.lower().endswith(\".txt\"):\n\t\t\t\t\t\tprint (\"File type must be .txt\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tupload(parsed.algid, parsed.file)\n\t\t\t\texcept SystemExit:\n\t\t\t\t\tNone\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in. Type 'help' for for info.\")\n\t\tif cmd[0:7] == \"history\":\n\t\t\tif session is not None:\n\t\t\t\targs = cmd[7:]\n\t\t\t\tparser = argparse.ArgumentParser(description='View history of submitted cracks.', prog='history')\n\t\t\t\tparser.add_argument(\"-r\", help='Reverse order of history.', required=False, action='store_true')\n\t\t\t\tparser.add_argument(\"-limit\", help='Number of rows to limit results.', required=False, type=int)\n\t\t\t\ttry:\n\t\t\t\t\tparsed = parser.parse_args(shlex.split(args))\n\t\t\t\t\tget_escrow_history(parsed.r, parsed.limit)\n\t\t\t\texcept SystemExit:\n\t\t\t\t\tNone\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in. Type 'help' for info.\")\n\t\tif cmd[0:7] == \"balance\":\n\t\t\tif session is not None:\n\t\t\t\tget_escrow_balance()\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in. Type 'help' for info.\")\n\t\tif cmd == \"withdraw\":\n\t\t\tif session is not None:\n\t\t\t\twithdraw()\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in. Type 'help' for info.\")\n\t\tif cmd == \"withdrawals\":\n\t\t\tif session is not None:\n\t\t\t\twithdraw_requests()\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in. Type 'help' for info.\")\n\t\tif cmd[0:6] == \"logout\":\n\t\t\tif session is not None:\n\t\t\t\tsession = None\n\t\t\t\tprint(\"Logged out.\")\n\t\t\telse:\n\t\t\t\tprint(\"You are not logged in.\")\n\t\tif cmd[0:5] == \"clear\":\n\t\t\tos.system('cls||clear');\n\t\tif cmd[0:4] == \"exit\":\n\t\t\tbreak\nexcept KeyboardInterrupt:\n\tFalse","sub_path":"hashes.py","file_name":"hashes.py","file_ext":"py","file_size_in_byte":17920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292216331","text":"\"\"\"NVIDIA end-to-end deep learning inference for self-driving cars.\n\nThis script loads a pretrained graph from a graph def protobuf file and\nperforms inference based on that graph using jpeg images\nas input and produces an output of steering wheel angle as propotions of a\nfull turn.\n\"\"\"\nimport tensorflow as tf\nimport scipy.misc\nimport cv2\nimport time\nimport logger\nimport os\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.core.framework import graph_pb2\n\n# Folder locations\nMODELDIR = './save'\nGRAPHFILE = 'frozen_graph.pb'\nLOGDIR = './logs'\nRESULTSDIR = './results'\nRESULTFILE = 'run.py.csv'\nDATASETDIR = './driving_dataset/scaled'\n\n# Create session and restore loaded graph\nsess = tf.InteractiveSession()\nsess.graph.as_default()\n\n# Load graph def from a protobuf file\ngraph_def = graph_pb2.GraphDef()\nwith open(os.path.join(MODELDIR, GRAPHFILE) , \"r\") as f:\n graph_def.ParseFromString(f.read())\n\ntf.import_graph_def(graph_def)\ngraph = tf.get_default_graph()\n\n# Recover placeholders and tensors\n# TensorFlow seems to namespace the imported tensors with \"import/\"\nx = graph.get_tensor_by_name(\"import/x:0\")\nkeep_prob = sess.graph.get_tensor_by_name(\"import/keep_prob:0\")\ny = graph.get_tensor_by_name(\"import/y:0\")\n\n# Initialize variables used during the inference loop\nsmoothed_angle = 0.0\noutput = 0.0\ni = -1\nt = time.time()\nt_prev = t\nt0 = t\n\n# Create ResultLogger and write initial log entry\nif not os.path.exists(RESULTSDIR):\n os.makedirs(RESULTSDIR)\nlog = logger.ResultLogger(os.path.join(RESULTSDIR, RESULTFILE))\nlog.write(i, t-t0, 0.0, output)\n\n# Inference loop. Run through all the images in the dataset and perform\n# inference.\nwhile(True):\n\n # Increment image index\n i += 1\n\n # Read the next 66 x 200 RGB image\n try:\n full_image = scipy.misc.imread(DATASETDIR + \"/\" + str(i) + \".jpg\", mode=\"RGB\")\n except:\n break\n\n # Normalize image\n normalized_image = full_image / 255.0\n\n # Perform inference\n output = sess.run(y, feed_dict={x: [normalized_image], keep_prob: 1.0})[0][0]\n\n # Measure current time\n t = time.time()\n\n # Write to driving log\n log.write(i, t-t0, t-t_prev, output)\n t_prev = t\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649849","text":"#\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2018 Intel 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#\n# SPDX-License-Identifier: EPL-2.0\n#\n\nfrom __future__ import print_function\n\nimport pytest\n\nfrom subprocess import CalledProcessError\nfrom test_utils.io import catch_stdout\n\nfrom mlt.commands.sync import SyncCommand\nfrom mlt.utils import constants\n\n\n@pytest.fixture\ndef init_mock(patch):\n return patch('config_helpers.load_config')\n\n\n@pytest.fixture\ndef isfile_mock(patch):\n return patch('os.path.isfile')\n\n\n@pytest.fixture\ndef open_mock(patch):\n return patch('open')\n\n\n@pytest.fixture\ndef json_mock(patch):\n return patch('json')\n\n\n@pytest.fixture\ndef subprocess_mock(patch):\n return patch('subprocess.check_output')\n\n\n@pytest.fixture\ndef default_sync_mock(patch):\n return patch('SyncCommand._default_sync')\n\n\n@pytest.fixture()\ndef get_sync_spec_mock(patch):\n return patch('sync_helpers.get_sync_spec')\n\n\ndef sync(create=False, reload=False, delete=False):\n sync_cmd = SyncCommand({\"create\": create, \"reload\": reload,\n \"delete\": delete})\n\n with catch_stdout() as caught_output:\n sync_cmd.action()\n output = caught_output.getvalue()\n return output\n\n\ndef test_uninitialized_sync():\n \"\"\"\n Tests calling the sync command before this app has been initialized.\n \"\"\"\n with catch_stdout() as caught_output:\n with pytest.raises(SystemExit):\n SyncCommand({})\n output = caught_output.getvalue()\n expected_error = \"This command requires you to be in an `mlt init` \" \\\n \"built directory\"\n assert expected_error in output\n\n\n@pytest.mark.parametrize(\"sync_subcommand\", [\n 'create',\n 'reload',\n 'delete',\n])\ndef test_sync_commands_no_enable_sync(sync_subcommand, init_mock, open_mock,\n isfile_mock):\n \"\"\"\n Tests calling the sync create, reload or delete command without\n --enable-sync during initialize.\n \"\"\"\n isfile_mock.side_effect = [False, False, False]\n sync_subcommand = 'create'\n sync = SyncCommand({sync_subcommand: True})\n\n with catch_stdout() as caught_output:\n with pytest.raises(SystemExit):\n sync.action()\n output = caught_output.getvalue()\n expected_output = \"This app is not initialized with \" \\\n \"'--enable-sync' option\"\n assert expected_output in output\n\n\ndef test_sync_synced(init_mock, open_mock, isfile_mock, json_mock,\n subprocess_mock, get_sync_spec_mock):\n \"\"\"\n Tests trying to setup sync again\n \"\"\"\n json_mock.load.side_effect = [{\"app_run_id\": \"123-456-789\"},\n {\"sync_spec\": \"hello-world\"}]\n get_sync_spec_mock.return_value = 'hello-world'\n\n with pytest.raises(SystemExit):\n output = sync(create=True)\n expected_output = \"Syncing has been already setup for this app\"\n assert expected_output in output\n\n\n@pytest.mark.parametrize(\"sync_subcommand\", [\n 'create',\n 'reload',\n 'delete',\n])\ndef test_sync_commands_not_deployed(sync_subcommand, init_mock, open_mock,\n isfile_mock):\n \"\"\"\n Tests calling the sync create, reload or delete command before the app has\n been deployed.\n \"\"\"\n isfile_mock.side_effect = [True, False, False]\n sync_subcommand = 'create'\n sync = SyncCommand({sync_subcommand: True})\n\n with catch_stdout() as caught_output:\n with pytest.raises(SystemExit):\n sync.action()\n output = caught_output.getvalue()\n expected_output = \"This app has not been deployed yet\"\n assert expected_output in output\n\n\ndef test_successful_sync(init_mock, open_mock, isfile_mock, json_mock,\n get_sync_spec_mock, subprocess_mock):\n \"\"\"\n Tests successful call to the sync create command.\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.return_value = {\"app_run_id\": \"123-456-789\"}\n get_sync_spec_mock.return_value = None\n expected_output = \"Syncing spec is created successfully\"\n subprocess_mock.return_value.decode.return_value = expected_output\n sync_output = sync(create=True)\n assert expected_output in sync_output\n\n\n@pytest.mark.parametrize(\"sync_command\", [\n 'sync(reload=True)',\n 'sync(delete=True)',\n])\ndef test_reload_delete_not_synced(sync_command, init_mock, open_mock,\n isfile_mock, json_mock, subprocess_mock,\n get_sync_spec_mock):\n \"\"\"\n Tests reloading sync agent or deleting sync spec before sync setup\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.return_value = {\"app_run_id\": \"123-456-789\"}\n get_sync_spec_mock.return_value = None\n\n with pytest.raises(SystemExit):\n output = eval(sync_command)\n expected_output = \"No syncing spec has been created for this app yet\"\n assert expected_output in output\n\n\ndef test_reload_synced(init_mock, open_mock, isfile_mock, json_mock,\n subprocess_mock, get_sync_spec_mock):\n \"\"\"\n Tests reloading sync agent after sync create\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.return_value = {\"app_run_id\": \"123-456-789\"}\n get_sync_spec_mock.return_value = \"hello-world\"\n expected_output = \"Sync agent is restarted\"\n subprocess_mock.return_value.decode.return_value = expected_output\n sync_output = sync(reload=True)\n assert expected_output in sync_output\n\n\ndef test_delete_synced(init_mock, open_mock, isfile_mock, json_mock,\n get_sync_spec_mock, subprocess_mock):\n \"\"\"\n Tests delete sync spec after sync setup\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.side_effect = [{\"app_run_id\": \"123-456-789\"},\n {\"sync_spec\": \"hello-world\"}]\n get_sync_spec_mock.return_value = \"hello-world\"\n expected_output = \"Syncing spec is successfully deleted\"\n subprocess_mock.return_value.decode.return_value = expected_output\n sync_output = sync(delete=True)\n assert expected_output in sync_output\n\n\ndef test_sync_create_not_in_makefile(init_mock, open_mock, isfile_mock,\n get_sync_spec_mock, json_mock,\n subprocess_mock):\n \"\"\"\n Tests use case where sync create target is not in the Makefile.\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.side_effect = [{\"app_run_id\": \"123-456-789\"},\n {\"sync_spec\": \"hello-world\"}]\n get_sync_spec_mock.return_value = None\n error_msg = \"This app does not support the `mlt sync create` command\"\n subprocess_mock.side_effect = CalledProcessError(\n returncode=2, cmd=\"make sync-create\", output=error_msg)\n sync_output = sync(create=True)\n assert error_msg in sync_output\n\n\ndef test_sync_reload_not_in_makefile(init_mock, open_mock, isfile_mock,\n get_sync_spec_mock, json_mock,\n subprocess_mock):\n \"\"\"\n Tests use case where sync reload target is not in the Makefile.\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.side_effect = [{\"app_run_id\": \"123-456-789\"},\n {\"sync_spec\": \"hello-world\"}]\n get_sync_spec_mock.return_value = 'hello-world'\n error_msg = \"This app does not support the `mlt sync reload` command\"\n subprocess_mock.side_effect = CalledProcessError(\n returncode=2, cmd=\"make sync-reload\", output=error_msg)\n sync_output = sync(reload=True)\n assert error_msg in sync_output\n\n\ndef test_sync_delete_not_in_makefile(init_mock, open_mock, isfile_mock,\n get_sync_spec_mock, json_mock,\n subprocess_mock):\n \"\"\"\n Tests use case where sync delete target is not in the Makefile.\n \"\"\"\n isfile_mock.side_effect = [True, True, False]\n mlt_config = {\n \"namespace\": \"foo\",\n \"registry\": \"bar\",\n \"name\": \"hello-world\",\n constants.TEMPLATE_PARAMETERS: {\n \"num_workers\": 2\n }\n }\n init_mock.return_value = mlt_config\n json_mock.load.side_effect = [{\"app_run_id\": \"123-456-789\"},\n {\"sync_spec\": \"hello-world\"}]\n get_sync_spec_mock.return_value = 'hello-world'\n error_msg = \"This app does not support the `mlt sync delete` command\"\n subprocess_mock.side_effect = CalledProcessError(\n returncode=2, cmd=\"make sync-delete\", output=error_msg)\n sync_output = sync(delete=True)\n assert error_msg in sync_output\n","sub_path":"tests/unit/commands/test_sync.py","file_name":"test_sync.py","file_ext":"py","file_size_in_byte":10649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398453146","text":"#from ..project_defs import SnovaultProject\nfrom ..project_app import app_project\nimport argparse\nimport atexit\nimport botocore.exceptions\nimport cgi\nimport datetime\nimport elasticsearch\nimport io\nimport json\nimport os\nimport psycopg2\nimport re\nimport signal\nimport structlog\nimport threading\nimport time\nimport webtest\n\nfrom dcicutils.env_utils import is_stg_or_prd_env\nfrom dcicutils.misc_utils import VirtualApp, ignored, check_true, full_class_name, environ_bool, PRINT\nfrom pyramid import paster\n# Possibly still needed by some commented-out code.\n# from pyramid.response import Response\nfrom pyramid.view import view_config\nfrom snovault.util import debug_log\nfrom ..embed import subrequest_object\nfrom ..types.ingestion import SubmissionFolio, IngestionSubmission\nfrom ..util import (\n debuglog, get_trusted_email, beanstalk_env_from_request,\n register_path_content_type, vapp_for_email, # vapp_for_ingestion,\n SettingsKey, make_s3_client, extra_kwargs_for_s3_encrypt_key_id,\n)\nfrom .common import metadata_bundles_bucket, get_parameter, IngestionReport\nfrom .exceptions import UnspecifiedFormParameter, SubmissionFailure # , BadParameter\nfrom .ingestion_listener_base import (\n DEBUG_SUBMISSIONS,\n IngestionListenerBase,\n)\nfrom .ingestion_message_handler_decorator import call_ingestion_message_handler\nfrom .ingestion_processor_decorator import get_ingestion_processor\nfrom .queue_utils import IngestionQueueManager\n\n\nlog = structlog.getLogger(__name__)\nEPILOG = __doc__\nINGESTION_QUEUE = 'ingestion_queue'\n\n\ndef includeme(config):\n # config.add_route('process_ingestion', '/process_ingestion')\n config.add_route('queue_ingestion', '/queue_ingestion')\n config.add_route('ingestion_status', '/ingestion_status')\n config.add_route('submit_for_ingestion', '/submit_for_ingestion')\n config.registry[INGESTION_QUEUE] = IngestionQueueManager(config.registry)\n config.scan(__name__)\n\n\nSUBMISSION_PATTERN = re.compile(r'^/ingestion-submissions/([0-9a-fA-F-]+)(|/.*)$')\n\nregister_path_content_type(path='/submit_for_ingestion', content_type='multipart/form-data')\n\n\ndef extract_submission_info(request):\n matched = SUBMISSION_PATTERN.match(request.path_info)\n if matched:\n submission_id = matched.group(1)\n else:\n raise SubmissionFailure(\"request.path_info is not in the expected form: %s\" % request.path_info)\n\n instance = subrequest_object(request, submission_id)\n return submission_id, instance\n\n\n@view_config(name='submit_for_ingestion', request_method='POST', context=IngestionSubmission,\n # Apparently adding this 'accept' causes discrimination on incoming requests not to find this method.\n # We do want this type, and instead we check the request to make sure we got it, but we omit it here\n # for practical reasons. -kmp 10-Sep-2020\n # accept='multipart/form-data',\n permission='edit')\n@debug_log\ndef submit_for_ingestion(context, request):\n ignored(context)\n\n check_true(request.content_type == 'multipart/form-data', # even though we can't declare we accept this\n \"Expected request to have content_type 'multipart/form-data'.\", error_class=SubmissionFailure)\n\n bs_env = beanstalk_env_from_request(request)\n bundles_bucket = metadata_bundles_bucket(request.registry)\n datafile = request.POST.get('datafile')\n if datafile is None:\n # S3 protocol; not uploading from here (SubmitCGAP uploads directly).\n # Added circa March 2023 for Fourfront ontology ingestion.\n filename = request.POST['datafile_source_filename']\n override_name = None\n elif isinstance(datafile, cgi.FieldStorage):\n filename = datafile.filename\n override_name = request.POST.get('override_name', None)\n else:\n # e.g., specifically it might be b'' when no file is selected,\n # but IMPORTANTLY, cgi.FieldStorage has no predefined boolean value,\n # so we can't just ask to check 'not datafile'. Sigh. -kmp 5-Aug-2020\n raise UnspecifiedFormParameter('datafile')\n parameters = dict(request.POST) # Convert to regular dictionary, which is also a copy\n parameters['datafile'] = filename\n\n # Other parameters, like validate_only, will ride in on parameters via the manifest on s3\n\n submission_id, instance = extract_submission_info(request)\n\n # The three arguments award, lab, and ingestion_type were needed in the old protocol\n # but are not needed in the new protocol because someone will have set up the IngestionSubmission\n # object already with the right values. We tolerate them here, but we insist they be consistent (redundant).\n # Note, too, that we use the 'update=True' option that causes them to be added to our parameters if they are\n # missing, defaulted from the previous item, so that they will be written to the parameter block stored on S3.\n # (We could do that differently now, by looking them up dynamically, but rather than risk making a mistake,\n # I just went with path of least resistance for now.)\n # -kmp 2-Dec-2020\n #\n # Same goes for award and lab which were brought from fourfront\n # into this common snovault version of ingestion_listener.py.\n # -dmichaels 12-May-2023\n\n if instance.get(\"institution\"):\n institution = instance['institution']['@id']\n institution_arg = get_parameter(parameters, \"institution\", default=institution, update=True)\n if institution_arg != institution:\n # If the \"institution\" argument was passed, which we no longer require, make sure it's consistent.\n raise SubmissionFailure(\"'institution' was supplied inconsistently for submit_for_ingestion.\")\n\n if instance.get(\"project\"):\n project = instance['project']['@id']\n project_arg = get_parameter(parameters, \"project\", default=project, update=True)\n if project_arg != project:\n # If the \"project\" argument was passed, which we no longer require, make sure it's consistent.\n raise SubmissionFailure(\"'project' was supplied inconsistently for submit_for_ingestion.\")\n\n if instance.get(\"award\"):\n award = instance['award']['@id']\n award_arg = get_parameter(parameters, \"award\", default=award, update=True)\n if award_arg != award:\n # If the \"award\" argument was passed, which we no longer require, make sure it's consistent.\n raise SubmissionFailure(\"'award' was supplied inconsistently for submit_for_ingestion.\")\n\n if instance.get(\"lab\"):\n lab = instance['lab']['@id']\n lab_arg = get_parameter(parameters, \"lab\", default=lab, update=True)\n if lab_arg != lab:\n # If the \"lab\" argument was passed, which we no longer require, make sure it's consistent.\n raise SubmissionFailure(\"'lab' was supplied inconsistently for submit_for_ingestion.\")\n\n ingestion_type = instance['ingestion_type']\n ingestion_type_arg = get_parameter(parameters, \"ingestion_type\", default=ingestion_type, update=True)\n if ingestion_type_arg != ingestion_type:\n # If the \"ingestion_type\" argument was passed, which we no longer require, make sure it's consistent.\n raise SubmissionFailure(\"'ingestion_type' was supplied inconsistently for submit_for_ingestion.\")\n\n # ``input_file`` contains the actual file data which needs to be\n # stored somewhere.\n\n if datafile is not None:\n input_file_stream = datafile.file\n input_file_stream.seek(0)\n\n # NOTE: Some reference information about uploading files to s3 is here:\n # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html\n\n # submission.set_item_detail(object_name=manifest['object_name'], parameters=manifest['parameters'],\n # institution=institution, project=project)\n\n # submission_id = str(uuid.uuid4())\n _, ext = os.path.splitext(filename)\n object_name = \"{id}/datafile{ext}\".format(id=submission_id, ext=ext) if datafile is not None else submission_id\n manifest_name = \"{id}/manifest.json\".format(id=submission_id)\n\n # We might need to extract some additional information from the GAC\n s3_client = make_s3_client()\n\n upload_time = datetime.datetime.utcnow().isoformat()\n success = True\n message = \"Uploaded successfully.\"\n\n # Set up potentially useful additional args\n s3_encrypt_key_id = request.registry.settings.get(SettingsKey.S3_ENCRYPT_KEY_ID)\n extra_kwargs = extra_kwargs_for_s3_encrypt_key_id(s3_encrypt_key_id=s3_encrypt_key_id,\n client_name='submit_for_ingestion')\n\n if extra_kwargs:\n additional_info = f\" (with SSEKMSKeyId: {s3_encrypt_key_id})\"\n else:\n additional_info = \" (no SSEKMSKeyId)\"\n\n if datafile is not None:\n try:\n # Make sure to pass any extra args.\n s3_client.upload_fileobj(input_file_stream, Bucket=bundles_bucket, Key=object_name, **extra_kwargs)\n except botocore.exceptions.ClientError as e:\n log.error(e)\n success = False\n message = f\"{full_class_name(e)}: {str(e)}{additional_info}\"\n\n # This manifest will be stored in the manifest.json file on on s3 AND will be returned from this endpoint call.\n manifest_content = {\n \"filename\": filename,\n \"object_name\": object_name,\n \"s3_encrypt_key_id\": s3_encrypt_key_id,\n \"submission_id\": submission_id,\n \"submission_uri\": SubmissionFolio.make_submission_uri(submission_id),\n \"beanstalk_env_is_prd\": is_stg_or_prd_env(bs_env),\n \"beanstalk_env\": bs_env,\n \"bucket\": bundles_bucket,\n \"authenticated_userid\": request.authenticated_userid,\n \"email\": get_trusted_email(request, context=\"Submission\", raise_errors=False),\n \"success\": success,\n \"message\": message,\n \"upload_time\": upload_time,\n \"parameters\": parameters,\n }\n\n manifest_content_formatted = json.dumps(manifest_content, indent=2)\n\n if success:\n\n try:\n with io.BytesIO(manifest_content_formatted.encode('utf-8')) as fp:\n s3_client.upload_fileobj(fp, Bucket=bundles_bucket, Key=manifest_name, **extra_kwargs)\n except botocore.exceptions.ClientError as e:\n log.error(e)\n message = f\"{full_class_name(e)} (while uploading metadata): {str(e)}{additional_info}\"\n raise SubmissionFailure(message)\n\n queue_manager = get_queue_manager(request, override_name=override_name)\n _, failed = queue_manager.add_uuids([submission_id], ingestion_type=ingestion_type)\n\n if failed:\n # If there's a failure, failed will be a list of one problem description since we only submitted one thing.\n raise SubmissionFailure(failed[0])\n\n if not success:\n\n raise SubmissionFailure(message)\n\n return manifest_content\n\n\n@view_config(route_name='ingestion_status', request_method='GET', permission='index')\n@debug_log\ndef ingestion_status(context, request):\n \"\"\" Status route, essentially identical to indexing_status. \"\"\"\n ignored(context)\n queue_manager = request.registry[INGESTION_QUEUE]\n n_waiting, n_inflight = queue_manager.get_counts()\n return {\n 'title': 'Ingestion Status',\n 'waiting': n_waiting,\n 'inflight': n_inflight\n }\n\n\n\ndef process_submission(*, submission_id, ingestion_type, app, bundles_bucket=None, s3_client=None):\n ignored(s3_client) # we might want to restore the ability to pass this, but no one actually does. -kmp 6-Dec-2021\n bundles_bucket = bundles_bucket or metadata_bundles_bucket(app.registry)\n s3_client = make_s3_client()\n manifest_name = \"{id}/manifest.json\".format(id=submission_id)\n log.warning(f'Processing submission {manifest_name}')\n obj = s3_client.get_object(Bucket=bundles_bucket, Key=manifest_name)\n # data = json.load(obj)['Body']\n data = json.load(obj['Body'])\n email = None\n try:\n email = data['email']\n except KeyError as e:\n ignored(e)\n debuglog(\"Manifest data is missing 'email' field.\")\n if DEBUG_SUBMISSIONS:\n pass\n debuglog(\"processing submission %s with email %s\" % (submission_id, email))\n with vapp_for_email(email=email, app=app) as vapp:\n if DEBUG_SUBMISSIONS:\n PRINT(\"PROCESSING FOR %s\" % email)\n submission = SubmissionFolio(vapp=vapp, ingestion_type=ingestion_type, submission_id=submission_id, log=None)\n handler = get_ingestion_processor(ingestion_type)\n result = handler(submission)\n if DEBUG_SUBMISSIONS:\n PRINT(\"DONE PROCESSING FOR %s\" % email)\n return {\n \"result\": result,\n \"ingestion_type\": ingestion_type,\n \"submission_id\": submission_id,\n }\n\n\n@view_config(route_name='queue_ingestion', request_method='POST', permission='index')\n@debug_log\ndef queue_ingestion(context, request):\n \"\"\" Queues uuids as part of the request body for ingestion. Can batch as many as desired in a\n single request. Note that you can also pass ingestion_type, which will apply to all uuids queued.\n The default is (SNV) ontology.\n \"\"\"\n ignored(context)\n uuids = request.json.get('uuids', [])\n ingestion_type = request.json.get('ingestion_type', 'ontology') # note that this applies to all uuids\n override_name = request.json.get('override_name', None)\n return enqueue_uuids_for_request(request, uuids, ingestion_type=ingestion_type, override_name=override_name)\n\n\ndef enqueue_uuids_for_request(request, uuids, *, ingestion_type, override_name=None):\n response = {\n 'notification': 'Failure',\n 'number_queued': 0,\n 'detail': 'Nothing was queued. Make sure to past in a list of uuids in in \"uuids\" key.'\n }\n if uuids is []:\n return response\n queue_manager = get_queue_manager(request, override_name=override_name)\n _, failed = queue_manager.add_uuids(uuids, ingestion_type=ingestion_type)\n if not failed:\n response['notification'] = 'Success'\n response['number_queued'] = len(uuids)\n response['detail'] = 'Successfully queued the following uuids: %s' % uuids\n app_project().note_ingestion_enqueue_uuids_for_request(ingestion_type, request, uuids)\n else:\n response['number_queued'] = len(uuids) - len(failed)\n response['detail'] = 'Some uuids failed: %s' % failed\n return response\n\n\ndef get_queue_manager(request, *, override_name):\n return (request.registry[INGESTION_QUEUE]\n if not override_name\n else IngestionQueueManager(request.registry, override_name=override_name))\n\n\nclass IngestionListener(IngestionListenerBase):\n \"\"\" Organizes helper functions for the ingestion listener \"\"\"\n POLL_INTERVAL = 10 # seconds between each poll\n INGEST_AS_USER = environ_bool('INGEST_AS_USER', default=True) # The new way, but possible to disable for now\n\n def __init__(self, vapp, _queue_manager=None, _update_status=None):\n self.vapp = vapp\n\n # Get queue_manager\n registry = None\n if isinstance(self.vapp, (webtest.TestApp, VirtualApp)): # TestApp in testing or VirtualApp in production\n registry = self.vapp.app.registry\n elif _queue_manager is None: # if we got here, we cannot succeed in starting\n raise Exception('Bad arguments given to IngestionListener: %s, %s, %s' %\n (self.vapp, _queue_manager, _update_status))\n self.queue_manager = IngestionQueueManager(registry) if not _queue_manager else _queue_manager\n self.update_status = _update_status\n\n @staticmethod\n def should_remain_online(override=None):\n \"\"\" A function that says whether 'run' should continue. This is provided because it\n can be mocked in testing.\n\n :param override: a lambda that will execute when evaluating if specified\n :return: True if should stay running, False otherwise\n \"\"\"\n if not override:\n return True\n return override()\n\n def get_messages(self):\n \"\"\" Sleeps (as to not hit SQS too frequently) then requests messages,\n returning the result bodies.\n\n NOTE: THIS FUNCTION SHOULD NOT BE USED OUTSIDE OF THIS CODE SINCE\n IT BLOCKS FOR RATE LIMITING REASONS\n\n :return: messages available on SQS\n \"\"\"\n time.sleep(self.POLL_INTERVAL) # sleep here before polling again\n return self.queue_manager.receive_messages()\n\n def delete_messages(self, messages):\n \"\"\" Deletes messages from SQS (after they have been processed). Does not return\n anything but will log if messages fail deletion.\n\n :param messages: messages to be deleted\n \"\"\"\n failed = self.queue_manager.delete_messages(messages)\n while True:\n debuglog(\"Trying to delete messages\")\n tries = 3\n if failed:\n debuglog(\"Failed to delete messages\")\n if tries > 0:\n failed = self.queue_manager.delete_messages(failed) # try again\n tries -= 1\n else:\n log.error('Failed to delete messages from SQS: %s' % failed)\n break\n else:\n debuglog(\"Deleted messages\")\n break\n\n def _patch_value(self, uuid, field, value):\n \"\"\" Patches field with value on item uuid \"\"\"\n self.vapp.patch_json('/' + uuid, {field: value})\n\n def patch_ingestion_report(self, report, uuid):\n \"\"\" Sets the file_ingestion_error field of the given uuid \"\"\"\n if isinstance(report, IngestionReport): # handle normal case\n self._patch_value(uuid, 'file_ingestion_error', report.get_errors())\n elif isinstance(report, list): # handle when build_ingestion_error_report result is passed\n self._patch_value(uuid, 'file_ingestion_error', report)\n else:\n raise TypeError('Got bad type for ingestion error report: %s' % report)\n\n def set_status(self, uuid, status):\n \"\"\" Sets the file_ingestion_status of the given uuid \"\"\"\n self._patch_value(uuid, 'file_ingestion_status', status)\n\n @staticmethod\n def build_ingestion_error_report(msg):\n \"\"\" Builds an ingestion error report in case an error is encountered that cannot be recovered from\n in VCF ingestion - see file_processed.json for structure definition. \"\"\"\n return [\n {\n 'body': msg,\n 'row': -1 # this exception may have occurred on a particular row but since it could not be recovered\n } # from we assume the msg has sufficient info to work backwards from - Will 4/9/21\n ]\n\n def run(self):\n \"\"\" Main process for this class. Runs forever doing ingestion as needed.\n\n HIGH LEVEL LOGIC:\n while True:\n while there are messages available:\n for each message:\n download, decompress, ingest, patch file status to \"Ingested\"\n delete processed messages\n \"\"\"\n log.info('Ingestion listener successfully online.')\n\n debuglog(\"Ingestion listener started.\")\n\n messages = [] # This'll get a better value below in each loop iteration. This is just a declaration of intent.\n\n def discard(msg):\n self.delete_messages([msg])\n # Assuming we didn't get an error trying to remove it,\n # it should also get removed from our to-do list.\n messages.remove(msg)\n\n while self.should_remain_online():\n\n debuglog(\"About to get messages.\")\n\n messages = self.get_messages() # wait here\n\n debuglog(\"Got\", len(messages), \"messages.\")\n\n # ingest each VCF file\n for message in list(messages):\n # C4-990/2023-02-09/dmichaels\n # Added the list wrapper around messages in the above loop,\n # i.e. list(messages), so that when we remove a message from\n # the messages list via the discard function (above) the loop\n # does not end up skipping the very next message.\n\n debuglog(\"Message:\", message)\n\n # C4-990/2023-02-09/dmichaels\n # This calls at most one our message handlers\n # registered via the @ingestion_message_handler decorator.\n if call_ingestion_message_handler(message, self):\n # Here one of our message handlers was called and it processed this message.\n discard(message)\n\n # This is just fallback cleanup in case messages weren't cleaned up within the loop.\n # In normal operation, they will be.\n self.delete_messages(messages)\n\n\ndef run(vapp=None, _queue_manager=None, _update_status=None):\n \"\"\" Entry-point for the ingestion listener for waitress. \"\"\"\n ingestion_listener = IngestionListener(vapp, _queue_manager=_queue_manager, _update_status=_update_status)\n try:\n ingestion_listener.run()\n except Exception as e:\n debuglog(str(e))\n raise\n\n\nclass ErrorHandlingThread(threading.Thread):\n \"\"\" Must be duplicated here so logging is correct. \"\"\"\n\n def run(self):\n # interval = self._kwargs.get('interval', DEFAULT_INTERVAL)\n interval = 60 # DB polling can and should be slower\n update_status = self._kwargs['_update_status'] # noQA - uses private instance variables of parent class\n while True:\n try:\n self._target(*self._args, **self._kwargs) # noQA - uses private instance variables of parent class\n except (psycopg2.OperationalError, elasticsearch.exceptions.ConnectionError) as e:\n # Handle database restart\n log.warning('Database not there, maybe starting up: %r', e)\n update_status(msg=repr(e))\n log.debug('sleeping')\n time.sleep(interval)\n continue\n except Exception as e:\n # Unfortunately mod_wsgi does not restart immediately\n log.exception('Exception in ingestion listener, restarting process at next request: %s' % e)\n os.kill(os.getpid(), signal.SIGINT)\n break\n\n\n# Composite Application (for wsgi)\ndef composite(loader, global_conf, **settings):\n \"\"\" This is a composite pyramid app, meant to run components of an application\n or an application extension. In our case we are running the ingestion listener,\n which requires executing a command with application context. This code lives\n in encoded top-level as it is a wsgi entry-point. Note that the local deployment\n does NOT run the listener this way, but runs the run method through main directly.\n This code is heavily based off of the es_index_listener in snovault.\n \"\"\"\n listener = None\n\n # Register before app creation.\n @atexit.register\n def join_listener():\n if listener:\n log.debug('joining listening thread')\n listener.join()\n\n # Composite app is used so we can load the main app\n app_name = settings.get('app', None)\n app = loader.get_app(app_name, global_conf=global_conf)\n username = settings.get('username', 'IMPORT')\n environ = {\n 'HTTP_ACCEPT': 'application/json',\n 'REMOTE_USER': username,\n }\n vapp = VirtualApp(app, environ)\n timestamp = datetime.datetime.utcnow().isoformat()\n status_holder = {\n 'status': {\n 'status': 'starting listener',\n 'started': timestamp,\n 'msgs': []\n },\n }\n\n def update_status(msg=None, **kw):\n \"\"\" Method passed to run to update \"global\" status. \"\"\"\n # Setting a value in a dictionary is atomic\n status = status_holder['status'].copy()\n status.update(**kw) # can hold generic info\n if msg is not None:\n status['msgs'].append(msg)\n status_holder['status'] = status\n\n kwargs = {\n 'vapp': vapp,\n '_update_status': update_status\n }\n\n # daemon thread that actually executes `run` method to call /index\n listener = ErrorHandlingThread(target=run, name='listener', kwargs=kwargs)\n listener.daemon = True\n log.debug('WSGI Ingestion Listener Started')\n listener.start()\n\n # Register after virtualapp creation.\n @atexit.register\n def shutdown_listener():\n \"\"\" Echo a statement at shutdown \"\"\"\n log.debug('shutting down listening thread')\n\n def status_app(environ, start_response):\n \"\"\" Allows you to get the status of the ingestion \"manager\". This will be much\n more useful once multi-processing is thrown at ingestion.\n \"\"\"\n ignored(environ)\n status = '200 OK'\n response_headers = [('Content-type', 'application/json')]\n start_response(status, response_headers)\n return [json.dumps(status_holder['status'])]\n\n return status_app\n\n\n# Command Application (for waitress)\ndef main():\n \"\"\" Entry point for the local deployment. \"\"\"\n parser = argparse.ArgumentParser( # noqa - PyCharm wrongly thinks the formatter_class is specified wrong here.\n description='Listen for VCF File uuids to ingest',\n epilog=EPILOG,\n formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument('--app-name', help='Pyramid app name in configfile')\n parser.add_argument('--username', '-u', default='IMPORT', help='Import username')\n parser.add_argument('--dry-run', action='store_true', help='Do not post variants, just validate')\n parser.add_argument('config_uri', help=\"path to configfile\")\n args = parser.parse_args()\n\n app = paster.get_app(args.config_uri, args.app_name)\n config = {\n 'HTTP_ACCEPT': 'application/json',\n 'REMOTE_USER': args.username,\n }\n\n vapp = VirtualApp(app, config)\n return run(vapp)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"snovault/ingestion/ingestion_listener.py","file_name":"ingestion_listener.py","file_ext":"py","file_size_in_byte":26153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350984207","text":"# coding=utf-8\nfrom lj import lj as dlj\n\nfrom codecs import decode\ndef write_file(c,s,d,i):\n fi = open(\"input_%s.md\" % i, 'w', encoding='utf-8')\n fi.write(\"title:%s\\ndate:%s\\n\\n\\n%s\" % (c, s, d))\n fi.close()\n i += 1\n\n\ndef make_list(r):\n i=0\n for key in r['events']:\n try:\n d = (key[\"event\"].data.decode())\n except AttributeError:\n d='no data'\n try:\n c=(key[\"subject\"].data.decode())\n except KeyError:\n c='(no subject)'\n s=key['logtime']\n i+=1\n write_file(c,s,d,i)\ndef ljj():\n lj = dlj.LJServer(\"lj-post-grabber\", \"example.com\")\n lj.login(\"login\", \"pass\")\n r=lj.getevents_lastn(50,'2019-11-20 21:54:00')\n make_list(r)\nif __name__ == '__main__':\n ljj()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633342376","text":"\"\"\"Week 3, Exercise 3\n\nSteps on the way to making your own guessing game.\n\"\"\"\n\nimport random\n\n\ndef advancedGuessingGame():\n \"\"\"Play a guessing game with a user.\n\n The exercise here is to rewrite the exampleGuessingGame() function\n from exercise 3, but to allow for:\n * a lower bound to be entered, e.g. guess numbers between 10 and 20\n * ask for a better input if the user gives a non integer value anywhere.\n I.e. throw away inputs like \"ten\" or \"8!\" but instead of crashing\n ask for another value.\n * chastise them if they pick a number outside the bounds.\n * see if you can find the other failure modes.\n There are three that I can think of. (They are tested for.)\n\n NOTE: whilst you CAN write this from scratch, and it'd be good for you to\n be able to eventually, it'd be better to take the code from exercise 2 and\n merge it with code from excercise 1.\n Remember to think modular. Try to keep your functions small and single\n purpose if you can!\n \"\"\"\n \n isnumber = 0\n \n print(\"\\nWelcome to the guessing game!\")\n\n while isnumber == 0: \n upperBound = get_good_number(\"Enter an upper bound: \")\n lowerBound = get_good_number(\"Enter an lower bound: \")\n if upperBound < 1:\n print(\"lower or equal to 1\")\n elif lowerBound >= upperBound:\n print(f\"{lowerBound} {upperBound} Range needs to be lower\")\n x = lowerBound\n lowerBound = upperBound\n upperBound = x\n isnumber = 1\n else:\n isnumber = 1\n\n print(f\"OK then, a number between {lowerBound}\" + f\" and {upperBound} ?\")\n actualNumber = random.randint(lowerBound, upperBound)\n print(f\"actualnumber {actualNumber}\")\n\n while isnumber == 1:\n guessedNumber = input(\"Now guess a number between the range!: \")\n try:\n guessedNumber = int(guessedNumber)\n if guessedNumber > upperBound or guessedNumber < lowerBound:\n print(\"OUTSIDE THE BOUNDS CHOOSE AGAIN\")\n else:\n print(f\"You guessed {guessedNumber}\")\n if guessedNumber == actualNumber:\n print(\"You got it!! It was {}\".format(actualNumber))\n return \"You got it!\"\n isnumber = 0\n elif guessedNumber < actualNumber:\n print(\"Too small, try again :'(\")\n else:\n print(\"Too big, try again :'(\")\n \n except:\n print(\"This is not a valid number\")\n\ndef get_good_number(message):\n while True:\n inputnum = input(message)\n try:\n inputnum = int(inputnum)\n return inputnum\n except:\n print(f\"{inputnum} This is not a valid number\")\n \n \n\n # while not guessed:\n # guessedNumber = int(input(\"Guess a number: \"))\n # print(\"You guessed {},\".format(guessedNumber),)\n # if guessedNumber == actualNumber:\n # print(\"You got it!! It was {}\".format(actualNumber))\n # guessed = True\n # elif guessedNumber < actualNumber:\n # print(\"Too small, try again :'(\")\n # else:\n # print(\"Too big, try again :'(\")\n # return \"You got it!\"\n\n # the tests are looking for the exact string \"You got it!\". Don't modify that!\n\n\nif __name__ == \"__main__\":\n print(advancedGuessingGame())\n","sub_path":"week3/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302148570","text":"import pymongo\nfrom flask import Flask, jsonify\nfrom bson.json_util import dumps\n\napp = Flask(__name__)\n\nconn = 'mongodb://localhost:27017'\nclient = pymongo.MongoClient(conn)\n\ndb = client.record_db\ncollection = db.item\n\n\n\n\n@app.route(\"/\")\ndef home():\n print(\"received request from 'home page'\")\n return (\"/api/v1.0/terrorism_data\")\n\n@app.route(\"/api/v1.0/terrorism_data\")\ndef data():\n print(\"received request from 'station page'\")\n results = db.item.find()\n # data = dumps(results)\n # return jsonify(data)\n\n return dumps(results)\n\n \n\nif __name__==\"__main__\":\n app.run(debug=True)","sub_path":"Project--2/Dashboard/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226608918","text":"# coding=utf-8\nFEMALE = 'female'\nMALE = 'male'\n\nBLONDE_HAIR = 'blonde'\nBLACK_HAIR = 'black'\nBROWN_HAIR = 'brown'\nGREY_HAIR = 'grey'\n\nLONG_HAIR = 'long'\nSHORT_HAIR = 'short'\n\nSTRAIGHT_HAIR = 'straight'\nCURLY_HAIR = 'curly'\n\nBROWN_EYES = 'brown'\nBLUE_EYES = 'blue'\nGREEN_HAIR = 'green'\n\nBIG_NOISE = 'big'\nSMALL_NOISE = 'small'\n\nHAT_ACCESSORY = 'hat'\nGLASSES_ACCESSORY = 'glasses'\n\nBEARD = 'beard'\nMOUSTACHE = 'moustache'\nNECKLACE = 'necklace'\n\nYES_RED_CHEEKED = \"yes\"\nNOT_RED_CHEEKED = \"not\"\n\nNOTHING = None\n\nGENDER = 'gender'\nHAIR_COLOUR = 'hair_colour'\nHAIR_LENGTH = 'hair_length'\nHAIR_TYPE = 'hair_type'\nEYE_COLOUR = 'eye_colour'\nNOSE_SIZE = 'nose_size'\nRED_CHEEKED = 'red_cheeked'\nACCESSORIES = 'accessories'\nSPECIAL_FEATURE = 'special_feature'\n\nPROPERTIES_FIRST_ROUND = {\n GENDER: [FEMALE, MALE],\n HAIR_COLOUR: [BLONDE_HAIR, BLACK_HAIR, BROWN_HAIR, GREY_HAIR],\n HAIR_LENGTH: [LONG_HAIR, SHORT_HAIR],\n HAIR_TYPE: [STRAIGHT_HAIR, CURLY_HAIR],\n EYE_COLOUR: [GREEN_HAIR, BLUE_EYES, BROWN_EYES],\n NOSE_SIZE: [BIG_NOISE, SMALL_NOISE],\n RED_CHEEKED: [YES_RED_CHEEKED, NOT_RED_CHEEKED],\n #Sacamos \"NOTHING\" porque propiedades lo usamos solo para formular preguntas\n ACCESSORIES: [HAT_ACCESSORY, GLASSES_ACCESSORY],\n SPECIAL_FEATURE: [BEARD, MOUSTACHE, NECKLACE],\n}\n","sub_path":"src/quien_es_quien/user/utils/variables/properties_round_1.py","file_name":"properties_round_1.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374527554","text":"import pyglet\nfrom pyglet.gl import *\nimport random\n\nwin = pyglet.window.Window()\n \n\nvertices = [(random.randint(1,350),random.randint(1,300))]\n\n\n\n\n\n\n@win.event\ndef on_draw():\n win.clear()\n # Clear buffers\n glClear(GL_COLOR_BUFFER_BIT)\n \n # Draw outlines only\n glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)\n \n # Draw some stuff\n glBegin(GL_TRIANGLE_STRIP)\n vertices.append((random.randint(1,350),random.randint(1,300)))\n for vertex in vertices:\n glVertex2i(vertex[0],vertex[1])\n glEnd()\n \npyglet.app.run()","sub_path":"3d/pyglet/first_try.py","file_name":"first_try.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"220524594","text":"# Add PSFEx FWHM values\n\nfrom __future__ import division, print_function\nimport sys, os, glob, time, warnings, gc\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table, vstack, hstack, join\nimport fitsio\n# from astropy.io import fits\n\nfrom multiprocessing import Pool\n\n\npsfex_unpatched_dir = '/global/cfs/cdirs/cosmo/work/legacysurvey/dr10/calib/unpatched-psfex'\npsfex_patched_dir = '/global/cfs/cdirs/cosmo/work/legacysurvey/dr10/calib/patched-psfex'\n\n# Unique exposures\ncat = Table(fitsio.read('/global/cfs/cdirs/cosmo/work/legacysurvey/dr10/survey-ccds-dr10-v4.fits', columns=['expnum', 'image_filename', 'ccdname']))\n_, idx = np.unique(cat['expnum'], return_index=True)\nexp = cat[idx].copy()\n\ncat['ccd_id_str'] = np.char.add(np.array(cat['expnum']).astype(str), cat['ccdname'])\n\ndef get_psfex_params(index):\n psfex_filename = exp['image_filename'][index].replace('.fits.fz', '-psfex.fits')\n psfex_fn = os.path.join(psfex_patched_dir, psfex_filename)\n if not os.path.isfile(psfex_fn):\n psfex_fn = os.path.join(psfex_unpatched_dir, psfex_filename)\n if not os.path.isfile(psfex_fn):\n return None\n tt = Table(fitsio.read(psfex_fn))\n if len(tt)==0:\n return None\n tt['ccd_id_str'] = np.char.add(np.array(tt['expnum']).astype(str), tt['ccdname'])\n tt['median_psf_fwhm'] = np.median(tt['psf_fwhm'])\n if 'moffat_alpha' in tt.colnames:\n tt = tt[['ccd_id_str', 'psf_fwhm', 'median_psf_fwhm', 'moffat_alpha', 'moffat_beta', 'failure']]\n else:\n tt = tt[['ccd_id_str', 'psf_fwhm', 'median_psf_fwhm']]\n return tt\n\nprint('Start!')\n\nn_processes = 128\nwith Pool(processes=n_processes) as pool:\n res = pool.map(get_psfex_params, np.arange(len(exp)))\n\n# Remove None elements from the list\nfor index in range(len(res)-1, -1, -1):\n if res[index] is None:\n res.pop(index)\n\npsf_params = vstack(res).filled(0)\ncat1 = cat[['expnum', 'ccdname', 'ccd_id_str']]\npsf_params = join(cat1, psf_params, keys='ccd_id_str', join_type='left')\npsf_params.remove_column('ccd_id_str')\n\npsf_params.write('/global/cfs/cdirs/desi/users/rongpu/dr10dev/misc/survey-ccds-dr10-v4-psfex-fwhm.fits', overwrite=True)\n","sub_path":"dr10/misc/survey_ccds_add_psfex_fwhm.py","file_name":"survey_ccds_add_psfex_fwhm.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39336102","text":"from GlobalPramaters import *\nfrom Global import *\nimport utils\n\n\nclass MarketPosition:\n def __init__(self):\n self.marketPosition = {}\n self.averageEntryPrice = {}\n self.unrealizedPnl = {}\n\n for symbol in SYMBOLS:\n self.marketPosition[symbol] = 0\n self.averageEntryPrice[symbol] = 0\n self.unrealizedPnl[symbol] = 0\n\n\n def renew_all_market_position(self):\n positions = utils.get_trader(common_pb2.FULL_INFO).positions\n for symbol in SYMBOLS:\n market_position = 0\n avg_entry_price = 0\n unrealized_pnl = 0\n\n if hasattr(positions, 'long_positions') and positions.long_positions[symbol] is not None:\n if hasattr(positions.long_positions[symbol], 'volume'):\n if positions.long_positions[symbol].volume > 0:\n market_position = positions.long_positions[symbol].volume\n avg_entry_price = positions.long_positions[symbol].avg_price\n unrealized_pnl = positions.long_positions[symbol].unrealized_pnl\n\n if hasattr(positions, 'short_positions') and positions.short_positions[symbol] is not None:\n if hasattr(positions.short_positions[symbol], 'volume'):\n if positions.short_positions[symbol].volume > 0:\n market_position = - positions.short_positions[symbol].volume\n avg_entry_price = positions.short_positions[symbol].avg_price\n unrealized_pnl = positions.short_positions[symbol].unrealized_pnl\n\n self.marketPosition[symbol] = market_position\n self.averageEntryPrice[symbol] = avg_entry_price\n self.unrealizedPnl[symbol] = unrealized_pnl\n return self.marketPosition\n\n\n","sub_path":"market position.py","file_name":"market position.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"341610514","text":"from argparse import ArgumentParser\nimport feedparser\nimport sys\n\n\n# replace this comment with your implementation of the FeedWrapper class.\nclass FeedWrapper: \n\n def __init__(self,url): \n\n self.url = url\n self.feed = feedparser.parse(url)\n\n def get_links(self):\n lst = []\n for entries in self.feed.entries:\n for results in entries.links:\n if \"audio\" in results[\"type\"]:\n lst.append((entries.title, results[\"href\"]))\n return lst\n\n \n\n \n\ndef main(url):\n \"\"\" Extract titles and links from an RSS feed. \"\"\"\n fw = FeedWrapper(url)\n l = fw.get_links()\n for title, link in fw.get_links():\n print(f\"{title} | {link}\")\n\n\ndef parse_args(arglist):\n \"\"\" Parse command-line arguments. \"\"\"\n parser = ArgumentParser()\n parser.add_argument(\"url\", help=\"url of the RSS feed of a podcast\")\n return parser.parse_args(arglist)\n\n\nif __name__ == \"__main__\":\n args = parse_args(sys.argv[1:])\n main(args.url)\n","sub_path":"episodes.py","file_name":"episodes.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631719934","text":"# Archery Program for Lab 8\n# Lehman College, CUNY, Fall 2012\n\nfrom graphics import *\nfrom math import *\n\ndef dist(p1,p2):\n dist = sqrt((p1.getX()-p2.getX())**2 + (p1.getY() - p2.getY())**2)\n return dist\n\ndef main():\n w = GraphWin(\"Target Practice\",500,500)\n w.setCoords(-250,-250,250,250)\n\n #make a point for the origin since we'll use it over and over again:\n origin = Point(0,0)\n\n #draw the target:\n for radius in range(10,0,-1):\n c = Circle(origin, 20*radius)\n if radius % 2 == 0:\n c.setFill(\"red\")\n else:\n c.setFill(\"yellow\")\n c.draw(w)\n\n #score the users click:\n t = Text(Point(0,-225), \"Click on the target\")\n t.setSize(20)\n t.draw(w)\n p = w.getMouse()\n d = dist(origin, p)\n\n #This line prints to the IDLE shell window, so, we can debug the program:\n print(\"You clicked on (\", p.getX(), \",\", p.getY(),\") with distance: \", d)\n\n if d < 20:\n t.setText(\"Bullseye! 10 points\")\n elif d < 200:\n t.setText(\"Hit the target! 1 point\")\n else:\n t.setText(\"Missed! 0 points\")\n \n #keep the window up until the user clicks\n w.getMouse()\n w.close()\n\nmain()\n","sub_path":"teaching/cmp/cmp230/f12/archery.py","file_name":"archery.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240758194","text":"import requests as api\n\nlng = 19.61954771\nlat = 40.81952034\ntoken = 'token'\n\nendpoint = 'https://api.under.test/'\nbody = {\n\t\t'lng':lng,\n\t\t'lat':lat,\n\t\t'accuracy':\" \",\n\t\t'altitude':\" \",\n\t\t'bearing':\" \",\n\t\t'speed':\" \"\t\t\n\t\t}\nheaders = {\n\t\t'Content-Type': \"application/json\",\n\t\t'Authorization': f\"Bearer {token}\",\n\t\t'Cache-Control': \"no-cache\"\n\t\t}\n\nresponce = api.request(\"POST\", url = endpoint, data=body, headers=headers)\nprint(responce.status_code, responce.text)","sub_path":"EmulateApiCall.py","file_name":"EmulateApiCall.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"163910571","text":"\"\"\"\nE - dict( : [, , ...])\nКлюч - строка, идентифицирующая вершину графа\nзначение - список вершин, достижимых из данной\nСделать так, чтобы по графу можно было итерироваться(обходом в ширину)\n\"\"\"\n\nfrom collections import deque\n\n\ndef bfs(graph, start):\n bfs_seq = [start]\n queue = deque(graph[start])\n for i in range(len(graph)):\n if queue:\n vertex = queue.popleft()\n bfs_seq.append(vertex)\n neighs = graph[vertex]\n for neigh in neighs:\n if neigh not in bfs_seq:\n if neigh not in queue:\n queue.append(neigh)\n return bfs_seq\n\n\nclass Graph:\n\n def __init__(self, E):\n self.E = E\n self.len = len(E)\n self.index = -1\n self.bfs_list = self.bf_search()\n\n def bf_search(self):\n self.vertexes = set(self.E.keys())\n self.queue = deque()\n self.bfs = []\n # try to find first vertex from which we can reach all other vertexes\n while self.vertexes:\n start_vertex = self.vertexes.pop()\n self.bfs = bfs(self.E, start_vertex)\n if len(self.bfs) == self.len:\n return self.bfs\n else:\n # Can not reach end of graph from any vertex\n # will do it in other way:\n self.vertexes_to_visit = set(self.E.keys())\n start_vertex = self.vertexes_to_visit.pop()\n self.bfs = bfs(self.E, start_vertex)\n self.vertexes_to_visit.difference_update(set(self.bfs))\n while len(self.bfs) != self.len:\n self.bfs_add = bfs(self.E, self.vertexes_to_visit.pop())\n for vertex in self.bfs_add:\n if vertex not in self.bfs:\n self.bfs.append(vertex)\n return self.bfs\n\n def __next__(self):\n if self.index + 1 >= self.len:\n self.index = -1\n raise StopIteration\n self.index += 1\n return self.bfs_list[self.index]\n\n def __iter__(self):\n return self\n\n\nE = {'A': ['B', 'C', 'D'], 'B': ['C'], 'C': [], 'D': ['A'], 'E': []}\n\n\ngraph = Graph(E)\n\nfor vertex in graph:\n print(vertex)\n","sub_path":"06-advanced-python/hw/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"618469715","text":"import fastdeploy as fd\nimport cv2\nimport os\n\n\ndef parse_arguments():\n import argparse\n import ast\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--model\", required=True, help=\"Path of PaddleSeg model.\")\n parser.add_argument(\n \"--image\", type=str, required=True, help=\"Path of test image file.\")\n return parser.parse_args()\n\n\nruntime_option = fd.RuntimeOption()\nruntime_option.use_kunlunxin()\n\n# setup runtime\nmodel_file = os.path.join(args.model, \"model.pdmodel\")\nparams_file = os.path.join(args.model, \"model.pdiparams\")\nconfig_file = os.path.join(args.model, \"deploy.yaml\")\nmodel = fd.vision.segmentation.PaddleSegModel(\n model_file, params_file, config_file, runtime_option=runtime_option)\n\n# predict\nim = cv2.imread(args.image)\nresult = model.predict(im)\nprint(result)\n\n# visualize\nvis_im = fd.vision.vis_segmentation(im, result, weight=0.5)\ncv2.imwrite(\"vis_img.png\", vis_im)\n","sub_path":"deploy/fastdeploy/semantic_segmentation/kunlunxin/python/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248411220","text":"import unittest\nimport json\nimport warnings\nimport yaml\n\nfrom pipeline import HDA, EventArticle, NLP, Geocoder\n\n\nclass TestPipeline(unittest.TestCase):\n\n\n _test_data = \"data/test-article.json\"\n _conf_file = \"nets.yaml\"\n\n def setUp(self):\n #todo - should only filter out resource warnings. Comment the following line to see\n warnings.filterwarnings(\"ignore\")\n raw_article = json.loads(open(self._test_data).read())\n source = raw_article[\"_source\"]\n self.article = EventArticle(\n raw_article['_id'],\n source['content'], source['url'], source['title'],source['language'],\n source['publisher'],source['publisher'], source['date_published'],source['date_collected'])\n\n with open( self._conf_file) as f:\n self.conf = yaml.load(f)\n\n def test_scalars(self):\n date_collected = \"2016-12-08T13:30:31.745201\"\n language = \"english\"\n title = \"Pakistani program would raise female literacy by cellphone\"\n url = \"http://www.upi.com/Top_News/Special/2014/03/29/Pakistani-program-would-raise-female-literacy-by-cellphone/51392269920323/\"\n publisher = \"upi\"\n date_published = \"2014-03-29T04:00:00\"\n\n self.assertEqual(title,self.article.title)\n self.assertEqual(date_collected,self.article.date_collected)\n self.assertEqual(language,self.article.language)\n self.assertEqual(title,self.article.title)\n self.assertEqual(url,self.article.url)\n self.assertEqual(publisher, self.article.publisher)\n self.assertEqual(date_published,self.article.date_published)\n\n def test_nlp(self):\n dates = ['six-month', 'this year', 'weekly', 'six days', 'two months', 'the third month', 'four months',\n '25-year-old', '2012', '1990', '2015', '2009', 'the previous three to four years']\n times = ['three hours']\n organizations = ['the Pakistan Social and Living Standards Measurement', 'UPI',\n 'the United Nations Educational', 'The provincial Education Department', 'UNICEF',\n 'Situation Analysis of Children', 'the Education for All',\n 'UNESCO', 'the U.N. Millennium Development Goals', 'Sindh', 'SEMIS']\n other = ['70 percent', '47 percent', '85 percent', '58 percent', '23 percent', '15', 'Around 750', '30', '10',\n 'Pakistani', 'three', 'Interactive', '7.3 million', '34 percent', '59 percent', '22 percent', 'more than half',\n 'More than 50 percent', '47,557', '42,328', '5,229', '3,995', '1,234', 'Nearly 20,000', 'one', '9,103', 'two']\n events = []\n places = ['Pakistan', 'Sindh', 'Urdu', 'Jacobabad', 'Thatta']\n languages = ['Sindhi']\n people = ['Nabi Leghari', 'Leghari', 'Sindhi', 'Shaista Sattar', 'Shaheed Benazirabad',\n 'Fazlullah Pechuho', 'Sindh']\n\n nlp = NLP()\n nlp.process(self.article)\n\n self.assertEqual(len(self.article.entity['times']),1)\n self.assertListEqual( dates, self.article.entity['dates'])\n self.assertListEqual( times, self.article.entity['times'])\n self.assertListEqual( organizations, self.article.entity['organizations'])\n self.assertListEqual( other, self.article.entity['other'])\n self.assertListEqual( events, self.article.entity['events'])\n self.assertListEqual( places, self.article.entity['places'])\n self.assertListEqual( languages, self.article.entity['languages'])\n self.assertListEqual( people, self.article.entity['people'])\n\n\n def test_time(self):\n text = \"On October 23, the frog dismissed the king. Yesterday, he preferred to eat biscuits.\"\n nlp = NLP()\n article = EventArticle(0, text, date_published='2020-06-07 12:32:54')\n nlp.process(article)\n self.assertEqual(['2020-10-23 12:32:54', '2020-06-06 09:00:00'], article.nlp.times)\n\n def test_geocoder(self):\n\n pakistan = {'geohash': 'tt0wzg1fgg3g', 'country_gid': 'c:85632659', 'place': 'Pakistan', 'confidence': 0.971,\n 'geometry': {'type': 'Point', 'coordinates': [68.546268, 29.328493]}, 'ancestry': 'c:85632659'}\n geocoder = Geocoder()\n\n geocoder.seturl(self.conf['geocode']['url'])\n nlp = NLP()\n nlp.process(self.article)\n geocoder.process(self.article)\n item = self.article.geography[0]\n self.assertDictEqual(item,pakistan)\n self.assertEqual(len(self.article.geography), 5)\n\n def test_HDA(self):\n self.maxDiff = 1000\n testval = [\n {'words': ['age'], 'name': 'People and Society: Demographics'},\n {'words': ['national'], 'name': 'Economy: Commerce: Legal and Financial'},\n {'words': ['Sindhi'], 'name': 'People and Society: Language'},\n {'words': ['phase'], 'name': 'Unassigned'},\n {'words': ['solutions'], 'name': 'Economy: Commerce: Business and Professional Services'},\n {'words': ['computer'], 'name': 'Economy: Commerce: Clothing and Accessories'},\n {'words': ['tin'], 'name': 'Economy: Commerce: Industry and Agriculture'},\n {'words': ['show'], 'name': 'Economy: Commerce: Arts and Entertainment'},\n {'words': ['home'], 'name': 'Economy: Commerce: Home and Garden'},\n {'words': ['services'], 'name': 'Infrastructure: Health and Medicine'},\n {'words': ['elected'], 'name': 'Government: Security and Public Services: Local'},\n {'words': ['pub'], 'name': 'Economy: Commerce: Food and Dining'},\n {'words': ['government'], 'name': 'People and Society: Political'},\n {'words': ['Mon'], 'name': 'People and Society: Ethnicity'},\n {'words': ['communications'], 'name': 'Infrastructure: Communications and Media'},\n {'words': ['crib'], 'name': 'Economy: Residential'},\n {'words': ['development'], 'name': 'Economy: Commerce: Real Estate'},\n {'words': ['prep'], 'name': 'Economy: Commerce: Education'},\n {'words': ['school'], 'name': 'Infrastructure: Education'},\n {'words': ['base'], 'name': 'Government: Military: Land'},\n {'words': ['company'], 'name': 'Economy: Commerce: Construction and Contractors'},\n {'words': ['phone'], 'name': 'Economy: Commerce: Computer and Electronics'}\n ]\n\n hda = HDA()\n hda.process(self.article)\n self.assertEqual({h['name'] for h in testval}, {h['name'] for h in self.article.hda})\n words1 = []\n for h in testval:\n for w in h['words'] : words1.append(w)\n words2 = []\n for h in self.article.hda:\n for w in h['words']: words2.append(w)\n\n self.assertEqual(words1.sort(),words2.sort())\n","sub_path":"nets/pipeline/pipeline_tests.py","file_name":"pipeline_tests.py","file_ext":"py","file_size_in_byte":6729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278235210","text":"\"\"\"\n@Author: Brian Lovelace\n@name: parser.py\nUsage: parser.py [ | ]*\nUsage: parser.py -d [/HtmlDirectoryPath]^+ [/CsvDumpDirectory] \nExtracts selected data from html files and writes it to csv files\n\"\"\"\nimport sys, os, datetime\n#sys.path.append(os.getcwd())\n\n#from Parser.Parser.fileParser import parse, can_parse, setup_parser, clean_env, NonexistantKeyError, UnparseableFileError, UnsetFileParserError\nfrom Parser.fileParser import parse, can_parse, make_parsingPackage, NonexistantKeyError, UnparseableFileError, UnsetFileParserError\n#from os.path.join(os.getcwd(), 'Parser') import parse, can_parse, setup_parser, clean_env, NonexistantKeyError, UnparseableFileError, UnsetFileParserError \nimport configparser\n\n\n#Variables are used when the module is being run as a \n#main script. \n_main = False\n_error = ''\n_parser = None\n_defaultConfig = os.path.join(os.path.dirname(__file__), 'config.ini')\n\n\n\n\n\"\"\"\nChecks for errors in the command line for a script\nusage containing the -d flag\nShould only be called from __Main__\n\"\"\"\ndef checkParseDirectoriesArgs(argv):\n global _error\n \n htmlfiles = []\n csvfiles = []\n textfiles = []\n directories = []\n fileTypes = getFileTypes(argv) \n htmlfiles = fileTypes['html']\n csvfiles = fileTypes['csv']\n textfiles = fileTypes['txt']\n directories = fileTypes['other']\n if len(directories) < 1:\n _error = 'No directories to parse'\n raise BadInputError()\n if len(htmlfiles) > 0:\n _error = 'Cannot parse individual html files with -d flag'\n raise BadInputError()\n if len(csvfiles) > 0:\n _error = 'Cannot specify csv files to write to with -d flag'\n raise BadInputError()\n if len(textfiles) > 0:\n _error = 'Cannot yet specify csv files to write to with -d flag'\n raise BadInputError()\n for d in directories:\n if not os.path.isdir(d):\n _error = 'Cannot find directory ' + d\n raise BadInputError()\n\n\"\"\"\nChecks for errors in the arguments sent to the script\nShould only be called from __Main__\n\"\"\"\ndef checkCommandLineArgs(argv):\n global _error\n\n htmlfiles = []\n csvfiles = []\n textfiles = []\n directories = []\n if len(argv) < 1:\n _error = 'Incorrect number of arguments'\n raise BadInputError()\n\n fileTypes = getFileTypes(argv)\n htmlfiles = fileTypes['html']\n csvfiles = fileTypes['csv']\n textfiles = fileTypes['txt']\n directories = fileTypes['other']\n\n if len(csvfiles) > len(htmlfiles):\n _error = 'Too many .csv files'\n raise BadInputError()\n if len(textfiles) > 1:\n _error = 'Only one file can be set as the parser\\'s log'\n raise BadInputError()\n if len(directories) > 0:\n _error = 'Use -c flag to specify a csv dump directory'\n raise BadInputError()\n\n fil = None\n try: \n for f in htmlfiles:\n fil = f\n open(f)\n except IOError as e:\n _error = 'Cannot open file ' + fil\n raise e\n except Exception as e:\n _error = 'An unexpected error occurred: ' + e\n raise e\n return True\n\n\"\"\"\nAppends all new entries to the designated .csv file. If file does\nnot exist it is created.\n@entries: A list of entry objects\n\"\"\"\ndef _writeCSV(entries, parser, CSVfilename = None):\n header = ''\n currentLines = {}\n\n for i in range(len(parser.WRITTEN_KEYWORDS)):\n header += parser.WRITTEN_KEYWORDS[i]\n if i != (len(parser.WRITTEN_KEYWORDS)-1):\n header += ','\n else:\n header += '\\n'\n\n csvFile = _createCSVFile(entries, parser, CSVfilename)\n csvFile.seek(0,0)\n for line in csvFile:\n currentLines[line] = True\n if header not in currentLines:\n currentLines[header] = True\n csvFile.write(header)\n \n if entries is not None:\n for e in entries:\n if restricted(e, parser):\n continue\n i = 0\n newEntry = ''\n for k in parser.WRITTEN_KEYWORDS:\n if e[k] is not None:\n newEntry += e[k]\n if i != (len(parser.WRITTEN_KEYWORDS) - 1):\n newEntry += ','\n else:\n newEntry += '\\n'\n i += 1\n if newEntry not in currentLines:\n currentLines[newEntry] = True\n csvFile.write(newEntry)\n \n\"\"\"\nCreates a file with the correct name for the parsed html file.\n\"\"\"\ndef _createCSVFile(entries, parser, CSVfilename):\n global _error#, CsvDump\n\n filename = ''\n\n if not os.path.isdir(parser.CsvDump):\n os.makedirs(parser.CsvDump)\n filepath = parser.CsvDump\n \n try:\n if CSVfilename is None:\n if len(entries) > 0:\n check = entries[0][parser.FILENAME_BASE]\n if check is not None:\n filename += check\n if len(filename) > 0:\n filename += '_'\n else:\n filename = CSVfilename \n except KeyError as e:\n _error = 'FILENAME_BASE must be listed as a keyword'\n raise e\n filepath = os.path.join(filepath, filename)\n\n if CSVfilename is not None:\n return open(filepath, 'a+')\n else:\n filepath += 'class_list.csv'\n return open(filepath, 'w+')\n\n\"\"\"\nChecks for any restrictions\n\"\"\"\ndef restricted(entry, parser):\n restricted = False\n\n for k in entry.keys():\n #Allowed values\n if k in parser.ENTRY_RESTRICTIONS.keys():\n restricted = True\n for v in parser.ENTRY_RESTRICTIONS[k]:\n if entry[k] == v:\n restricted = False\n break\n #Restricted Values\n if ('~' + k) in parser.ENTRY_RESTRICTIONS.keys():\n for v in parser.ENTRY_RESTRICTIONS[('~' + k)]:\n if entry[k] == v:\n restricted = True\n return restricted\n\n\"\"\"\nSeperates the given file names into lists of html, csv,\nand other file types.\n@arg files: List of file names\n@return Dictionary mapping file types to lists of files\n of that type. Dictionary keys are: 'html', 'csv',\n 'directory', and 'other'.\n\"\"\"\ndef getFileTypes(files):\n htmlfiles = []\n csvfiles = []\n# directories = []\n textfiles = []\n other = []\n\n i = 0 \n while i < len(files):\n parts = files[i].split('.')\n if parts[len(parts)-1] == 'html':\n htmlfiles.append(files[i])\n elif parts[len(parts)-1] == 'csv':\n csvfiles.append(files[i])\n elif parts[len(parts)-1] == 'txt':\n textfiles.append(files[i]) \n # elif os.path.isdir(files[i]):\n # directories.append(files[i])\n else:\n other.append(files[i])\n i += 1\n \n return {\n 'html': htmlfiles,\n 'csv': csvfiles,\n# 'directory': directories,\n 'txt': textfiles, \n 'other': other\n }\n\n\"\"\"\nScans the arguments and looks for flags and their\ncorresponding variables. Most flags are handled \nand removed from argv. If -d is present, it will\nbecome the first element of argv. \nShould only be called from __Main__()\n\"\"\"\ndef _handleFlags(argv):\n global _error#, Logger\n \n if len(argv) < 1:\n _error = 'No command line arguments'\n raise BadInputError()\n\n v_flag = False\n l_flag = False\n d_flag = False\n c_flag = False\n others = False\n i = 0\n while i < len(argv):\n removed = False\n if argv[i] == '-v':\n if v_flag:\n _error = 'Verbose should not be set twice'\n raise BadInputError()\n _parser.toggle_verbose()\n argv.pop(i)\n removed = True\n v_flag = True\n elif argv[i] == '-c':\n if c_flag:\n _error = 'Csv files can only be dumped into one directory'\n raise BadInputError()\n elif i == (len(argv) - 1):\n _error = 'No Csv dump directory given'\n elif os.path.exists(argv[i+1]):\n if not os.path.isdir(argv[i+1]):\n _error = 'Csv dump is not a directory'\n raise BadInputError()\n _parser.set_csv_dump(argv[i+1])\n argv.pop(i)\n argv.pop(i)\n removed = True\n c_flag = True\n elif argv[i] == '-l':\n if l_flag:\n _error = 'Log should not be set twice'\n raise BadInputError()\n elif i == (len(argv) - 1):\n _parser.Logger = None\n elif argv[i+1].split('.')[len(argv[i+1].split('.'))-1] == 'txt':\n _parser.set_logger(argv[i+1])\n argv.pop(i)\n else:\n _parser.Logger = None\n argv.pop(i)\n removed = True\n l_flag = True\n elif argv[i] == '-d':\n if d_flag:\n _error = 'Directory parsing mode should not be set twice'\n raise BadInputError()\n if others:\n _error = 'Directory parsing flag should come before any parser arguments'\n raise BadInputError()\n d_flag = True\n else:\n others = True\n if not removed:\n i += 1\n return argv\n\n\n\"\"\"\nParses files given by the command line. Arguments are validated\nand corresponding csv files are written.\nShould only be called be __Main__\n\"\"\"\ndef _parseCommandLine(argv):#, parser=_parser):\n global _error#, Csv_Dump\n #May cause issues setting a new CSVDUmp\n CsvDump = _parser.CsvDump\n message = ''\n checkCommandLineArgs(argv)\n _parser.set_csv_dump(CsvDump) \n \n fileTypes = getFileTypes(argv)\n htmlfiles = fileTypes['html']\n csvfiles = fileTypes['csv'] \n _parser.parse_files(htmlfiles, csvfiles)\n\n\"\"\"\nParses all files in the directory, and places them in the\nCsvDump.\nShould only be called by __Main__\n\"\"\"\ndef _parseDirectories(argv):\n# argv.pop(0)\n checkParseDirectoriesArgs(argv)\n directories = getFileTypes(argv)['other']\n for d in directories:\n _parser.parse_directory(os.path.abspath(d))\n \n\"\"\"\nAdds a message to a logger and prints it to stdio\nif verbose mode is active. Newlines are added automatically.\n\"\"\"\ndef addMessage(message, logOnly=False, parser=None):\n if parser.VERBOSE and _main and not logOnly:\n print(message)\n#uses Logger\n if parser.Logger is not None:\n logFile = open(parser.Logger, 'a')\n logFile.write(message + '\\n')\n logFile.close()\n\ndef parseKeywords(config, section, key):\n keywords = []\n try:\n val = config[section][key]\n for w in val.strip('\\n\\t ').split('\\n'):\n keywords.append(w)\n except KeyError as e:\n pass\n return keywords\n \n\ndef parseRestrictions(config, section):\n restrictions = {}\n section = config[section]\n try:\n for k in section:\n words = []\n vals = section[k]\n for w in vals.strip('\\n\\t ').split('\\n'):\n if w != '~None':\n words.append(w.strip('\\n\\t '))\n else:\n words.append(None)\n restrictions[k] = words\n except KeyError as e:\n pass\n return restrictions\n \ndef parseValue(config, section, key):\n val = '~None'\n try:\n val = config[section][key]\n except KeyError as e:\n pass\n if val == '~None':\n return None\n else:\n return val\n\ndef verifyDefaultValues(parser):\n global _error\n \n message = ''\n try:\n if not isinstance(parser.PARSED_KEYWORDS, list):\n message = 'parsed_keywords not properly set'\n raise BadConfigError(message)\n\n if not isinstance(parser.WRITTEN_KEYWORDS, list):\n message = 'parsed_keywords not properly set'\n raise BadConfigError(message)\n else:\n for w in parser.WRITTEN_KEYWORDS:\n if w not in parser.PARSED_KEYWORDS:\n message = 'Value ' + w + ' is not parsed from the file'\n raise BadConfigError(message)\n if not isinstance(parser.ENTRY_RESTRICTIONS, dict):\n message = 'ENTRY_RESTRICTIONS not properly set'\n raise BadConfigError(message)\n if not isinstance(parser.FILENAME_BASE, str):\n message = 'FILENAME_BASE not properly set'\n raise BadConfigError(message)\n elif parser.FILENAME_BASE not in parser.PARSED_KEYWORDS:\n message = 'FILENAME_BASE is not parsed'\n raise BadConfigError(message)\n if not isinstance(parser.CsvDump, str):\n message = 'CSV_DUMP not properly set'\n raise BadConfigError(message)\n\n except BadConfigError as e:\n _error = message\n raise e\n\"\"\"\nReturns the instance of ConfigParser that is used as the\ndefault configuration for this parser. \n\"\"\"\ndef default_config():\n config = configparser.ConfigParser()\n config.read(_defaultConfig)\n return config\n \n\"\"\"\nExtracts a dictionary mapping keywords to parsed data\n@f: An open file\n@return: A list of Entries\n\"\"\"\ndef get_entries(parsingPackage):\n global _error\n try:\n return parse(parsingPackage)\n except UnparseableFileError as e:\n _error = 'No schema available to parse ' + parsingPackage.filename\n raise e\n\n\"\"\"\nReturns the parsing package used by the fileParser module to\nparse a file.\n@parser: parser object\n@opened: Opened file header\n\"\"\"\ndef get_parsingPackage(parser, opened): \n return make_parsingPackage(parser.PARSED_KEYWORDS, opened)\n \n\"\"\"\nA parser object. Gives user access to the public functions in \nthis module\n\"\"\"\nclass Parser():\n def __init__(self, config=_defaultConfig):\n self._currentConfig = None\n self.FILENAME_BASE = None \n self.PARSED_KEYWORDS = []\n self.WRITTEN_KEYWORDS = []\n self.ENTRY_RESTRICTIONS = {}\n self.VERBOSE = False\n self.Logger = None\n #ErrorLog= None\n self.CsvDump = None\n self.parsingPackage = None\n\t\t\n try:\n self.apply_config(config)\n verifyDefaultValues(parser=self)\n \n except Exception as e:\n self.close_parser()\n raise e\n \n def __setup__(self, f):\n global _error\n try:\n self.parsingPackage = get_parsingPackage(self, open(f))\n except NonexistantKeyError as e:\n _error = 'The selected keys cannot be parsed'\n raise e\n except IOError as e:\n _error = 'The selected keys cannot be parsed'\n raise e\n \n def close_parser(self):\n self.FILENAME_BASE = None \n self.PARSED_KEYWORDS = []\n self.WRITTEN_KEYWORDS = []\n self.ENTRY_RESTRICTIONS = {}\n self.VERBOSE = False\n self.Logger = None\n #self.ErrorLog= None\n self.CsvDump = None\n self._currentConfig = None\n self.parsingPackage = None\n\n def set_logger(self, logname):\n global _error\n\n fname = logname.split('.')\n if len(fname) > 1:\n t = fname[len(fname) - 1]\n if t != 'txt':\n _error = 'Error log should be a text file'\n raise BadInputError()\n self.Logger = logname\n\n def apply_config(self, configFile):\n config = None\n if isinstance(configFile, configparser.ConfigParser):\n config = configFile\n else: \n config = configparser.ConfigParser()\n config.read(configFile)\n self._currentConfig = config\n \n self.PARSED_KEYWORDS = parseKeywords(config, \n 'PARSED_KEYWORDS',\n 'parsed_keywords'\n )\n self.WRITTEN_KEYWORDS = parseKeywords(config,\n 'WRITTEN_KEYWORDS',\n 'WRITTEN_keywords'\n )\n self.ENTRY_RESTRICTIONS = parseRestrictions(config,\n 'ENTRY_RESTRICTIONS')\n vTemp = parseValue(config, 'VALUES', 'VERBOSE')\n if vTemp == \"True\": \n self.VERBOSE = True\n else:\n self.VERBOSE = False\n self.Logger = parseValue(config, 'VALUES', 'Logger')\n self.FILENAME_BASE = parseValue(config, 'VALUES', 'FILENAME_BASE')\n self.CsvDump = parseValue(config, 'VALUES', 'CSV_DUMP')\n \n def parse_files(self, htmlfiles, csvfiles=[]):\n i = 0\n for f in htmlfiles:\n try:\n if len(csvfiles) > i:\n parsed = self.parse_and_write(f, csvfiles[i])\n else:\n parsed = self.parse_and_write(f)\n if not parsed:\n i += 1\n raise Exception()\n i += 1\n message = str(i) + ': Parsed ' + f\n addMessage(message, parser=self)\n except Exception as e:\n message = str(i) + ': Could not parse ' + f\n addMessage(message, parser=self)\n if len(_error) == 0:\n raise e\n\n def parse_and_write(self, htmlFile, CsvFile=None): \n try:\n self.__setup__(htmlFile)\n entries = get_entries(self.parsingPackage)\n if entries is None:\n #Won't need this\n# clean_env()\n return False\n else:\n _writeCSV(entries, self, CSVfilename=CsvFile)\n #Won't need this\n# clean_env()\n return True\n \n except Exception as e:\n #won't need this anymore\n# clean_env()\n raise e\n \n def parse_directory(self, directory):\n files = os.listdir(directory)\n htmlfiles = getFileTypes(files)['html']\n\n i = 1\n for f in htmlfiles:\n try:\n self.parse_and_write(os.path.join(sys.path[0], directory, f))\n message = str(i) + ':\\tParsed ' + f\n addMessage(message, parser=self)\n except Exception as e:\n message = str(i) + ':\\tCould not parse ' + f\n addMessage(message, parser=self)\n if len(_error) == 0:\n raise e\n i += 1\n \n def set_csv_dump(self, directory): \n if not os.path.isabs(directory):\n directory = os.path.abspath(directory)\n self.CsvDump = directory\n \n def toggle_verbose(self):\n self.VERBOSE = not self.VERBOSE\n \n def is_verbose(self):\n return self.VERBOSE\n \n def get_config(self):\n return self._currentConfig \n \n def is_set(self):\n return self._parserSet\n \n\"\"\"\n self.close_parser = close_parser\n self.set_logger = set_logger\n self.apply_config = apply_config\n self.parse_files = parse_files\n self.parse_and_write= parse_and_write\n self.set_csv_dump = set_csv_dump\n self.toggle_verbose = toggle_verbose\n self.is_set = is_set\n self.get_config = get_config\n self.is_verbose = is_verbose\n\"\"\"\n\n\"\"\"\nMain function. Only run when script is run as main program.\nMain handles errors that script is designed to catch,\nit allows all others to pass.\n\"\"\"\ndef __main__():\n global _parser\n\n try:\n _parser = Parser(os.path.abspath(os.path.join(sys.path[0],'config.ini')))\n argv = sys.argv\n argv.pop(0)\n \n argv = _handleFlags(argv)\n message = '' \n for i in range(25):\n message += '_'\n message += '\\nNew entries added ' + str(datetime.datetime.now())\n addMessage(message, logOnly=True, parser=_parser)\n\n if argv[0] == '-d':\n argv.pop(0)\n _parseDirectories(argv)\n else:\n _parseCommandLine(argv)\n sys.exit(0)\n except Exception as e:\n if len(_error) > 0:\n sys.stderr.write(\"Usage: \" + _error + \"\\n\")\n sys.exit(1)\n else:\n raise e\n\n#Custom Exception raised for bad input\nclass BadInputError(Exception):\n pass\nclass BadConfigError(Exception):\n def __init__(self, message):\n super()\n self.message = message\n def __repr__(cls):\n return cls.message + '\\n'\n\nif __name__ == \"__main__\":\n _main = True\n __main__()\n\n","sub_path":"parser/Parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":20696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"295651029","text":"# %matplotlib inline\nimport torch\nimport torch.nn as nn\nfrom config import Encoder_Localizer_config\nfrom noise_layers.cropout import Cropout\nfrom noise_layers.jpeg_compression import JpegCompression\nfrom noise_layers.quantization import Quantization\nfrom noise_layers.identity import Identity\nimport numpy as np\nfrom network.conv_bn_relu import ConvBNRelu\nfrom network.down_sample import Down\nfrom network.up_sample import Up\nfrom network.double_conv import DoubleConv\nfrom network.encoder import EncoderNetwork\n\ndevice = torch.device(\"cuda\")\n\ndef gaussian(tensor, mean=0, stddev=0.1):\n '''Adds random noise to a tensor.'''\n\n noise = torch.nn.init.normal_(torch.Tensor(tensor.size()).to(device), mean, stddev)\n\n return tensor + noise\n\n# class DecoderNetwork(nn.Module):\n# def __init__(self, config=Encoder_Localizer_config()):\n# super(DecoderNetwork, self).__init__()\n# self.config = config\n# # self.upsample = nn.Sequential(\n# # # Size:16->32\n# # Up(self.config.encoder_features,self.config.encoder_features),\n# # # Size:32->64\n# # Up(self.config.encoder_features, self.config.encoder_features),\n# # # Size:64->128\n# # Up(self.config.encoder_features, self.config.encoder_features),\n# # # Size:128->256\n# # Up(self.config.encoder_features, self.config.encoder_features)\n# # )\n#\n# self.conv_kernel_size_1 = nn.Sequential(\n# nn.Conv2d(self.config.encoder_features, 3, kernel_size=3, padding=1),\n# # nn.Conv2d(self.config.encoder_features, 3, kernel_size=1, padding=0))\n# )\n#\n# def forward(self, h):\n# h1 = self.upsample(h)\n#\n# out = self.conv_kernel_size_1(h1)\n# out_noise = gaussian(out.data, 0, 0.1)\n# return out, out_noise\n\n\nclass LocalizeNetwork(nn.Module):\n def __init__(self, config=Encoder_Localizer_config()):\n super(LocalizeNetwork, self).__init__()\n self.config = config\n channels = int(self.config.Width*self.config.Height/self.config.block_size/self.config.block_size)\n self.initialR3 = nn.Sequential(\n ConvBNRelu(3, self.config.decoder_channels),\n nn.MaxPool2d(2),\n ConvBNRelu(self.config.decoder_channels, self.config.decoder_channels),\n nn.MaxPool2d(2),\n ConvBNRelu(self.config.decoder_channels, self.config.decoder_channels),\n nn.MaxPool2d(2),\n ConvBNRelu(self.config.decoder_channels, self.config.decoder_channels),\n nn.MaxPool2d(2),\n )\n # Size: 256->128\n self.Down1_conv = DoubleConv(3, 64)\n self.Down1_pool = nn.MaxPool2d(2)\n # Size: 128->64\n self.Down2_conv = DoubleConv(64, 128)\n self.Down2_pool = nn.MaxPool2d(2)\n # Size: 64->32\n self.Down3_conv = DoubleConv(128, 256)\n self.Down3_pool = nn.MaxPool2d(2)\n # Size: 32->16\n self.Down4_conv = DoubleConv(256, 512)\n self.Down4_pool = nn.MaxPool2d(2)\n\n self.last_conv = nn.Sequential(\n nn.Conv2d(512,2,kernel_size=1,stride=1),\n nn.BatchNorm2d(2),\n nn.Sigmoid()\n )\n\n\n def forward(self, r):\n # r1 = self.initialR3(r)\n # Size: 256->128\n down1_c = self.Down1_conv(r)\n down1_p = self.Down1_pool(down1_c)\n # Size: 128->64\n down2_c = self.Down2_conv(down1_p)\n down2_p = self.Down2_pool(down2_c)\n # Size: 64->32\n down3_c = self.Down3_conv(down2_p)\n down3_p = self.Down3_pool(down3_c)\n # Size: 32->16\n down4_c = self.Down4_conv(down3_p)\n down4_p = self.Down4_pool(down4_c)\n r1_conv = self.last_conv(down4_p)\n\n\n return r1_conv\n\n\n# Join three networks in one module\nclass Encoder_Localizer(nn.Module):\n def __init__(self,config=Encoder_Localizer_config(),crop_size=(0.5,0.5)):\n super(Encoder_Localizer, self).__init__()\n self.config = config\n self.encoder = EncoderNetwork(is_embed_message=False,config=config).to(device)\n\n # self.decoder = DecoderNetwork(config).to(device)\n self.cropout_noise_layer = Cropout(self.config.crop_size,config).to(device)\n\n self.other_noise_layers = [Identity()]\n self.other_noise_layers.append(JpegCompression(device))\n self.other_noise_layers.append(Quantization(device))\n\n self.localize = LocalizeNetwork(config).to(device)\n\n def forward(self, secret, cover):\n # 得到Encode后的特征平面\n x_1 = self.encoder(secret)\n # Decode得到近似原图,这里的x_2_noise为添加高斯噪声后的结果\n # x_2, x_2_noise = self.decoder(x_1)\n # 添加Cropout噪声,cover是跟secret无关的图\n x_1_crop, cropout_label = self.cropout_noise_layer(x_1, cover)\n # 添加一般噪声:Gaussian JPEG 等(optional)\n random_noise_layer = np.random.choice(self.other_noise_layers, 1)[0]\n x_1_crop_attacked = random_noise_layer(x_1_crop)\n\n #如果不添加其他攻击,就是x_1_crop,否则是x_1_crop_attacked\n pred_label = self.localize(x_1_crop_attacked)\n return x_1, pred_label, cropout_label","sub_path":"network/Encoder_Localizer.py","file_name":"Encoder_Localizer.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"186779829","text":"from importlib import import_module\n\nfrom flask import Flask\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import Blueprint\n\nblueprint = Blueprint('base_blueprint',\n __name__,\n template_folder='templates',\n static_folder='static')\n\ndb = SQLAlchemy()\nlogin_manager = LoginManager()\n\n\ndef configure_database(app):\n @app.before_first_request\n def init_database():\n db.create_all()\n\n @app.teardown_request\n def shutdown_session(exception=None):\n db.session.remove()\n\n\ndef register_extensions(app):\n db.init_app(app)\n login_manager.init_app(app)\n\n\ndef register_blueprints(app):\n module = import_module('flaskr.routes')\n app.register_blueprint(module.blueprint)\n\n\ndef create_app(config):\n app = Flask(__name__)\n app.config.from_object(config)\n\n register_blueprints(app)\n register_extensions(app)\n configure_database(app)\n\n return app\n","sub_path":"flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81929868","text":"import time\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport os # Used to create folders\nfrom shutil import copyfile # Used to copy parameters file to directory\nfrom sklearn.metrics import mean_squared_error\nimport math\nfrom matplotlib.ticker import FuncFormatter\n\ndef get_parameters(parameters):\n d = {}\n with open(parameters, \"r\") as f:\n for line in f:\n line = line.replace(\":\", \"\")\n line = line.replace(\",\", \"\")\n line = line.split()\n key = line.pop(0)\n if len(line) > 1:\n d[key] = line\n else:\n d[key] = line[0]\n return d\n \ndef get_dfs(d, i):\n if i is None:\n df1 = pd.read_csv(d[\"file_location\"] + d[\"input_files\"] + \".csv\", encoding='latin-1', low_memory=False)\n return df1\n else:\n if d[\"input_files\"][i] == \"July\":\n df1 = pd.read_csv(d[\"file_location\"] + \"man_PreJuly_July_LR_predictions.csv\", encoding='latin-1', low_memory=False)\n df2 = pd.read_csv(d[\"file_location\"] + \"man_PreJuly_July_EN_predictions.csv\", encoding='latin-1', low_memory=False)\n df3 = pd.read_csv(d[\"file_location\"] + \"man_PreJuly_July_GBR_predictions.csv\", encoding='latin-1', low_memory=False)\n df4 = pd.read_csv(d[\"file_location\"] + \"man_PreJuly_July_RFR_predictions.csv\", encoding='latin-1', low_memory=False)\n\n maindf = pd.DataFrame()\n maindf[\"TimeTaken\"] = df1[\"TimeTaken\"]\n maindf[\"Mean_TimeTaken\"] = df1[\"Mean_TimeTaken\"]\n maindf[\"TimeTaken_LinearRegression\"] = df1[\"TimeTaken_LinearRegression\"]\n maindf[\"TimeTaken_ElasticNet\"] = df2[\"TimeTaken_ElasticNet\"]\n maindf[\"TimeTaken_GradientBoostingRegressor\"] = df3[\"TimeTaken_GradientBoostingRegressor\"]\n maindf[\"TimeTaken_RandomForestRegressor\"] = df4[\"TimeTaken_RandomForestRegressor\"]\n\n return maindf\n elif d[\"input_files\"][i] == \"June\":\n df1 = pd.read_csv(d[\"file_location\"] + \"man_PreJune_June_LR_predictions.csv\", encoding='latin-1',\n low_memory=False)\n df2 = pd.read_csv(d[\"file_location\"] + \"man_PreJune_June_EN_predictions.csv\", encoding='latin-1',\n low_memory=False)\n df3 = pd.read_csv(d[\"file_location\"] + \"man_PreJune_June_GBR_predictions.csv\", encoding='latin-1',\n low_memory=False)\n df4 = pd.read_csv(d[\"file_location\"] + \"man_PreJune_June_RFR_predictions.csv\", encoding='latin-1',\n low_memory=False)\n\n maindf = pd.DataFrame()\n maindf[\"TimeTaken\"] = df1[\"TimeTaken\"]\n maindf[\"Mean_TimeTaken\"] = df1[\"Mean_TimeTaken\"]\n maindf[\"TimeTaken_LinearRegression\"] = df1[\"TimeTaken_LinearRegression\"]\n maindf[\"TimeTaken_ElasticNet\"] = df2[\"TimeTaken_ElasticNet\"]\n maindf[\"TimeTaken_GradientBoostingRegressor\"] = df3[\"TimeTaken_GradientBoostingRegressor\"]\n maindf[\"TimeTaken_RandomForestRegressor\"] = df4[\"TimeTaken_RandomForestRegressor\"]\n\n return maindf\n\n else:\n df1 = pd.read_csv(d[\"file_location\"] + d[\"input_files\"][i] + \".csv\", encoding='latin-1', low_memory=False)\n return df1\n\ndef get_RMSEs(df, pred_cols):\n RMSEs = []\n for col in pred_cols:\n RMSEs.append(np.sqrt(mean_squared_error(df[\"TimeTaken\"], df[col])))\n return RMSEs\n\ndef get_stats(df):\n pred_cols = [\"Mean_TimeTaken\", \"TimeTaken_LinearRegression\", \"TimeTaken_ElasticNet\", \"TimeTaken_GradientBoostingRegressor\", \"TimeTaken_RandomForestRegressor\"]\n\n # pred_cols = [\"Mean_TimeTaken\", \"TimeTaken_RandomForestRegressor\"]\n\n number_close = [[0 for _ in range(24)] for _ in range(len(pred_cols))]\n percent_close = [[] for _ in range(len(pred_cols))]\n\n interesting_hours = [(x+1)*2 for x in range(24)]\n # todo - 96 / this = what the xticks has to be for pct correct plot\n\n number_close96 = [0 for _ in range(len(pred_cols))]\n percent_close96 = []\n\n for i in range(len(df[pred_cols[0]])):\n for k, col in enumerate(pred_cols):\n if abs(df[col].iloc[i] - df[\"TimeTaken\"].iloc[i]) <= 48: # Within 1 hour\n number_close96[k] += 1\n\n for j, hour in enumerate(interesting_hours):\n for k, col in enumerate(pred_cols):\n if abs(df[col].iloc[i] - df[\"TimeTaken\"].iloc[i]) <= hour: # Within 1 hour\n number_close[k][j] += 1\n\n for i in range(len(number_close)):\n for j in number_close[i]:\n percent_close[i].append(j / len(df[\"TimeTaken\"]) * 100)\n\n for i in number_close96:\n percent_close96.append(i / len(df[\"TimeTaken\"]) * 100)\n\n RMSEs = get_RMSEs(df, pred_cols)\n return percent_close, percent_close96, RMSEs\n \ndef multi_plot_pct_correct(ys, newpath, d, title):\n fig, ax = plt.subplots(dpi=300) # figsize=(3.841, 7.195),\n ys_plot = ys.copy()\n for i in range(len(ys_plot)):\n ys_plot[i] = [0] + ys[i]\n\n x = [x*2 for x in range(len(ys_plot[0]))]\n # todo - change to reflect how many datapoints there are with np.where\n\n alg_initial_list = [\"B\", \"LR\", \"EN\", \"GBR\", \"RFR\"]\n colours = [\".m--\", \".r-\", \".g-\", \".y-\", \".b-\"]\n\n for y, alg_initial, colour in zip(ys_plot, alg_initial_list, colours):\n plt.plot(x, y, colour, label=alg_initial, alpha=0.8)\n\n plt.title(\"%% Correct Predictions +/- Given Time (%s)\" % (title))\n\n plt.xlim(0, 48)\n plt.ylim(0, 100)\n \n # plt.legend(loc=5, bbox_to_anchor=(1.2, 0.5))\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles[::-1], labels[::-1], title='Algorithms', loc=5, bbox_to_anchor=(1.21, 0.5))\n\n xticks = [(x + 1) * 4 for x in range(12)]\n\n plt.xticks(xticks, xticks)\n\n yticks_i = [i * 10 for i in range(11)]\n yticks = [\"0%\", \"10%\", \"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"]\n plt.yticks(yticks_i, yticks)\n\n # plt.grid()\n plt.xlabel(\"Time Buckets (hours)\")\n plt.ylabel(\"% Correct Predictions\")\n \n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_pct_correct.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_pct_correct.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n print(\"excepting\")\n plt.close()\n\n fig, ax = plt.subplots(dpi=300)\n\n x = [x*2 for x in range(len(ys_plot[0]))]\n # todo - change to reflect how many datapoints there are with np.where\n\n alg_initial_list = [\"Average Case Processing Time\", \"LR\", \"EN\", \"GBR\", \"Recommended Model\"]\n colours = [\".m--\", \".r-\", \".g-\", \".y-\", \".b-\"]\n\n for y, alg_initial, colour in zip(ys_plot, alg_initial_list, colours):\n if alg_initial != \"LR\" and alg_initial != \"EN\" and alg_initial != \"GBR\" :\n plt.plot(x, y, colour, label=alg_initial, alpha=0.8)\n\n plt.title(\"% Correct Predictions +/- Given Time\") # (%s)\" % (title))\n\n plt.xlim(0, 48)\n plt.ylim(0, 100)\n \n # plt.legend(bbox_to_anchor=(1.2, 0.5), loc=\"center\", fontsize=12)\n handles, labels = ax.get_legend_handles_labels()\n ax.legend(handles[::-1], labels[::-1], loc=\"center\", fontsize=12)#, loc=5, bbox_to_anchor=(1.21, 0.5))\n\n xticks = [(x + 1) * 8 for x in range(6)]\n # xticks = [(x + 1) * 4 for x in range(12)]\n\n plt.xticks(xticks, xticks)\n\n ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y / 100)))\n # yticks_i = [i * 10 for i in range(11)]\n # yticks = [\"0%\", \"10%\", \"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"]\n # plt.yticks(yticks_i, yticks)\n\n # plt.grid()\n plt.xlabel(\"Time (hours)\")\n plt.ylabel(\"% of Correct Predictions\")\n \n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_pct_correct_B_RF.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_pct_correct_B_RF.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n plt.close()\n\ndef multi_plot_RMSEs_bar(ys, newpath, d, title, actual_title):\n fig, ax = plt.subplots(dpi=300)\n x = range(len(ys[0]))\n x = np.array(x)\n ys = np.array(ys)\n\n alg_initial_list = [\"B\", \"LR\", \"EN\", \"GBR\", \"RFR\"]\n colours = [\"#F1948A\", \"#85C1E9\"]\n if len(ys) == 3:\n colours += [\"#F7DC6F\"] #b30000 AF000E\n\n\n width = len(x)/(len(x) * (len(title)+1))\n newwidth = width\n for y, colour, exp in zip(ys, colours, title):\n plt.bar(x+newwidth, y, width, color=colour, label=exp, alpha=1, align=\"center\")\n newwidth += width\n\n plt.title(actual_title)\n\n plt.legend(loc=5, bbox_to_anchor=(1.2, 0.5))\n\n plt.xticks(x+(width*(len(title)+1) /2), alg_initial_list)\n\n plt.xlabel(\"Algorithms\")\n plt.ylabel(\"RMSE (hours)\")\n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_RMSEs_bar.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_RMSEs_bar.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n plt.close()\n\ndef multi_plot_RMSEs_line(ys, newpath, d, title):\n fig, ax = plt.subplots(dpi=300)\n x = range(len(title))\n x = np.array(x)\n ys = np.array(ys)\n\n alg_initial_list = [\"B\", \"LR\", \"EN\", \"GBR\", \"RFR\"]\n colours = [\".m--\", \".r-\", \".g-\", \".y-\", \".b-\"]\n\n for y, alg_initial, colour in zip(ys, alg_initial_list, colours):\n plt.plot(x, y, colour, label=alg_initial, alpha=0.8)\n\n plt.title(\"RMSE with Decreasing Features\")\n\n plt.legend(loc=5, bbox_to_anchor=(1.2, 0.5))\n\n plt.xticks(x, title)\n\n plt.xlabel(\"Decreasing Features\")\n plt.ylabel(\"RMSE (hours)\")\n\n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_RMSEs_line.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_RMSEs_line.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n plt.close()\n\ndef multi_plot_within96(ys, newpath, d, title):\n fig, ax = plt.subplots(dpi=300)\n x = range(len(title))\n\n alg_initial_list = [\"B\", \"LR\", \"EN\", \"GBR\", \"RFR\"]\n colours = [\".m--\", \".r-\", \".g-\", \".y-\", \".b-\"]\n\n for y, alg_initial, colour in zip(ys, alg_initial_list, colours):\n plt.plot(x, y, colour, label=alg_initial, alpha=0.8)\n\n plt.title(\"Correct Predictions Within 96 Hours with Decreasing Features\")\n\n plt.legend(loc=5, bbox_to_anchor=(1.2, 0.5))\n plt.xticks(x, title)\n\n plt.xlabel(\"Decreasing Features\")\n plt.ylabel(\"Correct Predictions Within 96 hours\")\n\n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_within96.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_within96.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n plt.close()\n\ndef multi_plot_within96_bar(ys, newpath, d, title, actual_title):\n fig, ax = plt.subplots(dpi=300)\n x = range(len(ys[0]))\n x = np.array(x)\n ys = np.array(ys)\n\n alg_initial_list = [\"B\", \"LR\", \"EN\", \"GBR\", \"RFR\"]\n colours = [\"#F1948A\", \"#85C1E9\"]\n if len(ys) == 3:\n colours += [\"#F7DC6F\"] #b30000 AF000E\n\n width = len(x)/(len(x) * (len(title)+1))\n newwidth = width\n minsofar = 100\n maxsofar = 0\n for y, colour, exp in zip(ys, colours, title):\n if min(y) < minsofar:\n minsofar = min(y)\n if max(y) > maxsofar:\n maxsofar = max(y)\n plt.bar(x+newwidth, y, width, color=colour, label=exp, alpha=1, align=\"center\")\n newwidth += width\n\n plt.title(actual_title)\n\n plt.legend(loc=5, bbox_to_anchor=(1.2, 0.5))\n plt.xticks(x+(width*(len(title)+1) /2), alg_initial_list)\n\n plt.xlabel(\"Algorithms\")\n plt.ylabel(\"Correct Predictions Within 96 hours\")\n\n ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y/100)))\n # yticks_i = [i * 5 for i in range(21)]\n # # yticks = [\"0%\", \"10%\", \"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"]\n # yticks = [\"0%\",\"5%\", \"10%\", \"15%\", \"20%\", \"25%\", \"30%\", \"35%\", \"40%\", \"45%\", \"50%\", \"55%\",\n # \"60%\", \"65%\", \"70%\", \"75%\", \"80%\", \"85%\", \"90%\", \"95%\", \"100%\"]\n # plt.yticks(yticks_i, yticks)\n\n # if minsofar < 10:\n # low = 0\n # else:\n # low = math.ceil(minsofar-5)\n #\n # if maxsofar > 90:\n # high = 100\n # else:\n # high = math.ceil(maxsofar+5)\n #\n # plt.ylim(low, high)\n\n if not os.path.exists(newpath + \"PDFs/\"):\n os.makedirs(newpath + \"PDFs/\") # Make folder for storing results if it does not exist\n\n plt.savefig(\"%s%s_within96_bar.png\" % (newpath, title), bbox_inches='tight', dpi=300)\n plt.savefig(\"%sPDFs/%s_within96_bar.pdf\" % (newpath, title), bbox_inches='tight')\n\n try:\n get_ipython\n plt.show()\n except:\n plt.close()\n\nif __name__ == \"__main__\": # Run program\n parameters = \"../../../Data/parameters.txt\" # Parameters file\n sample_parameters = \"../Sample Parameter File/parameters.txt\"\n\n print(\"Modeling dataset\", time.strftime(\"%Y.%m.%d\"), time.strftime(\"%H.%M.%S\"))\n\n d = get_parameters(parameters)\n sample_d = get_parameters(parameters)\n\n for key in sample_d.keys():\n if key not in d.keys():\n print(\"\\\"%s\\\" not in parameters.txt - please update parameters file with this key\" % key)\n print(\"Default key and value => \\\"%s: %s\\\"\" % (key, sample_d[key]))\n exit()\n for key in d.keys():\n if key not in sample_d.keys():\n print(\"\\\"%s\\\" not in sample parameters\" % key)\n\n if d[\"resample\"] == \"y\":# if resample is selected then all results are put in a resample folder\n newpath = r\"../0. Results/\" + d[\"user\"] + \"/multi_plot/\" + \"/resample/\"\n elif d[\"specify_subfolder\"] == \"n\":\n print(\"please specify a subfolder inside multiplot\")\n print(\"..exiting\")\n exit()\n else:\n newpath = r\"../0. Results/\" + d[\"user\"] + \"/multi_plot/\" + d[\"specify_subfolder\"] +\"/\"\n if not os.path.exists(newpath):\n os.makedirs(newpath) # Make folder for storing results if it does not exist\n\n copyfile(parameters, newpath + \"parameters.txt\") # Save parameters\n np.random.seed(int(d[\"seed\"])) # Set seed\n\n dfs = []\n if type(d[\"input_files\"]) == str:\n dfs.append(get_dfs(d, None))\n print(\"df shape : \" , dfs[0].shape)\n input_file_names = [d[\"input_file_names\"]]\n else:\n for i in range(len(d[\"input_files\"])):\n dfs.append(get_dfs(d, i))\n print(\"dfs[%s] shape : \" % i, dfs[i].shape)\n input_file_names = d[\"input_file_names\"]\n\n if d[\"resample\"] == \"y\":\n from sklearn.utils import resample\n print(\"\\n..resampling\\n\")\n for i in range(len(dfs)):\n dfs[i] = resample(dfs[i], n_samples=int(d[\"n_samples\"]), random_state=int(d[\"seed\"]))\n dfs[i] = dfs[i].reset_index(drop=True)\n print(\"DF Shape:\", dfs[i].shape)\n\n dfs_pct_close96 = []\n df_pct_closes = []\n dfs_RMSEs = []\n\n print(\"\\n..calculating stats..\\n\")\n for i, df in enumerate(dfs):\n percent_close, number_close96, RMSEs = get_stats(df)\n dfs_pct_close96.append(number_close96)\n dfs_RMSEs.append(RMSEs)\n df_pct_closes.append(percent_close) # for 1 df\n\n # if len(dfs) == 1:\n # for pct_close, title in zip(df_pct_closes, input_file_names):\n # multi_plot_pct_correct(pct_close, newpath, d, title)\n # else:\n print(\"\\n..plotting pct correct..\\n\")\n for pct_close, title in zip(df_pct_closes, input_file_names):\n multi_plot_pct_correct(pct_close, newpath, d, title)\n\n print(\"\\n..plotting RMSE bar..\\n\")\n\n if \"July\" in input_file_names or \"June\" in input_file_names:\n actual_title = \"RMSE for Training and Testing Stages\"\n else:\n actual_title = \"RMSE for each Algorithm\"\n\n multi_plot_RMSEs_bar(dfs_RMSEs, newpath, d, input_file_names, actual_title)\n\n print(\"\\n..plotting RMSE line..\\n\")\n dfs_RMSEs_T = np.transpose(dfs_RMSEs)\n multi_plot_RMSEs_line(dfs_RMSEs_T, newpath, d, input_file_names)\n\n print(\"\\n..plotting pct correct within 96 hours..\\n\")\n dfs_pct_close96_T = np.transpose(dfs_pct_close96)\n multi_plot_within96(dfs_pct_close96_T, newpath, d, input_file_names)\n\n actual_title = \"Correct Predictions Within 96 Hours\"\n multi_plot_within96_bar(dfs_pct_close96, newpath, d, input_file_names, actual_title=actual_title)\n","sub_path":"7th Iteration/5. Evaluation/multi_plot.py","file_name":"multi_plot.py","file_ext":"py","file_size_in_byte":17015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"431122877","text":"#This module deals with sound and music playback\nfrom random import choice\nfrom pygame.mixer import *\nfrom pygame.mixer import Sound as Mixer_sound\npre_init(44100,-16, 2, 2048)\ninit()\nset_num_channels(50)\n\n# event queue for scheduling end events\nfrom pyaudiogame import event_queue\n\n# Position is to controll the 3D audio\nfrom pyaudiogame import position\n\n# this is a list of currently playing sounds so that when the listener moves, the listener can be updated on any looping sound\nplaying_sounds = []\n\n# The listener is set facing north at 90 degrees. east is 0 degrees and the positions move counterclockwise.\nposition.set_listener(0,0,90)\n\ndef get_listener():\n\treturn position.get_listener()\n\ndef set_listener(x,y,o):\n\t\"\"\"Sets pos of the listener. east is o=0 and north is o=90\"\"\"\n\tposition.set_listener(x,y,o)\n\t[sound.set_volume() for sound in playing_sounds]\n\nclass Sound(object):\n\t\"\"\"\n\t\ttodo is to wrap all the channel methods so they only work on the sound. This could happen either by checking if the sound is playing on the channel or possibly by calling methods on the sound itself.\n\t\tmixer documentation:\n\t\thttps://www.pygame.org/docs/ref/mixer.html\n\n\t\tThis class ads support for 3D positioning. Just pass the position of the sound in a tuple of (x,y) coordinates after the path of the file.\n\t\"\"\"\n\n\tdef __init__(self, filename, position=None, single_channel=True):\n\t\tself.name = filename\n\t\tself.pos = position # should be a tuple (x, y)\n\t\tself.channel = None\n\t\tself.paused = False\n\t\tself.playing = False\n\t\tself.stopped = False # this is to tell a callback if the sound was stopped by a stop function or not.\n\t\tself.single_channel = single_channel\n\t\tself.callback = lambda e: None # the callback is passed this object as an argument and is triggered at the end of the sound\n\t\tself._id = \"sound-%s-%s\" % (self.name, id(self))\n\n\t\ttry:\n\t\t\tself.sound = Mixer_sound(filename)\n\t\texcept:\n\t\t\traise Exception(\"Unable to open file %r\" % filename)\n\n\n\tdef play(self, loops=0, maxtime=0, fade_ms=0):\n\t\tself.playing = True\n\t\tself.stopped = False\n\t\tif not self.channel or ((not self.single_channel or self.channel.get_sound() != self.sound) and self.channel.get_busy()):\n\t\t\tself.channel = find_channel() or self.channel\n\t\tself.channel.play(self.sound, loops, maxtime, fade_ms)\n\t\tif self.pos:\n\t\t\tplaying_sounds.append(self)\n\t\t\tself.set_volume()\n\t\tevent_queue.schedule(function=self.check_if_finished, repeats=-1, delay=0, name=self._id) # this uses the channel.get_busy to figure out if the sound has finished playing.\n#\t\tevent_queue.schedule(function=self.finish, repeats=1, delay=self.get_length()-0.09, name=self._id) # This does the same as above, but uses the length of the sound to schedule an end event. The problem with this is that if one pauses the sound, the event still runs. The pro is that the end event can be faster than the actual sound.\n\n\tdef get_volume(self):\n\t\treturn self.channel.get_volume()\n\n\tdef move_pos(self, x=0, y=0):\n\t\tcx, cy = self.pos\n\t\tself.set_pos(cx+x, cy+y)\n\t\treturn self.pos\n\n\tdef set_pos(self, x, y):\n\t\tself.pos = (float(x), float(y))\n\t\tif(self.channel):\n\t\t\tself.channel.set_volume(*position.stereo(*self.pos))\n\n\tdef get_pos(self):\n\t\treturn self.pos\n\n\tdef get_length(self):\n\t\treturn self.sound.get_length()\n\n\tdef toggle_pause(self):\n\t\t\"\"\"This function can be called to pause and unpause a sound without the script needing to handle the check for paused and unpaused. If the sound is paused when this function is called, then the sound is unpaused and if the sound is playing when this function is called, then the sound is paused. It's very good for buttons to play and pause sounds.\"\"\"\n\t\tif not self.channel or not self.playing:\n\t\t\tself.play()\n\t\telif self.paused:\n\t\t\tself.unpause()\n\t\telse:\n\t\t\tself.pause()\n\n\tdef unpause(self):\n\t\tif not self.channel: return False\n\t\tself.channel.unpause()\n\t\tself.paused = False\n\n\tdef is_paused(self):\n\t\treturn self.paused\n\n\tdef pause(self):\n\t\tif not self.channel: return False\n\t\tself.channel.pause()\n\t\tself.paused = True\n\n\tdef stop(self):\n\t\t\"\"\"This stops the channel from playing.\"\"\"\n\t\tevent_queue.unschedule(self._id)\n\t\tif self in playing_sounds:\n\t\t\tplaying_sounds.remove(self)\n\t\tself.playing = False\n\t\tself.paused = False\n\t\tself.stopped = True\n\t\tself.unpause()\n\t\tif self.channel:\n\t\t\tself.channel.stop()\n\t\tself.finish()\n\n\tdef stop_sound(self):\n\t\t\"\"\"This stops the sound object from playing rather than the channel\"\"\"\n\t\tself.sound.stop()\n\t\tself.unpaws()\n\t\tself.playing = False\n\t\tmixer_queue.remove(self.channel)\n\t\tif self in playing_sounds:\n\t\t\tplaying_sounds.remove(self)\n\n\tdef get_busy(self):\n\t\t\"\"\"Returns if the channel is active. This is used for triggering the callback\"\"\"\n\t\tif self.channel:\n\t\t\treturn self.channel.get_busy()\n\t\treturn False\n\n\tdef check_if_finished(self):\n\t\t\"\"\"This runs every tick to see if the channel is done. if it is done, then it runs the finish method and removes itself from the event_queue.\"\"\"\n\t\tif not self.get_busy():\n\t\t\tself.finish()\n\t\t\tevent_queue.unschedule(self._id)\n\n\tdef toggle_playing(self):\n\t\tif self.playing:\n\t\t\tself.stop()\n\t\telse:\n\t\t\tself.play()\n\n\tdef set_volume(self, volume=1, right=None):\n\t\t\"\"\"Sets the volume if there is a channel. If there is a position, then volume is adjusted to be that position. If no arguments are passed, then it will update the volume to be the current pos, or set volume back to 1.\"\"\"\n\t\tif not self.channel:\n\t\t\treturn 0\n\t\tif volume > 1:\n\t\t\tvolume = 1\n\t\telif volume <= 0:\n\t\t\tself.channel.set_volume(0)\n\t\t\treturn 0\n\t\tif not self.pos and not right:\n\t\t\tself.channel.set_volume(volume)\n\t\telif right:\n\t\t\tself.channel.set_volume(volume, right)\n\t\telse:\n\t\t\tx, y = self.pos\n\t\t\tif x == 0 and y == 0:\n\t\t\t\tself.channel.set_volume(volume)\n\t\t\t\treturn 0\n\t\t\tself.channel.set_volume(*position.stereo(x/volume, y/volume))\n\n\tdef finish(self):\n\t\tself.playing = False\n\t\tself.paused = False\n\t\tself.callback(self)\n\nmixer_paused = False\ndef mixer_toggle_pause(excluded_channels=[]):\n\tglobal mixer_paused\n\tif mixer_paused:\n\t\tunpause()\n\t\t[c.pause() for c in excluded_channels if c.is_paused()]\n\t\tmixer_paused = False\n\telse:\n\t\tpause()\n\t\tmixer_paused = True\n\t\t[c.unpause() for c in excluded_channels if not c.is_paused()]\n\nclass SoundIterator(object):\n\tdef __init__(self, *args, random=False, random_repeat=True):\n\t\t\"\"\"Pass in sound files, or SoundIterator objects (anything with a play method and an on_end event (if the play_loop functionality is desired)), and if random is false, then they will be played in order. Otherwise they will be played randomly. Sound objects can be passed in as well, but their callback functionality will be replaced. It is better to pass in strings.\"\"\"\n\t\tself.sounds = []\n\t\tself.random = random\n\t\tself.random_repeat = random_repeat\n\t\tself.index = 0\n\t\tself.event_name = \"%sEndSoundEvent\" % id(self)\n\t\tself.playing = False\n\t\tfor s in args:\n\t\t\tif type(s) == str:\n\t\t\t\ts = Sound(s)\n\t\t\tself.sounds.append(s)\n\n\tdef play(self, looping=False):\n\t\t\"\"\"Plays sounds\"\"\"\n\t\tself.playing = True\n\t\tif looping:\n\t\t\tself._play_looping()\n\t\telse:\n\t\t\tself._play_single()\n\n\tdef toggle_looping(self, current_sound=True):\n\t\tif self.playing:\n\t\t\tself.stop(current_sound)\n\t\telse:\n\t\t\tself.play(looping=True)\n\n\tdef _play_looping(self, e=None):\n\t\t\"\"\"plays the sounds until stop is called. makes this function the callback of the sound. If this sound is called, it should not have a callback as it overwrites the callback\"\"\"\n\t\tif self.playing:\n\t\t\ts = self.sounds[self.index]\n\t\t\ts.callback = self._play_looping\n\t\t\tself._play_single()\n\n\tdef stop(self, current_sound=True):\n\t\t\"\"\"Stops all sounds. If current_sound is False, then the current sound will finish, and no more sounds will play.\"\"\"\n\t\tself.playing = False\n\t\tif current_sound:\n\t\t\t[s.stop() for s in self.sounds]\n\n\tdef _play_single(self):\n\t\t\"\"\"Will play either the next sound, or a random sound. If there are no sounds, it plays no sounds.\"\"\"\n\t\tif not self.sounds:\n\t\t\treturn False\n\t\tself.sounds[self.index].play()\n\t\tif self.random:\n\t\t\tif self.random_repeat:\n\t\t\t\tself.index = choice(list(range(len(self.sounds))))\n\t\t\telse:\n\t\t\t\tr = list(range(self.index)) + list(range(self.index + 1, len(self.sounds)))\n\t\t\t\tself.index = choice(r)\n\t\telse:\n\t\t\tself.index += 1\n\t\t\tif self.index == len(self.sounds):\n\t\t\t\tself.index = 0\n\n\t@property\n\tdef callback(self):\n\t\t\"\"\"Just needed as a getter for the property, not needed for the code\"\"\"\n\t\tpass\n\n\t@callback.setter\n\tdef callback(self, cb):\n\t\t\"\"\"Sets all the sound objects to have the passed callback (cb)\"\"\"\n\t\tfor s in self.sounds:\n\t\t\ts.callback = cb\n","sub_path":"venv/Lib/site-packages/pyaudiogame/mixer.py","file_name":"mixer.py","file_ext":"py","file_size_in_byte":8444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176840840","text":"from Tkinter import *\nfrom ScrolledText import ScrolledText\nimport string\n\nmaster = Tk()\nmaster.wm_title(\"Word Counter\")\n\ndef highlightall(self):\n textbox.tag_add(\"sel\",\"1.0\",\"end\")\n return \"break\" #stops class binding from overwriting this\n\ndef autoupdate():\n raw=str(textbox.get(\"1.0\", \"end-1c\")) \n lines= str(len(raw.split(\"\\n\")))\n chars=str(len(raw.replace(\"\\n\",\"\")))\n raw = raw.translate(string.maketrans(\"\",\"\"), string.punctuation)\n a= str(\" \".join(raw.split()))\n if chars==\"0\" and lines == \"1\":\n wordcount.set(\"0 Words 0 Lines 0 Characters\")\n else: \n b=a.split(\" \")\n if b[0]==\"\":\n wordcount.set(\"0 Words \"+lines+ \" Lines \"+chars+\" Characters\")\n else:\n wordcount.set(str(len(b))+\" Words \"+lines+ \" Lines \"+chars+\" Characters\")\n\n master.after(100,autoupdate)\n \nwordcount=StringVar()\n\ntextbox = ScrolledText(master)\ntextbox.pack()\ntextbox.focus_set()\ntextbox.event_generate('<>')\ntextbox.bind('', highlightall)\ntextbox.bind('', highlightall)\n\nwords=Label(master,textvariable=wordcount)\nwords.pack(side=BOTTOM,padx=20)\n\nautoupdate()\nmainloop()\n\n","sub_path":"wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"173161480","text":"import sys\nimport imp\nimport classify\n\ndef main():\n\t# constant strings\n\ttrain_csv_file = 'data/train.csv'\n\ttest_csv_file = 'data/test.csv'\n\n\t# util\n\tutils = imp.load_source('utils', '../Utilities/utils.py')\n\tutil = utils.Utils()\n\tclassifier = classify.Classify()\n\n\t# create the arrays from the file\n\ttrain_array = util.createArrayFromCsvFile(train_csv_file)\n\ttest_array = util.createArrayFromCsvFile(test_csv_file)\n\n\t# train the classifier\n\tclassifier.train(train_array)\n\n\t# predict the test model\n\tresults = classifier.predict(test_array)\n\n\t# util out results to view\n\tutil.createCsvFileFromArray(results, 'results/digitResults.csv')\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Digits/source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"51993118","text":"from __future__ import absolute_import\n\nfrom django.conf.urls import patterns, include, url\n\n\nurlpatterns = patterns('', # noqa\n url(r'', include('magicgallery.urls')),\n)\n\n\nurlpatterns += patterns(\n 'django.contrib.auth.views',\n # login page, required by some tests\n url(r'^accounts/login/$', 'login', {'template_name': 'blank.html'},\n name='url_login_auth'),\n url(r'^auth/login/$', 'login', {'template_name': 'blank.html'}),\n)\n","sub_path":"tests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565647523","text":"# Copyright 2015 Vinicius Chiele. All rights reserved.\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\n\"\"\"Implements the logging related objects.\"\"\"\n\nfrom logging import Handler\nfrom simplebus import current_bus\nfrom simplebus_mail.mail import Mail\nfrom simplebus_mail.mail import Message\n\n\nclass MailHandler(Handler):\n \"\"\"Provides a logging handler to send email.\"\"\"\n\n def __init__(self, sender, recipients, queue_name=None):\n super().__init__()\n\n if not isinstance(sender, str):\n raise TypeError('Parameter sender must be a string.')\n\n if not isinstance(recipients, list):\n raise TypeError('Parameter recipients must be a list.')\n\n if len(recipients) == 0:\n raise ValueError('Parameter recipients must have at least one address.')\n\n self.__mail = Mail()\n self.__mail.config.MAIL_DEFAULT_SENDER = sender\n self.__mail.config.MAIL_DEFAULT_RECIPIENTS = recipients\n\n if queue_name:\n self.__mail.config.MAIL_QUEUE_NAME = queue_name\n\n def emit(self, record):\n \"\"\"Creates a message from the record and sends through the bus.\"\"\"\n\n self.__ensure_initialized()\n\n body = self.format(record)\n subject = self.__build_subject(body)\n message = Message(subject=subject, body=body)\n self.__mail.send(message)\n\n def __build_subject(self, body):\n \"\"\"Builds a subject from the record.\"\"\"\n\n subject = self.__mail.bus.app_id\n\n if subject:\n subject += ': '\n\n if body:\n i = body.find('\\n')\n if i == -1:\n i = len(body)\n subject += body[:200] if i > 200 else body[:i]\n subject = subject.strip('\\n').strip('\\r')\n\n return subject\n\n def __ensure_initialized(self):\n \"\"\"Ensures the Mail instance is initialized.\"\"\"\n\n if not self.__mail.bus:\n if not current_bus:\n raise RuntimeError('No Bus is running.')\n self.__mail.init_bus(current_bus)\n","sub_path":"simplebus_mail/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"620911855","text":"import importlib\r\nimport inspect\r\nimport sys\r\nimport os\r\n\r\nfrom typing import Union\r\n\r\nfrom iris.logger import Logger\r\nfrom iris.module import Module, ModuleWrapper\r\nfrom iris.command import Shell\r\nfrom iris.util import PathUtil, ConsoleUtil\r\n\r\n\r\nclass Application:\r\n\r\n class __ModuleManager:\r\n \"\"\" Used to manage IRIS modules \"\"\"\r\n\r\n DISABLE_PREFIX = '-'\r\n \"\"\" The module manager will ignore (not register) any modules which file name is prefixed with this prefix \"\"\"\r\n\r\n def __init__(self):\r\n self.__modules = []\r\n\r\n def register_module(self, path: str, mod: \"Module\"):\r\n \"\"\" Register module wrapper to module list \"\"\"\r\n self.__modules.append(ModuleWrapper(path, mod))\r\n\r\n def get_module_by_name(self, mod_name: str) -> Union[\"ModuleWrapper\", None]:\r\n \"\"\" Get module wrapper object by string name from module list \"\"\"\r\n mod_name = mod_name.lower()\r\n for mod in self.get_registered_modules():\r\n if mod_name == mod.name.lower():\r\n return mod\r\n return None\r\n\r\n def get_module(self, module: Union[str, int]) -> \"ModuleWrapper\":\r\n \"\"\" Get module by name or index. This method will raise an Exception if module is not found \"\"\"\r\n if module.isdigit():\r\n mod_index = int(module) - 1\r\n\r\n if mod_index < 0:\r\n raise Exception('Module not found')\r\n\r\n try:\r\n mod = self.get_registered_modules()[mod_index]\r\n except IndexError:\r\n raise Exception('Module not found')\r\n else:\r\n mod = self.get_module_by_name(module)\r\n\r\n if mod is None:\r\n raise Exception('Module not found')\r\n return mod\r\n\r\n def get_registered_modules(self) -> list[\"ModuleWrapper\"]:\r\n \"\"\" Get list of registered modules sorted in alphabetical order \"\"\"\r\n return sorted(self.__modules.copy(), key=(lambda x : x.name))\r\n\r\n def clear(self):\r\n \"\"\" Clear module list \"\"\"\r\n self.__modules.clear()\r\n\r\n def register_modules_from_path(self, path):\r\n \"\"\" Register modules from system path \"\"\"\r\n for root, _, files in os.walk(path):\r\n for file_name in files:\r\n if not file_name.endswith('.py') or file_name.startswith('__') or file_name.startswith(self.DISABLE_PREFIX):\r\n continue\r\n\r\n file_path = os.path.join(root, file_name)\r\n mod_path = PathUtil.sys_to_module(file_path)\r\n\r\n try:\r\n if not importlib.import_module(mod_path):\r\n continue\r\n except Exception as e:\r\n Logger.error(f'Failed to import module: {file_path}')\r\n Logger.error(f'Exception: \\x1b[91m{e}\\x1b[0m')\r\n\r\n if ConsoleUtil.yn_prompt('Continue? (Y/n): ') is True:\r\n continue\r\n\r\n sys.exit(-1)\r\n\r\n for _, Class in inspect.getmembers(sys.modules[mod_path], inspect.isclass):\r\n if issubclass(Class, Module) and Class != Module:\r\n self.register_module(file_path, Class())\r\n\r\n def __init__(self):\r\n if os.name == 'nt': \r\n import colorama\r\n colorama.init(convert=True)\r\n\r\n self.__shell = Shell('\\x1b[94m➜\\x1b[0m ')\r\n\r\n self.__module_manager = self.__ModuleManager()\r\n self.__module_manager.register_modules_from_path('modules')\r\n\r\n self.__shell.command_manager.register_commands_from_path(os.path.join('iris', 'command', 'impl'))\r\n\r\n @property\r\n def modules(self):\r\n \"\"\" Get module manager \"\"\"\r\n return self.__module_manager\r\n\r\n def start(self):\r\n \"\"\" Start application \"\"\"\r\n ConsoleUtil.clear_screen()\r\n ConsoleUtil.set_title('IRIS v%(version)s by %(author)s')\r\n ConsoleUtil.print_banner()\r\n\r\n self.__shell.start()\r\n","sub_path":"iris/app/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612232671","text":"import functools\nfrom .ftrack_base_handler import BaseHandler\n\n\nclass BaseEvent(BaseHandler):\n '''Custom Event base class\n\n BaseEvent is based on ftrack.update event\n - get entities from event\n\n If want to use different event base\n - override register and *optional _translate_event method\n\n '''\n\n type = 'Event'\n\n def __init__(self, session, plugins_presets={}):\n '''Expects a ftrack_api.Session instance'''\n super().__init__(session, plugins_presets)\n\n # Decorator\n def launch_log(self, func):\n @functools.wraps(func)\n def wrapper_launch(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as exc:\n self.session.rollback()\n self.log.error(\n 'Event \"{}\" Failed: {}'.format(\n self.__class__.__name__, str(exc)\n ),\n exc_info=True\n )\n return wrapper_launch\n\n def register(self):\n '''Registers the event, subscribing the discover and launch topics.'''\n self.session.event_hub.subscribe(\n 'topic=ftrack.update',\n self._launch,\n priority=self.priority\n )\n\n def _launch(self, event):\n self.session.rollback()\n self.session._local_cache.clear()\n\n self.launch(self.session, event)\n\n def _translate_event(self, session, event):\n '''Return *event* translated structure to be used with the API.'''\n return [\n self._get_entities(session, event),\n event\n ]\n\n def _get_entities(\n self, session, event, ignore=['socialfeed', 'socialnotification']\n ):\n _selection = event['data'].get('entities', [])\n _entities = list()\n if isinstance(ignore, str):\n ignore = list(ignore)\n for entity in _selection:\n if entity['entityType'] in ignore:\n continue\n _entities.append(\n (\n session.get(\n self._get_entity_type(entity),\n entity.get('entityId')\n )\n )\n )\n return _entities\n","sub_path":"pype/ftrack/lib/ftrack_event_handler.py","file_name":"ftrack_event_handler.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159204807","text":"# -*- coding: utf-8 -*-\n\"\"\"Story: yusha now\n\"\"\"\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\nsys.path.append('storybuilder')\n\nfrom storybuilder.builder import world as wd\nfrom src.yunow import config as cnf\nfrom src.yunow import chapter01 as chap1\nfrom src.yunow import chapter02 as chap2\nfrom src.yunow import chapter03 as chap3\nfrom src.yunow import chapter04 as chap4\nfrom src.yunow import chapter05 as chap5\nTHM = cnf.THEMES\n\n\n# scenes\n# episodes\n\n# outline\ndef story_baseinfo(w: wd.World):\n return [\n (\"story\", story(w), w.yusha, w.yusha),\n ] + chap1.story_baseinfo(w) \\\n + chap2.story_baseinfo(w) \\\n + chap3.story_baseinfo(w) \\\n + chap4.story_baseinfo(w) \\\n + chap5.story_baseinfo(w)\n\ndef story_outline(w: wd.World):\n return [\n (\"story\", story(w),\n w.yusha.deal(w.i.beat_maou),\n w.yusha.know(w.i.destroy_peace),\n w.yusha.deal(w.phone),\n w.yusha.go(w.i.trouble),\n True),\n ] + chap1.story_outline(w) \\\n + chap2.story_outline(w) \\\n + chap3.story_outline(w) \\\n + chap4.story_outline(w) \\\n + chap5.story_outline(w)\n\n# main\ndef world():\n w = wd.World(\"Yusha now\")\n w.set_db(cnf.CHARAS,\n cnf.STAGES,\n cnf.DAYS,\n cnf.ITEMS,\n cnf.INFOS,\n cnf.FLAGS,\n )\n return w\n\ndef story(w: wd.World):\n return (w.maintitle(\"勇者なう!\"),\n chap1.story(w),\n chap2.story(w),\n chap3.story(w),\n chap4.story(w),\n chap5.story(w),\n )\n\ndef main(): # pragma: no cover\n w = world()\n return w.build(story(w))\n\n\nif __name__ == '__main__':\n import sys\n sys.exit(main())\n\n","sub_path":"archives/old_story.py","file_name":"old_story.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289828142","text":"\"\"\"Model definitions for the iati_standard app.\"\"\"\n\nfrom home.models import AbstractContentPage, DefaultPageHeaderImageMixin\n\n\nclass IATIStandardPage(DefaultPageHeaderImageMixin, AbstractContentPage):\n \"\"\"A model for the IATI Standard Page, a landing page for IATI reference.\"\"\"\n\n parent_page_types = ['home.HomePage']\n subpage_types = []\n","sub_path":"iati_standard/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"293176414","text":"import pygame, sys\nfrom pygame.locals import *\nfrom random import randint\n\ndef drawWorm(wormCoords):\n i = 0\n while (i < len(wormCoords)):\n pygame.draw.circle(DISPLAYSURF, GREEN, (wormCoords[i][0], wormCoords[i][1]), 4, 0)\n i += 1\n \npygame.init()\n\nFPS = 30\nfpsClock = pygame.time.Clock()\n\nDISPLAYSURF = pygame.display.set_mode((400, 300),0,32)\npygame.display.set_caption('Dis B My Game')\n\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nBLUE = (100,140,255)\nRED = (255,0,0)\nGREEN = (0,255,0)\n\nsnk = [(27,72), (22, 72)]\nrandx = randint(22,380)\nrandy = randint(72,280)\ndirection = 'right'\n\nDISPLAYSURF.fill(BLUE)\n\nfontObj = pygame.font.SysFont('freesansbold.ttf', 45)\ntitleSurfaceObj = fontObj.render('SNAKE!', True, WHITE, BLUE)\ntitleRectObj = titleSurfaceObj.get_rect()\ntitleRectObj.center = (200, 35)\npygame.display.set_caption('Snk')\n\ncount = 0\nscore = 0\ncaught = 0\nover = False\n\nwhile True: # main game loop\n if not over:\n DISPLAYSURF.fill(BLUE)\n pygame.draw.polygon(DISPLAYSURF, WHITE, ((20,70),(380,70),(380,280),(20,280)))\n DISPLAYSURF.blit(titleSurfaceObj,titleRectObj)\n\n scoreSurfaceObj = fontObj.render(str(score), True, WHITE, BLUE)\n scoreRectObj = scoreSurfaceObj.get_rect()\n scoreRectObj.center = (40, 35)\n DISPLAYSURF.blit(scoreSurfaceObj,scoreRectObj)\n\n pygame.draw.circle(DISPLAYSURF, RED, (randx,randy), 4, 0)\n \n if (((randx+4 >= snk[0][0]) & (randx-4 <= snk[0][0])) & ((randy+4 >= snk[0][1]) & (randy-4 <= snk[0][1]))):\n caught = 1\n randx = randint(22,380)\n randy = randint(72,280)\n caught = 0\n score = score+10\n\n else:\n del snk[-1]\n \n if (direction == 'right'):\n snk.insert(0,(snk[count][0]+5,snk[count][1]))\n if ((snk[0][0]) >= 380):\n over = True\n if (direction == 'left'):\n snk.insert(0,(snk[count][0]-5,snk[count][1]))\n if ((snk[0][0]) <= 20):\n over = True\n if (direction == 'up'):\n snk.insert(0,(snk[count][0],snk[count][1]-5))\n if ((snk[0][1]) <= 70):\n over = True\n if (direction == 'down'):\n snk.insert(0,(snk[count][0],snk[count][1]+5))\n if ((snk[0][1]) >= 280):\n over = True\n\n drawWorm(snk)\n \n if over:\n overSurfaceObj = fontObj.render('GAME OVER', True, RED, WHITE)\n overRectObj = overSurfaceObj.get_rect()\n overRectObj.center = (200, 175)\n DISPLAYSURF.blit(overSurfaceObj,overRectObj)\n \n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n direction = 'up'\n if event.key == pygame.K_DOWN:\n direction = 'down'\n if event.key == pygame.K_LEFT:\n direction = 'left'\n if event.key == pygame.K_RIGHT:\n direction = 'right'\n \n if (over) & (event.type == pygame.MOUSEBUTTONUP):\n score = 0\n over = False\n snk = [(27,72), (22, 72)]\n randx = randint(20,380)\n randy = randint(70,280)\n direction = 'right'\n\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n pygame.display.update()\n fpsClock.tick(FPS)\n\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"595818402","text":"# import numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom IPython.parallel.client.map import numpy\nimport numpy as np\nfrom scipy.constants.constants import alpha\nx = []\nlabels = []\nf = open(\"/afs/cern.ch/work/m/mgeorgio/logs_statistics/lxplus/lxplus_weekday_average.txt\", \"r\") \nfor line in f:\n tokens = line.split(\",\")\n x_add = float(tokens[1])\n labels.append(tokens[0])\n x.append(x_add)\nweek = {'0':\"Monday\", '1':\"Tuesday\", '2':\"Wednesday\", '3':\"Thursday\", '4':\"Friday\", '5':\"Saturday\", '6':\"Sunday\"}\nlabels = [week[l] for l in labels]\n#===============================================================================\n# plt.rcdefaults()\n# fig, ax = plt.subplots()\n# \n# # Example data\n# people = np.arange(14)\n# y_pos = np.arange(len(people))\n# performance = x[:1]+x[2:15]\n# error = np.random.rand(len(people))\n# \n# ax.barh(y_pos, performance, xerr=error, align='center',\n# color='blue', ecolor='black', alpha = 0.4)\n# ax.set_yticks(y_pos)\n# ax.set_yticklabels(people)\n# ax.invert_yaxis() # labels read top-to-bottom\n# ax.set_xlabel('Number of SSH requests')\n# ax.set_ylabel('User')\n# ax.set_title('')\n# \n# \n# plt.yticks(y_pos, ['root','user1','user2','user3','user4','user5','user6','user7','user8','user9','user10','user11','user12','user12','user14','user15'])\n# plt.show()\n#===============================================================================\n\n# years = ('root','user1','user2','user3','user4','user5','user6','user7','user8','user9','user10','user11','user12','user12','user14','user15')\nfrom math import log\na = x\nvisitors = [log(y) for y in a]\nindex = np.arange(len(a))\nbar_width = 0.9\nplt.bar(index, a, bar_width, color=\"blue\", ecolor='black', alpha=0.4)\n# plt.xlabel(\"users\")\nplt.xticks(range(len(labels)), labels, size='small') # labels get centeredcd pic plt.show() \nplt.savefig('/home/mary/Documents/studious-octo-disco-log_representations/pics/lxplus-week.pgf')\n","sub_path":"source/statistics/plots_test.py","file_name":"plots_test.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"385490446","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"An experimental library for reading and converting SVG.\n\nThis is an experimental converter from SVG to RLG (ReportLab Graphics)\ndrawings. It converts mainly basic shapes, paths and simple text. \nThe current intended usage is either as module within other projects:\n\n from svglib.svglib import svg2rlg\n drawing = svg2rlg(\"foo.svg\")\n \nor from the command-line where right now it is usable as an SVG to PDF\nconverting tool named sv2pdf (which should also handle SVG files com-\npressed with gzip and extension .svgz).\n\"\"\"\n\nimport sys\nimport os\nimport glob\nimport copy\nimport types\nimport re\nimport operator\nimport gzip\nimport xml.dom.minidom \nfrom functools import reduce\ntry:\n import tinycss\nexcept:\n tinycss=None\n\nfrom reportlab.pdfbase.pdfmetrics import stringWidth\nfrom reportlab.graphics.shapes import *\nfrom reportlab.lib import colors\nfrom reportlab.lib.units import cm, inch, mm, pica, toLength\n\n__version__ = \"0.6.3\"\n__license__ = \"LGPL 3\"\n__author__ = \"Dinu Gherman\"\n__date__ = \"2010-03-01\"\n\npt = 1\n### helpers ###\n\ndef convertToFloats(aList):\n \"Convert number strings in list to floats (leave rest untouched).\"\n\n for i in range(len(aList)):\n try:\n aList[i] = float(aList[i])\n except ValueError:\n try:\n aList[i] = aList[i].encode(\"ASCII\")\n except:\n pass\n return aList\n\ndef convertQuadraticToCubicPath(Q0, Q1, Q2):\n \"Convert a quadratic Bezier curve through Q0, Q1, Q2 to a cubic one.\"\n C0 = Q0\n C1 = (Q0[0]+2./3*(Q1[0]-Q0[0]), Q0[1]+2./3*(Q1[1]-Q0[1]))\n C2 = (C1[0]+1./3*(Q2[0]-Q0[0]), C1[1]+1./3*(Q2[1]-Q0[1]))\n C3 = Q2\n return C0, C1, C2, C3\n\nfrom math import cos, sin, pi, sqrt, acos, ceil, copysign, fabs, hypot, degrees, radians\ndef vectorAngle(u,v):\n d = hypot(*u)*hypot(*v)\n c = (u[0]*v[0]+u[1]*v[1])/d\n if c<-1: c = -1\n elif c>1: c = 1\n s = u[0]*v[1]-u[1]*v[0]\n return degrees(copysign(acos(c),s))\n\ndef endPointToCenterParameters(x1,y1,x2,y2,fA,fS,rx,ry,phi=0):\n '''\n see http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5\n note that we reduce phi to zero outside this routine \n '''\n rx = fabs(rx)\n ry = fabs(ry)\n\n #step 1\n if phi:\n phiRad = radians(phi)\n sinPhi = sin(phiRad)\n cosPhi = cos(phiRad)\n tx = 0.5*(x1-x2)\n ty = 0.5*(y1-y2)\n x1d = cosPhi*tx - sinPhi*ty\n y1d = sinPhi*tx + cosPhi*ty\n else:\n x1d = 0.5*(x1-x2)\n y1d = 0.5*(y1-y2)\n\n #step 2\n #we need to calculate\n # (rx*rx*ry*ry-rx*rx*y1d*y1d-ry*ry*x1d*x1d)\n # -----------------------------------------\n # (rx*rx*y1d*y1d+ry*ry*x1d*x1d)\n #\n # that is equivalent to\n # \n # rx*rx*ry*ry \n # = ----------------------------- - 1\n # (rx*rx*y1d*y1d+ry*ry*x1d*x1d)\n #\n # 1\n # = -------------------------------- - 1\n # x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry)\n #\n # = 1/r - 1\n #\n # it turns out r is what they recommend checking\n # for the negative radicand case\n r = x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry)\n if r>1:\n rr = sqrt(r)\n rx *= rr\n ry *= rr\n r = x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry)\n r = 1/r - 1\n if -1e-100: dtheta -= 360\n elif fS==1 and dtheta<0: dtheta += 360\n return cx, cy, rx, ry, -theta1, -dtheta\n\ndef bezierArcFromCentre(cx,cy, rx, ry, startAng=0, extent=90):\n if abs(extent) <= 90:\n arcList = [startAng]\n fragAngle = float(extent)\n Nfrag = 1\n else:\n arcList = []\n Nfrag = int(ceil(abs(extent)/90.))\n fragAngle = float(extent) / Nfrag\n\n fragRad = radians(fragAngle)\n halfRad = fragRad * 0.5\n kappa = abs(4. / 3. * (1. - cos(halfRad)) / sin(halfRad))\n\n if fragAngle < 0:\n kappa = -kappa\n\n pointList = []\n pointList_append = pointList.append\n theta1 = radians(startAng)\n startRad = theta1 + fragRad\n\n c1 = cos(theta1)\n s1 = sin(theta1)\n for i in range(Nfrag):\n c0 = c1\n s0 = s1\n theta1 = startRad + i*fragRad\n c1 = cos(theta1)\n s1 = sin(theta1)\n pointList_append((cx + rx * c0,\n cy - ry * s0,\n cx + rx * (c0 - kappa * s0),\n cy - ry * (s0 + kappa * c0),\n cx + rx * (c1 + kappa * s1),\n cy - ry * (s1 - kappa * c1),\n cx + rx * c1,\n cy - ry * s1))\n return pointList\n\ndef bezierArcFromBox(x1,y1, x2,y2, startAng=0, extent=90):\n \"\"\"bezierArcFromBox(x1,y1, x2,y2, startAng=0, extent=90) --> List of Bezier\ncurve control points.\n\n(x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The\ncoordinate system has coordinates that increase to the right and down.\nAngles, measured in degress, start with 0 to the right (the positive X\naxis) and increase counter-clockwise. The arc extends from startAng\nto startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down\nsemi-circle.\n\nThe resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)\nsuch that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and\n(x3, y3) as their respective Bezier control points.\n\nContributed by Robert Kern.\n\nThe algorithm is an elliptical generalization of the formulae in\nJim Fitzsimmon's TeX tutorial .\n\"\"\"\n cx, cy, rx,ry = _bd2cr(x1,y1,x2,y2)\n return bezierArcFromCentre(cx,cy, rx, ry, startAng, extent)\n\ndef bezierArcFromEndPoints(x1,y1,rx,ry,phi,fA,fS,x2,y2):\n if phi:\n #our box bezier arcs can't handle rotations directly\n #move to a well known point, eliminate phi and transform the other point\n mx = mmult(rotate(-phi),translate(-x1,-y1))\n tx2,ty2 = transformPoint(mx,(x2,y2))\n #convert to box form in unrotated coords\n cx, cy, rx, ry, startAng, extent = endPointToCenterParameters(0,0,tx2,ty2,fA,fS,rx,ry)\n bp = bezierArcFromCentre(cx,cy, rx, ry, startAng, extent)\n #re-rotate by the desired angle and add back the translation\n mx = mmult(translate(x1,y1),rotate(phi))\n res = []\n for x1,y1,x2,y2,x3,y3,x4,y4 in bp:\n res.append(transformPoint(mx,(x1,y1))+transformPoint(mx,(x2,y2))+transformPoint(mx,(x3,y3))+transformPoint(mx,(x4,y4)))\n return res\n else:\n cx, cy, rx, ry, startAng, extent = endPointToCenterParameters(x1,y1,x2,y2,fA,fS,rx,ry)\n return bezierArcFromCentre(cx,cy, rx, ry, startAng, extent)\n\ndef fixSvgPath(aList):\n \"\"\"Normalise certain \"abnormalities\" in SVG paths.\n\n Basically, this reduces adjacent number values for h and v\n operators to the sum of these numbers and those for H and V\n operators to the last number only.\n\n Returns a slightly more compact list if such reductions\n were applied or a copy of the same list, otherwise.\n \"\"\"\n\n # this could also modify the path to contain an op code\n # for each coord. tuple of a tuple sequence... \n\n hPos, vPos, HPos, VPos, numPos = [], [], [], [], []\n for i in range(len(aList)):\n hPos.append(aList[i]=='h')\n vPos.append(aList[i]=='v')\n HPos.append(aList[i]=='H')\n VPos.append(aList[i]=='V')\n numPos.append(type(aList[i])==type(1.0))\n\n fixedList = []\n fixedList_append = fixedList.append\n\n i = 0\n while i < len(aList):\n if hPos[i] + vPos[i] + HPos[i] + VPos[i] == 0:\n fixedList_append(aList[i])\n elif hPos[i] == 1 or vPos[i] == 1:\n fixedList_append(aList[i])\n s = 0\n j = i+1\n while j < len(aList) and numPos[j] == 1:\n s += aList[j]\n j += 1\n fixedList_append(s)\n i = j-1\n elif HPos[i] == 1 or VPos[i] == 1:\n fixedList_append(aList[i])\n last = 0\n j = i+1\n while j < len(aList) and numPos[j] == 1:\n last = aList[j]\n j += 1\n fixedList_append(last)\n i = j-1\n i += 1\n return fixedList\n\ndef normaliseSvgPath(attr):\n \"\"\"Normalise SVG path.\n\n This basically introduces operator codes for multi-argument\n parameters. Also, it fixes sequences of consecutive M or m\n operators to MLLL... and mlll... operators. It adds an empty\n list as argument for Z and z only in order to make the resul-\n ting list easier to iterate over.\n\n E.g. \"M 10 20, M 20 20, L 30 40, 40 40, Z\" \n -> ['M', [10, 20], 'L', [20, 20], 'L', [30, 40], 'L', [40, 40], 'Z', []]\n \"\"\"\n\n # operator codes mapped to the minimum number of expected arguments \n ops = {'A':7, 'a':7,\n 'Q':4, 'q':4, 'T':2, 't':2, 'S':4, 's':4, \n 'M':2, 'L':2, 'm':2, 'l':2, 'H':1, 'V':1, \n 'h':1, 'v':1, 'C':6, 'c':6, 'Z':0, 'z':0}\n\n # do some preprocessing\n opKeys = list(ops.keys())\n a = attr\n a = a.replace(',', ' ')\n a = string.replace(a, 'e-', 'ee')\n a = string.replace(a, '-', ' -')\n a = string.replace(a, 'ee', 'e-')\n for op in opKeys:\n a = a.replace(op, \" %s \" % op)\n a = a.strip()\n a = a.split()\n a = convertToFloats(a)\n a = fixSvgPath(a)\n\n # insert op codes for each argument of an op with multiple arguments\n res = []\n res_append = res.append\n i = 0\n while i < len(a):\n el = a[i]\n if el in opKeys:\n if el in 'zZ':\n res_append(el)\n res_append([])\n else:\n n = ops[el]\n if el in 'mM':\n if not i:\n #first element\n eln = 'l'\n el = 'M'\n else:\n eln = 'l' if el=='m' else 'L'\n else:\n eln = el\n while i < len(a)-1:\n if a[i+1] not in opKeys:\n res_append(el)\n res_append(a[i+1:i+1+n])\n el = eln\n i += n\n else:\n break\n i += 1\n\n return res\n\n### attribute converters (from SVG to RLG)\n\nclass AttributeConverter:\n \"An abstract class to locate and convert attributes in a DOM instance.\"\n\n def __init__(self,verbose=0):\n self.verbose = verbose\n\n def parseMultiAttributes(self, line):\n \"\"\"Try parsing compound attribute string.\n\n Return a dictionary with single attributes in 'line'.\n \"\"\"\n \n try:\n line = line.encode(\"ASCII\")\n except:\n pass\n\n attrs = [_f for _f in [x.strip() for x in line.split(';')] if _f]\n\n newAttrs = {}\n for a in attrs:\n k, v = a.split(':')\n k, v = [s.strip() for s in (k, v)]\n newAttrs[k] = v\n return newAttrs\n\n def findAttr(self, svgNode, name):\n \"\"\"Search an attribute with some name in some node or above.\n\n First the node is searched, then its style attribute, then\n the search continues in the node's parent node. If no such\n attribute is found, '' is returned. \n \"\"\"\n\n # This needs also to lookup values like \"url(#SomeName)\"... \n\n try:\n attrValue = svgNode.getAttribute(name)\n except:\n return ''\n\n if attrValue and attrValue != \"inherit\":\n return attrValue\n elif svgNode.getAttribute(\"style\"):\n dict = self.parseMultiAttributes(svgNode.getAttribute(\"style\"))\n if name in dict:\n return dict[name]\n else:\n if svgNode.parentNode:\n return self.findAttr(svgNode.parentNode, name)\n return ''\n\n def getAllAttributes(self, svgNode):\n \"Return a dictionary of all attributes of svgNode or those inherited by it.\"\n\n dict = {}\n\n if svgNode.parentNode and svgNode.parentNode == 'g':\n dict.update(self.getAllAttributes(svgNode.parentNode))\n\n if svgNode.nodeType == svgNode.ELEMENT_NODE:\n style = svgNode.getAttribute(\"style\")\n if style:\n d = self.parseMultiAttributes(style)\n dict.update(d)\n\n attrs = svgNode.attributes\n for i in range(attrs.length):\n a = attrs.item(i)\n if a.name != \"style\":\n dict[a.name.encode(\"ASCII\")] = a.value\n return dict\n\n def id(self, svgAttr):\n \"Return attribute as is.\"\n return svgAttr\n\n def convertTransform(self, svgAttr):\n \"\"\"Parse transform attribute string.\n\n E.g. \"scale(2) translate(10,20)\" \n -> [(\"scale\", 2), (\"translate\", (10,20))]\n \"\"\"\n\n line = svgAttr\n\n try:\n line = line.encode(\"ASCII\")\n except:\n pass\n\n line = line.strip()\n ops = line[:]\n brackets = []\n indices = []\n for i in range(len(line)):\n if line[i] in \"()\": brackets.append(i)\n for i in range(0, len(brackets), 2):\n bi, bj = brackets[i], brackets[i+1]\n subline = line[bi+1:bj]\n subline = subline.strip()\n subline = subline.replace(',', ' ')\n subline = re.sub(\"[ ]+\", ',', subline)\n indices.append(eval(subline))\n ops = ops[:bi] + ' '*(bj-bi+1) + ops[bj+1:]\n ops = ops.split()\n\n assert len(ops) == len(indices)\n result = []\n for i in range(len(ops)):\n result.append((ops[i], indices[i]))\n return result\n\nclass Svg2RlgAttributeConverter(AttributeConverter):\n \"A concrete SVG to RLG attribute converter.\"\n\n def convertLength(self, svgAttr, percentOf=100):\n \"Convert length to points.\"\n\n text = svgAttr\n if not text:\n return 0.0\n\n if text[-1] == '%':\n if self.verbose:\n print(\"Fiddling length unit: %\")\n return float(text[:-1]) / 100 * percentOf\n elif text[-2:] == \"pc\":\n return float(text[:-2]) * pica\n\n newSize = text[:]\n for u in \"em ex px\".split():\n if newSize.find(u) >= 0:\n if self.verbose:\n print(\"Ignoring unit: %s\" % u)\n newSize = newSize.replace(u, '')\n\n newSize = newSize.strip()\n length = toLength(newSize)\n return length\n\n def convertLengthList(self, svgAttr):\n \"Convert a list of lengths.\"\n\n t = svgAttr.replace(',', ' ')\n t = t.strip()\n t = re.sub(\"[ ]+\", ' ', t)\n a = t.split(' ')\n a = list(map(self.convertLength, a))\n return a\n\n def convertColor(self, svgAttr):\n \"Convert string to a RL color object.\"\n\n # fix it: most likely all \"web colors\" are allowed\n predefined = \"aqua black blue fuchsia gray green lime maroon navy \"\n predefined = predefined + \"olive orange purple red silver teal white yellow \"\n predefined = predefined + \"lawngreen indianred aquamarine lightgreen brown\"\n\n # This needs also to lookup values like \"url(#SomeName)\"... \n\n text = svgAttr\n if not text or text == \"none\":\n return None\n\n try:\n text = text.encode(\"ASCII\")\n except:\n pass\n\n if text in predefined.split():\n return getattr(colors, text)\n elif text == \"currentColor\":\n return \"currentColor\"\n elif len(text) == 7 and text[0] == '#':\n return colors.HexColor(text)\n elif len(text) == 4 and text[0] == '#':\n return colors.HexColor('#' + 2*text[1] + 2*text[2] + 2*text[3])\n elif text[:3] == \"rgb\" and text.find('%') < 0:\n t = text[:][3:]\n t = t.replace('%', '')\n tup = eval(t)\n tup = [h[2:] for h in list(map(hex, tup))]\n tup = [(2-len(h))*'0'+h for h in tup]\n col = \"#%s%s%s\" % tuple(tup)\n return colors.HexColor(col)\n elif text[:3] == 'rgb' and text.find('%') >= 0:\n t = text[:][3:]\n t = t.replace('%', '')\n tup = eval(t)\n tup = [c/100.0 for c in tup]\n col = colors.Color(*tup)\n return col\n\n if self.verbose:\n print(\"Can't handle color:\", text)\n return None\n\n def convertLineJoin(self, svgAttr):\n return {\"miter\":0, \"round\":1, \"bevel\":2}[svgAttr]\n\n def convertLineCap(self, svgAttr):\n return {\"butt\":0, \"round\":1, \"square\":2}[svgAttr]\n\n def convertDashArray(self, svgAttr):\n strokeDashArray = self.convertLengthList(svgAttr)\n return strokeDashArray\n\n def convertDashOffset(self, svgAttr):\n strokeDashOffset = self.convertLength(svgAttr)\n return strokeDashOffset\n\n def convertFontFamily(self, svgAttr):\n # very hackish\n fontMapping = {\"sans-serif\":\"Helvetica\", \n \"serif\":\"Times-Roman\", \n \"monospace\":\"Courier\"}\n fontName = svgAttr\n if not fontName:\n return ''\n try:\n fontName = fontMapping[fontName]\n except KeyError:\n pass\n if fontName not in (\"Helvetica\", \"Times-Roman\", \"Courier\"):\n fontName = \"Helvetica\"\n return fontName\n\nclass NodeTracker:\n \"\"\"An object wrapper keeping track of arguments to certain method calls.\n\n Instances wrap an object and store all arguments to one special\n method, getAttribute(name), in a list of unique elements, usedAttrs.\n \"\"\"\n\n def __init__(self, anObject):\n self.object = anObject\n self.usedAttrs = []\n\n def getAttribute(self, name):\n # add argument to the history, if not already present\n if name not in self.usedAttrs:\n self.usedAttrs.append(name)\n # forward call to wrapped object\n return self.object.getAttribute(name)\n\n # also getAttributeNS(uri, name)?\n\n def __getattr__(self, name):\n # forward attribute access to wrapped object \n return getattr(self.object, name)\n\n\nclass Definitions(dict):\n '''dict that performs an action when pending definitions are set'''\n def __new__(cls,renderer,*args):\n self = dict.__new__(cls,*args)\n self.pending = {}\n self.renderer = renderer\n return self\n\n def __init__(self,renderer,*args):\n dict.__init__(self,*args)\n\n def addPending(self,key,g,node):\n self.pending.setdefault(key,[]).append((g,node))\n\n def __setitem__(self,key,value):\n dict.__setitem__(self,key,value)\n if key in self.pending:\n P = self.pending.pop(key)\n renderer = self.renderer\n for gr, node in P:\n x = renderer.attrConverter.convertLength(renderer.attrConverter.findAttr(node,'x'))\n y = renderer.attrConverter.convertLength(renderer.attrConverter.findAttr(node,'y'))\n transform = n.getAttribute('transform')\n if x or y:\n transform += 'translate(%s,%s)' % (x,y)\n if transform:\n renderer.shapeConverter.applyTransformOnGroup(transform, gr)\n gr.add(copy.deepcopy(value))\n\n### the main meat ###\nclass SvgRenderer:\n \"\"\"Renderer that renders an SVG file on a ReportLab Drawing instance.\n\n This is the base class for walking over an SVG DOM document and\n transforming it into a ReportLab Drawing instance.\n \"\"\"\n\n def __init__(self, path=None, verbose=0):\n self.attrConverter = Svg2RlgAttributeConverter(verbose=verbose)\n self.shapeConverter = Svg2RlgShapeConverter(verbose=verbose)\n self.shapeConverter.svgSourceFile = path\n self.handledShapes = self.shapeConverter.getHandledShapes()\n self.drawing = None\n self.mainGroup = Group()\n self.definitions = Definitions(self)\n self.doesProcessDefinitions = 0\n self.verbose = verbose\n self.level = 0\n self.path = path\n self.logFile = None\n #if self.path:\n # logPath = os.path.splitext(self.path)[0] + \".log\"\n # self.logFile = open(logPath, 'w')\n\n def render(self, node, parent=None):\n if parent == None:\n parent = self.mainGroup\n name = node.nodeName\n if self.verbose:\n format = \"%s%s\"\n args = (' '*self.level, name)\n #if not self.logFile:\n # print format % args\n #else:\n # self.logFile.write((format+\"\\n\") % args)\n\n if name == \"svg\":\n self.level += 1\n n = NodeTracker(node)\n drawing = self.renderSvg(n)\n children = n.childNodes\n for child in children:\n if child.nodeType != 1:\n continue\n self.render(child, self.mainGroup)\n self.level -= 1\n self.printUnusedAttributes(node, n)\n elif name == \"defs\":\n self.doesProcessDefinitions = 1\n n = NodeTracker(node)\n self.level += 1\n self.renderG(n)\n self.level -= 1\n self.doesProcessDefinitions = 0\n self.printUnusedAttributes(node, n)\n elif name == 'a':\n self.level += 1\n n = NodeTracker(node)\n item = self.renderA(n)\n parent.add(item)\n self.level -= 1\n self.printUnusedAttributes(node, n)\n elif name == 'g':\n self.level += 1\n n = NodeTracker(node)\n display = n.getAttribute(\"display\")\n if display != \"none\":\n item = self.renderG(n)\n parent.add(item)\n if self.doesProcessDefinitions:\n id = n.getAttribute(\"id\")\n if id:\n self.definitions[id] = item\n self.level -= 1\n self.printUnusedAttributes(node, n)\n elif name == \"symbol\":\n self.level += 1\n n = NodeTracker(node)\n item = self.renderSymbol(n)\n # parent.add(item)\n if self.doesProcessDefinitions:\n id = n.getAttribute(\"id\")\n if id:\n self.definitions[id] = item\n self.level -= 1\n self.printUnusedAttributes(node, n)\n elif name == 'use':\n self.level += 1\n n = NodeTracker(node)\n xlink_href = n.getAttribute('xlink:href').lstrip('#')\n gr = Group()\n if xlink_href in self.definitions:\n x = self.attrConverter.convertLength(self.attrConverter.findAttr(n,'x'))\n y = self.attrConverter.convertLength(self.attrConverter.findAttr(n,'y'))\n transform = n.getAttribute('transform')\n if x or y:\n transform += 'translate(%s,%s)' % (x,y)\n if transform:\n self.shapeConverter.applyTransformOnGroup(transform, gr)\n gr.add(copy.deepcopy(self.definitions[xlink_href]))\n parent.add(gr)\n self.level -= 1\n self.printUnusedAttributes(node, n)\n else:\n parent.add(gr)\n self.level -= 1\n self.definitions.addPending(xlink_href,gr,node)\n elif name in self.handledShapes:\n methodName = \"convert\"+name.capitalize()\n n = NodeTracker(node)\n shape = getattr(self.shapeConverter, methodName)(n)\n if shape:\n self.shapeConverter.applyStyleOnShape(shape, n)\n transform = n.getAttribute(\"transform\")\n display = n.getAttribute(\"display\")\n if transform and display != \"none\":\n gr = Group()\n self.shapeConverter.applyTransformOnGroup(transform, gr)\n gr.add(shape)\n parent.add(gr)\n elif display != \"none\":\n if self.doesProcessDefinitions:\n id = n.getAttribute(\"id\")\n if id:\n self.definitions[id] = shape\n parent.add(shape)\n self.printUnusedAttributes(node, n)\n else:\n if self.verbose:\n print(\"Ignoring node: %s\" % name)\n\n def printUnusedAttributes(self, node, n):\n allAttrs = list(self.attrConverter.getAllAttributes(node).keys())\n unusedAttrs = []\n\n for a in allAttrs:\n if a not in n.usedAttrs:\n unusedAttrs.append(a)\n\n if self.verbose and unusedAttrs:\n format = \"%s-Unused: %s\"\n args = (\" \"*(self.level+1), ', '.join(unusedAttrs))\n #if not self.logFile:\n # print format % args\n #else:\n # self.logFile.write((format+\"\\n\") % args)\n\n if self.verbose and unusedAttrs:\n #print \"Used attrs:\", n.nodeName, n.usedAttrs\n #print \"All attrs:\", n.nodeName, allAttrs\n print(\"Unused attrs:\", n.nodeName, unusedAttrs)\n\n def renderTitle_(self, node):\n # Main SVG title attr. could be used in the PDF document info field.\n pass\n\n def renderDesc_(self, node):\n # Main SVG desc. attr. could be used in the PDF document info field.\n pass\n\n def renderSvg(self, node):\n getAttr = node.getAttribute\n width, height = list(map(getAttr, (\"width\", \"height\")))\n width, height = list(map(self.attrConverter.convertLength, (width, height)))\n viewBox = getAttr(\"viewBox\")\n if viewBox:\n viewBox = self.attrConverter.convertLengthList(viewBox)\n width, height = viewBox[2:4]\n self.drawing = Drawing(width, height)\n return self.drawing\n\n def renderG(self, node, display=1):\n getAttr = node.getAttribute\n id, style, transform = list(map(getAttr, (\"id\", \"style\", \"transform\")))\n #sw = map(getAttr, (\"stroke-width\",))\n self.attrs = self.attrConverter.parseMultiAttributes(style)\n gr = Group()\n children = node.childNodes\n for child in children:\n if child.nodeType != 1:\n continue\n item = self.render(child, parent=gr)\n if item and display: \n gr.add(item)\n\n if transform:\n self.shapeConverter.applyTransformOnGroup(transform, gr)\n return gr\n\n def renderSymbol(self, node):\n return self.renderG(node, display=0)\n\n def renderA(self, node):\n # currently nothing but a group...\n # there is no linking info stored in shapes, maybe a group should?\n return self.renderG(node)\n\n def renderUse(self, node):\n xlink_href = node.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\")\n grp = Group()\n try:\n item = self.definitions[xlink_href[1:]]\n grp.add(item)\n transform = node.getAttribute(\"transform\")\n if self.verbose>2:\n print('renderUse: transform=%r'%transform)\n if transform:\n self.shapeConverter.applyTransformOnGroup(transform, grp)\n except KeyError:\n if self.verbose:\n print(\"Ignoring unavailable object width ID '%s'.\" % xlink_href)\n return grp\n\n def finish(self):\n height = self.drawing.height\n self.mainGroup.scale(1, -1)\n self.mainGroup.translate(0, -height)\n self.drawing.add(self.mainGroup)\n return self.drawing\n\nclass SvgShapeConverter:\n \"\"\"An abstract SVG shape converter.\n\n Implement subclasses with methods named 'renderX(node)', where\n 'X' should be the capitalised name of an SVG node element for \n shapes, like 'Rect', 'Circle', 'Line', etc.\n\n Each of these methods should return a shape object appropriate\n for the target format.\n \"\"\"\n\n def __init__(self,verbose=0,attrConverter=AttributeConverter):\n self.verbose = verbose\n self.attrConverter = attrConverter(verbose=verbose)\n self.svgSourceFile = ''\n\n def getHandledShapes(self):\n \"Determine a list of handled shape elements.\"\n\n items = dir(self)\n items = list(self.__class__.__dict__.keys())\n keys = []\n for i in items:\n keys.append(getattr(self, i))\n keys = [k for k in keys if type(k) == types.MethodType]\n keys = [k.__name__ for k in keys]\n keys = [k for k in keys if k[:7] == \"convert\"]\n keys = [k for k in keys if k != \"convert\"]\n keys = [k[7:] for k in keys]\n shapeNames = [k.lower() for k in keys]\n return shapeNames\n\ndef svgPath2RL(path,verbose=False):\n pts = []\n ops = []\n ops_append = ops.append\n lastM = 0,0\n wasz = False\n prevOp = None\n\n for i in range(0, len(path), 2):\n op, nums = path[i:i+2]\n if ops and op in 'mM' and not wasz:\n #special check to see if we should 'close' previous sub-path\n if pts[-2]==lastM[0] and pts[-1]==lastM[1]:\n ops_append(3)\n wasz = False\n\n # moveto, lineto absolute\n if op in ('M', 'L'):\n xn, yn = nums\n pts += [xn, yn]\n if op == 'M': \n ops_append(0)\n lastM = xn, yn\n elif op == 'L': \n ops_append(1)\n\n # moveto, lineto relative\n elif op == 'm':\n xn, yn = nums\n xn += pts[-2]\n yn += pts[-1]\n pts += [xn,yn]\n ops_append(0)\n lastM = xn, yn\n elif op == 'l':\n xn, yn = nums\n pts += [pts[-2]+xn, pts[-1]+yn]\n ops_append(1)\n elif op in 'aA':\n rx,ry,phi,fA,fS,x2,y2 = nums\n x1, y1 = pts[-2:]\n if op=='a':\n x2 += x1\n y2 += y1\n if abs(rx)<=1e-10 or abs(ry)<=1e-10:\n ops_append(1)\n pts += [x2,y2]\n else:\n bp = bezierArcFromEndPoints(x1,y1,rx,ry,phi,fA,fS,x2,y2)\n for x1,y1,x2,y2,x3,y3,x4,y4 in bp:\n ops_append(2)\n pts += [x2,y2,x3,y3,x4,y4]\n # horizontal/vertical line absolute\n elif op in ('H', 'V'):\n k = nums[0]\n if op == 'H':\n pts += [k, pts[-1]]\n elif op == 'V':\n pts += [pts[-2], k]\n ops_append(1)\n\n # horizontal/vertical line relative\n elif op in ('h', 'v'):\n k = nums[0]\n if op == 'h':\n pts += [pts[-2]+k, pts[-1]]\n elif op == 'v':\n pts += [pts[-2], pts[-1]+k]\n ops_append(1)\n\n # cubic bezier, absolute\n elif op == 'C':\n x1, y1, x2, y2, xn, yn = nums\n pts += [x1, y1, x2, y2, xn, yn]\n ops_append(2)\n elif op == 'S':\n x2, y2, xn, yn = nums\n if ops:\n x0, y0 = pts[-2:]\n if prevOp in 'CcSs':\n xp, yp, = pts[-4:-2]\n else:\n xp = x0\n yp = y0\n else:\n xp = x0 = x2\n yp = y0 = y2\n xi, yi = x0+(x0-xp), y0+(y0-yp)\n pts += [xi, yi, x2, y2, xn, yn]\n ops_append(2)\n\n # cubic bezier, relative\n elif op == 'c':\n xp, yp = pts[-2:]\n x1, y1, x2, y2, xn, yn = nums\n pts += [xp+x1, yp+y1, xp+x2, yp+y2, xp+xn, yp+yn]\n ops_append(2)\n elif op == 's':\n x2, y2, xn, yn = nums\n if ops:\n x0, y0 = pts[-2:]\n if prevOp in 'CcSs':\n xp, yp = pts[-4:-2]\n else:\n xp = x0\n yp = y0\n else:\n xp = x0 = x2\n yp = y0 = y2\n xi, yi = x0+(x0-xp), y0+(y0-yp)\n pts += [xi, yi, x0+x2, y0+y2, x0+xn, y0+yn]\n ops_append(2)\n\n # quadratic bezier, absolute\n elif op == 'Q':\n x0, y0 = pts[-2:]\n x1, y1, xn, yn = nums\n (x0,y0), (x1,y1), (x2,y2), (xn,yn) = \\\n convertQuadraticToCubicPath((x0,y0), (x1,y1), (xn,yn))\n pts += [x1,y1, x2,y2, xn,yn]\n ops_append(2)\n elif op == 'T':\n xn, yn = nums\n if ops:\n x0, y0 = pts[-2:]\n if prevOp in 'QqTt':\n xp, yp = pts[-4:-2]\n else:\n xp = x0\n yp = y0\n xi, yi = x0+(x0-xp), y0+(y0-yp)\n (x0,y0), (x1,y1), (x2,y2), (xn,yn) = \\\n convertQuadraticToCubicPath((x0,y0), (xi,yi), (xn,yn))\n pts += [x1,y1, x2,y2, xn,yn]\n ops_append(2)\n\n # quadratic bezier, relative\n elif op == 'q':\n x1, y1, xn, yn = nums\n if ops:\n x0, y0 = pts[-2:]\n else:\n x0 = x1\n y0 = y1\n x1, y1, xn, yn = x0+x1, y0+y1, x0+xn, y0+yn\n (x0,y0), (x1,y1), (x2,y2), (xn,yn) = \\\n convertQuadraticToCubicPath((x0,y0), (x1,y1), (xn,yn))\n pts += [x1,y1, x2,y2, xn,yn]\n ops_append(2)\n elif op == 't':\n xn, yn = nums\n if ops:\n x0, y0 = pts[-2:]\n xn += x0\n yn += y0\n if prevOp in 'QqTt':\n xp, yp = pts[-4:-2]\n else:\n xp = x0\n yp = y0\n else:\n xp = x0 = xn\n yp = y0 = yn\n xi, yi = x0+(x0-xp), y0+(y0-yp)\n (x0,y0), (x1,y1), (x2,y2), (xn,yn) = \\\n convertQuadraticToCubicPath((x0,y0), (xi,yi), (xn,yn))\n pts += [x1,y1, x2,y2, xn,yn]\n ops_append(2)\n\n # close path\n elif op in ('Z', 'z'):\n ops_append(3)\n wasz = True\n try:\n nextOp = path[i+1]\n if nextOp!='M':\n pts += list(lastM)\n ops_append(0)\n except:\n pass\n\n # arcs\n else: #if op in unhandledOps.keys():\n if verbose:\n print(\"Suspicious path operator:\", op)\n prevOp = op\n\n return ops, pts\n\nclass Svg2RlgShapeConverter(SvgShapeConverter):\n \"Converte from SVG shapes to RLG (ReportLab Graphics) shapes.\"\n\n def __init__(self,verbose=0):\n SvgShapeConverter.__init__(self,verbose=verbose,attrConverter=Svg2RlgAttributeConverter)\n\n def convertLine(self, node):\n getAttr = node.getAttribute\n x1, y1, x2, y2 = list(map(getAttr, (\"x1\", \"y1\", \"x2\", \"y2\")))\n x1, y1, x2, y2 = list(map(self.attrConverter.convertLength, (x1, y1, x2, y2)))\n shape = Line(x1, y1, x2, y2)\n return shape\n\n def convertRect(self, node):\n getAttr = node.getAttribute\n x, y, width, height = list(map(getAttr, ('x', 'y', \"width\", \"height\")))\n x, y, width, height = list(map(self.attrConverter.convertLength, (x, y, width, height)))\n rx, ry = list(map(getAttr, (\"rx\", \"ry\")))\n rx, ry = list(map(self.attrConverter.convertLength, (rx, ry)))\n shape = Rect(x, y, width, height, rx=rx, ry=ry)\n return shape\n\n def convertCircle(self, node):\n # not rendered if r == 0, error if r < 0.\n getAttr = node.getAttribute\n cx, cy, r = list(map(getAttr, (\"cx\", \"cy\", 'r')))\n cx, cy, r = list(map(self.attrConverter.convertLength, (cx, cy, r)))\n shape = Circle(cx, cy, r)\n return shape\n\n def convertEllipse(self, node):\n getAttr = node.getAttribute\n cx, cy, rx, ry = list(map(getAttr, (\"cx\", \"cy\", \"rx\", \"ry\")))\n cx, cy, rx, ry = list(map(self.attrConverter.convertLength, (cx, cy, rx, ry)))\n width, height = rx, ry\n shape = Ellipse(cx, cy, width, height)\n return shape\n\n def convertPolyline(self, node):\n getAttr = node.getAttribute\n points = getAttr(\"points\")\n points = points.replace(',', ' ')\n points = points.split()\n points = list(map(self.attrConverter.convertLength, points))\n\n # Need to use two shapes, because standard RLG polylines\n # do not support filling...\n gr = Group()\n shape = Polygon(points)\n self.applyStyleOnShape(shape, node)\n shape.strokeColor = None\n gr.add(shape)\n shape = PolyLine(points)\n self.applyStyleOnShape(shape, node)\n gr.add(shape)\n return gr\n\n def convertPolygon(self, node):\n getAttr = node.getAttribute\n points = getAttr(\"points\")\n points = points.replace(',', ' ')\n points = points.split()\n points = list(map(self.attrConverter.convertLength, points))\n shape = Polygon(points)\n return shape\n\n def convertText0(self, node):\n getAttr = node.getAttribute\n x, y = list(map(getAttr, ('x', 'y')))\n if not x: x = '0'\n if not y: y = '0'\n text = ''\n if node.firstChild.nodeValue:\n try:\n text = node.firstChild.nodeValue.encode(\"ASCII\")\n except:\n text = \"Unicode\"\n x, y = list(map(self.attrConv.convertLength, (x, y)))\n shape = String(x, y, text)\n self.applyStyleOnShape(shape, node)\n gr = Group()\n gr.add(shape)\n gr.scale(1, -1)\n gr.translate(0, -2*y)\n return gr\n\n def convertText(self, node):\n attrConv = self.attrConverter\n getAttr = node.getAttribute\n x, y = list(map(getAttr, ('x', 'y')))\n x, y = list(map(attrConv.convertLength, (x, y)))\n\n gr = Group()\n\n text = ''\n chNum = len(node.childNodes)\n frags = []\n fragLengths = []\n\n dx0, dy0 = 0, 0\n x1, y1 = 0, 0\n ff = attrConv.findAttr(node, \"font-family\") or \"Helvetica\"\n ff = ff.encode(\"ASCII\")\n ff = attrConv.convertFontFamily(ff)\n fs = attrConv.findAttr(node, \"font-size\") or \"12\"\n fs = fs.encode(\"ASCII\")\n fs = attrConv.convertLength(fs)\n for c in node.childNodes:\n dx, dy = 0, 0\n baseLineShift = 0\n if c.nodeType == c.TEXT_NODE:\n frags.append(c.nodeValue)\n try:\n tx = ''.join([chr(ord(f)) for f in frags[-1]])\n except ValueError:\n tx = \"Unicode\"\n elif c.nodeType == c.ELEMENT_NODE and c.nodeName == \"tspan\":\n frags.append(c.firstChild.nodeValue)\n tx = ''.join([chr(ord(f)) for f in frags[-1]])\n getAttr = c.getAttribute\n y1 = getAttr('y')\n y1 = attrConv.convertLength(y1)\n dx, dy = list(map(getAttr, (\"dx\", \"dy\")))\n dx, dy = list(map(attrConv.convertLength, (dx, dy)))\n dx0 += dx\n dy0 += dy\n baseLineShift = getAttr(\"baseline-shift\") or '0'\n if baseLineShift in (\"sub\", \"super\", \"baseline\"):\n baseLineShift = {\"sub\":-fs/2, \"super\":fs/2, \"baseline\":0}[baseLineShift]\n else:\n baseLineShift = attrConv.convertLength(baseLineShift, fs)\n elif c.nodeType == c.ELEMENT_NODE and c.nodeName != \"tspan\":\n continue\n\n fragLengths.append(stringWidth(tx, ff, fs))\n rl = reduce(operator.__add__, fragLengths[:-1], 0)\n try:\n text = ''.join([chr(ord(f)) for f in frags[-1]])\n except ValueError:\n text = \"Unicode\"\n shape = String(x+rl, y-y1-dy0+baseLineShift, text)\n self.applyStyleOnShape(shape, node)\n if c.nodeType == c.ELEMENT_NODE and c.nodeName == \"tspan\":\n self.applyStyleOnShape(shape, c)\n\n gr.add(shape)\n\n gr.scale(1, -1)\n gr.translate(0, -2*y)\n return gr\n\n def convertPath(self, node):\n d = node.getAttribute('d')\n path = normaliseSvgPath(d)\n if self.verbose: print(repr(path))\n ops, pts = svgPath2RL(path,self.verbose)\n\n if not ops: return\n\n # hack because RLG has no \"semi-closed\" paths...\n gr = Group()\n if ops[-1] == 3:\n p = Path(pts, ops)\n self.applyStyleOnShape(p, node)\n fc = self.attrConverter.findAttr(node, \"fill\")\n if not fc:\n p.fillColor = colors.black\n sc = self.attrConverter.findAttr(node, \"stroke\")\n if not sc:\n p.strokeColor = None\n gr.add(p)\n else:\n fc = self.attrConverter.findAttr(node, \"fill\")\n if fc:\n p = Path(pts, ops+[3])\n self.applyStyleOnShape(p, node)\n p.strokeColor = None\n gr.add(p)\n else:\n sc = self.attrConverter.findAttr(node, \"stroke\")\n if sc:\n p = Path(pts, ops)\n self.applyStyleOnShape(p, node)\n gr.add(p)\n return gr\n\n def convertImage(self, node):\n if self.verbose:\n print(\"Adding box instead image.\")\n getAttr = node.getAttribute\n x, y, width, height = list(map(getAttr, ('x', 'y', \"width\", \"height\")))\n x, y, width, height = list(map(self.attrConverter.convertLength, (x, y, width, height)))\n xlink_href = node.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\")\n try:\n xlink_href = xlink_href.encode(\"ASCII\")\n except:\n pass\n xlink_href = os.path.join(os.path.dirname(self.svgSourceFile), xlink_href)\n # print \"***\", x, y, width, height, xlink_href[:30]\n\n magic = \"data:image/jpeg;base64\"\n if xlink_href[:len(magic)] == magic:\n pat = \"data:image/(\\w+?);base64\"\n ext = re.match(pat, magic).groups()[0]\n import base64, md5\n jpegData = base64.decodestring(xlink_href[len(magic):])\n hashVal = md5.new(jpegData).hexdigest()\n name = \"images/img%s.%s\" % (hashVal, ext)\n path = os.path.join(dirname(self.svgSourceFile), name)\n open(path, \"wb\").write(jpegData)\n img = Image(x, y+height, width, -height, path)\n # this needs to be removed later, not here...\n # if exists(path): os.remove(path)\n else:\n xlink_href = os.path.join(os.path.dirname(self.svgSourceFile), xlink_href)\n img = Image(x, y+height, width, -height, xlink_href)\n return img\n\n def applyTransformOnGroup(self, transform, group):\n \"\"\"Apply an SVG transformation to a RL Group shape.\n\n The transformation is the value of an SVG transform attribute\n like transform=\"scale(1, -1) translate(10, 30)\".\n\n rotate( [ ]) is equivalent to:\n translate( ) rotate() translate(- -)\n \"\"\"\n\n tr = self.attrConverter.convertTransform(transform)\n for op, values in tr:\n if op == \"scale\":\n if type(values) != tuple:\n values = (values, values)\n group.scale(*values)\n elif op == \"translate\":\n try: # HOTFIX\n values = values[0], values[1]\n except TypeError:\n return\n group.translate(*values)\n elif op == \"rotate\":\n if type(values) != tuple or len(values) == 1:\n group.rotate(values)\n elif len(values) == 3:\n angle, cx, cy = values\n group.translate(cx, cy)\n group.rotate(angle)\n group.translate(-cx, -cy)\n elif op == \"skewX\":\n group.skew(values, 0)\n elif op == \"skewY\":\n group.skew(0, values)\n elif op == \"matrix\":\n group.transform = values\n else:\n if self.verbose:\n print(\"Ignoring transform:\", op, values)\n\n def applyStyleOnShape(self, shape, *nodes):\n \"Apply styles from SVG elements to an RLG shape.\"\n\n # RLG-specific: all RLG shapes\n \"Apply style attributes of a sequence of nodes to an RL shape.\"\n\n # tuple format: (svgAttr, rlgAttr, converter, default)\n mappingN = (\n (\"fill\", \"fillColor\", \"convertColor\", \"none\"), \n (\"stroke\", \"strokeColor\", \"convertColor\", \"none\"),\n (\"stroke-width\", \"strokeWidth\", \"convertLength\", \"0\"),\n (\"stroke-linejoin\", \"strokeLineJoin\", \"convertLineJoin\", \"0\"),\n (\"stroke-linecap\", \"strokeLineCap\", \"convertLineCap\", \"0\"),\n (\"stroke-dasharray\", \"strokeDashArray\", \"convertDashArray\", \"none\"),\n )\n mappingF = (\n (\"font-family\", \"fontName\", \"convertFontFamily\", \"Helvetica\"),\n (\"font-size\", \"fontSize\", \"convertLength\", \"12\"),\n (\"text-anchor\", \"textAnchor\", \"id\", \"start\"),\n )\n\n ac = self.attrConverter\n for node in nodes:\n for mapping in (mappingN, mappingF):\n if shape.__class__ != String and mapping == mappingF:\n continue\n for (svgAttrName, rlgAttr, func, default) in mapping:\n try:\n svgAttrValue = ac.findAttr(node, svgAttrName) or default\n if svgAttrValue == \"currentColor\":\n svgAttrValue = ac.findAttr(node.parentNode, \"color\") or default\n meth = getattr(ac, func)\n setattr(shape, rlgAttr, meth(svgAttrValue))\n except:\n pass\n\n if shape.__class__ == String:\n svgAttr = ac.findAttr(node, \"fill\") or \"black\"\n setattr(shape, \"fillColor\", ac.convertColor(svgAttr))\n\ndef svg2rlg(path,verbose=0):\n \"Convert an SVG file to an RLG Drawing object.\"\n \n # unzip .svgz file into .svg\n unzipped = False\n if os.path.splitext(path)[1].lower() == \".svgz\":\n data = gzip.GzipFile(path, \"rb\").read()\n open(path[:-1], 'w').write(data)\n path = path[:-1]\n unzipped = True\n\n\n # load SVG file\n try:\n doc = xml.dom.minidom.parse(path)\n svg = doc.documentElement\n except:\n print(\"!!!!! Failed to load input file!\")\n return\n\n # convert to a RLG drawing\n svgRenderer = SvgRenderer(path,verbose=verbose)\n svgRenderer.render(svg)\n drawing = svgRenderer.finish()\n\n # remove unzipped .svgz file (.svg)\n if unzipped:\n os.remove(path)\n \n return drawing\n\nif __name__=='__main__':\n import glob, traceback\n argv = sys.argv[1:]\n outDir = os.getcwd()\n formats = ['pdf']\n verbose = 0\n i = 0\n while i < len(argv):\n arg = argv[i]\n i += 1\n if arg.startswith('--outdir='):\n outDir = arg[9:]\n continue\n if arg.startswith('--formats='):\n formats = list(map(str.strip,arg[10:].split(',')))\n continue\n if arg.startswith('--verbose='):\n verbose = int(arg[10:])\n continue\n for fn in glob.glob(arg):\n try:\n d = svg2rlg(fn,verbose=verbose)\n if d:\n d.save(formats=formats,verbose=verbose,fnRoot=os.path.splitext(os.path.basename(fn))[0],outDir=outDir)\n except:\n traceback.print_exc()\n","sub_path":"env/lib/python3.4/site-packages/rlextra/thirdparty/svg/svglib.py","file_name":"svglib.py","file_ext":"py","file_size_in_byte":48153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43604193","text":"from sqlalchemy import Column, ForeignKey, Integer, String, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\n\nBase = declarative_base()\nengine = create_engine('sqlite:///database.db')\n\nclass User(Base):\n __tablename__ = 'user'\n\n pid = Column(String(250), primary_key=True) # pid is uuid key\n account = Column(String(250), unique=True, nullable=True)\n user_name = Column(String(250), unique=True, nullable=True)\n country = Column(String(250), nullable=True)\n\nclass Game(Base):\n __tablename__ = 'game'\n\n pid = Column(Integer, primary_key=True, autoincrement=True)\n game_name = Column(String(250))\n\n\nclass Record_Entity(Base):\n __tablename__ = 'record_entity'\n\n pid = Column(Integer, primary_key=True, autoincrement=True)\n record_id = Column(Integer)\n point = Column(Integer, nullable=True)\n\nclass Record(Base):\n __tablename__ = 'record'\n\n pid = Column(Integer, primary_key=True, autoincrement=True)\n time =Column(DateTime, unique=True)\n user_id = Column(Integer, ForeignKey('user.pid'))\n game_id = Column(Integer, ForeignKey('game.pid'))\n record_entity_id = Column(Integer, ForeignKey('record_entity.pid'), unique=True)\n relationship(User)\n relationship(Game)\n relationship(Record_Entity)\n\n\n\nBase.metadata.create_all(engine)\n\n\n","sub_path":"database_declarative.py","file_name":"database_declarative.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207144558","text":"all_variables = {\n \"pT_j1\": \"Jet_Pt[0]\",\n \"eta_j1\": \"Jet_Eta[0]\",\n \"CSV_j1\": \"Jet_CSV[0]\",\n\n \"pT_j2\": \"Jet_Pt[1]\",\n \"eta_j2\": \"Jet_Eta[1]\",\n \"CSV_j2\": \"Jet_CSV[1]\",\n\n \"pT_j3\": \"Jet_Pt[2]\",\n \"eta_j3\": \"Jet_Eta[2]\",\n \"CSV_j3\": \"Jet_CSV[2]\",\n\n \"pT_j4\": \"Jet_Pt[3]\",\n \"eta_j4\": \"Jet_Eta[3]\",\n \"CSV_j4\": \"Jet_CSV[3]\",\n\n \"pT_lep1\": \"LooseLepton_Pt[0]\" ,\n \"eta_lep1\": \"LooseLepton_Eta[0]\",\n\n \"HT\": \"Evt_HT\",\n \"HT_tag\": \"BDT_common5_input_HT_tag\",\n\n \"min_dR_jj\": \"Evt_Dr_MinDeltaRJets\",\n \"min_dR_bb\": \"Evt_Dr_MinDeltaRTaggedJets\",\n\n \"max_dR_jj\": \"BDT_common5_input_max_dR_jj\",\n \"max_dR_bb\": \"BDT_common5_input_max_dR_bb\",\n\n \"aplanarity_jets\": \"BDT_common5_input_aplanarity_jets\",\n \"aplanarity_tags\": \"BDT_common5_input_aplanarity_tags\",\n\n \"centrality_jets\": \"Evt_JetPtOverJetE\",\n \"centrality_tags\": \"BDT_common5_input_pt_all_jets_over_E_all_jets_tags\",\n\n \"sphericity_jets\": \"BDT_common5_input_sphericity_jets\",\n \"sphericity_tags\": \"BDT_common5_input_sphericity_tags\",\n\n # transverse sphericities\n \"sphericityT_jets\": \"BDT_common5_input_transverse_sphericity_jets\",\n \"sphericityT_tags\": \"BDT_common5_input_transverse_sphericity_tags\",\n\n \"avg_CSV_jets\": \"Evt_CSV_Average\",\n \"avg_CSV_tags\": \"Evt_CSV_Average_Tagged\",\n\n \"max_CSV_jets\": \"CSV[0]\",\n \"max_CSV_tags\": \"CSV[0]\",\n\n \"min_CSV_jets\": \"Evt_CSV_Min\",\n \"min_CSV_tags\": \"Evt_CSV_Min_Tagged\",\n\n \"min_dR_lep_jet\": \"Evt_Dr_MinDeltaRLeptonJet\",\n \"min_dR_lep_tag\": \"Evt_Dr_MinDeltaRLeptonTaggedJet\",\n\n # fox wolframs\n \"H_2\": \"BDT_common5_input_h1\",\n \"H_3\": \"BDT_common5_input_h2\",\n \"H_4\": \"BDT_common5_input_h3\",\n\n \"M_lep_closest_tag\": \"Evt_M_MinDeltaRLeptonTaggedJet\",\n\n \"avg_deta_bb\": \"Evt_Deta_TaggedJetsAverage\",\n \"avg_dR_bb\": \"Evt_Dr_TaggedJetsAverage\",\n\n \"M2_of_min_dR_bb\": \"BDT_common5_input_closest_tagged_dijet_mass\",\n \"2nd_moment_tagged_jets_CSVs\": \"BDT_common5_input_dev_from_avg_disc_btags\",\n\n \"avg_M_jets\": \"Evt_M_JetsAverage\",\n \"avg_M2_tags\": \"Evt_M2_TaggedJetsAverage\",\n\n \"N_tags_tight\": \"N_BTagsT\",\n\n \"M2_bb_closest_to_125\": \"BDT_common5_input_tagged_dijet_mass_closest_to_125\",\n\n \"2nd_highest_CSV\": \"CSV[1]\",\n\n \"blr\": \"Evt_blr_ETH\",\n \"blr_transformed\": \"Evt_blr_ETH_transformed\",\n \"dank_MEM\": \"memDBp\",\n}\n\n\nundefined_variables = [\n #\"dank_MEM\",\n \"max_CSV_tags\", #already covered\n #\"sphericityT_jets\",\n #\"sphericityT_tags\",\n #\"HT_tag\",\n #\"aplanarity_tags\",\n #\"aplanarity_jets\",\n #\"sphericity_jets\",\n #\"sphericity_tags\",\n #\"max_dR_bb\",\n #\"max_dR_jj\",\n #\"centrality_tags\",\n ]\n\n\n# categories\n# SL 4j,>=3b\nvariables_4j_3b = [\n \"pT_j1\",\n \"CSV_j1\",\n\n \"eta_j2\",\n \"CSV_j2\",\n\n \"eta_j3\",\n \"CSV_j3\",\n\n \"pT_j4\",\n \"eta_j4\",\n \"CSV_j4\",\n\n \"eta_lep1\",\n\n \"HT_tag\",\n\n \"min_dR_jj\",\n \"min_dR_bb\",\n\n \"aplanarity_tags\",\n \"sphericity_jets\",\n\n \"sphericityT_jets\",\n \"sphericityT_tags\",\n\n \"avg_CSV_jets\",\n \"avg_CSV_tags\",\n \"max_CSV_jets\",\n \"max_CSV_tags\",\n \"min_CSV_jets\",\n \"min_CSV_tags\",\n\n \"min_dR_lep_jet\",\n\n \"H_3\",\n \"H_4\",\n\n \"M_lep_closest_tag\",\n \"M2_of_min_dR_bb\",\n \"2nd_moment_tagged_jets_CSVs\",\n\n \"avg_M_jets\",\n \"avg_M2_tags\",\n\n \"N_tags_tight\",\n\n \"2nd_highest_CSV\",\n\n \"blr\",\n \"blr_transformed\",\n \"dank_MEM\",\n ]\n\n# SL 5j,>=3b\nvariables_5j_3b = [\n \"pT_j1\",\n \"eta_j1\",\n \"CSV_j1\",\n\n \"pT_j2\",\n \"eta_j2\",\n \"CSV_j2\",\n\n \"pT_j3\",\n \"eta_j3\",\n \"CSV_j3\",\n\n \"pT_j4\",\n \"eta_j4\",\n\n \"pT_lep1\",\n\n \"HT\",\n \"HT_tag\",\n\n \"min_dR_jj\",\n \"min_dR_bb\",\n\n \"max_dR_jj\",\n\n \"aplanarity_jets\",\n \"aplanarity_tags\",\n\n \"sphericity_jets\",\n \"sphericity_tags\",\n\n \"sphericityT_jets\",\n \"sphericityT_tags\",\n\n \"avg_CSV_jets\",\n \"avg_CSV_tags\",\n\n \"max_CSV_jets\",\n \"max_CSV_tags\",\n\n \"min_CSV_jets\",\n \"min_CSV_tags\",\n\n \"min_dR_lep_jet\",\n \"min_dR_lep_tag\",\n\n \"H_2\",\n \"H_3\",\n\n \"M_lep_closest_tag\",\n\n \"avg_dR_bb\",\n\n \"M2_of_min_dR_bb\",\n \"2nd_moment_tagged_jets_CSVs\",\n\n \"avg_M_jets\",\n\n \"N_tags_tight\",\n\n \"M2_bb_closest_to_125\",\n\n \"2nd_highest_CSV\",\n\n \"blr\",\n \"blr_transformed\",\n \"dank_MEM\",\n ]\n\n\n\n# SL >=6j, >=3b\nvariables_6j_3b = [\n \"eta_j1\",\n \"CSV_j1\",\n\n \"eta_j2\",\n \"CSV_j2\",\n\n \"eta_j3\",\n \"CSV_j3\",\n\n \"eta_j4\",\n \"CSV_j4\",\n\n \"pT_lep1\",\n \"eta_lep1\",\n\n \"HT_tag\",\n\n \"min_dR_jj\",\n \"min_dR_bb\",\n\n \"max_dR_bb\",\n\n \"aplanarity_jets\",\n \"aplanarity_tags\",\n\n \"centrality_jets\",\n \"centrality_tags\",\n\n \"sphericity_jets\",\n \"sphericity_tags\",\n\n \"sphericityT_jets\",\n \"sphericityT_tags\",\n\n \"avg_CSV_jets\",\n \"avg_CSV_tags\",\n\n \"max_CSV_jets\",\n \"max_CSV_tags\",\n\n \"min_CSV_jets\",\n \"min_CSV_tags\",\n\n \"min_dR_lep_tag\",\n\n \"H_4\",\n\n \"M_lep_closest_tag\",\n\n \"avg_deta_bb\",\n \"avg_dR_bb\",\n\n \"M2_of_min_dR_bb\",\n \"2nd_moment_tagged_jets_CSVs\",\n\n \"avg_M_jets\",\n \"avg_M2_tags\",\n\n \"N_tags_tight\",\n\n \"M2_bb_closest_to_125\",\n\n \"2nd_highest_CSV\",\n\n \"blr\",\n \"blr_transformed\",\n \"dank_MEM\",\n ]\n\n\nvariables_4j_3b = [all_variables[var] for var in variables_4j_3b if not var in undefined_variables]\nvariables_5j_3b = [all_variables[var] for var in variables_5j_3b if not var in undefined_variables]\nvariables_6j_3b = [all_variables[var] for var in variables_6j_3b if not var in undefined_variables]\nall_variables_list = [all_variables[var] for var in all_variables if not var in undefined_variables and not \"MEM\" in var]\nprint(all_variables_list)\n","sub_path":"preprocessing/root2pandas/variable_info.py","file_name":"variable_info.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"106448408","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nE_f = -0.7545643550000001\n\nGAMMA = 0.0, 0.0, 0.0\nX = 0.0, 1.0, 0.0\nL = 0.5, 0.5, 0.5\nW = 0.5, 1.0, 0.0\n\nlattice_points = {GAMMA: \"$\\Gamma$\",\n X: \"X\",\n L: \"L\",\n W: \"W\"}\n\nlattice_points = W, L, GAMMA, X, W, GAMMA\nlattice_points_labels = \"W\", \"L\", \"$\\Gamma$\", \"X\", \"W\", \"$\\Gamma$\"\n\n\n \ndef arraylinspace(start, stop, steps=100, retstep=False, dtype=None):\n dim, dim2 = len(start), len(stop)\n if dim != dim2:\n raise ValueError(f\"Dimesnions {dim} and {dim2} don't match: \")\n axis_arrays = np.zeros((dim, steps), dtype=dtype)\n step_sizes = np.zeros((dim, ))\n if retstep:\n for d in range(dim):\n axis_arrays[d, :], step_sizes[d] = np.linspace(start[d], stop[d], steps, retstep=True)\n vectors = np.swapaxes(axis_arrays, 0, 1)\n return vectors, np.linalg.norm(step_sizes)\n else:\n for d in range(dim):\n axis_arrays[d, :] = np.linspace(start[d], stop[d], steps)\n vectors = np.swapaxes(axis_arrays, 0, 1)\n return vectors\n \n \ndef band_linspace(points, steps_per_section, return_1d=True):\n n_points = len(points)\n total_steps = (n_points-1) * steps_per_section\n shape = total_steps, len(points[0])\n k_vectors = np.zeros(shape)\n for i in range(n_points-1):\n section = arraylinspace(points[i], points[i+1], steps_per_section)\n add_subarrays(k_vectors, section, i, steps_per_section)\n return k_vectors, np.linspace(0, n_points-1, total_steps) if return_1d else k_vectors\n \n \ndef add_subarrays(array, subarray, index, fixed_size):\n start, end = index * fixed_size, (index + 1) * fixed_size\n array[start:end, :] = subarray\n","sub_path":"dft/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"334737552","text":"import cv2\nimport numpy as np\n\n# Normal routines\n#img = cv2.imread('ws.png')\n\n\ndef detct_shapes(img):\n #img = cv2.imread(img)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(gray, 50, 255, 1)\n\n # Remove some small noise if any.\n dilate = cv2.dilate(thresh, None)\n erode = cv2.erode(dilate, None)\n\n # Find contours with cv2.RETR_CCOMP\n contours, hierarchy = cv2.findContours(\n erode, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n image_subs = []\n for i, cnt in enumerate(contours):\n # Check if it is an external contour and its area is more than 100\n if hierarchy[0, i, 3] == -1 and cv2.contourArea(cnt) > 100:\n detail = []\n x, y, w, h = cv2.boundingRect(cnt)\n img_inst = img[y-10:y+h+10, x-10:(x+w+10)]\n detail.append([[x-10, y-10], [x+w+10, y+h+10]])\n detail.append(img_inst)\n image_subs.append(detail)\n cv2.rectangle(img, (x-10, y-10), (x+w+10, y+h+10),\n (255, 255, 255), 2)\n #k = 'sofsqure'+str(x)+'.png'\n #cv2.imwrite(\"asa.jpg\", img)\n\n return image_subs\n\n","sub_path":"4.testScripts/test_subObjects/sd1.py","file_name":"sd1.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574123575","text":"from fenics import *\r\nimport os\r\nimport errno\r\nfrom datetime import datetime\r\nfrom copy import copy\r\nimport numpy as np\r\n\r\n__this_files_path = os.path.realpath(__file__)\r\n__this_files_dir = os.path.dirname(__this_files_path)\r\n\r\n# Pfad zum Ordner mit den Gitter Dateien\r\nDATA_DIR = os.path.abspath(os.path.join(__this_files_dir, 'Meshes'))\r\n\r\n\r\nclass MeshData:\r\n\r\n # Objekt mit allen Daten des Gitters\r\n def __init__(self, mesh, subdomains, boundaries, ind):\r\n\r\n # FEniCS Mesh\r\n self.mesh = mesh\r\n\r\n # FEniCS Subdomains\r\n self.subdomains = subdomains\r\n\r\n # FEniCS Boundaries\r\n self.boundaries = boundaries\r\n\r\n # Indizes der Knotenpunkte mit Traeger nicht am inneren Rand\r\n self.indNotIntBoundary = ind\r\n\r\n\r\nclass bfgs_memory:\r\n \"\"\"\r\n Klasse, welche alle Information fuer das L-BFGS-Verfahren enthaelt.\r\n Besteht aus length Gradienten- und Deformationsvektoren, welche jeweils\r\n in einem Array der Historie nach absteigend sortiert sind.\r\n Besitzt die Funktion, Gradienten und Deformationen zu updaten, wobei der aelteste\r\n Eintrag verworfen wird. step_nr ist ein counter fuer das Verfahren.\r\n \"\"\"\r\n\r\n # Objekt mit gespeicherten Gradienten und Deformationen der letzten l Schritte in Form von Arrays\r\n def __init__(self, gradient, deformation, length, step_nr):\r\n\r\n # Liste von Gradientenvektorfeldern\r\n if (len(gradient) == length): self.gradient = gradient\r\n else: raise SystemExit(\"Fehler: Anzahl der Gradienten passt nicht zur Memorylaenge!\")\r\n\r\n # Liste von Deformationsvektorfeldern\r\n if (len(deformation) == length): self.deformation = deformation\r\n else: raise SystemExit(\"Fehler: Anzahl der Deformationen passt nicht zur Memorylaenge!\")\r\n\r\n # Anzahl der gespeicherten letzten Schritte\r\n self.length = length\r\n\r\n # Anzahl der bereits ausgefuehrten l-BFGS-Schritte\r\n if (step_nr >= 0 and isinstance(step_nr, int)): self.step_nr = step_nr\r\n else: raise SystemExit(\"Fehler: step_nr muss Integer groesser gleich 0 sein!\")\r\n\r\n # macht ein Update der Memory; neueste Elemente bekommen Index 0\r\n def update_grad(self, upd_grad):\r\n\r\n for i in range(self.length-1): self.gradient[-(i+1)] = self.gradient[-(i+2)]\r\n\r\n self.gradient[0] = upd_grad\r\n\r\n def update_defo(self, upd_defo):\r\n\r\n for i in range(self.length-1): self.deformation[-(i+1)] = self.deformation[-(i+2)]\r\n\r\n self.deformation[0] = upd_defo\r\n\r\n def initialize_grad(self, meshData, i):\r\n # erzeugt eine FEniCS-Funktion des Gradientenfeldes i auf einem Mesh aus den gespeicherten Arrays\r\n # ermoeglicht dadurch Transport; i entspricht Index in Speichermatrix self.gradient, aufsteigend im Alter\r\n\r\n if isinstance(meshData, MeshData): pass\r\n else: raise SystemExit(\"initialize_grad benoetigt Objekt der MeshData-Klasse als Input!\")\r\n\r\n V = VectorFunctionSpace(meshData.mesh, \"P\", 1, dim=2)\r\n f = Function(V)\r\n f.vector()[:] = self.gradient[i]\r\n return f\r\n\r\n def initialize_defo(self, meshData, i):\r\n # erzeugt eine FEniCS-Funktion des Deformationsfeldes i auf einem Mesh aus den gespeicherten Arrays\r\n # ermoeglicht dadurch Transport; i entspricht Index in Speichermatrix self.deformation, aufsteigend im Alter\r\n\r\n if isinstance(meshData, MeshData): pass\r\n else: raise SystemExit(\"initialize_defo benoetigt Objekt der MeshData-Klasse als Input!\")\r\n\r\n V = VectorFunctionSpace(meshData.mesh, \"P\", 1, dim=2)\r\n f = Function(V)\r\n f.vector()[:] = self.deformation[i]\r\n return f\r\n\r\n\r\ndef create_outputfolder():\r\n '''\r\n Erstelt einen Outputordner, falls nicht vorhanden\r\n '''\r\n\r\n try:\r\n os.mkdir('Output')\r\n except OSError as exc:\r\n if exc.errno != errno.EEXIST:\r\n raise exc\r\n pass\r\n\r\n # Erstelle Ordner fuer jeden Durchlauf nach Datum und Zeit\r\n outputfolder = os.path.join(__this_files_dir,\r\n 'Output',\r\n datetime.now().strftime('%Y%m%d_%H%M%S'))\r\n os.mkdir(outputfolder)\r\n\r\n # Gibt den Pfad zum speziellen Order im Output Ordner zurueck\r\n return outputfolder\r\n\r\n\r\ndef load_mesh(name):\r\n '''\r\n Initialisiert ein Objekt der MeshData-klasse mittels per GMesh und Dolfin erzeugter\r\n .xml Dateien\r\n '''\r\n # Pfad zur speziellen Gitter Datei\r\n path_meshFile = os.path.join(DATA_DIR, name)\r\n\r\n # Erstelle FEniCS Mesh mit Subdomains und Boundaries\r\n mesh = Mesh(path_meshFile + \".xml\")\r\n subdomains = MeshFunction(\"size_t\", mesh,\r\n path_meshFile + \"_physical_region.xml\")\r\n boundaries = MeshFunction(\"size_t\", mesh,\r\n path_meshFile + \"_facet_region.xml\")\r\n\r\n # Berechne Indizes mit Traeger nicht am inneren Rand\r\n ind = __get_index_not_interior_boundary(mesh, subdomains, boundaries)\r\n\r\n # Rueckgabe als MeshData Objekt\r\n return MeshData(mesh, subdomains, boundaries, ind)\r\n\r\n\r\ndef __get_index_not_interior_boundary(mesh, subdomains, boundaries, interior = True):\r\n \"\"\"\r\n Gibt Indizes der Elemente ohne Traeger am inneren Rand zurueck.\r\n Falls interior = False, so werden die Indizes der Vertices\r\n des Inneren Randes zurueckgegeben. Diese nicht verwechseln mit DOF-Indizes!\r\n \"\"\"\r\n\r\n # Facetten Indizes des inneren Randes bestimmen\r\n ind_interior_boundary_facets = []\r\n for i in range(0,len(boundaries)):\r\n if boundaries[i] > 4:\r\n ind_interior_boundary_facets.append(i)\r\n\r\n # Knoten Indizes des inneren Randes bestimmen\r\n ind_interior_boundary_vertices = []\r\n for c in cells(mesh):\r\n for f in facets(c):\r\n if f.index() in ind_interior_boundary_facets:\r\n for v in vertices(f):\r\n ind_interior_boundary_vertices.append(v.index())\r\n\r\n if(interior == False): return list(set(ind_interior_boundary_vertices))\r\n\r\n ind_interior_boundary_vertices = list(set(ind_interior_boundary_vertices))\r\n\r\n # Element Indizes des inneren Randes bestimmen\r\n ind_around_interior_boundary_cells = []\r\n for c in cells(mesh):\r\n ind = False\r\n for v in vertices(c):\r\n if v.index() in ind_interior_boundary_vertices:\r\n ind = True\r\n if ind:\r\n ind_around_interior_boundary_cells.append(c.index())\r\n\r\n # Als neue Subdomain definieren\r\n new_sub = MeshFunction(\"size_t\", mesh, 2)\r\n new_sub.set_all(0)\r\n for i in ind_around_interior_boundary_cells:\r\n if subdomains[i] == 1:\r\n new_sub[i] = 1\r\n else:\r\n new_sub[i] = 2\r\n\r\n # Indizes berechenen mit Traeger nicht am inneren Rand ueber Testproblem\r\n V = VectorFunctionSpace(mesh, \"P\", 1, dim=2)\r\n\r\n dx_int = Measure('dx',\r\n domain=mesh,\r\n subdomain_data=new_sub)\r\n\r\n v = TestFunction(V)\r\n\r\n dummy_y = Constant((1.0, 1.0))\r\n\r\n f_elas_int_1 = inner(dummy_y, v)*dx_int(1)\r\n F_elas_int_1 = assemble(f_elas_int_1)\r\n f_elas_int_2 = inner(dummy_y, v)*dx_int(2)\r\n F_elas_int_2 = assemble(f_elas_int_2)\r\n\r\n # Indizes setzen durch alle Punkte mit Wert 0, die keinen Einfluss haben\r\n ind1 = (F_elas_int_1.get_local() == 0.0)\r\n ind2 = (F_elas_int_2.get_local() == 0.0)\r\n\r\n ind = ind1 | ind2\r\n\r\n if(interior): return ind\r\n\r\n\r\ndef mesh_distance(mesh1, mesh2):\r\n \"\"\"\r\n Berechnet einen integrierten Abstand der Minima aller Punkte zweier Formen.\r\n mesh2 dient dabei als Ausgangsform, d.h. von dort aus wird Abstand gemessen.\r\n Input sind Objekte der MeshData-Klasse.\r\n \"\"\"\r\n\r\n # Berechne Indizes der Vertices der Boundaries\r\n boundary_index_mesh1 = __get_index_not_interior_boundary(mesh1.mesh, mesh1.subdomains, mesh1.boundaries, interior = False)\r\n boundary_index_mesh2 = __get_index_not_interior_boundary(mesh2.mesh, mesh2.subdomains, mesh2.boundaries, interior = False)\r\n\r\n # Berechne die Abstaende alle Vertices von mesh1 zu jeweils einem festen Vertex aus mesh2,\r\n # dann bilde das Minimum und fuege in Liste hinzu\r\n distance_list_vertex = np.zeros(mesh2.mesh.num_vertices())\r\n\r\n for i in boundary_index_mesh2:\r\n temp_distance_list = []\r\n\r\n for j in boundary_index_mesh1:\r\n local_dist = np.linalg.norm(mesh2.mesh.coordinates()[i] - mesh1.mesh.coordinates()[j])\r\n temp_distance_list.append(local_dist)\r\n\r\n\r\n dist = np.amin(temp_distance_list)\r\n distance_list_vertex[i] = dist\r\n\r\n # definiere eine Funktion auf mesh2 mit Abstandswerten auf Boundaries der Form\r\n V = FunctionSpace(mesh2.mesh, \"P\", 1)\r\n distance_function = Function(V)\r\n vtod = dolfin.vertex_to_dof_map(V)\r\n\r\n # uebersetze Vertexindizes in zugehoerige DOF-Indizes (der fenicsfunction), da Indizes nicht gleich\r\n distance_list_dof = np.zeros(len(distance_function.vector().get_local()))\r\n for i in boundary_index_mesh2: distance_list_dof[vtod[i]] = distance_list_vertex[i]\r\n\r\n # definiere Funktion auf der Form\r\n distance_function.vector()[:] = distance_list_dof\r\n\r\n # Berechne das zugehoerige Integral\r\n dS = Measure('dS', subdomain_data=mesh2.boundaries)\r\n distance_integral = distance_function('+')*dS(5) + distance_function('+')*dS(6)\r\n value = assemble(distance_integral)\r\n\r\n return value\r\n\r\n\r\ndef targetfunction(meshData, deformation, y_z, fValues, nu):\r\n \"\"\"\r\n Berechnet den Wert des Zielfunktionals nach Verschiebung\r\n \"\"\"\r\n\r\n # erzeuge lokale Gitterkopie\r\n msh = Mesh(meshData.mesh)\r\n sbd = MeshFunction(\"size_t\", msh, 2)\r\n sbd.set_values(meshData.subdomains.array())\r\n bnd = MeshFunction(\"size_t\", msh, 1)\r\n bnd.set_values(meshData.boundaries.array())\r\n ind = __get_index_not_interior_boundary(msh, sbd, bnd)\r\n local_mesh = MeshData(msh, sbd, bnd, ind)\r\n\r\n # verschiebe Gitterkopie\r\n ALE.move(local_mesh.mesh, deformation)\r\n\r\n # Berechne Zustand in verschobenem Gitter\r\n y = solve_state(local_mesh, fValues)\r\n\r\n # Assembliere Zielfunktional\r\n V = FunctionSpace(local_mesh.mesh, 'P', 1)\r\n z_1 = project(y_z[0], V)\r\n z_2 = project(y_z[1], V)\r\n z = [z_1, z_2]\r\n\r\n j = 1./2.*norm(project(y[1]-z[1], V), 'L2', local_mesh.mesh)**2\r\n\r\n ds = Measure('dS', subdomain_data=local_mesh.boundaries)\r\n ones = Function(V)\r\n ones.vector()[:] = 1.\r\n j_reg_integral = ones*ds(5) + ones*ds(6)\r\n j_reg = nu*assemble(j_reg_integral)\r\n\r\n J = j + j_reg\r\n\r\n return J\r\n\r\n\r\ndef shape_deriv(meshData, p, y, z, fValues, nu, V):\r\n \"\"\"\r\n Berechnet die Formableitung in Richtung V; V ist FEniCS Funktion, z ist Projektion von y_z\r\n \"\"\"\r\n\r\n dx = Measure('dx',\r\n domain=meshData.mesh,\r\n subdomain_data=meshData.subdomains)\r\n dS = Measure('dS', subdomain_data=meshData.boundaries)\r\n\r\n f1 = Constant(fValues[0])\r\n f2 = Constant(fValues[1])\r\n epsilon_V = sym(nabla_grad(V))\r\n n = FacetNormal(meshData.mesh)\r\n\r\n # Gradient f ist 0, da f stueckweise konstant\r\n Dj = ((-inner(grad(y[0]), dot(epsilon_V*2, grad(p[0])))\r\n -inner(grad(y[1]), dot(epsilon_V * 2, grad(p[1])))) * dx\r\n + nabla_div(V) * (1 / 2 * (y[1] - z[1]) ** 2 + inner(grad(y[0]), grad(p[0]))\r\n + inner(grad(y[1]), grad(p[1]))) * dx\r\n - nabla_div(V)*(f1*p[0] + y[0]*p[1])*dx(1) - nabla_div(V)*(f2*p[0] + y[0]*p[1])*dx(2))\r\n\r\n Dj_reg = nu*((nabla_div(V('+'))\r\n - inner(dot(nabla_grad(V('+')), n('+')), n('+')))*dS(5)\r\n + (nabla_div(V('+'))\r\n - inner(dot(nabla_grad(V('+')), n('+')), n('+')))*dS(6))\r\n\r\n deriv = assemble(Dj + Dj_reg)\r\n\r\n return deriv\r\n\r\n\r\ndef solve_state(meshData, fValues):\r\n \"\"\"\r\n Loest Zustandsgleichung ohne Variationsungleichung\r\n \"\"\"\r\n\r\n # Funktionen Raum\r\n V = FunctionSpace(meshData.mesh, \"P\", 1)\r\n\r\n # Randbedingungen\r\n y_out = Constant(0.0)\r\n bcs = [ DirichletBC(V, y_out, meshData.boundaries, i) for i in range(1, 5) ]\r\n\r\n # Problem definieren\r\n dx = Measure('dx',\r\n domain=meshData.mesh,\r\n subdomain_data=meshData.subdomains)\r\n\r\n f1 = Constant(fValues[0])\r\n f2 = Constant(fValues[1])\r\n\r\n # Loesung der ersten Gleichung berechnen\r\n y_trial = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n a = lhs(inner(grad(y_trial), grad(v))*dx('everywhere'))\r\n b = rhs(f1*v*dx(1) + f2*v*dx(2))\r\n\r\n y_1 = Function(V, name=\"state_sol\")\r\n solve(a == b, y_1, bcs)\r\n\r\n # Loesung der zweiten Gleichung berechnen\r\n y_trial = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n a = lhs(inner(grad(y_trial), grad(v))*dx('everywhere'))\r\n b = rhs(y_1*v*dx('everywhere'))\r\n\r\n y_2 = Function(V, name=\"state_sol\")\r\n solve(a == b, y_2, bcs)\r\n\r\n # Rueckgabe der Loesungen\r\n y = [y_1, y_2]\r\n #y.rename(\"state_sol\", \"label\")\r\n\r\n return y\r\n\r\n\r\ndef solve_adjoint(meshData, y, z):\r\n \"\"\"\r\n Loest Adjungierte Gleichung ohne Variationsungleichung\r\n \"\"\"\r\n\r\n # Funktionen Raum\r\n V = FunctionSpace(meshData.mesh, \"P\", 1)\r\n\r\n # Randbedingungen\r\n p_out = Constant(0.0)\r\n bcs = [ DirichletBC(V, p_out, meshData.boundaries, i) for i in range(1, 5) ]\r\n\r\n # Variationsproblem definieren\r\n dx = Measure('dx',\r\n domain=meshData.mesh,\r\n subdomain_data=meshData.subdomains)\r\n\r\n # Loesung der ersten Gleichung berechnen\r\n p_trial = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n a = lhs(inner(grad(p_trial), grad(v))*dx)\r\n l = rhs(-y[1]*v*dx + z[1]*v*dx)\r\n\r\n p_1 = Function(V)\r\n solve(a == l, p_1, bcs)\r\n\r\n # Loesung der zweiten Gleichung berechnen\r\n p_trial = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n a = lhs(inner(grad(p_trial), grad(v))*dx)\r\n l = rhs(p_1*v*dx)\r\n\r\n p_2 = Function(V)\r\n solve(a == l, p_2, bcs)\r\n\r\n # Rueckgabe der Loesung\r\n # ACHTUNG: ERSTER EINTRAG VON P ENTSPRICHT ZWEITEM EINTRAG VON Y UND VICE VERSA (muss noch geaendert werden)\r\n p = [p_2, p_1]\r\n return p\r\n\r\n\r\ndef calc_lame_par(meshData, mu_min_value, mu_max_value):\r\n \"\"\"\r\n Berechnet die lokal variierenden Lame-Parameter mu_elas\r\n \"\"\"\r\n\r\n # Funktionen Raum\r\n V = FunctionSpace(meshData.mesh, \"P\", 1)\r\n\r\n # Randbedingungen\r\n mu_min = Constant(mu_min_value)\r\n mu_max = Constant(mu_max_value)\r\n bcs = ([ DirichletBC(V, mu_min, meshData.boundaries, i) for i in range(1, 5) ]\r\n + [ DirichletBC(V, mu_max, meshData.boundaries, i) for i in range(5, 7) ])\r\n\r\n # Variationsproblem definieren\r\n dx = Measure('dx',\r\n domain=meshData.mesh,\r\n subdomain_data=meshData.subdomains)\r\n\r\n mu_elas = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n f = Expression(\"0.0\", degree=1)\r\n\r\n a = inner(grad(mu_elas), grad(v))*dx\r\n l = f*v*dx\r\n\r\n # Loesung berechnen\r\n mu_elas = Function(V, name=\"lame_par\")\r\n solve(a == l, mu_elas, bcs)\r\n\r\n # Rueckgabe des Lame-Parameters\r\n return mu_elas\r\n\r\n\r\ndef solve_linelas(meshData, p, y, z, fValues, mu_elas, nu, zeroed = True):\r\n \"\"\"\r\n Loest lineare Elastizitaetsgleichung ohne Variationsungleichung\r\n \"\"\"\r\n\r\n # Funktionenraum\r\n V = VectorFunctionSpace(meshData.mesh, \"P\", 1, dim=2)\r\n\r\n # Randbedingungen\r\n u_out = Constant((0.0, 0.0))\r\n bcs = [ DirichletBC(V, u_out, meshData.boundaries, i) for i in range (1, 5) ]\r\n\r\n\r\n U = TrialFunction(V)\r\n v = TestFunction(V)\r\n\r\n LHS = bilin_a(meshData, U, v, mu_elas)\r\n\r\n F_elas = shape_deriv(meshData, p, y, z, fValues, nu, v)\r\n\r\n # Alle die keine Traeger am innerend Rand haben auf 0 setzen\r\n if(zeroed): F_elas[meshData.indNotIntBoundary] = 0.0\r\n\r\n for bc in bcs:\r\n bc.apply(LHS)\r\n bc.apply(F_elas)\r\n\r\n # Norm der assemblierten rechten Seite wegen Abbruchbedingung\r\n nrm_f_elas = norm(F_elas, 'L2', meshData.mesh)\r\n\r\n # Berechne Loesung\r\n U = Function(V, name=\"deformation_vec\")\r\n solve(LHS, U.vector(), F_elas)\r\n\r\n # Rueckgabe des Gradientenvektorfeldes U und der Abbruchbedingung\r\n return U, nrm_f_elas\r\n\r\n\r\ndef bilin_a(meshData, U, V, mu_elas):\r\n \"\"\"\r\n Berechnet den Wert der Bilinearform (lin. El.) fuer gegebene Vektorfelder U, V\r\n Beide Vektorfelder muessen auf dem selben Mesh definiert sein\r\n Lame parameter lambda = 0\r\n \"\"\"\r\n\r\n dx = Measure(\"dx\", domain=meshData.mesh, subdomain_data=meshData.subdomains)\r\n\r\n epsilon_V = (1./2.)*sym(nabla_grad(V))\r\n sigma_U = mu_elas*sym(nabla_grad(U))\r\n\r\n a = inner(sigma_U, epsilon_V)*dx('everywhere')\r\n value = assemble(a)\r\n\r\n return value\r\n\r\n\r\ndef bfgs_step(meshData, memory, mu_elas, q_target):\r\n \"\"\"\r\n berechnet aus einer BFGS-memory eine Mesh-Deformation q mittels double-loop-L-BFGS-Verfahren, welche zu memory.grad[0] gehoert\r\n benoetigt memory.grad[0] als aktuellen Gradienten, memory.deformation[0] als aktuell neueste Deformation\r\n Output q ist eine Fenics-Funktion der Art Function(V), V=VectorFunctionSpace(mesh, \"P\", 1, dim=2)\r\n \"\"\"\r\n\r\n if isinstance(meshData, MeshData): pass\r\n else: raise SystemExit(\"bfgs_step benoetigt Objekt der MeshData-Klasse als Input!\")\r\n\r\n if isinstance(memory, bfgs_memory): pass\r\n else: raise SystemExit(\"bfgs_step benoetigt Objekt der BFGS-Memory-Klasse als Input!\")\r\n\r\n V = VectorFunctionSpace(meshData.mesh, \"P\", 1, dim=2)\r\n q = Function(V)\r\n q.vector()[:] = q_target\r\n alpha = np.zeros(memory.length)\r\n\r\n diff_grad = Function(V)\r\n first_diff_grad = Function(V)\r\n\r\n\r\n if(memory.step_nr + 1 >= memory.length):\r\n # bei voll besetzter memory werden alle Eintraege verwendet\r\n\r\n for i in range(memory.length-1):\r\n # Vorwaertsschleife\r\n i = i+1\r\n diff_grad.vector()[:] = (memory.initialize_grad(meshData, i-1).vector() - memory.initialize_grad(meshData, i).vector())\r\n alpha[i] = bilin_a(meshData, memory.initialize_defo(meshData, i-1), q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, i-1), mu_elas)\r\n q.vector()[:] = q.vector() - float(alpha[i])*diff_grad.vector()\r\n\r\n # Reskalierung von q\r\n first_diff_grad.vector()[:] = (memory.initialize_grad(meshData, 0).vector() - memory.initialize_grad(meshData, 1).vector())\r\n gamma = bilin_a(meshData, first_diff_grad, memory.initialize_defo(meshData, 0), mu_elas) / bilin_a(meshData, first_diff_grad, first_diff_grad, mu_elas)\r\n q.vector()[:] = gamma*q.vector()\r\n\r\n for i in range(memory.length-1):\r\n # Rueckwaertsschleife\r\n i = i+1\r\n diff_grad.vector()[:] = (memory.initialize_grad(meshData, -(i+1)).vector() - memory.initialize_grad(meshData, -i).vector())\r\n beta = bilin_a(meshData, diff_grad, q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, -(i+1)), mu_elas)\r\n q.vector()[:] = q.vector() + (float(alpha[-i]) - beta)*memory.initialize_defo(meshData, -(i+1)).vector()\r\n\r\n elif(memory.step_nr == 0):\r\n # der erste BFGS-Schritt ist ein Gradientenschritt, U Gradient ist in negativer Richtung\r\n q.vector()[:] = -1.*q.vector().get_local()\r\n return q\r\n\r\n else:\r\n # bei nicht voll besetzter memory werden lediglich die besetzten Eintraege verwendet\r\n\r\n for i in range(memory.step_nr):\r\n # Vorwaertsschleife\r\n i = i+1\r\n diff_grad.vector()[:] = (memory.initialize_grad(meshData, i-1).vector() - memory.initialize_grad(meshData, i).vector())\r\n alpha[i] = bilin_a(meshData, memory.initialize_defo(meshData, i-1), q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, i-1), mu_elas)\r\n q.vector()[:] = q.vector() - float(alpha[i])*diff_grad.vector()\r\n\r\n # Reskalierung von q\r\n first_diff_grad.vector()[:] = (memory.initialize_grad(meshData, 0).vector() - memory.initialize_grad(meshData, 1).vector())\r\n gamma = bilin_a(meshData, first_diff_grad, memory.initialize_defo(meshData, 0), mu_elas) / bilin_a(meshData, first_diff_grad, first_diff_grad, mu_elas)\r\n q.vector()[:] = gamma*q.vector()\r\n\r\n for i in range(memory.step_nr):\r\n # Rueckwaertsschleife\r\n shift = (memory.length-1) - memory.step_nr\r\n i = i+1\r\n diff_grad.vector()[:] = (memory.initialize_grad(meshData, -(i+1)-shift).vector() - memory.initialize_grad(meshData, -i-shift).vector())\r\n beta = bilin_a(meshData, diff_grad, q, mu_elas) / bilin_a(meshData, diff_grad, memory.initialize_defo(meshData, -(i+1)-shift), mu_elas)\r\n q.vector()[:] = q.vector() + (float(alpha[-i-shift]) - beta)*memory.initialize_defo(meshData, -(i+1)-shift).vector()\r\n\r\n q.vector()[:] = -1. * q.vector()\r\n return q\r\n\r\n","sub_path":"shape_bib_polyharmonic.py","file_name":"shape_bib_polyharmonic.py","file_ext":"py","file_size_in_byte":21003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"391077727","text":"from machine import Pin, I2C\n# import bme280_float as bme280\nimport BME280\n\ni2c = I2C(scl=Pin(5), sda=Pin(4))\n# bme = bme280.BME280(i2c=i2c)\n# print(bme.values)\n\nbme = BME280.BME280(i2c=i2c)\ntemp = bme.temperature\nhum = bme.humidity\npres = bme.pressure\n\n# uncomment for temperature in Fahrenheit\ntemp = (bme.read_temperature()/100) * (9/5) + 32\ntemp = str(round(temp, 2)) + 'F'\n\nsensor_readings = {'value1': temp, 'value2': hum, 'value3': pres}\nprint(sensor_readings)\n","sub_path":"bme280/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"451619465","text":"# a quick-and-dirty module to provide\n# pseudo-aliveness by discovering open\n# SimRobot sockets (Linux-only for now)\n\nfrom datetime import datetime\n\nimport platform\nimport sys\nimport time\n\nfrom .models import Robot\nfrom .models import RobotInfo\nfrom .models import RobotList\n\n\ndef socket_paths():\n # This whole function feels terrible,\n # any better idea? --martin\n\n if platform.system() != \"Linux\":\n print(\"warning: SimRobot pseudo-aliveness \"\n \"is only supported on Linux!\",\n file=sys.stderr)\n return []\n\n # Look for open unix sockets\n with open(\"/proc/net/unix\", 'r') as f:\n lines = f.readlines()\n\n # Keep lines containing \"simrobot\"\n lines = filter(lambda line: \"simrobot\" in line, lines)\n\n # Extract socket paths\n # (like /tmp/simrobot/robot4/config, /tmp/simrobot/robot4/debug)\n lines = map(lambda line: line.split()[-1], lines)\n\n # Throw away /config, /debug and remove duplicates\n lines = [l.replace(\"/config\", '').replace(\"/debug\", '')\n for l in lines]\n lines = list(set(lines))\n\n lines.sort()\n return lines\n\n\ndef virtual_robots():\n robots = RobotList()\n\n for socket_path in socket_paths():\n robot = Robot(\n info=RobotInfo(\n head_num=0,\n body_num=0,\n player_num=0\n ),\n ip_lan=socket_path,\n ip_wlan=socket_path,\n )\n robot.set_aliveness(\n alive=True,\n lan=True,\n wlan=True,\n timestamp=datetime.now(),\n address=socket_path,\n player_num=0\n )\n robots.append(robot)\n\n return robots\n","sub_path":"tools/libPython/hulks/aliveness/simrobot.py","file_name":"simrobot.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"312662061","text":"# -*- coding: utf-8 -*-\n# Copyright 2015 Yelp Inc.\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.\nfrom datetime import date, timedelta\nimport gzip\nimport logging\nimport os\nimport shutil\nimport tempfile\n\nimport staticconf.testing\nimport testifycompat as T\n\nfrom clog.handlers import CLogHandler, DEFAULT_FORMAT\nfrom clog.handlers import get_scribed_logger\nfrom clog.loggers import GZipFileLogger, MockLogger\nfrom clog.utils import scribify\n\n\nfirst_line = 'First Line.'\nsecond_line = 'Second Line.'\ncomplete_line = '%s\\n%s\\n' % (first_line, second_line)\n\n\nclass TestGZipFileLogger(object):\n\n @T.setup_teardown\n def setup_log_dir(self):\n self.log_dir = tempfile.mkdtemp()\n with staticconf.testing.MockConfiguration(log_dir=self.log_dir,\n namespace='clog'):\n yield\n shutil.rmtree(self.log_dir)\n\n def _open_and_remove(self, filename):\n gz_fh = gzip.open(filename)\n content = gz_fh.read()\n gz_fh.close()\n os.remove(filename)\n return content.decode('utf8')\n\n def test_no_day(self):\n logger = GZipFileLogger()\n stream = 'first'\n logger.log_line(stream, first_line)\n logger.log_line(stream, second_line)\n logger.close()\n\n log_filename = GZipFileLogger.get_filename(stream)\n content = self._open_and_remove(log_filename)\n T.assert_equal(content, complete_line)\n\n def test_single_day(self):\n stream = 'second'\n day = date.today()\n logger = GZipFileLogger(day=day)\n logger.log_line(stream, first_line)\n logger.log_line(stream, second_line)\n logger.close()\n\n log_filename = GZipFileLogger.get_filename(stream, day=day)\n content = self._open_and_remove(log_filename)\n T.assert_equal(content, complete_line)\n\n def test_multi_day(self):\n stream = 'multi'\n first_day = date.today()\n second_day = date.today() + timedelta(days=1)\n\n for day in (first_day, second_day):\n logger = GZipFileLogger(day=day)\n logger.log_line(stream, first_line)\n logger.log_line(stream, second_line)\n logger.close()\n\n for day in (first_day, second_day):\n log_filename = GZipFileLogger.get_filename(stream, day=day)\n content = self._open_and_remove(log_filename)\n T.assert_equal(content, complete_line)\n\n\nclass MyError(Exception):\n pass\n\n\nclass CLogTestBase(T.TestCase):\n SIMPLE_FORMAT=\"%(message)s\"\n STREAM_NAME='unit_test'\n\n @T.setup\n def _create_logger(self):\n self.logger = MockLogger()\n self.handler = CLogHandler(stream=self.STREAM_NAME, logger=self.logger)\n self.handler.setFormatter(logging.Formatter(self.SIMPLE_FORMAT))\n self.log_instance = logging.getLogger(self.STREAM_NAME)\n self.log_instance.handlers = [self.handler]\n\n\nclass CLogHandlerTest(CLogTestBase):\n\n def test_handler_preserves_exceptions(self):\n \"\"\"Test exception preservation a la 18848\"\"\"\n # set the default formatter\n self.log_instance.handlers[0].setFormatter(logging.Formatter(DEFAULT_FORMAT))\n try:\n raise MyError(\"foobar\")\n except MyError:\n self.log_instance.exception(\"example log message\")\n T.assert_equal(1, len([message for message in self.logger.list_lines(self.STREAM_NAME) if \"example log message\" in message]))\n\n\nclass MiscellaneousCLogMethodsTest(CLogTestBase):\n def test_get_scribed_logger(self):\n log = get_scribed_logger(\"unit_test_scribed\", logging.INFO, fmt=self.SIMPLE_FORMAT, clogger_object=self.logger)\n log.info(\"This is a test\")\n T.assert_in(\"This is a test\", self.logger.list_lines(\"unit_test_scribed\"))\n self.logger.clear_lines(\"unit_test_scribed\")\n # test that we don\"t double-add\n log = get_scribed_logger(\"unit_test_scribed\", logging.INFO, fmt=self.SIMPLE_FORMAT, clogger_object=self.logger)\n log.info(\"This is a test\")\n T.assert_equal(1, len([message for message in self.logger.list_lines(\"unit_test_scribed\") if message == \"This is a test\"]))\n\n def test_scribify(self):\n T.assert_equal(scribify(\"this is a test\"), \"this_is_a_test\")\n T.assert_equal(scribify(\"this\\0is a-test\\n\\n\"), \"this_is_a-test__\")\n T.assert_equal(scribify(u'int\\xe9rna\\xe7ionalization'), 'int_rna_ionalization')\n","sub_path":"tests/test_clog.py","file_name":"test_clog.py","file_ext":"py","file_size_in_byte":4910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138143320","text":"import sys\nfrom dateutil import parser\nfrom os.path import dirname, abspath, join\nimport pandas as pd\n\nsys.path.insert(0, dirname(dirname(dirname(abspath(__file__)))))\n\nfrom datetime import datetime\nfrom services.reg_service.reg_service import RegService\n\nfrom fleets.battery_inverter_fleet.battery_inverter_fleet import BatteryInverterFleet\nfrom fleets.electric_vehicles_fleet.electric_vehicles_fleet import ElectricVehiclesFleet\nfrom grid_info import GridInfo\nfrom datetime import datetime\n\nfrom pdb import set_trace as bp \n\n\nif __name__ == '__main__':\n\n # Battery Inverter Fleet\n grid = GridInfo('Grid_Info_DATA_2.csv')\n battery_inverter_fleet = BatteryInverterFleet(GridInfo=grid, model_type='ERM')\n battery_inverter_fleet.is_autonomous = False\n battery_inverter_fleet.VV11_Enabled = False\n battery_inverter_fleet.FW21_Enabled = False\n\n\n # Test with EV.\n # Time stamp to start the simulation\n dt = 2 # time step (in seconds) Is this used anywhere in the EV model?\n ts = datetime(2017, 1, 1, 0, 0, 00, 000000)\n\n fleet_test = ElectricVehiclesFleet(grid, ts)\n fleet_test.is_autonomous = False\n fleet_test.is_P_priority = True\n fleet_test.dt = dt\n\n # Test with PV.\n from fleets.PV.PV_Inverter_Fleet import PVInverterFleet\n fleet = PVInverterFleet(GridInfo=grid)\n\n\n service = RegService()\n service.fleet = battery_inverter_fleet\n\n # For a short test run, can use code below instead of running for the full year,\n # which takes ~1.5 hours per month to run.\n monthtimes = dict({\n 'January': [\"2017-01-01 00:00:00\", \"2017-01-31 23:59:58\"],\n })\n\n # Generate monthly start and end times to loop through\n # monthtimes = dict({\n # 'January': [\"2017-01-01 00:00:00\", \"2017-01-31 23:59:58\"],\n # 'February': [\"2017-02-01 00:00:00\", \"2017-02-28 23:59:58\"],\n # 'March': [\"2017-03-01 00:00:00\", \"2017-03-30 23:59:58\"],\n # 'April': [\"2017-04-01 00:00:00\", \"2017-04-30 23:59:58\"],\n # 'May': [\"2017-05-01 00:00:00\", \"2017-05-31 23:59:58\"],\n # 'June': [\"2017-06-01 00:00:00\", \"2017-06-30 23:59:58\"],\n # 'July': [\"2017-07-01 00:00:00\", \"2017-07-31 23:59:58\"],\n # 'August': [\"2017-08-01 00:00:00\", \"2017-08-31 23:59:58\"],\n # 'September': [\"2017-09-01 00:00:00\", \"2017-09-30 23:59:58\"],\n # 'October': [\"2017-10-01 00:00:00\", \"2017-10-31 23:59:58\"],\n # 'November': [\"2017-11-01 00:00:00\", \"2017-11-30 23:59:58\"],\n # 'December': [\"2017-12-01 00:00:00\", \"2017-12-31 23:59:58\"]\n # })\n\n # Get name of fleet for inclusion in results file names\n fleet_name = service.fleet.__class__.__name__\n\n # To run for either \"Traditional\" or \"Dynamic\" regulation, specify \"service_type\" in the for-loop below accordingly.\n startTime = datetime.now()\n for service_type in ['Dynamic']:\n all_results = pd.DataFrame(columns=['performance_score', 'hourly_integrated_MW',\n 'mileage_ratio', 'Regulation_Market_Clearing_Price(RMCP)',\n 'Reg_Clearing_Price_Credit'])\n for month in monthtimes.keys():\n print('Starting ' + str(month) + ' ' + service_type + ' at ' + datetime.now().strftime('%H:%M:%S'))\n fleet_response = service.request_loop(service_type=service_type,\n start_time=parser.parse(monthtimes[month][0]),\n end_time=parser.parse(monthtimes[month][1]),\n clearing_price_filename='historical-ancillary-service-data-2017.xls',\n fleet_name=fleet_name)\n month_results = pd.DataFrame.from_dict(fleet_response, orient='index')\n all_results = pd.concat([all_results, month_results])\n print(' Finished ' + str(month) + ' ' + service_type)\n # Fix formatting of all_results dataframe to remove tuples\n all_results[['Perf_score', 'Delay_score', 'Corr_score', 'Prec_score']] = all_results['performance_score'].apply(pd.Series)\n all_results[['MCP', 'REG_CCP', 'REG_PCP']] = all_results['Regulation_Market_Clearing_Price(RMCP)'].apply(pd.Series)\n all_results[['Reg_Clr_Pr_Credit', 'Reg_RMCCP_Credit', 'Reg_RMPCP_Credit']] = all_results['Reg_Clearing_Price_Credit'].apply(pd.Series)\n all_results.drop(columns=['performance_score', 'Regulation_Market_Clearing_Price(RMCP)', 'Reg_Clearing_Price_Credit'],\n inplace=True)\n print('Writing result .csv')\n file_dir = join(dirname(abspath(__file__)), 'results')\n all_results.to_csv(file_dir + datetime.now().strftime('%Y%m%d') + '_annual_hourlyresults_' + service_type + '_' + fleet_name + '.csv')\n print('Duration:')\n print(datetime.now() - startTime)","sub_path":"src/services/reg_service/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"607164110","text":"import cv2\nfrom keras import backend as K\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\n\n# load Image\nf = h5py.File('D:/data/HDF5/face_Doberman.hdf5', 'r') # Dog Image\nx = f['doberman'][10]\n# x = cv2.imread('D:\\image/image4.jpg')\n# x = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)\nx = cv2.resize(x, dsize = (256, 256), interpolation = cv2.INTER_LINEAR)#/255.\nx = x.reshape(-1, 256, 256, 3)\n\ny = cv2.imread('D:/data/Gan/FFHQ/02000/02010.png') # Human Image\ny = cv2.cvtColor(y, cv2.COLOR_BGR2RGB)\ny = cv2.resize(y, dsize=(256, 256), interpolation = cv2.INTER_LINEAR)/ 255.\ny = y.reshape(-1, 256, 256, 3)\n\n# keras backend를 사용하기 위해서 numpy -> tensor로 변환\nx = tf.convert_to_tensor(x, np.float32)\ny = tf.convert_to_tensor(y, np.float32)\n\naxis = -1\nepsilon=1e-3\n\ninput_shape = K.int_shape(x)\n# print(input_shape) # (400, 750, 3)\n\nreduction_axes = list(range(0, len(input_shape)))\nprint(reduction_axes) # [0, 1, 2]\n\nif axis is not None:\n del reduction_axes[axis]\n\ndel reduction_axes[0]\n\nprint(reduction_axes)\n\ngamma = K.std(y, reduction_axes, keepdims=True) + epsilon # S(y)\nbeta = K.mean(y, reduction_axes, keepdims=True) # mean(y)\nprint(beta.shape) # (1, 1, 1, 3)\nprint(gamma.shape) # (1, 1, 1, 3)\n\n# Adain\nmean = K.mean(x, reduction_axes, keepdims=True) # mean(x)\nstddev = K.std(x, reduction_axes, keepdims=True) + epsilon # S(x)\nnormed = (x - mean) / stddev\n\nprint(mean.shape) # (1, 1, 1, 3)\nprint(stddev.shape) # (1, 1, 1, 3)\nprint(normed.shape) # (1, 400, 750, 3)\n\n# result\nimage = normed * gamma + beta\nprint(image.shape) # (1, 400, 750, 3)\n\n\nnormed = K.reshape(normed, (256, 256, 3))\n\nx = K.reshape(x, (256, 256, 3))\ny = K.reshape(y, (256, 256, 3))\nimage = K.reshape(image, (256, 256, 3))\n\n# show Image\nfig, axes = plt.subplots(1, 3)\n\naxes[0].imshow(x)\naxes[1].imshow(y)\naxes[2].imshow(image)\n\naxes[0].set_title('Contents Image')\naxes[1].set_title('Style Image')\naxes[2].set_title('Mix_Style')\n\naxes[0].axis('off')\naxes[1].axis('off')\naxes[2].axis('off')\n\nplt.show()","sub_path":"project/project02/study/AdaIN_sample.py","file_name":"AdaIN_sample.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129698942","text":"import numpy, random\r\n\r\nclass Board:\r\n\r\n def __init__(self, size=(3,3)):\r\n self.size = size\r\n self.board = numpy.zeros(size, int)\r\n self.score = 0\r\n self.moved = False\r\n\r\n def getBoard(self):\r\n return self.board\r\n\r\n def getSize(self):\r\n return self.size\r\n\r\n def getScore(self):\r\n return self.score\r\n\r\n def isEmpty(self, x, y):\r\n if (x < 0 or x > self.size[0])\\\r\n or (y < 0 or y > self.size[1]):\r\n print(\"Error from isEmpty(), called with \", x, \", \", y)\r\n exit()\r\n if self.board[y][x] == 0:\r\n return True\r\n else:\r\n return False\r\n\r\n def isOver(self):\r\n for y in range(self.size[0]):\r\n for x in range(self.size[1]):\r\n if y > 0 and self.board[y-1][x] == self.board[y][x]:\r\n #check y\r\n return False\r\n if self.board[y][x] == 0:\r\n return False\r\n if x != 2 and self.board[y][x] == self.board[y][x+1]:\r\n return False\r\n return True\r\n\r\n def resetBoard(self):\r\n self.board = numpy.zeros(self.size, int)\r\n self.score = 0\r\n #randomize\r\n tile = 2\r\n x = random.randint(0, self.size[0] - 1)\r\n y = random.randint(0, self.size[1] - 1)\r\n self.board[x][y] = tile\r\n\r\n self.addRandomTiles()\r\n\r\n def addRandomTiles(self):\r\n x = 0\r\n y = 0\r\n tile = random.randint(-1, 1)\r\n if tile > 0:\r\n tile = 2\r\n else:\r\n tile = 4\r\n while not self.isEmpty(x, y):\r\n x = random.randint(0, self.size[0] - 1)\r\n y = random.randint(0, self.size[1] - 1)\r\n self.board[x][y] = tile\r\n\r\n def compressing_up(self):\r\n clone_board = self.board\r\n #starting from the top\r\n for y in range(1, self.size[0]):\r\n for x in range(self.size[1]):\r\n if clone_board[y][x] != 0:\r\n if clone_board[y-1][x] == 0:\r\n #got place to go\r\n clone_board[y-1][x] = clone_board[y][x]\r\n clone_board[y][x] = 0\r\n self.moved = True\r\n return clone_board\r\n\r\n def merge_up(self):\r\n clone_board = self.board\r\n for y in range(1, self.size[1]):\r\n for x in range(self.size[0]):\r\n if clone_board[y][x] != 0:\r\n if clone_board[y][x] == clone_board[y-1][x]:\r\n clone_board[y-1][x] = clone_board[y-1][x] * 2\r\n clone_board[y][x] = 0\r\n self.moved = True\r\n self.score += clone_board[y-1][x]\r\n return clone_board\r\n\r\n def action_up(self):\r\n self.moved = False\r\n self.board = self.compressing_up()\r\n self.board = self.merge_up()\r\n self.board = self.compressing_up()\r\n return self.moved\r\n\r\n def action_down(self):\r\n #mirror\r\n self.board = numpy.flipud(self.board)\r\n vm = self.action_up()\r\n #mirror again\r\n self.board = numpy.flipud(self.board)\r\n return vm\r\n\r\n def action_left(self):\r\n #turn right\r\n self.board = numpy.rot90(self.board, 1, (1,0))\r\n #now it face upward\r\n vm = self.action_up()\r\n #turn it back\r\n self.board = numpy.rot90(self.board)\r\n return vm\r\n\r\n def action_right(self):\r\n # turn left\r\n self.board = numpy.rot90(self.board)\r\n # now it face upward\r\n vm = self.action_up()\r\n # turn it back\r\n self.board = numpy.rot90(self.board, 1, (1, 0))\r\n return vm\r\n\r\n\r\nif __name__ == \"__main__\":\r\n board = Board()\r\n board.resetBoard()\r\n while True:\r\n\r\n if board.isOver():\r\n print(\"##########\")\r\n print(\"Final Score: \", board.getScore())\r\n board.resetBoard()\r\n #Action\r\n valid_move = False\r\n print(board.getBoard())\r\n user = input(\"cmd: \")\r\n if user == \"w\":\r\n valid_move = board.action_up()\r\n elif user == \"s\":\r\n valid_move = board.action_down()\r\n elif user == \"a\":\r\n valid_move = board.action_left()\r\n elif user == \"d\":\r\n valid_move = board.action_right()\r\n\r\n #Add tiles\r\n if(valid_move):\r\n board.addRandomTiles()","sub_path":"2048/core_2048.py","file_name":"core_2048.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566182748","text":"from mongoengine import *\nimport common as c\nfrom datetime import datetime\nimport time\nimport json\nimport cluster\n\nclass Event(Document):\n\n meta = {\n 'allow_inheritance': False,\n 'indexes' : ['user_id', 'loc'] #should automatically create a 2d geospatial index\n }\n\n user_id = StringField(required = True) #maybe replace _id later\n loc = GeoPointField(required = True) #[lat, lon]\n time = DateTimeField(required = True) #from timestamp\n timestamp = IntField(required = True)\n\n @staticmethod\n def add(user_id, lat, lon, timestamp):\n existing_event = Event.objects(user_id = user_id).first()\n if existing_event is not None:\n existing_event.delete()\n dt = datetime.fromtimestamp(float(timestamp))\n event = Event(user_id = user_id, loc = [lat, lon], timestamp = timestamp, time = dt)\n event.save()\n\n @staticmethod\n def get_group(user_id):\n e = Event.objects(user_id = user_id).first()\n if e:\n nearby = Event.objects( \n __raw__ = { 'loc' : { '$within' : \n {\"$center\" : [e.loc, c.RADIUS_THRESHOLD]}\n }\n } \n ).limit(c.MAX_GROUP_SIZE).all()\n in_time_range = lambda e2 : abs(e.timestamp - e2.timestamp) < c.TIME_DIFF_THRESHOLD\n nearby = filter(in_time_range, nearby)\n return json.dumps([e.user_id for e in nearby], ensure_ascii=True).decode('ascii')\n return json.dumps([]).decode('ascii')\n\n @staticmethod\n def get_cluster(user_id):\n nearby = json.loads(Event.get_group(user_id))\n events = [Event.objects(user_id = user_id).first() for user_id in nearby]\n locs = [e.loc for e in events]\n group = zip(nearby, locs)\n cl = cluster.get_cluster(group)\n return json.dumps([uid for (uid, loc) in cl])\n","sub_path":"mongo/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88485618","text":"import crabber\nimport os\nimport random\nimport sys\nfrom typing import Optional\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\n\n\ndef load_last_checked(base_dir: Optional[str] = None) -> str:\n # Load ratings from disk\n last_checked_file = os.path.join(base_dir or '', 'last_checked.txt')\n if os.path.exists(last_checked_file):\n with open(last_checked_file, 'r') as f:\n last_checked = f.read()\n return last_checked\n return '0'\n\n\ndef write_last_checked(last_checked: str, base_dir: Optional[str] = None):\n last_checked_file = os.path.join(base_dir or '', 'last_checked.txt')\n with open(last_checked_file, 'w') as f:\n f.write(str(last_checked))\n\n\ndef load_ratings(base_dir: Optional[str] = None):\n # Load ratings from disk\n ratings = {'image': [], 'no_image': []}\n with open(os.path.join(base_dir or '', 'no_image.txt'), 'r') as f:\n ratings['no_image'] = [rating.strip()\n for rating in f.read().splitlines()\n if rating.strip()\n and not rating.strip().startswith('#')]\n with open(os.path.join(base_dir or '', 'ratings.txt'), 'r') as f:\n ratings['image'] = [rating.strip()\n for rating in f.read().splitlines()\n if rating.strip()\n and not rating.strip().startswith('#')]\n\n return ratings\n\n\ndef get_mentions(since_ts: Optional[int] = None):\n global api\n\n mentions = api.get_current_user().get_mentions(since_ts=since_ts)\n return mentions\n\n\ndef get_rating(image=True):\n global ratings\n return random.choice(ratings['image' if image else 'no_image'])\n\n\n# Local testing\nif '--test' in sys.argv:\n api_key = os.environ.get('DOGRATER_LOCAL_KEY')\n access_token = os.environ.get('DOGRATER_LOCAL_TOKEN')\n base_url = 'http://localhost'\nelse:\n api_key = os.environ.get('DOGRATER_DEPLOY_KEY')\n access_token = os.environ.get('DOGRATER_DEPLOY_TOKEN')\n base_url = 'https://crabber.net'\n\n# Connect to Crabber\napi = crabber.API(api_key, access_token=access_token, base_url=base_url)\n\n# Get username of authenticated user\nratings = load_ratings(script_dir)\nlast_checked = load_last_checked(script_dir)\n\n# Respond to new mentions\nmentions = get_mentions(since_ts=last_checked)\nfor mention in reversed(mentions):\n last_checked = mention.timestamp + 1\n print(f'{mention.timestamp} @{mention.author.username:10} | {mention.content}')\n\n response = get_rating(image=mention.image)\n mention.reply(response)\n\n# Save state\nwrite_last_checked(last_checked, script_dir)\n","sub_path":"dog_rater.py","file_name":"dog_rater.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53790788","text":"#!/usr/bin/env python\n\n''' Two classes that constitute a hypergraph (forest): Node and Hyperedge\n On top of these, there is a separate Forest class in forest.py which collects the nodes,\n\tand deals with the loading and dumping of forests.\n\n\timplementation details:\n\t1. node has a local score \"node_score\" and hyperedge \"edge_score\".\n\t2. and they both have \"beta\" \\'s.\n\n\tthis design is quite different from the original, where only edge-prob is present.\n\t\n'''\n\nimport sys, os, re\nimport math\nimport copy\n\n#sys.path.append(os.environ[\"NEWCODE\"])\n\n#import mycode\nimport heapq\n\nlogs = sys.stderr\n\nfrom tree import Tree\n\nfrom svector import Vector as FVector\nfrom utility import symbol\n\nfrom deptree import DepTree\n\nclass Node(Tree):\n\t''' Node is based on Tree so that it inherits various functions like binned_len and is_terminal. '''\n\n\tdef copy(self):\n\t\treturn copy.deepcopy(self)\n\t\n\tdef __init__(self, iden, labelspan, size, fvector, sent):\n\t\t# NP [0-3]\n\t\tself.iden = iden\n\t\t\n\t\tlabel, span = labelspan.split()\n\t\tself.span = tuple(map(int, span[1:-1].split(\"-\")))\n\t\t\n\t\tif label[-1] == \"*\":\n\t\t\tlabel = label[:-1]\n\t\t\tself._spurious = True\n\t\telse:\n\t\t\tself._spurious = False\n\t\t\t\n\t\tself.label = \"TOP\" if label == \"S1\" else label\n\t\tself.label = symbol(self.label)\n\t\tself.edges = []\n\t\t\n\t\tword = sent[self.span[0]] if (size == 0) else None\n\t\tself.prepare_stuff(label, word)\n\n\t\tself.fvector = fvector\n\n\t\tself._root = False\n\n\t\tself._bin_len = None\n\n\n\tdef prepare_kbest(self):\n\t\tself.klist = []\n\t\tself.kset = set()\n\t\tself.fixed = False\n\t\tif self.is_terminal():\n\t\t\tself.klist = [self.bestres]\n\t\t\tself.kset.add(self.besttree)\n\t\t\tself.fixed = True\n\t\t\t \n\t\tself.bestedge = None\n\t\tself.cand = None\n\n\tdef mapped_span(self, mapping):\n\t\treturn (mapping[self.span[0]], mapping[self.span[1]]) \n\t\n\tdef labelspan(self, separator=\":\", include_id=True):\n\t\tss = \"%s%s \" % (self.iden, separator) if include_id else \"\"\n\t\tlbspn = \"%s [%d-%d]\" % (self.label + (\"*\" if self.is_spurious() else \"\"), \\\n\t\t\t\t\t\t\t\tself.span[0], self.span[1])\n\t\treturn ss + lbspn\n\n\t__str__ = labelspan\n\t__repr__ = __str__\n\t\n\tdef is_spurious(self):\n\t\treturn self._spurious\n\n\tdef sp_terminal(self):\n\t\treturn self.is_spurious() and self.edges[0].subs[0].is_terminal()\n\n\tdef add_edge(self, hyperedge):\n\t\tself.edges.append(hyperedge)\n\t\thyperedge.node = self ## important backpointer!\n\n\tdef assemble(self, subtrees):\n\t\t'''this is nice. to be used by k-best tree generation.'''\n##\t\tt = Tree(self.label, self.span, subs=subtrees, sym=False) if not self._spurious else subtrees[0]\n\t\tif self._root:\n\t\t\tt = subtrees[0]\n\t\telse:\n\t\t\tleft, right = subtrees[0], subtrees[1]\n\t\t\taction = (2, ) if left.headidx == int(self.label) else (1, )\n\t\t\tt = left.combine(right, action)\n\t\t\t\n#\t\t\tt = DepTree(int(self.label), [left], [right])\n\t\t\t\n\t\tassert t is not None, (self.label, self.span, subtrees, self._spurious)\n\t\tif self._root:\n\t\t\t## notice that, roots are spurious! so...\n\t\t\tpass #t.set_root(True)\n\t\treturn t\n\n\tdef this_tree(self):\n\t\t## very careful: sym=False! do not symbolize again\n##\t\treturn Tree(self.label, self.span, wrd=self.word, sym=False)\n\t\treturn DepTree(int(self.label))\n\n\tdef bestparse(self, weights=FVector(\"0=-1\"), dep=0):\n\t\t'''now returns a triple (score, tree, fvector) '''\n\t\t\n\t\tif self.bestres is not None:\n\t\t\treturn self.bestres\n\n\t\tself.node_score = self.fvector.dot(weights)\n\t\tif self._terminal:\n\t\t\tself.beta = self.node_score\n\t\t\tself.besttree = self.this_tree()\n\t\t\tself.bestres = (self.node_score, self.besttree, FVector(self.fvector)) ## caution copy\n\n\t\telse:\n\n\t\t\tself.bestedge = None\n\t\t\tfor edge in self.edges:\n\t\t\t\t## weights are attached to the forest, shared by all nodes and hyperedges\n\t\t\t\tscore = edge.edge_score = edge.fvector.dot(weights)\n\t\t\t\tfvector = FVector(edge.fvector) ## N.B.! copy!\n\t\t\t\tsubtrees = []\n\t\t\t\tfor sub in edge.subs:\n\t\t\t\t\tsc, tr, fv = sub.bestparse(weights, dep+1)\n\t\t\t\t\tscore += sc\n\t\t\t\t\tfvector += fv\n\t\t\t\t\tsubtrees.append(tr)\n\n\t\t\t\tedge.beta = score\n\n\t\t\t\tif self.bestedge is None or score < self.bestedge.beta:\n\t\t\t\t\tself.bestedge = edge\n\t\t\t\t\tbest_subtrees = subtrees\n\t\t\t\t\tbest_fvector = fvector\n\n\t\t\tself.besttree = self.assemble(best_subtrees)\n\t\t\tself.beta = self.bestedge.beta + self.node_score\n\t\t\tbest_fvector += self.fvector ## nodefvector\n\n\t\t\tself.bestres = (self.beta, self.besttree, best_fvector)\n\n\t\treturn self.bestres\n\n\n\tdef getcandidates(self, dep=0):\n\t\tself.cand = []\n\t\tfor edge in self.edges:\n\t\t\tvecone = edge.vecone()\n\t\t\tedge.oldvecs = set([vecone])\n\t\t\tres = edge.getres(vecone, dep)\n\t\t\tassert res, \"bad at candidates\"\n\t\t\tself.cand.append( (res, edge, vecone) )\n\t\t\t\n\t\theapq.heapify (self.cand)\n\t\t\n\tdef lazykbest(self, k, dep=0):\n\t\t\n\t\tnow = len(self.klist)\n\t\tif self.fixed or now >= k:\n\t\t\treturn\n\n\t\tif self.cand is None:\n\t\t\tself.getcandidates(dep)\n\t\t\t\n\t\twhile now < k:\n\t\t\tif self.cand == []:\n\t\t\t\tself.fixed = True\n\t\t\t\treturn \n\t\t\t\n\t\t\t(score, tree, fvector), edge, vecj = heapq.heappop(self.cand)\n\t\t\tif tree not in self.kset:\n\t\t\t\t## assemble dynamically\n\t\t\t\tself.klist.append ((score, tree, fvector))\n\t\t\t\tself.kset.add(tree)\n\t\t\t\tnow += 1\n\t\t\telse:\n\t\t\t\tprint >> logs, \"*** duplicate %s %d\" % (tree.labelspan(), now)\n\t\t\t\t\n\t\t\tedge.lazynext(vecj, self.cand, dep+1)\n\t\n\nclass Hyperedge(object):\n\n\tdef unary(self):\n\t\treturn not self.head.is_root() and len(self.subs) == 1\n\n\tdef unary_cycle(self):\n\t\treturn self.unary() and self.subs[0].label == self.head.label\n\t\n\tdef __str__(self):\n\t\treturn \"%-17s -> %s \" % (self.head, \" \".join([str(x) for x in self.subs]))\n\n\tdef shorter(self):\n\t\t''' shorter form str: NP [3-5] -> DT [3-4] NN [4-5]'''\n\t\treturn \"%s -> %s \" % (self.head.labelspan(include_id=False), \\\n\t\t\t\t\t\t\t\t\" \".join([x.labelspan(include_id=False) for x in self.subs]))\t\t\t\n\n\tdef shortest(self):\n\t\t''' shortest form str: NP -> DT NN '''\n\t\treturn \"%s -> %s \" % (self.head.label, \" \".join([str(x.label) for x in self.subs]))\t\t\t\n\t\t\t\t\t\t\t \n\t__repr__ = __str__\n\n\tdef __init__(self, head, tails, fvector):\n\t\tself.head = head\n\t\tself.subs = tails\n\t\tself.fvector = fvector\n\n\tdef arity(self):\n\t\treturn len(self.subs)\n\n\tdef vecone(self):\n\t\treturn (0,) * self.arity()\n\n\tdef compatible(self, tree, care_POS=False):\n\t\tif self.arity() == tree.arity():\n\t\t\t\n\t\t\tfor sub, tsub in zip(self.subs, tree.subs):\n\t\t\t\tif not sub.compatible(tsub, care_POS):\n\t\t\t\t\treturn False\n\t\t\treturn True\n\n\tdef getres(self, vecj, dep=0):\n\t\tscore = self.edge_score \n\t\tfvector = self.fvector + self.head.fvector\n\t\tsubtrees = []\n\t\tfor i, sub in enumerate(self.subs):\n\n\t\t\tif vecj[i] >= len(sub.klist) and not sub.fixed:\n\t\t\t\tsub.lazykbest(vecj[i]+1, dep+1)\n\t\t\tif vecj[i] >= len(sub.klist):\n\t\t\t\treturn None\n\t\t\t\n\t\t\tsc, tr, fv = sub.klist[vecj[i]]\n\t\t\tsubtrees.append(tr)\n\t\t\tscore += sc\n\t\t\tfvector += fv\n\t\t\n\t\treturn (score, self.head.assemble(subtrees), fvector)\n\n\tdef lazynext(self, vecj, cand, dep=0):\n\t\tfor i in xrange(self.arity()):\n\t\t\t## vecj' = vecj + b^i (just change the i^th dimension\n\t\t\tnewvecj = vecj[:i] + (vecj[i]+1,) + vecj[i+1:]\n\n\t\t\tif newvecj not in self.oldvecs:\n\t\t\t\tnewres = self.getres(newvecj, dep)\n\t\t\t\tif newres is not None:\n\t\t\t\t\tself.oldvecs.add (newvecj)\n\t\t\t\t\theapq.heappush(cand, (newres, self, newvecj))\n\n\t@staticmethod\n\tdef _deriv2tree(edgelist, i=0):\n\t\t'''convert a derivation (a list of edges) to a tree, using assemble\n\t\t like Tree.parse, returns (pos, tree) pair\n\t\t'''\n\t\tedge = edgelist[i]\n\t\tnode = edge.head\n\t\tsubs = []\n\t\tfor sub in edge.subs:\n\t\t\tif not sub.is_terminal():\n\t\t\t\ti, subtree = Hyperedge._deriv2tree(edgelist, i+1)\n\t\t\telse:\n\t\t\t\tsubtree = sub.this_tree()\n\t\t\tsubs.append(subtree)\n\n\t\treturn i, node.assemble(subs)\n\n\t@staticmethod\n\tdef deriv2tree(edgelist):\n\t\t_, tree = Hyperedge._deriv2tree(edgelist)\n\t\treturn tree\n\t\n\t@staticmethod\n\tdef deriv2fvector(edgelist):\n\t\t'''be careful -- not only edge fvectors, but also node fvectors, including terminals'''\n\t\t\n\t\tfv = FVector()\n\t\tfor edge in edgelist:\n\t\t\tfv += edge.fvector + edge.head.fvector\n\t\t\tfor sub in edge.subs:\n\t\t\t\tif sub.is_terminal():\n\t\t\t\t\tfv += sub.fvector\n\t\treturn fv\n","sub_path":"liang_parser/r38-nomulti/code/inttag/node_and_hyperedge.py","file_name":"node_and_hyperedge.py","file_ext":"py","file_size_in_byte":7901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226002179","text":"\"\"\"\nUnit test for DataLoader.VirtualFile\n\"\"\"\n\nfrom VSR.DataLoader.VirtualFile import *\nfrom VSR.DataLoader.Loader import *\nfrom VSR.DataLoader.Dataset import *\n\ntry:\n DATASETS = load_datasets('./Data/datasets.json')\nexcept FileNotFoundError:\n DATASETS = load_datasets('../Data/datasets.json')\n\nRAW = DATASETS['MCL-V'].test[0]\nIMG = DATASETS['GOPRO'].train[0]\n\n\ndef test_raw_seek():\n vf = RawFile(RAW, 'YV12', [1920, 1080])\n f1 = vf.read_frame(1)[0]\n vf.seek(0, SEEK_SET)\n f2 = vf.read_frame(1)[0]\n vf.seek(-1, SEEK_CUR)\n f3 = vf.read_frame(1)[0]\n vf.seek(-1, SEEK_END)\n f4 = vf.read_frame(1)[0]\n vf.seek(-2, SEEK_END)\n vf.seek(1, SEEK_CUR)\n f5 = vf.read_frame(1)[0]\n\n F = [f1, f2, f3, f4, f5]\n F = [ImageProcess.img_to_array(f) for f in F]\n assert np.all(F[0] == F[1])\n assert np.all(F[1] == F[2])\n assert np.all(F[3] == F[4])\n\n\ndef test_image_seek():\n vf = ImageFile(IMG, False)\n f1 = vf.read_frame(1)[0]\n vf.seek(0, SEEK_SET)\n f2 = vf.read_frame(1)[0]\n vf.seek(-1, SEEK_CUR)\n f3 = vf.read_frame(1)[0]\n vf.seek(-1, SEEK_END)\n f4 = vf.read_frame(1)[0]\n vf.seek(-2, SEEK_END)\n vf.seek(1, SEEK_CUR)\n f5 = vf.read_frame(1)[0]\n\n F = [f1, f2, f3, f4, f5]\n F = [ImageProcess.img_to_array(f) for f in F]\n assert np.all(F[0] == F[1])\n assert np.all(F[1] == F[2])\n assert np.all(F[3] == F[4])\n","sub_path":"UTest/virtualfile_test.py","file_name":"virtualfile_test.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"386597063","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\ndef sort_peaks_valleys1(data):\r\n \"\"\"T: O(N log N). Doesn't work with duplicated elements!\"\"\"\r\n data.sort()\r\n for i in range(1, len(data), 2):\r\n data[i], data[i-1] = data[i-1], data[i]\r\n\r\n\r\ndef sort_peaks_valleys2(data):\r\n \"\"\"T: O(N). Doesn't work with duplicated elements!\"\"\"\r\n for i in range(1, len(data), 2):\r\n if data[i] > data[i-1]:\r\n data[i], data[i-1] = data[i-1], data[i]\r\n if i+1 < len(data) and data[i] > data[i+1]:\r\n data[i], data[i+1] = data[i+1], data[i]\r\n\r\n\r\ndef sort_peaks_valleys3(data):\r\n \"\"\"T: O(N log N).\"\"\"\r\n data_sorted = sorted(data)\r\n length = len(data)\r\n for i in range(length):\r\n index = i // 2\r\n if i % 2 == 1:\r\n index = length - index - 1\r\n data[i] = data_sorted[index]\r\n\r\n\r\nif __name__ == '__main__':\r\n tests = [\r\n [5, 3, 1, 2, 3],\r\n [5, 8, 6, 2, 3, 4, 6],\r\n [9, 1, 0, 4, 8, 7],\r\n [0, 1, 4, 7, 8, 9],\r\n [2, 3, 4],\r\n [2, 3, 4, 5, 6, 6, 8]\r\n ]\r\n\r\n for test in tests:\r\n test = test.copy()\r\n print(test, '->', end=' ')\r\n sort_peaks_valleys1(test)\r\n print(test)\r\n\r\n print()\r\n for test in tests:\r\n test = test.copy()\r\n print(test, '->', end=' ')\r\n sort_peaks_valleys2(test)\r\n print(test)\r\n\r\n print()\r\n for test in tests:\r\n test = test.copy()\r\n print(test, '->', end=' ')\r\n sort_peaks_valleys3(test)\r\n print(test)\r\n","sub_path":"ctci/python/ch10_sorting_and_searching/q11_peaks_and_valleys.py","file_name":"q11_peaks_and_valleys.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"474972102","text":"from turtle import Turtle, Screen\nimport time\n\ntry:\n import psyco\n from psyco.classes import *\n psyco.full()\n print (\"PSYCO -- SUPER!!\")\nexcept:\n print (\"-- psyco not installed - reduced performance --\")\n print (\"-- Download psyco at http://psyco.sourceforge.net/ --\")\n\n# MAX_X and MAX_Y must be odd\nMAX_X = 79\nMAX_Y = 57\nSQUARE_WIDTH = 10 # must be even\nFREEROWS = 3\nWINHEIGHT = MAX_Y + FREEROWS\nMARG_X = 2 + SQUARE_WIDTH//2 \nMARG_Y = 8\nDM = 10\n\nscreen = Screen()\n\ndef coords(col, row):\n\treturn ((-MAX_X//2 + col)*SQUARE_WIDTH + MARG_X,\n ((-MAX_Y+ FREEROWS)//2 + row )*SQUARE_WIDTH + MARG_Y)\n\ndef cellindices(x, y):\n return ((x-MARG_X + (SQUARE_WIDTH-1)//2)//SQUARE_WIDTH + MAX_X//2 + 1,\n (y-MARG_Y + (SQUARE_WIDTH-1)//2)//SQUARE_WIDTH + (MAX_Y- FREEROWS)//2)\n\ndef calccolor(i):\n i = min(20, i)\n return (1.05-i/20., 0., i/20.-0.05)\n \ndef generate(state):\n NBADDR = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1))\n while True:\n yield state\n cd = {}\n for (x,y) in state:\n for dx, dy in NBADDR:\n xx, yy = x+dx, y+dy\n cd[(xx,yy)] = cd.get((xx,yy), 0) + 1\n cd[(x,y)] = cd.get((x,y), 0) + 10\n cells = [c for c in cd if cd[c] in (3,12,13)]\n state1 = {c:1 for c in cells if c not in state}\n for c in cells:\n if c in state:\n state1[c] = state[c]+1\n state = state1\n\n\nclass Patch(Turtle):\n def __init__(self, col, row):\n Turtle.__init__(self, shape=\"square\", visible=False)\n self.pu()\n self.goto(coords(col, row))\n self.color(\"black\")\n self.shapesize((SQUARE_WIDTH-2)/20.0)\n \n \nclass Game(object):\n\n def __init__(self):\n screen.tracer(False)\n screen.setup(width=MAX_X*SQUARE_WIDTH + DM,\n height = (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM,\n startx = -20,\n starty = 20)\n screen.screensize(MAX_X*SQUARE_WIDTH + DM - 50,\n (MAX_Y+FREEROWS)*SQUARE_WIDTH + DM -50)\n self.designer = Turtle(visible=False)\n starttime = time.clock()\n self.messagero = Turtle(visible=False)\n self.messagero.penup()\n self.messagero.pencolor(\"blue\")\n self.messagero.goto(0, -(MAX_Y+FREEROWS)*SQUARE_WIDTH/2+6)\n self.message(\"Please wait a moment!\")\n self.designer.pencolor(\"gray90\")\n w2 = SQUARE_WIDTH // 2\n for c in range(MAX_X+1):\n x1, y1 = coords(c,0)\n x2, y2 = coords(c, MAX_Y)\n x1, y1, y2 = x1 - w2, y1 - w2, y2 - w2\n self.line(x1, y1, x1, y2)\n for r in range(MAX_Y+1):\n x1, y1 = coords(0, r)\n x2, y2 = coords(MAX_X, r)\n x1, y1, x2 = x1 - w2, y1 - w2, x2 - w2\n self.line(x1, y1, x2, y1)\n screen.update()\n self.patches = {}\n for r in range(MAX_Y):\n for c in range(MAX_X):\n self.patches[(c, r)] = Patch(c, r)\n\n self.state = {(41,33):1, (42,33):1, (43,34):1,\n (42,32):1, (42,34):1}\n for cell in self.state:\n self.patches[cell].showturtle()\n self.newstate = None\n\n stoptime = time.clock()\n print(stoptime - starttime)\n screen.update()\n screen.onkey(self.run, \"space\")\n screen.onkey(screen.bye, \"Escape\")\n screen.onkey(self.clear, \"c\")\n screen.listen()\n screen.onclick(self.toggle)\n self.message(\"spacebar:start/pause | left click:toggle cell | c:clear\"\n \" | escape:quit\")\n\n def message(self, txt):\n self.messagero.clear()\n self.messagero.write(txt, align=\"center\", font=(\"Courier\", 14, \"bold\"))\n \n\n def line(self, x1, y1, x2, y2):\n self.designer.penup()\n self.designer.goto(x1, y1)\n self.designer.pendown()\n self.designer.goto(x2, y2)\n\n def update_display(self):\n screen.tracer(False)\n for cell in self.state:\n if cell not in self.newstate:\n try:\n self.patches[cell].hideturtle()\n except KeyError:\n pass\n for cell in self.newstate:\n try:\n self.patches[cell].showturtle()\n self.patches[cell].color(calccolor(self.newstate[cell]))\n except KeyError:\n pass\n screen.tracer(True)\n\n def clear(self):\n self.newstate = {}\n self.update_display()\n self.state = {}\n\n def toggle(self, x, y):\n cell = cellindices(int(x), int(y))\n self.newstate = self.state.copy()\n if cell in self.newstate:\n del self.newstate[cell]\n else:\n self.newstate[cell] = 1\n self.update_display()\n self.state = self.newstate\n \n\n def run(self):\n starttime = time.clock()\n anzahl_generationen = 0\n screen.onkey(self.stop, \"space\")\n generation = generate(self.state)\n self.RUNNING = True\n while self.RUNNING:\n self.newstate = next(generation)\n self.update_display()\n self.state = self.newstate\n anzahl_generationen +=1\n stoptime = time.clock()\n t = stoptime - starttime\n print(anzahl_generationen, t, anzahl_generationen/t)\n\n def stop(self):\n self.RUNNING = False\n screen.onkey(self.run, \"space\")\n\ndef main():\n game=Game()\n return \"EVENTLOOP\"\n \n\nif __name__ == \"__main__\":\n msg = main()\n print(msg)\n screen.mainloop()\n","sub_path":"6. Python/海龟模块-Python/TurtleDemo-Python3.x/tdemo_games/tdemo_game_of_life_coloured.py","file_name":"tdemo_game_of_life_coloured.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"267711860","text":"import copy\nimport functools\nfrom p4p.nt.ndarray import ntndarray as NTNDArrayData\nfrom online_model import REDUNDANT_INPUT_OUTPUT, PROTOCOL, ARRAY_PVS\n\n# Some input/output variables have the same name and must be unique.\n# Below are utility functions to fix this:\n\n\ndef apply_temporary_ordering_patch(ordering, prefix):\n # TEMPORARY PATCH FOR INPUT/OUTPUT REDUNDANT VARS\n rebuilt_order = copy.copy(ordering)\n for i, val in enumerate(ordering):\n if val in REDUNDANT_INPUT_OUTPUT:\n rebuilt_order[i] = f\"{prefix}_{val}\"\n\n return rebuilt_order\n\n\ndef apply_temporary_output_patch(output):\n # TEMPORARY PATCH FOR OUTPUT ORDERING\n rebuilt_output = {}\n for item in output:\n if item in REDUNDANT_INPUT_OUTPUT:\n rebuilt_output[f\"out_{item}\"] = output[item]\n\n else:\n rebuilt_output[item] = output[item]\n return rebuilt_output\n\n\ndef format_outputs_by_protocol(f):\n \"\"\"\n Wrapper method for formatting arrays appropriately by protocol. \\\n Collects output from the SurrogateModel.predict dictionary of process\\\n variable names to values, and formats for assignment.\n \"\"\"\n\n def format_wrapper(*args, **kwargs):\n output_state = f(*args, **kwargs)\n\n rebuilt_output = {}\n if PROTOCOL == \"ca\":\n for pv, value in output_state.items():\n if pv in ARRAY_PVS:\n rebuilt_output[f\"{pv}:ArrayData_RBV\"] = value.flatten()\n else:\n rebuilt_output[pv] = value\n\n elif PROTOCOL == \"pva\":\n for pv, value in output_state.items():\n if pv in ARRAY_PVS:\n # populate image data\n array_data = value.view(NTNDArrayData)\n\n # get dw and dh from model output\n array_data.attrib = {\n # \"ColorMode\": DEFAULT_COLOR_MODE,\n \"dw\": output_state[f\"{pv}:dw\"],\n \"dh\": output_state[f\"{pv}:dh\"],\n }\n rebuilt_output[pv] = array_data\n\n # do not build attribute pvs\n elif not \".dw\" in pv and not \".dh\" in pv:\n rebuilt_output[pv] = value\n\n return rebuilt_output\n\n return format_wrapper\n","sub_path":"online_model/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393997246","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 3 22:34:33 2018\n\n@author: Alex\n\"\"\"\n\ndef factorsum(num):\n start = num\n factors = []\n for i in range(2,num):\n while start % i == 0:\n start = start/i\n factors.append(i)\n return sum(set(factors))","sub_path":"distinctprimesum.py","file_name":"distinctprimesum.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251118950","text":"from twitchpy.other.constants import *\nfrom twitchpy.other.decorators import oauth_required\nfrom twitchpy.other.helper import dict_gen\nfrom twitchpy.v5.base import TwitchBase\n\n\nclass Videos(TwitchBase):\n def get_video(self, video_id):\n request = 'videos/{}'.format(video_id)\n return self._get(request)\n\n def get_top_videos(\n self,\n limit=None,\n offset=None,\n game=None,\n period=None,\n broadcast_type=None,\n language=None,\n sort=None):\n request = 'videos/top'\n params = dict_gen(\n limit=limit,\n offset=offset,\n game=game,\n period=period,\n broadcast_type=broadcast_type,\n language=language,\n sort=sort)\n return self._get(request, params=params)\n\n @oauth_required\n def get_followed_videos(\n self,\n limit=None,\n offset=None,\n broadcast_type=None,\n language=None,\n sort=None):\n request = 'videos/followed'\n params = dict_gen(\n limit=limit,\n offset=offset,\n broadcast_type=broadcast_type,\n language=language,\n sort=sort)\n return self._get(request, params=params)\n","sub_path":"twitchpy/v5/videos.py","file_name":"videos.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"634996987","text":"#! /usr/bin/env python3\n\n# Usage visualizer.py python_file.py annotations=annotation_file.txt args\n\n################################################################################\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> IMPORTS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n################################################################################\nimport subprocess\nimport sys\nimport os\nimport time\n\n\n################################################################################\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> RUN PROGRAMS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n################################################################################\n\ndef main():\n # file that will be visualized\n python_file = sys.argv[1]\n\n # paths to the two subprograms\n stepperPath = os.path.join(os.path.dirname(__file__), \"stepper.py\")\n visualizerPath = os.path.join(os.path.dirname(__file__), \"gtk_visualizer.py\")\n\n if (len(sys.argv) >= 3): # annotation file has been given\n stepper = subprocess.Popen([\"python3\", stepperPath, python_file, sys.argv[2]])\n else:\n stepper = subprocess.Popen([\"python3\", stepperPath, python_file])\n\n # start visualization\n visualizer = subprocess.Popen([\"python3\", visualizerPath])\n\n # check if one of the subprocesses have terminated\n try:\n proc = [stepper, visualizer]\n while True:\n if stepper.poll() != None:\n visualizer.terminate()\n break\n if visualizer.poll() != None:\n stepper.terminate()\n break\n time.sleep(0.2)\n except KeyboardInterrupt:\n stepper.terminate()\n visualizer.terminate()\n\n os.system(\"stty sane\") # reset the terminal properly to not have echo issues\n sys.exit(0)\n\nmain()\n","sub_path":"visualizer/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9589841","text":"#\n#\n#\tadmin/data/split_google_file.py\n#\n#\tTakes as input the list of google analytics metrics and dimensions and splits it into 2 files\n#\n#\tCopyright 2014 Netbiquity\n#\tCreated by Cameron Johnson\n#\n#\n\nimport json\n\nf = open('analytics_data.json','r');\nf = f.read();\n\nobj = json.loads(f)\nmetrics = [];\ndimens = []\n\nfor i in obj['items']:\n\tif i['attributes']['type'] == 'METRIC':\n\t\tmetrics.append(i);\n\telif i['attributes']['type'] == 'DIMENSION':\n\t\tdimens.append(i);\n\telse:\n\t\tprint(i)\n\nmf = open('ga_metrics_data.json','w');\nmf.write(json.dumps(metrics, indent=4));\nmf.close();\n\ndf = open('ga_dimensions_data.json','w');\ndf.write(json.dumps(dimens, indent=4));\ndf.close();","sub_path":"admin/data/split_google_file.py","file_name":"split_google_file.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515177161","text":"from flask import Flask\nfrom flask_bootstrap import Bootstrap\nfrom flask_basicauth import BasicAuth\n\nbootstrap = Bootstrap()\nhttpauth = BasicAuth()\n\n\ndef teardown(func):\n \"\"\"Teardown works after initialization.\"\"\"\n _app = None\n\n def wrapper(*args, **kwargs):\n global _app\n _app = func(*args, **kwargs)\n return _app\n return wrapper\n\n\n@teardown\ndef create_app(cfg):\n \"\"\"Create flask instance from configuration.\"\"\"\n\n # Initialize flask instance.\n app = Flask(__name__)\n app.config.update(_upper(cfg.basic))\n\n # Initialize Flask-Bootstrap.\n _init_bootstrap(app, cfg)\n\n # Initialize Flask-BasicAuth.\n _init_httpauth(app, cfg)\n\n # Initialize index blueprint.\n _init_index(app, cfg)\n\n return app\n\n\ndef _init_bootstrap(app, cfg):\n \"\"\"Initialize Flask-Bootstrap.\"\"\"\n if cfg.has_attr('bootstrap'):\n app.config.update(_upper(cfg.bootstrap))\n bootstrap.init_app(app)\n\n\ndef _init_httpauth(app, cfg):\n \"\"\"Initialize Flask-BasicAuth.\"\"\"\n if cfg.has_attr('httpauth'):\n app.config.update(_upper(cfg.httpauth))\n httpauth.init_app(app)\n\n\ndef _init_index(app, cfg):\n \"\"\"Initialize index blueprint.\"\"\"\n if cfg.has_attr('index'):\n app.config.update(_upper(cfg.index))\n\n from scrapymon.views.index import index as index_blueprint\n app.register_blueprint(\n index_blueprint, url_prefix=cfg.index['index_blueprint_prefix'])\n\n\ndef _upper(d):\n \"\"\"Return non-lower dictionary from dictonary.\"\"\"\n return dict(((k, d[k]) for k in d if k.isupper()))\n","sub_path":"scrapymon/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"462963997","text":"from contextlib import contextmanager\nfrom time import time\n\n\n@contextmanager\ndef timing():\n start = time()\n yield\n end = time()\n print(\"Took {}s\".format(end - start))\n\n\nclass BridgeSolver(object):\n\n def __init__(self, bridges, w, e):\n self.bridges = bridges\n self.w = w\n self.e = e\n self.tolls = {}\n self.maxTollSum = 0\n\n self._initToll()\n # for r in range(w):\n # print(\"| \", end='')\n # for c in range(e):\n # print(\"{} \".format(self.tolls.get(\"{}|{}\".format(r, c), \" \")), end='')\n # print(\"|\")\n\n def _initToll(self):\n self.maxTollSum = 0\n for bridge in self.bridges:\n self.tolls[\"{}|{}\".format(bridge[0], bridge[1])] = bridge[2]\n\n def maxToll(self):\n self._initToll()\n self._maxToll(0, 0)\n return self.maxTollSum\n\n def _maxToll(self, w, e):\n\n for i in range(self.w):\n for j in range(self.e):\n currToll = self.getToll(i, j)\n leftToll = self.getToll(i - 1, j)\n upToll = self.getToll(i, j - 1)\n diagToll = self.getToll(i - 1, j - 1)\n currMax = max(currToll + diagToll, leftToll, upToll)\n\n if currMax > self.maxTollSum:\n self.maxTollSum = currMax\n self.setToll(i, j, currMax)\n\n def getToll(self, w, e):\n return self.tolls.get(\"{}|{}\".format(w, e), 0)\n\n def setToll(self, w, e, toll):\n self.tolls[\"{}|{}\".format(w, e)] = toll\n\ndef build(bridges, w, e):\n solver = BridgeSolver(bridges, w, e)\n return solver.maxToll()\n\nif __name__ == \"__main__\":\n input1 = [\n [0, 1, 3],\n [1, 0, 6],\n [2, 1, 5],\n [2, 2, 2]\n ]\n input2 = [\n [0, 1, 3],\n [1, 1, 5],\n [1, 2, 4],\n [2, 0, 8]\n ]\n input3 = [\n [0, 1, 3],\n [1, 1, 5],\n [1, 2, 4],\n [2, 0, 8],\n [2, 2, 6]\n ]\n input4 = [\n [0, 0, 4],\n [1, 0, 4],\n [2, 0, 4],\n [2, 1, 4],\n [2, 2, 4]\n ]\n input5 = []\n for i in range(60):\n for j in range(60):\n input5.append([i, j, 3])\n\n input6 = []\n for i in range(12):\n input6.append([i, i, 1])\n input6.append([0, 11, 13])\n input6.append([11, 0, 14])\n\n with timing():\n print(\"Found: {}\".format(build(input1, 3, 3)))\n with timing():\n print(\"Found: {}\".format(build(input2, 3, 3)))\n with timing():\n print(\"Found: {}\".format(build(input3, 3, 3)))\n with timing():\n print(\"Found: {}\".format(build(input4, 3, 3)))\n with timing():\n print(\"Found: {} should be {}\".format(build(input5, 60, 60), 3*60))\n with timing():\n print(\"Found: {} should be {}\".format(build(input6, 12, 12), 14))\n","sub_path":"bridges_dynamic/bridges3.py","file_name":"bridges3.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449136471","text":"from django.shortcuts import render\nfrom myschedule.models import Event\n\nimport json\n\ndef mycalendar(request):\n if request.user.is_authenticated:\n events = [addurl(e) for e in Event.objects.filter(owner__exact=request.user)]\n events = '\\n' + json.dumps(events, indent=4)\n events = '\\t\\t\\t\\t'.join(events.splitlines(True))\n else:\n events = []\n return render(request, 'mycalendar/calendar.html', {'events': events})\n\ndef addurl(e):\n eventdict = Event.getdict(e)\n eventdict['url'] = '/schedule/' + str(e.id) + '/' + 'edit/'\n return eventdict","sub_path":"mycalendar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"240911608","text":"# -*- coding: utf-8 -*- \n'''\n UDP Client\n'''\nimport socket\n\n\nlocalIP = \"127.0.0.1\"\nlocalPort = 20007\n\nbufferSize = 1024\n\nmsgFromClient = \"UnitTest UDP Server\"\nbytesToSend = str.encode(msgFromClient)\nserverAddressPort = (localIP, localPort)\n\n# Create a UDP socket at client side\nUDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n\n# Send to server using created UDP socket\nUDPClientSocket.sendto(bytesToSend, serverAddressPort)\n\n#msgFromServer = UDPClientSocket.recvfrom(bufferSize)\n#msg = \"Message from Server {}\".format(msgFromServer[0])\n\nmsg = \"Message OK\"\n\nprint(msg)","sub_path":"Socket/UDP/udpclient.py","file_name":"udpclient.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226743074","text":"import matplotlib.pyplot as plt\nimport math\n\nimport StateSpace as ss\n\ndef sign(x):\n if x > 0: return 1\n elif x < 0: return -1\n else: return 0\n\ndef aPrioriFunction(theta):\n return sign(10-theta[0])+sign(theta[1]*(1-theta[1])) + sign(0.1 - theta[2])\n\n\nif __name__ == '__main__':\n y0, t0, dt, t1 = [0,0], 0.0, 1, 50.0\n process = ss.MassSpringDamperParallel(m=0.1, d=0.2, k=0.5)\n\n msd = ss.LinearStateSpace([[0,1],[-1,-1]], [[0, 1]], [1, 0], [0, 0], [[5],[-1]])\n\n def control_law(t):\n return 10\n\n ys, us, ts = [y0], [control_law(t0)], [t0]\n while ts[~0] < t1:\n # update process\n u = control_law(ts[~0])\n us.append(u)\n process.update(u,dt)\n\n # setup for next timestep\n ts.append(ts[~0] + dt)\n ys.append(process.measure(u))\n\n plt.plot(ts,ys)\n plt.legend(['control_position', 'mass_position'])\n plt.show()\n\n\n\n \n","sub_path":"ttk4215/assignment6_python/problem_4_10.py","file_name":"problem_4_10.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63715983","text":"# Profile API here\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import flash\nimport sys\nfrom db import db\nsys.path.append(\"../\")\n\nprofiles_api = Blueprint(\"profiles\", __name__)\n\n@profiles_api.route(\"/\", methods = [\"GET\"])\ndef searchProfiles(id):\n for set in db:\n if id == set[\"name\"]:\n return set\n return \"Wrong id\" #What type of error should I throw in here\n\n@profiles_api.route(\"/profiles\", methods = [\"POST\"])\ndef createProfile():\n for set in db:\n if request.form[\"name\"] == set[\"name\"]:\n return \"User already exist\"\n\n db.append\n ({\n \"name\": request.form[\"name\"],\n \"score\": [] #empty because it creates name only \n })\n return \"Profile created\"\n\n@profiles_api.route('/', methods = [\"DELETE\"])\ndef deleteProfile(id):\n flash(\"Are you sure you want to delete profile?\")\n flash(\"Please note that once deleted, lost data cannot be recovered. Are you sure?\")\n # theres not much in the documentation for creating these messages. \n for set in db:\n if id == set[\"name\"]:\n db.remove(set)\n return \"User has been deleted\"\n \n return \"User does not exist\"\n\n@profiles_api.route('//score', methods = [\"GET\"])\ndef profileScore(id):\n allScores = []\n for set in db:\n if id == set[\"name\"]:\n allScores = set[\"scores\"]\n if (allScores == []):\n return \"No scores are found\" \n aboveMinScore = list(filter(lambda x: x > int(request.args.get(\"minScore\"))), allScores)\n return aboveMinScore\n# In profiles API (/profiles prefix) \n# GET /{id} to retrieve the name and all scores of a profile \n# POST /profiles to create a new profile (name only) \n# DELETE /{id} to delete a profile \n# GET /{id}/score?minScore= to retrieve all scores of a profile, above the min score ","sub_path":"Profiles/ProfilesAPI.py","file_name":"ProfilesAPI.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13427464","text":"# Copyright 2015 Red Hat, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"Plugin action implementation\"\"\"\n\nimport copy\nimport logging\nimport netaddr\nimport os\nfrom oslo_config import cfg\nfrom tripleoclient.v1 import undercloud_preflight\nimport yaml\n\n\nPARAMETER_MAPPING = {\n 'network_gateway': 'UndercloudNetworkGateway',\n 'enabled_drivers': 'IronicEnabledDrivers',\n 'inspection_iprange': 'IronicInspectorIpRange',\n 'inspection_interface': 'IronicInspectorInterface',\n 'dhcp_start': 'UndercloudDhcpRangeStart',\n 'dhcp_end': 'UndercloudDhcpRangeEnd',\n 'network_cidr': 'UndercloudNetworkCidr',\n 'undercloud_debug': 'Debug',\n 'ipxe_enabled': 'IronicInspectorIPXEEnabled',\n 'certificate_generation_ca': 'CertmongerCA',\n 'undercloud_public_host': 'CloudName',\n 'scheduler_max_attempts': 'NovaSchedulerMaxAttempts',\n}\n\nTHT_HOME = os.environ.get('THT_HOME',\n \"/usr/share/openstack-tripleo-heat-templates/\")\n\nTELEMETRY_DOCKER_ENV_YAML = [\n 'environments/services-docker/undercloud-gnocchi.yaml',\n 'environments/services-docker/undercloud-aodh.yaml',\n 'environments/services-docker/undercloud-panko.yaml',\n 'environments/services-docker/undercloud-ceilometer.yaml']\n\n\nclass Paths(object):\n @property\n def CONF_PATH(self):\n return os.path.expanduser('~/undercloud.conf')\n\n\nCONF = cfg.CONF\nPATHS = Paths()\n\n\n# When adding new options to the lists below, make sure to regenerate the\n# sample config by running \"tox -e genconfig\" in the project root.\n_opts = [\n cfg.StrOpt('undercloud_hostname',\n help=('Fully qualified hostname (including domain) to set on '\n 'the Undercloud. If left unset, the '\n 'current hostname will be used, but the user is '\n 'responsible for configuring all system hostname '\n 'settings appropriately. If set, the undercloud install '\n 'will configure all system hostname settings.'),\n ),\n cfg.StrOpt('local_ip',\n default='192.168.24.1/24',\n help=('IP information for the interface on the Undercloud '\n 'that will be handling the PXE boots and DHCP for '\n 'Overcloud instances. The IP portion of the value will '\n 'be assigned to the network interface defined by '\n 'local_interface, with the netmask defined by the '\n 'prefix portion of the value.')\n ),\n cfg.StrOpt('network_gateway',\n default='192.168.24.1',\n help=('Network gateway for the Neutron-managed network for '\n 'Overcloud instances. This should match the local_ip '\n 'above when using masquerading.')\n ),\n cfg.StrOpt('undercloud_public_host',\n deprecated_name='undercloud_public_vip',\n default='192.168.24.2',\n help=('Virtual IP or DNS address to use for the public '\n 'endpoints of Undercloud services. Only used with SSL.')\n ),\n cfg.StrOpt('undercloud_admin_host',\n deprecated_name='undercloud_admin_vip',\n default='192.168.24.3',\n help=('Virtual IP or DNS address to use for the admin '\n 'endpoints of Undercloud services. Only used with SSL.')\n ),\n cfg.ListOpt('undercloud_nameservers',\n default=[],\n help=('DNS nameserver(s) to use for the undercloud node.'),\n ),\n cfg.ListOpt('undercloud_ntp_servers',\n default=[],\n help=('List of ntp servers to use.')),\n cfg.StrOpt('overcloud_domain_name',\n default='localdomain',\n help=('DNS domain name to use when deploying the overcloud. '\n 'The overcloud parameter \"CloudDomain\" must be set to a '\n 'matching value.')\n ),\n cfg.StrOpt('undercloud_service_certificate',\n default='',\n help=('Certificate file to use for OpenStack service SSL '\n 'connections. Setting this enables SSL for the '\n 'OpenStack API endpoints, leaving it unset disables SSL.')\n ),\n cfg.BoolOpt('generate_service_certificate',\n default=False,\n help=('When set to True, an SSL certificate will be generated '\n 'as part of the undercloud install and this certificate '\n 'will be used in place of the value for '\n 'undercloud_service_certificate. The resulting '\n 'certificate will be written to '\n '/etc/pki/tls/certs/undercloud-[undercloud_public_host].'\n 'pem. This certificate is signed by CA selected by the '\n '\"certificate_generation_ca\" option.')\n ),\n cfg.StrOpt('certificate_generation_ca',\n default='local',\n help=('The certmonger nickname of the CA from which the '\n 'certificate will be requested. This is used only if '\n 'the generate_service_certificate option is set. '\n 'Note that if the \"local\" CA is selected the '\n 'certmonger\\'s local CA certificate will be extracted to '\n '/etc/pki/ca-trust/source/anchors/cm-local-ca.pem and '\n 'subsequently added to the trust chain.')\n\n ),\n cfg.StrOpt('service_principal',\n default='',\n help=('The kerberos principal for the service that will use '\n 'the certificate. This is only needed if your CA '\n 'requires a kerberos principal. e.g. with FreeIPA.')\n ),\n cfg.StrOpt('local_interface',\n default='eth1',\n help=('Network interface on the Undercloud that will be '\n 'handling the PXE boots and DHCP for Overcloud '\n 'instances.')\n ),\n cfg.IntOpt('local_mtu',\n default=1500,\n help=('MTU to use for the local_interface.')\n ),\n cfg.StrOpt('network_cidr',\n default='192.168.24.0/24',\n help=('Network CIDR for the Neutron-managed network for '\n 'Overcloud instances. This should be the subnet used '\n 'for PXE booting.')\n ),\n cfg.StrOpt('masquerade_network',\n default='192.168.24.0/24',\n help=('Network that will be masqueraded for external access, '\n 'if required. This should be the subnet used for PXE '\n 'booting.')\n ),\n cfg.StrOpt('dhcp_start',\n default='192.168.24.5',\n help=('Start of DHCP allocation range for PXE and DHCP of '\n 'Overcloud instances.')\n ),\n cfg.StrOpt('dhcp_end',\n default='192.168.24.24',\n help=('End of DHCP allocation range for PXE and DHCP of '\n 'Overcloud instances.')\n ),\n cfg.StrOpt('hieradata_override',\n default='',\n help=('Path to hieradata override file. If set, the file will '\n 'be copied under /etc/puppet/hieradata and set as the '\n 'first file in the hiera hierarchy. This can be used '\n 'to custom configure services beyond what '\n 'undercloud.conf provides')\n ),\n cfg.StrOpt('net_config_override',\n default='',\n help=('Path to network config override template. If set, this '\n 'template will be used to configure the networking via '\n 'os-net-config. Must be in json format. '\n 'Templated tags can be used within the '\n 'template, see '\n 'instack-undercloud/elements/undercloud-stack-config/'\n 'net-config.json.template for example tags')\n ),\n cfg.StrOpt('inspection_interface',\n default='br-ctlplane',\n deprecated_name='discovery_interface',\n help=('Network interface on which inspection dnsmasq will '\n 'listen. If in doubt, use the default value.')\n ),\n cfg.StrOpt('inspection_iprange',\n default='192.168.24.100,192.168.24.120',\n deprecated_name='discovery_iprange',\n help=('Temporary IP range that will be given to nodes during '\n 'the inspection process. Should not overlap with the '\n 'range defined by dhcp_start and dhcp_end, but should '\n 'be in the same network.')\n ),\n cfg.BoolOpt('inspection_extras',\n default=True,\n help=('Whether to enable extra hardware collection during '\n 'the inspection process. Requires python-hardware or '\n 'python-hardware-detect package on the introspection '\n 'image.')),\n cfg.BoolOpt('inspection_runbench',\n default=False,\n deprecated_name='discovery_runbench',\n help=('Whether to run benchmarks when inspecting nodes. '\n 'Requires inspection_extras set to True.')\n ),\n cfg.BoolOpt('inspection_enable_uefi',\n default=True,\n help=('Whether to support introspection of nodes that have '\n 'UEFI-only firmware.')\n ),\n cfg.BoolOpt('enable_node_discovery',\n default=False,\n help=('Makes ironic-inspector enroll any unknown node that '\n 'PXE-boots introspection ramdisk in Ironic. By default, '\n 'the \"fake\" driver is used for new nodes (it is '\n 'automatically enabled when this option is set to True).'\n ' Set discovery_default_driver to override. '\n 'Introspection rules can also be used to specify driver '\n 'information for newly enrolled nodes.')\n ),\n cfg.StrOpt('discovery_default_driver',\n default='ipmi',\n help=('The default driver or hardware type to use for newly '\n 'discovered nodes (requires enable_node_discovery set to '\n 'True). It is automatically added to enabled_drivers '\n 'or enabled_hardware_types accordingly.')\n ),\n cfg.BoolOpt('undercloud_debug',\n default=True,\n help=('Whether to enable the debug log level for Undercloud '\n 'OpenStack services.')\n ),\n cfg.BoolOpt('undercloud_update_packages',\n default=False,\n help=('Whether to update packages during the Undercloud '\n 'install. This is a no-op for containerized undercloud.')\n ),\n cfg.BoolOpt('enable_tempest',\n default=True,\n help=('Whether to install Tempest in the Undercloud.'\n 'This is a no-op for containerized undercloud.')\n ),\n cfg.BoolOpt('enable_telemetry',\n default=False,\n help=('Whether to install Telemetry services '\n '(ceilometer, gnocchi, aodh, panko ) in the Undercloud.')\n ),\n cfg.BoolOpt('enable_ui',\n default=True,\n help=('Whether to install the TripleO UI.')\n ),\n cfg.BoolOpt('enable_validations',\n default=True,\n help=('Whether to install requirements to run the TripleO '\n 'validations.')\n ),\n cfg.BoolOpt('enable_cinder',\n default=False,\n help=('Whether to install the Volume service. It is not '\n 'currently used in the undercloud.')),\n cfg.BoolOpt('enable_novajoin',\n default=False,\n help=('Whether to install novajoin metadata service in '\n 'the Undercloud.')\n ),\n cfg.BoolOpt('enable_container_images_build',\n default=True,\n help=('Whether to enable docker container images to be build '\n 'on the undercloud.')\n ),\n cfg.StrOpt('ipa_otp',\n default='',\n help=('One Time Password to register Undercloud node with '\n 'an IPA server. '\n 'Required when enable_novajoin = True.')\n ),\n cfg.BoolOpt('ipxe_enabled',\n default=True,\n help=('Whether to use iPXE for deploy and inspection.'),\n deprecated_name='ipxe_deploy',\n ),\n cfg.IntOpt('scheduler_max_attempts',\n default=30, min=1,\n help=('Maximum number of attempts the scheduler will make '\n 'when deploying the instance. You should keep it '\n 'greater or equal to the number of bare metal nodes '\n 'you expect to deploy at once to work around '\n 'potential race condition when scheduling.')),\n cfg.BoolOpt('clean_nodes',\n default=False,\n help=('Whether to clean overcloud nodes (wipe the hard drive) '\n 'between deployments and after the introspection.')),\n cfg.ListOpt('enabled_drivers',\n default=['pxe_ipmitool', 'pxe_drac', 'pxe_ilo'],\n help=('List of enabled bare metal drivers.'),\n deprecated_for_removal=True,\n deprecated_reason=('Please switch to hardware types and '\n 'the enabled_hardware_types option.')),\n cfg.ListOpt('enabled_hardware_types',\n default=['ipmi', 'redfish', 'ilo', 'idrac'],\n help=('List of enabled bare metal hardware types (next '\n 'generation drivers).')),\n cfg.StrOpt('docker_registry_mirror',\n default='',\n help=('An optional docker \\'registry-mirror\\' that will be'\n 'configured in /etc/docker/daemon.json.')\n ),\n cfg.ListOpt('docker_insecure_registries',\n default=[],\n help=('Used to add custom insecure registries in '\n '/etc/sysconfig/docker.')\n ),\n cfg.StrOpt('templates',\n default='',\n help=('heat templates file to override.')\n ),\n cfg.BoolOpt('heat_native',\n default=True,\n help=('Use native heat templates.')),\n cfg.StrOpt('heat_container_image',\n default='',\n help=('URL for the heat container image to use.')\n ),\n cfg.StrOpt('container_images_file',\n default='',\n help=('Container yaml file with all available images in the'\n 'registry')\n ),\n cfg.BoolOpt('enable_ironic',\n default=True,\n help=('Whether to enable the ironic service.')),\n cfg.BoolOpt('enable_ironic_inspector',\n default=True,\n help=('Whether to enable the ironic inspector service.')),\n cfg.BoolOpt('enable_mistral',\n default=True,\n help=('Whether to enable the mistral service.')),\n cfg.BoolOpt('enable_zaqar',\n default=True,\n help=('Whether to enable the zaqar service.')),\n cfg.ListOpt('custom_env_files',\n default=[],\n help=('List of any custom environment yaml files to use')),\n]\n\nCONF.register_opts(_opts)\n\nLOG = logging.getLogger(__name__ + \".undercloud_config\")\n\n\ndef list_opts():\n return [(None, copy.deepcopy(_opts))]\n\n\ndef _load_config():\n conf_params = []\n if os.path.isfile(PATHS.CONF_PATH):\n conf_params += ['--config-file', PATHS.CONF_PATH]\n else:\n LOG.warning('%s does not exist. Using defaults.' % PATHS.CONF_PATH)\n CONF(conf_params)\n\n\ndef _is_classic_driver(name):\n \"\"\"Poor man's way to detect if something is a driver or a hardware type.\n\n To be removed when we remove support for classic drivers.\n \"\"\"\n return (name == 'fake' or\n name.startswith('fake_') or\n name.startswith('pxe_') or\n name.startswith('agent_') or\n name.startswith('iscsi_'))\n\n\ndef _process_drivers_and_hardware_types(conf, env):\n \"\"\"Populate the environment with ironic driver information.\"\"\"\n # Ensure correct rendering of the list and uniqueness of the items\n enabled_drivers = set(conf.enabled_drivers)\n enabled_hardware_types = set(conf.enabled_hardware_types)\n if conf.enable_node_discovery:\n if _is_classic_driver(conf.discovery_default_driver):\n if conf.discovery_default_driver not in enabled_drivers:\n enabled_drivers.add(conf.discovery_default_driver)\n else:\n if conf.discovery_default_driver not in enabled_hardware_types:\n enabled_hardware_types.add(conf.discovery_default_driver)\n env['IronicInspectorEnableNodeDiscovery'] = True\n env['IronicInspectorDiscoveryDefaultDriver'] = (\n conf.discovery_default_driver)\n\n # In most cases power and management interfaces are called the same, so we\n # use one variable for them.\n mgmt_interfaces = {'fake', 'ipmitool'}\n # TODO(dtantsur): can we somehow avoid hardcoding hardware types here?\n for hw_type in ('redfish', 'idrac', 'ilo', 'irmc', 'staging-ovirt'):\n if hw_type in enabled_hardware_types:\n mgmt_interfaces.add(hw_type)\n for (hw_type, iface) in [('cisco-ucs-managed', 'ucsm'),\n ('cisco-ucs-standalone', 'cimc')]:\n if hw_type in enabled_hardware_types:\n mgmt_interfaces.add(iface)\n\n # Two hardware types use non-default boot interfaces.\n boot_interfaces = {'pxe'}\n for hw_type in ('ilo', 'irmc'):\n if hw_type in enabled_hardware_types:\n boot_interfaces.add('%s-pxe' % hw_type)\n\n raid_interfaces = {'no-raid'}\n if 'idrac' in enabled_hardware_types:\n raid_interfaces.add('idrac')\n\n vendor_interfaces = {'no-vendor'}\n for (hw_type, iface) in [('ipmi', 'ipmitool'),\n ('idrac', 'idrac')]:\n if hw_type in enabled_hardware_types:\n vendor_interfaces.add(iface)\n\n env['IronicEnabledDrivers'] = sorted(enabled_drivers)\n env['IronicEnabledHardwareTypes'] = sorted(enabled_hardware_types)\n\n env['IronicEnabledBootInterfaces'] = sorted(boot_interfaces)\n env['IronicEnabledManagementInterfaces'] = sorted(mgmt_interfaces)\n env['IronicEnabledRaidInterfaces'] = sorted(raid_interfaces)\n env['IronicEnabledVendorInterfaces'] = sorted(vendor_interfaces)\n\n # The snmp hardware type uses fake management and snmp power\n if 'snmp' in enabled_hardware_types:\n mgmt_interfaces.add('snmp')\n env['IronicEnabledPowerInterfaces'] = sorted(mgmt_interfaces)\n\n\ndef prepare_undercloud_deploy(upgrade=False, no_validations=False):\n \"\"\"Prepare Undercloud deploy command based on undercloud.conf\"\"\"\n\n env_data = {}\n deploy_args = []\n _load_config()\n\n # Set the undercloud home dir parameter so that stackrc is produced in\n # the users home directory.\n env_data['UndercloudHomeDir'] = os.environ.get('HOME', '')\n\n for param_key, param_value in PARAMETER_MAPPING.items():\n if param_key in CONF.keys():\n env_data[param_value] = CONF[param_key]\n\n # Parse the undercloud.conf options to include necessary args and\n # yaml files for undercloud deploy command\n\n # we use this to set --dns-nameserver for the ctlplane network\n # so just pick the first entry\n if CONF.get('undercloud_nameservers', None):\n env_data['UndercloudNameserver'] = CONF['undercloud_nameservers'][0]\n\n if CONF.get('undercloud_ntp_servers', None):\n env_data['NtpServer'] = CONF['undercloud_ntp_servers'][0]\n\n # FIXME need to add admin VIP as well\n env_data['DockerInsecureRegistryAddress'] = [\n '%s:8787' % CONF['local_ip'].split('/')[0]]\n env_data['DockerInsecureRegistryAddress'].extend(\n CONF['docker_insecure_registries'])\n\n if CONF.get('docker_registry_mirror', None):\n env_data['DockerRegistryMirror'] = CONF['docker_registry_mirror']\n\n if CONF.get('local_ip', None):\n # local_ip is defined as a CIDR\n just_local_ip = CONF['local_ip'].split('/')[0]\n deploy_args.append('--local-ip=%s' % just_local_ip)\n\n if CONF.get('templates', None):\n tht_templates = CONF['templates']\n deploy_args.append('--templates=%s' % tht_templates)\n else:\n tht_templates = THT_HOME\n deploy_args.append('--templates=%s' % THT_HOME)\n\n if upgrade:\n # Containerized undercloud upgrade is still WIP\n # We're in upgrade scenario, include the major upgrade steps\n deploy_args += ['-e', os.path.join(\n tht_templates,\n \"environments/major-upgrade-composable-steps-docker.yaml\")]\n\n if CONF.get('heat_native', None):\n deploy_args.append('--heat-native')\n\n if CONF.get('heat_container_image'):\n deploy_args.append('--heat-container-image=%s'\n % CONF['heat_container_image'])\n\n if CONF.get('container_images_file'):\n deploy_args += ['-e', CONF['container_images_file']]\n\n if CONF.get('enable_ironic'):\n deploy_args += ['-e', os.path.join(\n tht_templates, \"environments/services-docker/ironic.yaml\")]\n\n # ironic-inspector can only work if ironic is enabled\n if CONF.get('enable_ironic_inspector'):\n deploy_args += ['-e', os.path.join(\n tht_templates,\n \"environments/services-docker/ironic-inspector.yaml\")]\n\n _process_drivers_and_hardware_types(CONF, env_data)\n\n if CONF.get('enable_mistral'):\n deploy_args += ['-e', os.path.join(\n tht_templates, \"environments/services-docker/mistral.yaml\")]\n\n if CONF.get('enable_zaqar'):\n deploy_args += ['-e', os.path.join(\n tht_templates, \"environments/services-docker/zaqar.yaml\")]\n\n if CONF.get('enable_telemetry'):\n for env_file in TELEMETRY_DOCKER_ENV_YAML:\n deploy_args += ['-e', os.path.join(tht_templates, env_file)]\n\n if CONF.get('enable_cinder'):\n deploy_args += ['-e', os.path.join(\n tht_templates,\n \"environments/services-docker/undercloud-cinder.yaml\")]\n\n if CONF.get('generate_service_certificate'):\n try:\n public_host = CONF.get('undercloud_public_host')\n netaddr.IPAddress(public_host)\n endpoint_environment = os.path.join(\n tht_templates,\n \"environments/tls-endpoints-public-ip.yaml\")\n except netaddr.core.AddrFormatError:\n endpoint_environment = os.path.join(\n tht_templates,\n \"environments/tls-endpoints-public-dns.yaml\")\n\n deploy_args += ['-e', os.path.join(\n tht_templates,\n \"environments/public-tls-undercloud.yaml\"),\n '-e', endpoint_environment]\n\n deploy_args += [\n \"-e\", os.path.join(tht_templates, \"environments/docker.yaml\"),\n \"-e\",\n os.path.join(tht_templates,\n \"environments/config-download-environment.yaml\"),\n \"-e\", os.path.join(tht_templates, \"environments/undercloud.yaml\")]\n\n env_file = _write_env_file(env_data)\n deploy_args += ['-e', env_file]\n\n if CONF.get('custom_env_files'):\n for custom_file in CONF['custom_env_files']:\n deploy_args += ['-e', custom_file]\n\n if CONF.get('enable_validations') and not no_validations:\n undercloud_preflight.check()\n\n cmd = [\"sudo\", \"openstack\", \"undercloud\", \"deploy\"]\n cmd += deploy_args[:]\n\n return cmd\n\n\ndef _write_env_file(env_data,\n env_file=\"/tmp/undercloud_parameters.yaml\"):\n \"\"\"Write the undercloud parameters to yaml\"\"\"\n\n data = {'parameter_defaults': env_data}\n env_file = os.path.abspath(env_file)\n with open(env_file, \"w\") as f:\n try:\n yaml.dump(data, f, default_flow_style=False)\n except yaml.YAMLError as exc:\n raise exc\n return env_file\n","sub_path":"tripleoclient/v1/undercloud_config.py","file_name":"undercloud_config.py","file_ext":"py","file_size_in_byte":25289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"461656796","text":"import datetime\n\nimport pyprinter\n\nfrom ..utils.exceptions import MissingFieldException\nfrom ..utils.muted_objects import MutedList\nfrom ..utils.orm.connector import session_scope\nfrom ..utils.orm.orm import Project\n\n\ndef get_projects(user_id=None, verbose=True):\n \"\"\"\n Fetch all projects from the DB.\n :param user_id: Filter by user_id\n :param verbose: If True, each project's details will be printed.\n :return: The projects list.\n \"\"\"\n results_list = MutedList('ProjectsList')\n with session_scope() as session:\n query = session.query(Project).filter(Project.owner_id == user_id).order_by(Project.project_name)\n # Process results.\n for project in query:\n if verbose:\n project.pretty_print()\n results_list.append(project)\n return results_list\n\n\ndef get_project(project_id, verbose=True):\n \"\"\"\n Fetch details for the project with the given ID.\n\n :param project_id: The project ID to look for.\n :param verbose: If True, project details will be printed.\n :return: The projects's details, or None if the project wasn't found.\n \"\"\"\n # Validate parameters.\n if not project_id:\n return None\n with session_scope() as session:\n # Load the related project as well.\n project = session.query(Project).filter(Project.project_id == project_id).first()\n if verbose and project:\n project.pretty_print()\n return project\n\n\ndef update_project(owner_id=None, project_name=None, project_id=None, verbose=True):\n \"\"\"\n Update (or create) a project.\n\n :param owner_id: The project owner's user_id.\n :param project_name: The project name.\n :param project_id: The project ID to update.\n :param verbose: If True, updated project details will be printed.\n :return: The updated project.\n \"\"\"\n with session_scope() as session:\n new_project = False\n project = None\n # Find project.\n if project_id:\n project = session.query(Project).filter(Project.project_id == project_id).first()\n if not project:\n project = Project()\n if not project_name:\n raise MissingFieldException('Must supply project name for new projects!')\n if not project_name:\n raise MissingFieldException('Must supply user ID for creating a new project!') \n new_project = True\n # Update details.\n if project_name is not None:\n project.project_name = project_name\n current_time = datetime.datetime.now()\n project.last_update_time = current_time\n # If this is a new project, add it.\n if new_project:\n project.creation_time = datetime.datetime.now()\n project.owner_id = owner_id\n session.add(project)\n session.commit()\n # We have to use a query in order to get a session-detached project.\n project = session.query(Project).filter(Project.project_id == project.project_id).one()\n if verbose:\n project.pretty_print()\n return project\n \n \ndef delete_project(project_id, verbose=True):\n \"\"\"\n Delete a project from the DB.\n\n :param project_id: The project ID to delete.\n :param verbose: If True, a summary will be printed to the screen.\n \"\"\"\n with session_scope() as session:\n session.query(Project).filter(Project.project_id == project_id).delete(synchronize_session='fetch')\n session.commit()\n if verbose:\n printer = pyprinter.get_printer()\n printer.write_line(printer.YELLOW + 'Deleted project {}!'.format(project_id))\n\n\n__all__ = ['get_projects', 'get_project', 'update_project', 'delete_project']\n","sub_path":"pyreact/query/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"135489535","text":"from VKinter_functions_for_test import show_list_of_dating_users, show_blacklist_of_dating_users,\\\r\n add_user_info\r\nfrom VKinter_database import engine\r\n\r\nconnection = engine.connect()\r\n\r\n\r\nclass TestVKinter:\r\n\r\n def setup(self):\r\n print('method setup')\r\n\r\n def teardown(self):\r\n print('method teardown')\r\n\r\n def test_show_list_of_dating_users(self, monkeypatch):\r\n monkeypatch.setattr('builtins.input', lambda x: 12345678)\r\n assert show_list_of_dating_users() == connection.execute(\"\"\"SELECT vk_id, dating_user_first_name,\r\n dating_user_last_name, age, user_id, city, photo_link FROM dating_user d\r\n JOIN photos p ON p.vk_id_dating_user = d.vk_id\r\n WHERE user_id = 12345678;\r\n \"\"\").fetchall()\r\n\r\n def test_show_blacklist_of_dating_users(self, monkeypatch):\r\n monkeypatch.setattr('builtins.input', lambda x: 12345678)\r\n assert show_blacklist_of_dating_users() == connection.execute(f\"\"\"SELECT vk_id, dating_user_first_name,\r\n dating_user_last_name, age, city\r\n FROM blacklist\r\n WHERE user_id = 12345678;\r\n \"\"\").fetchall()\r\n\r\n def test_add_user_info(self):\r\n assert add_user_info() == connection.execute(\"\"\"SELECT vk_id, range_for_search_age FROM vk_user\r\n WHERE vk_id = 111222333;\r\n \"\"\").fetchall()\r\n","sub_path":"adpy_diplom/test_VKinter.py","file_name":"test_VKinter.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416890896","text":"import json\nimport logging\nimport os\nimport re\nimport sys\nimport time\nimport uuid\n\nfrom hashlib import sha256, pbkdf2_hmac\nfrom hmac import compare_digest\nfrom random import uniform\nfrom typing import List, Dict, Any, Optional\n\nimport boto3\nimport jwt\nimport pydgraph\nfrom chalice import Chalice, Response, CORSConfig\n\nfrom grapl_analyzerlib.nodes.any_node import NodeView, raw_node_from_node_key\nfrom grapl_analyzerlib.nodes.dynamic_node import DynamicNodeView\nfrom pydgraph import DgraphClient\n\nIS_LOCAL = bool(os.environ.get(\"IS_LOCAL\", False))\n\n\nGRAPL_LOG_LEVEL = os.getenv(\"GRAPL_LOG_LEVEL\")\nLEVEL = \"ERROR\" if GRAPL_LOG_LEVEL is None else GRAPL_LOG_LEVEL\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(LEVEL)\nLOGGER.addHandler(logging.StreamHandler(stream=sys.stdout))\n\n\nif IS_LOCAL:\n import time\n\n while True:\n try:\n secretsmanager = boto3.client(\n \"secretsmanager\",\n region_name=\"us-east-1\",\n aws_access_key_id=\"dummy_cred_aws_access_key_id\",\n aws_secret_access_key=\"dummy_cred_aws_secret_access_key\",\n endpoint_url=\"http://secretsmanager.us-east-1.amazonaws.com:4566\",\n )\n\n JWT_SECRET = secretsmanager.get_secret_value(SecretId=\"JWT_SECRET_ID\",)[\n \"SecretString\"\n ]\n break\n except Exception as e:\n LOGGER.debug(e)\n time.sleep(1)\nelse:\n JWT_SECRET_ID = os.environ[\"JWT_SECRET_ID\"]\n\n secretsmanager = boto3.client(\"secretsmanager\")\n\n JWT_SECRET = secretsmanager.get_secret_value(SecretId=JWT_SECRET_ID,)[\n \"SecretString\"\n ]\n\nORIGIN = os.environ[\"UX_BUCKET_URL\"].lower()\n\nORIGIN_OVERRIDE = os.environ.get(\"ORIGIN_OVERRIDE\", None)\nDYNAMO = None\n\nif IS_LOCAL:\n MG_ALPHA = \"master_graph:9080\"\nelse:\n MG_ALPHA = \"alpha0.mastergraphcluster.grapl:9080\"\n\napp = Chalice(app_name=\"engagement-edge\")\n\norigin_re = re.compile(\n f'https://{os.environ[\"BUCKET_PREFIX\"]}-engagement-ux-bucket.s3[.\\w\\-]{1,14}amazonaws.com/',\n re.IGNORECASE,\n)\n\n\ndef list_all_lenses(prefix: str) -> List[Dict[str, Any]]:\n LOGGER.info(f\"connecting to dgraph at {MG_ALPHA}\")\n client_stub = pydgraph.DgraphClientStub(MG_ALPHA)\n dg_client = pydgraph.DgraphClient(client_stub)\n\n # DGraph query for all nodes with a 'lens' that matches the 'prefix'\n if prefix:\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: alloftext(lens, $a), orderdesc: score)\n {\n uid,\n node_key,\n node_type: dgraph.type,\n lens,\n score\n }\n }\"\"\"\n\n variables = {\"$a\": prefix}\n else:\n query = \"\"\"\n {\n q0(func: has(lens), orderdesc: score)\n {\n uid,\n node_key,\n node_type: dgraph.type,\n lens,\n score\n }\n }\"\"\"\n\n variables = {}\n\n txn = dg_client.txn(read_only=True)\n\n try:\n res = json.loads(txn.query(query, variables=variables).json)\n return res[\"q0\"]\n finally:\n txn.discard()\n\n\ndef edge_in_lens(\n dg_client: DgraphClient, node_uid: str, edge_name: str, lens_name: str\n) -> List[Dict[str, Any]]:\n query = f\"\"\"\n query q0($node_uid: string, $lens_name: string)\n {{\n q0(func: uid($node_uid)) @cascade {{\n {edge_name} {{\n uid,\n node_key,\n node_type: dgraph.type,\n\n ~scope @filter(eq(lens, $lens_name)) {{\n uid,\n node_type: dgraph.type,\n }}\n }}\n }}\n }}\n \"\"\"\n\n txn = dg_client.txn(read_only=True)\n\n try:\n variables = {\"$node_uid\": node_uid, \"$lens_name\": lens_name}\n res = json.loads(txn.query(query, variables=variables).json)\n return res[\"q0\"]\n finally:\n txn.discard()\n\n\ndef get_lens_scope(dg_client: DgraphClient, lens: str) -> Dict[str, Any]:\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: eq(lens, $a)) {\n uid,\n node_type: dgraph.type,\n node_key,\n lens,\n score,\n scope {\n uid,\n expand(_all_),\n node_type: dgraph.type,\n }\n }\n }\"\"\"\n\n txn = dg_client.txn(read_only=True)\n\n try:\n variables = {\"$a\": lens}\n res = json.loads(txn.query(query, variables=variables).json)\n if not res[\"q0\"]:\n return {}\n return res[\"q0\"][0]\n finally:\n txn.discard()\n\n\ndef get_lens_risks(dg_client: DgraphClient, lens: str) -> List[Dict[str, Any]]:\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: eq(lens, $a)) {\n uid,\n node_type: dgraph.type,\n node_key,\n lens,\n score,\n scope {\n uid,\n node_key,\n node_type: dgraph.type\n risks {\n uid,\n node_key,\n analyzer_name,\n node_type: dgraph.type,\n risk_score\n }\n }\n }\n }\"\"\"\n\n txn = dg_client.txn(read_only=True)\n\n try:\n variables = {\"$a\": lens}\n res = json.loads(txn.query(query, variables=variables).json)\n if not res[\"q0\"]:\n return []\n return res[\"q0\"][0][\"scope\"]\n finally:\n txn.discard()\n\n\ndef expand_forward_edges_in_scope(\n dgraph_client: DgraphClient, node: NodeView, lens: str\n) -> None:\n for edge_name, edge_type in node._get_forward_edge_types().items():\n\n if isinstance(edge_type, list):\n inner_edge_type = edge_type[0]\n else:\n inner_edge_type = edge_type\n edges_in_lens = edge_in_lens(dgraph_client, node.uid, edge_name, lens)\n for edge in edges_in_lens:\n for neighbors in edge.values():\n if not isinstance(neighbors, list):\n neighbors = [neighbors]\n for neighbor in neighbors:\n if neighbor.get(\"~scope\"):\n neighbor.pop(\"~scope\")\n node_edge = getattr(node, edge_name)\n try:\n neighbor_view = inner_edge_type(\n dgraph_client,\n node_key=neighbor[\"node_key\"],\n uid=neighbor[\"uid\"],\n )\n except Exception as e:\n LOGGER.error(f\"neighbor_view failed with: {e}\")\n continue\n LOGGER.debug(\n neighbor_view, neighbor_view.uid, neighbor_view.node_key\n )\n if isinstance(node_edge, list):\n node_edge.append(neighbor_view)\n else:\n node_edge = neighbor_view\n setattr(node, edge_name, node_edge)\n\n\ndef expand_reverse_edges_in_scope(\n dgraph_client: DgraphClient, node: NodeView, lens: str\n) -> None:\n for edge_name, (edge_type, forward_name) in node._get_reverse_edge_types().items():\n\n if isinstance(edge_type, list):\n inner_edge_type = edge_type[0]\n else:\n inner_edge_type = edge_type\n edges_in_lens = edge_in_lens(dgraph_client, node.uid, edge_name, lens)\n for edge in edges_in_lens:\n for neighbors in edge.values():\n\n if not isinstance(neighbors, list):\n neighbors = [neighbors]\n\n for neighbor in neighbors:\n if neighbor.get(\"~scope\"):\n neighbor.pop(\"~scope\")\n neighbor_view = inner_edge_type(\n dgraph_client,\n node_key=neighbor[\"node_key\"],\n uid=neighbor[\"uid\"],\n )\n\n node_edge = getattr(node, forward_name)\n\n if isinstance(node_edge, list):\n node_edge.append(neighbor_view)\n else:\n node_edge = neighbor_view\n setattr(node, forward_name, node_edge)\n\n\ndef expand_concrete_nodes(\n dgraph_client: DgraphClient, lens_name: str, concrete_nodes: List[NodeView]\n) -> None:\n for node in concrete_nodes:\n expand_forward_edges_in_scope(dgraph_client, node, lens_name)\n expand_reverse_edges_in_scope(dgraph_client, node, lens_name)\n\n for node in concrete_nodes:\n for prop_name, prop_type in node._get_property_types().items():\n setattr(node, prop_name, node.fetch_property(prop_name, prop_type))\n\n\ndef expand_node_forward(\n dgraph_client: DgraphClient, node_key: str\n) -> Optional[Dict[str, Any]]:\n query = \"\"\"\n query res($node_key: string)\n {\n\n res(func: eq(node_key, $node_key))\n {\n uid,\n expand(_all_) {\n uid,\n expand(_all_),\n node_type: dgraph.type\n }\n node_type: dgraph.type\n }\n\n }\n \"\"\"\n\n txn = dgraph_client.txn(read_only=True)\n variables = {\"$node_key\": node_key}\n try:\n res = json.loads(txn.query(query, variables=variables).json)\n finally:\n txn.discard()\n return res[\"res\"][0]\n\n\ndef expand_dynamic_node(dynamic_node: DynamicNodeView) -> Dict[str, Any]:\n node = raw_node_from_node_key(dynamic_node.dgraph_client, dynamic_node.node_key)\n edges = []\n expanded_node = expand_node_forward(\n dynamic_node.dgraph_client, dynamic_node.node_key\n )\n assert expanded_node, \"expanded_node\"\n for prop, val in expanded_node.items():\n if prop == \"node_type\" or prop == \"dgraph.type\" or prop == \"risks\":\n continue\n\n if isinstance(val, list):\n if val and isinstance(val[0], dict):\n for edge in val:\n edges.append(\n {\n \"from\": dynamic_node.node_key,\n \"edge_name\": prop,\n \"to\": edge[\"node_key\"],\n }\n )\n if isinstance(val, dict):\n edges.append(\n {\n \"from\": dynamic_node.node_key,\n \"edge_name\": prop,\n \"to\": val[\"node_key\"],\n }\n )\n\n return {\"node\": node, \"edges\": edges}\n\n\ndef lens_to_dict(dgraph_client: DgraphClient, lens_name: str) -> List[Dict[str, Any]]:\n current_graph = get_lens_scope(dgraph_client, lens_name)\n LOGGER.info(f\"Getting lens as dict {current_graph}\")\n if not current_graph or not current_graph.get(\"scope\"):\n return []\n nodes = []\n for graph in current_graph[\"scope\"]:\n try:\n nodes.append(NodeView.from_dict(dgraph_client, graph))\n except Exception as e:\n LOGGER.error(\"Failed to get NodeView from dict\", e)\n if current_graph.get(\"scope\"):\n current_graph.pop(\"scope\")\n\n concrete_nodes = [n.node for n in nodes if not isinstance(n.node, DynamicNodeView)]\n dynamic_nodes = [n.node for n in nodes if isinstance(n.node, DynamicNodeView)]\n\n expanded_dynamic_nodes = []\n for dynamic_node in dynamic_nodes:\n expanded = expand_dynamic_node(dynamic_node)\n expanded_dynamic_nodes.append(expanded)\n\n expand_concrete_nodes(dgraph_client, lens_name, concrete_nodes)\n\n results = [{\"node\": current_graph, \"edges\": []}]\n\n lens_risks = get_lens_risks(dgraph_client, lens_name)\n for node in lens_risks:\n edges = []\n risks = node.get(\"risks\", [])\n if not risks:\n LOGGER.warning(f\"Node in engagement graph has no connected risks {node}\")\n for risk in risks:\n try:\n risk[\"node_key\"] = node[\"node_key\"] + risk[\"analyzer_name\"]\n edge = {\n \"from\": node[\"node_key\"],\n \"edge_name\": \"risks\",\n \"to\": risk[\"node_key\"],\n }\n edges.append(edge)\n except Exception as e:\n LOGGER.error(f\"risk edge failed: {risk} {e}\")\n\n results.append(\n {\"node\": node, \"edges\": edges,}\n )\n\n results.extend([n.to_dict() for n in concrete_nodes])\n results.extend(expanded_dynamic_nodes)\n return results\n\n\ndef try_get_updated_graph(body):\n LOGGER.info(\"Trying to update graph\")\n LOGGER.info(f\"connecting to dgraph at {MG_ALPHA}\")\n client_stub = pydgraph.DgraphClientStub(MG_ALPHA)\n dg_client = pydgraph.DgraphClient(client_stub)\n\n lens = body[\"lens\"]\n\n # Mapping from `uid` to node hash\n initial_graph = body[\"uid_hashes\"]\n\n while True:\n LOGGER.info(\"Getting updated graph\")\n current_graph = lens_to_dict(dg_client, lens)\n\n updates = {\"updated_nodes\": current_graph, \"removed_nodes\": []}\n\n return updates\n\n\ndef respond(err, res=None, headers=None):\n req_origin = app.current_request.headers.get(\"origin\", \"\")\n\n LOGGER.info(f\"responding, origin: {app.current_request.headers.get('origin', '')}\")\n if not headers:\n headers = {}\n\n if IS_LOCAL:\n override = app.current_request.headers.get(\"origin\", \"\")\n LOGGER.info(f\"overriding origin with {override}\")\n else:\n override = ORIGIN_OVERRIDE\n\n if origin_re.match(req_origin):\n LOGGER.info(\"Origin matched\")\n allow_origin = req_origin\n else:\n LOGGER.info(\"Origin did not match\")\n # allow_origin = override or ORIGIN\n allow_origin = req_origin\n\n return Response(\n body={\"error\": err} if err else json.dumps({\"success\": res}),\n status_code=400 if err else 200,\n headers={\n \"Access-Control-Allow-Origin\": allow_origin,\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Methods\": \"GET,POST,OPTIONS\",\n \"X-Requested-With\": \"*\",\n \"Access-Control-Allow-Headers\": \"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With\",\n **headers,\n },\n )\n\n\ndef get_salt_and_pw(table, username):\n LOGGER.info(f\"Getting salt for user: {username}\")\n response = table.get_item(Key={\"username\": username,})\n\n if not response.get(\"Item\"):\n return None, None\n\n salt = response[\"Item\"][\"salt\"].value\n password = response[\"Item\"][\"password\"]\n return salt, password\n\n\ndef hash_password(cleartext, salt) -> str:\n hashed = sha256(cleartext).digest()\n return pbkdf2_hmac(\"sha256\", hashed, salt, 512000).hex()\n\n\ndef user_auth_table():\n global DYNAMO\n if IS_LOCAL:\n DYNAMO = DYNAMO or boto3.resource(\n \"dynamodb\",\n region_name=\"us-west-2\",\n endpoint_url=\"http://dynamodb:8000\",\n aws_access_key_id=\"dummy_cred_aws_access_key_id\",\n aws_secret_access_key=\"dummy_cred_aws_secret_access_key\",\n )\n else:\n DYNAMO = DYNAMO or boto3.resource(\"dynamodb\")\n\n return DYNAMO.Table(os.environ[\"USER_AUTH_TABLE\"])\n\n\ndef create_user(username, cleartext):\n table = user_auth_table()\n # We hash before calling 'hashed_password' because the frontend will also perform\n # client side hashing\n pepper = \"f1dafbdcab924862a198deaa5b6bae29aef7f2a442f841da975f1c515529d254\"\n\n hashed = sha256(cleartext + pepper + username).digest()\n for i in range(0, 5000):\n hashed = sha256(hashed).digest()\n\n salt = os.urandom(16)\n password = hash_password(hashed, salt)\n\n table.put_item(Item={\"username\": username, \"salt\": salt, \"password\": password})\n\n\ndef login(username, password):\n # Connect to dynamodb table\n table = user_auth_table()\n\n # Get salt for username\n salt, true_pw = get_salt_and_pw(table, username)\n if not salt or not true_pw:\n return None\n\n # Hash password\n to_check = hash_password(password.encode(\"utf8\"), salt)\n\n if not compare_digest(to_check, true_pw):\n time.sleep(round(uniform(0.1, 3.0), 2))\n return None\n\n # Use JWT to generate token\n return jwt.encode({\"username\": username}, JWT_SECRET, algorithm=\"HS256\").decode(\n \"utf8\"\n )\n\n\ndef check_jwt(headers):\n encoded_jwt = None\n for cookie in headers.get(\"Cookie\", \"\").split(\";\"):\n if \"grapl_jwt=\" in cookie:\n encoded_jwt = cookie.split(\"grapl_jwt=\")[1].strip()\n\n if not encoded_jwt:\n return False\n\n try:\n jwt.decode(encoded_jwt, JWT_SECRET, algorithms=[\"HS256\"])\n return True\n except Exception as e:\n LOGGER.error(e)\n return False\n\n\ndef lambda_login(event):\n body = event.json_body\n login_res = login(body[\"username\"], body[\"password\"])\n # Clear out the password from the dict, to avoid accidentally logging it\n body[\"password\"] = \"\"\n if IS_LOCAL:\n domain = \"\"\n else:\n domain = \"Domain=.amazonaws.com;\"\n cookie = f\"grapl_jwt={login_res}; {domain} secure; HttpOnly; SameSite=None\"\n if login_res:\n return cookie\n\n\ncors_config = CORSConfig(\n allow_origin=ORIGIN_OVERRIDE or ORIGIN, allow_credentials=\"true\",\n)\n\n\ndef requires_auth(path):\n if not IS_LOCAL:\n path = \"/{proxy+}\" + path\n\n def route_wrapper(route_fn):\n @app.route(path, methods=[\"OPTIONS\", \"POST\"])\n def inner_route():\n if app.current_request.method == \"OPTIONS\":\n return respond(None, {})\n\n if not check_jwt(app.current_request.headers):\n LOGGER.warn(\"not logged in\")\n return respond(\"Must log in\")\n try:\n return route_fn()\n except Exception as e:\n LOGGER.error(e)\n return respond(\"Unexpected Error\")\n\n return inner_route\n\n return route_wrapper\n\n\ndef no_auth(path):\n if not IS_LOCAL:\n path = \"/{proxy+}\" + path\n\n def route_wrapper(route_fn):\n @app.route(path, methods=[\"OPTIONS\", \"GET\", \"POST\"])\n def inner_route():\n if app.current_request.method == \"OPTIONS\":\n return respond(None, {})\n try:\n return route_fn()\n except Exception as e:\n LOGGER.error(e)\n return respond(\"Unexpected Error\")\n\n return inner_route\n\n return route_wrapper\n\n\n@no_auth(\"/login\")\ndef login_route():\n LOGGER.debug(\"/login_route\")\n request = app.current_request\n cookie = lambda_login(request)\n if cookie:\n LOGGER.info(\"logged in\")\n return respond(None, \"True\", headers={\"Set-Cookie\": cookie})\n else:\n LOGGER.warn(\"not logged in\")\n return respond(\"Failed to login\")\n\n\n@no_auth(\"/checkLogin\")\ndef check_login():\n LOGGER.debug(\"/checkLogin\")\n request = app.current_request\n if check_jwt(request.headers):\n return respond(None, \"True\")\n else:\n return respond(None, \"False\")\n\n\n@app.route(\"/{proxy+}\", methods=[\"OPTIONS\", \"POST\", \"GET\"])\ndef nop_route():\n LOGGER.debug(app.current_request.context[\"path\"])\n\n path = app.current_request.context[\"path\"]\n\n if path == \"/prod/login\":\n return login_route()\n elif path == \"/prod/checkLogin\":\n return check_login()\n\n return respond(\"InvalidPath\")\n","sub_path":"src/python/engagement_edge/src/engagement_edge.py","file_name":"engagement_edge.py","file_ext":"py","file_size_in_byte":19750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136387500","text":"import logging\nfrom typing import List, Optional\nfrom chia.types.blockchain_format.program import Program, SerializedProgram\nfrom chia.types.generator_types import BlockGenerator, GeneratorArg, GeneratorBlockCacheInterface\nfrom chia.util.ints import uint32\nfrom chia.wallet.puzzles.load_clvm import load_clvm\n\nDESERIALIZE_MOD = load_clvm(\"chialisp_deserialisation.clvm\", package_or_requirement=\"chia.wallet.puzzles\")\n\nlog = logging.getLogger(__name__)\n\n\ndef create_block_generator(\n generator: SerializedProgram, block_heights_list: List[uint32], generator_block_cache: GeneratorBlockCacheInterface\n) -> Optional[BlockGenerator]:\n \"\"\" `create_block_generator` will returns None if it fails to look up any referenced block \"\"\"\n generator_arg_list: List[GeneratorArg] = []\n for i in block_heights_list:\n previous_generator = generator_block_cache.get_generator_for_block_height(i)\n if previous_generator is None:\n log.error(f\"Failed to look up generator for block {i}. Ref List: {block_heights_list}\")\n return None\n generator_arg_list.append(GeneratorArg(i, previous_generator))\n return BlockGenerator(generator, generator_arg_list)\n\n\ndef make_generator_args(generator_ref_list: List[SerializedProgram]) -> SerializedProgram:\n \"\"\"\n `make_generator_args`: The format and contents of these arguments affect consensus.\n \"\"\"\n gen_ref_list = [Program.from_bytes(bytes(g)) for g in generator_ref_list]\n return SerializedProgram.from_bytes(bytes(Program.to([DESERIALIZE_MOD, gen_ref_list])))\n","sub_path":"chia/full_node/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559932183","text":"import os\nfrom tqdm import trange\nfrom time import sleep\n\ndef msj1():\n current_path = os.getcwd()\n print(f'''\n-----------------------------------------------\n(admin) {current_path}> cd semana7/miercoles/sorpresas''')\n sleep(1)\n print(f'''(admin) {current_path}\\\\semana7\\\\miercoles\\\\sorpresas> simulacion.exe''')\n sleep(2)\n print(f''' -simulacion.exe is running-\n-----------------------------------------------\n ''')\n for epoch in trange(5 , ncols=75):\n sleep(0.5)\n print(f'''WAR[0]: simulacion.exe requiere confirmacion de identidad''')\n sleep(2)\n print(f'''Activando webcam''')\n sleep(5)\n print(f'''Presiona: ''')\n sleep(1)\n print(f'''espacio - tomar foto''')\n sleep(1)\n print(f'''q - para continuar''')\n sleep(1)\n\n\ndef msj2():\n sleep(0.5)\n print(f'''AUTENTIFICANDO''')\n sleep(2)\n\ndef msj3():\n sleep(0.5)\n print(f'''\nRECONOCIMIENTO DE CARITA CONFIRMADO\n''')\n sleep(5)\n print(f'''(Deivi) C:\\\\> No se que tenga tu voz''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> que hasta a un loco calma''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> un loco en simulacion''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> con una loca del alma''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> Aun hay una sorpresa''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> Pero tendras que esperar''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> Solo un poco ...''')\n sleep(1)\n print(f'''(Deivi) C:\\\\> https://github.com/LuisDFJ/Sirio''')\n sleep(1)\n","sub_path":"msj.py","file_name":"msj.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34974369","text":"\nimport shutil\nimport os\nfrom enum import Enum\nfrom os import listdir\nfrom os.path import isfile, join\n\nclass All_Day_Night(Enum):\n all_ = 'all'\n day = 'day'\n night = 'night'\n\n\n# Force delete folder if exist\ndef mkdir(path, force = False):\n try:\n os.mkdir(path)\n except FileExistsError:\n if force:\n shutil.rmtree(path)\n os.mkdir(path)\n\n\n\ndef parse_xml_to_dict(xml_path):\n # private\n def recursive_parse_xml_to_dict(xml):\n if not len(xml):\n return {xml.tag: xml.text}\n result = {}\n for child in xml:\n child_result = recursive_parse_xml_to_dict(child)\n if child.tag != 'object':\n result[child.tag] = child_result[child.tag]\n else:\n if child.tag not in result:\n result[child.tag] = []\n result[child.tag].append(child_result[child.tag])\n return {xml.tag: result}\n\n import tensorflow as tf\n from lxml import etree\n with tf.gfile.GFile(xml_path, 'r') as fid:\n xml_str = fid.read()\n xml = etree.fromstring(xml_str)\n return recursive_parse_xml_to_dict(xml)['annotation']\n\n\n\n\ndef get_files(dir):\n return [f for f in listdir(dir) if isfile(join(dir, f))]","sub_path":"python_tools/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"123517966","text":"\"\"\"bus_line_scorer.py\n\nScores each district based on bus lines.\n\"\"\"\n\nimport json\n\nfrom math import log\n\nfrom sp_districts import get_districts, is_line_in_district\n\n\n_INPUT_FILE = 'data/bus_lines_accessibility.json'\n_OUTPUT_FILE = 'data/bus_lines_scores.csv'\n\n\ndef get_bus_lines():\n \"\"\"Returns an object with raw bus lines data.\n \"\"\"\n with open(_INPUT_FILE, 'r') as f:\n bus_lines_json = json.load(f)\n\n for bus_line in bus_lines_json:\n # Transforms coordinates to GeoJson standard.\n bus_line['shape'] = map(lambda pair: (pair['lng'], pair['lat']),\n bus_line['shape'])\n\n return bus_lines_json\n\n\ndef calculate_score(districts=None, bus_lines=None):\n \"\"\"Scores each district, based on bus lines data.\n \"\"\"\n bus_lines = bus_lines or get_bus_lines()\n districts = districts or get_districts()\n\n for district in districts:\n print('Calculating score for {}...'.format(district['name']))\n district['weight'] = 0\n district['count'] = 0\n for bus_line in bus_lines:\n if is_line_in_district(district, bus_line['shape']):\n district['weight'] += bus_line['accessibility_score']\n district['count'] += 1\n\n # Districts score is the \"density\" of weighted bus lines.\n district['score'] = log(district['weight'] / district['polygon'].area)\n\n # Normalizes scores.\n max_score = max(district['score'] for district in districts)\n for district in districts:\n district['score'] = district['score'] / max_score\n\n return districts\n\n\ndef export_csv(districts):\n \"\"\"Exports result to a csv file.\n \"\"\"\n headers = ['district_id', 'name', 'count', 'weight', 'score']\n lines = [\n [\n dtc['code'],\n dtc['name'],\n str(dtc['count']),\n str(dtc['weight']),\n str(dtc['score']),\n ]\n for dtc in districts\n ]\n\n lines = sorted(lines, key=lambda line: int(line[0]))\n\n # Writes to file.\n with open(_OUTPUT_FILE, 'w') as f:\n f.write('\\n'.join(','.join(line) for line in ([headers] + lines)))\n\n\n\nif __name__ == '__main__':\n export_csv(calculate_score())\n","sub_path":"scripts/python/bus_line_scorer.py","file_name":"bus_line_scorer.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"183495888","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2017 Autonomous Inc. All rights reserved.\n#\n\nfrom __future__ import print_function\nimport os\nimport io\nimport time\nimport threading\nimport subprocess\nimport picamera\nimport json\nfrom PIL import Image \nimport zbar\nimport time \nimport numpy as np\nfrom grpc.beta import implementations\nimport zmq\nfrom apis import (prediction_service_pb2, predict_pb2, dtypes, tensor_pb2,\n tensor_util)\n\nfrom sklearn.cluster import KMeans \nfrom matplotlib.colors import rgb_to_hsv \nfrom ProductControl import ProductControl\nfrom Commands import COMMANDS\nfrom help import Help\n\nfrom aos.system.libs.util import Util\nimport requests\nfrom aos.system.sdk.python.service_wrapper import AutonomousService\n\nfrom trashControl import TrashControlClientTask \nimport helpers\n\n# Create a pool of image processors\ndone = False\nlock = threading.Lock()\npool = [] \n\nhost = \"35.198.234.42\"\nAPI_AI = \"35.198.234.42\"\nAPI_POST_IMG=\"http://35.198.228.87/api/image/\"\nAPI_POST_VERIFY = \"http://35.198.228.87/api/image-profile/\"\nAPI_POST_ADD_PRODUCT = \"http://35.198.228.87/api/product/\"\nAPI_POST_DELETE_PRODUCT = \"http://35.198.228.87/api/product/\" \n\n\n\nport = 9001\nmessage =None\ntrash = None \ncheck_internet_connection = False\nwifi_info = {}\ninit_state=0\nTIME_CHECK = 10\nMAX_COUNT = 3\nMAX_TIME_DELAY = 6\nZMQ_WIFI_SERVICE_PORT=\"tcp://127.0.0.1:9950\" \nSETTING_FILE = \"/home/pi/aos/data/product_settings.json\" \nIMAGE_TEST =\"image.jpg\" \nPRODUCT_ID = \"\" \nTOKEN = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im9zY2FyQGF1dG9ub21vdXMuYWkiLCJleHAiOjE1MzAzNDkwMTgsImlkIjo3OTc1Nn0.3SG7UnPHSfFLSSwb5gwL2sQJq-ThEO8LvSXSOVSKWcs\"\nDONE_CAM0 = False\nDONE_CAM1 = False\n\n\nclass TrashControlServerTask(threading.Thread):\n def __init__(self):\n \"\"\"ClientTask\"\"\"\n threading.Thread.__init__ (self)\n\n def run(self):\n global message, wifi_info , PRODUCT_ID, TOKEN\n context = zmq.Context()\n socket = context.socket(zmq.REP) \n socket.bind(\"ipc:///tmp/sensor:9999\") \n #OpenCamera Here... \n while True:\n try:\n data = socket.recv_json()\n time.sleep(1)\n socket.send(\"1\")\n print(\"recive: {0}\".format(data)) \n print(\"message: {0}\".format(message)) \n if message == None or (message[\"ID\"]!=\"SCAN_WIFI_SSID\" and message[\"ID\"]!=\"WIFI_ERROR\"):\n if data[\"ID\"]==\"COVER_STATUS\" and data[\"Value\"]==1:\n #trash.disable_local_control() \n #time.sleep(2)\n trash.enable_local_control() \n message=data\n if data[\"ID\"]!=\"COVER_STATUS\":\n message=data\n\n if data[\"ID\"]==\"RESET_BUTTON\":\n print (\"RESET_BUTTON\")\n\n #call delete product ...\n url = API_POST_DELETE_PRODUCT + str(PRODUCT_ID) + \"/\"\n headers = {\n 'Authorization': 'JWT ' + TOKEN\n }\n try:\n response = requests.delete(url, data=None, headers=headers) \n print (response) \n except:\n print(\"error\") \n\n trash.enable_local_control() \n message={}\n message[\"ID\"]=\"SCAN_WIFI_SSID\"\n trash.send_led(\"red\") \n trash.send_open_cover_case() \n cmd =[\"rm\",\"-rf\", SETTING_FILE]\n wifi_info = None \n helpers.execute_cmd_return(cmd, 5) \n trash.send_blink_led(\"red\",\"MS_300\")\n\n except:\n print(\"error\")\n \n\n\ndef capturecc(cam):\n global DONE_CAM0, DONE_CAM1\n if cam == \"0\":\n DONE_CAM0=False\n if cam == \"1\":\n DONE_CAM1=False\n if os.path.exists(\"/home/pi/aos/data/image\"+cam+\".jpg\"):\n os.remove(\"/home/pi/aos/data/image\"+cam+\".jpg\")\n \n print(\"start capturecc \" + cam)\n os.sys\n t = time.time()\n #os.system(\"sudo fswebcam -d /dev/video\"+cam+\" -r 640x320 image\"+cam+\".jpg\")\n os.system(\"sudo fswebcam -d /dev/video\"+cam+\" -r 640x320 /home/pi/aos/data/image\"+cam+\".jpg\") \n print( time.time()-t) \n print (\"done\")\n if cam == \"0\":\n DONE_CAM0=True\n if cam == \"1\":\n DONE_CAM1=True\n\nclass ImageProcessor(threading.Thread):\n\n channel = None#implementations.insecure_channel(API_AI, int(port))\n stub = None #prediction_service_pb2.beta_create_PredictionService_stub(channel)\n request = None \n def __init__(self):\n super(ImageProcessor, self).__init__()\n self.stream = io.BytesIO()\n self.event = threading.Event()\n self.imagebk = None \n self.terminated = False\n self.wifi_status= False \n self.detect_object_count=0 \n self.start() \n\n def mapping_class(self, class_id):\n class_id = class_id[0]\n if class_id == 1 or class_id == 3 or class_id == 5 or class_id == 9 or class_id == 11 or class_id == 12:\n return 0\n elif class_id == 0 or class_id == 2 or class_id == 4 or class_id == 6 or class_id == 7 or class_id == 8 or class_id == 10:\n return 1\n \n def init_ai_streaming(self):\n print (\"init streaming ai\")\n try:\n self.channel = implementations.insecure_channel(API_AI, int(port))\n self.stub = prediction_service_pb2.beta_create_PredictionService_stub(self.channel)\n self.request = predict_pb2.PredictRequest()\n self.request.model_spec.name = \"recycle\"\n self.request.model_spec.signature_name = \"scores\"\n except:\n print (\"fail streaming ai\") \n\n def post_request_ai(self,data): \n try: \n t = time.time() \n self.request.inputs[\"image\"].CopyFrom(tensor_util.make_tensor_proto([data])) \n result = self.stub.Predict(self.request, 30.0) \n print(\"Print TIME POST:\")\n print(time.time() - t) \n prob = tensor_util.MakeNdarray(result.outputs[\"prob\"]) \n print (prob[0]) \n class_id = tensor_util.MakeNdarray(result.outputs[\"class_id\"]) \n result_value = self.mapping_class( class_id ) \n index = np.argmax(prob[0])\n return {\"result_value\":result_value, \"index\":index, \"prob\": prob, \"class_id\": class_id}\n except Exception as e:\n print (\"error\", e)\n self.init_ai_streaming() \n return {\"result_value\":3, \"index\":0, \"prob\": None,\"class_id\":None}\n \n def run(self):\n # This method runs in a separate thread\n global done\n global message \n global wifi_info , PRODUCT_ID, TOKEN\n detect_count = 0\n #self.init_ai_streaming()\n\n while not self.terminated:\n # Wait for an image to be written to the stream \n if self.event.wait(1):\n try:\n ###Get New Frame here....\n print (\"get_images\") \n self.stream.seek(0) \n pil = Image.open(self.stream)\n if detect_count > 0 :\n detect_count=detect_count+1\n print (\"Sleep %d \" % detect_count)\n time.sleep(1)\n if detect_count >= (MAX_TIME_DELAY + MAX_TIME_DELAY):\n detect_count =0\n message = None \n if message!=None and message[\"ID\"]==\"SCAN_WIFI_SSID\":\n \n outputstream = io.BytesIO() \n pil.save(outputstream, format='JPEG') \n data_image_post_reconnect = outputstream.getvalue() \n\n print (\"...Waiting for QR_CODE setup...\")\n #message = None \n # create a reader\n scanner = zbar.ImageScanner() \n # configure the reader\n scanner.parse_config('enable') \n pil = pil.convert('L')\n #pil = crop_img(pil) # Add\n width, height = pil.size\n raw = pil.tobytes() \n # wrap image data\n image = zbar.Image(width, height, 'Y800', raw) \n # scan the image for barcodes\n scanner.scan(image) \n # extract results\n datajson= None \n for symbol in image:\n # do something useful with results\n print ('decoded', symbol.type, 'symbol', '\"%s\"' % symbol.data)\n datajson = symbol.data \n try: \n wifi_info=json.loads(datajson) \n try:\n message[\"ID\"] = \"WIFI_PROCESSING\" \n trash.send_blink_led(\"red\",\"MS_50\")\n command = ['sudo','/home/pi/aos/ability/product_control/wifi.sh',wifi_info[\"ssid\"], wifi_info[\"pass\"]]\n print(command)\n percent = helpers.execute_cmd_return(command,10) \n message= None\n wifi_connect_check= False\n counntt = 0 \n while counntt <=5:\n if (helpers.check_internet()==True):\n message = None \n print (\"reconnect---\")\n if wifi_connect_check == False:\n wifi_connect_check = True\n trash.send_turn_off_blink_led()\n trash.send_led(\"blue\")\n trash.send_close_cover_case()\n #Add PRODUCT_ID \n try:\n addresult = helpers.postData(API_POST_ADD_PRODUCT,{\"name\":\"Oscar\"}, None , wifi_info[\"token\"] )\n print(addresult)\n if addresult != None :\n PRODUCT_ID = addresult[\"id\"]\n wifi_info[\"product_id\"]=PRODUCT_ID\n #TOKEN = wifi_info[\"token\"]\n helpers.write_file(SETTING_FILE,wifi_info)\n\n counntt = 10\n break;\n else :\n addresult = None \n except Exception as ex:\n print (str(ex) ) \n addresult = None\n\n time.sleep(1)\n counntt = counntt+1\n\n if wifi_connect_check ==False:\n message= None\n trash.send_blink_led(\"red\",\"MS_300\")\n message={}\n message[\"ID\"]=\"SCAN_WIFI_SSID\"\n\n except Exception as ex:\n print (str(ex) )\n \n except Exception as e:\n raise ParseError(e)\n\n #### \n if (detect_count==0 or detect_count >=MAX_TIME_DELAY) and message!=None and message[\"ID\"]==\"COVER_STATUS\" and message[\"Value\"]==1: \n t1 = threading.Thread(target=capturecc, args=(\"1\",)).start()\n t2 = threading.Thread(target=capturecc, args=(\"0\",)).start()\n\n output = io.BytesIO() \n pil.save(output, format='JPEG') \n data = output.getvalue() \n self.detect_object_count = 1 \n print (\"capture from front camera\")\n detect_count = 0\n message = None \n self.detect_object_count =0 \n trash.send_close_cover_case() \n\n while True:\n time.sleep(1)\n if os.path.exists(\"/home/pi/aos/data/image1.jpg\"):\n #ai_result0 = helpers.postDataFile(API_POST_IMG,{\"category\":1, \"product\":PRODUCT_ID}, \"/home/pi/aos/data/image1.jpg\", TOKEN )\n data0 = open(\"/home/pi/aos/data/image1.jpg\",'rb').read()\n ai_result0 = helpers.postData2(\"http://192.168.1.113:8545/api/capture1\", data0 , TOKEN )\n print(\"respone data from server image1\")\n print(ai_result0)\n break\n while True:\n if os.path.exists(\"/home/pi/aos/data/image0.jpg\"):\n #ai_result0 = helpers.postDataFile(API_POST_IMG,{\"category\":1, \"product\":PRODUCT_ID}, \"/home/pi/aos/data/image0.jpg\" , TOKEN )\n data0 = open(\"/home/pi/aos/data/image0.jpg\",'rb').read()\n ai_result0 = helpers.postData2(\"http://192.168.1.113:8545/api/capture2\", data0 , TOKEN )\n print(\"respone data from server image0\")\n print(ai_result0)\n break\n\n # ai_result = helpers.post3DataFile(API_POST_IMG,{\"category\":1, \"product\":PRODUCT_ID}, \n # data, \"/home/pi/aos/data/image0.jpg\" , \"/home/pi/aos/data/image1.jpg\" , TOKEN )\n # print (ai_result)\n \n #ai_result = helpers.postData(API_POST_IMG,{\"category\":1, \"product\":PRODUCT_ID}, data , TOKEN )\n \n ai_result = helpers.postData2(\"http://192.168.1.113:8545/api/capture0\", data , TOKEN )\n# print(\"respone data from server imagemid\")\n# print(ai_result)\n# if ai_result == None :\n# ai_result = {\"type_ai\":0}\n# #ai_result[\"type_ai\"] = 2\n#\n# if ai_result[\"type_ai\"] == 1: # and prob[0][index] >=0.3:\n# #tai' che\n# trash.send_go_recycle()\n# print (\"1\" )\n# elif ai_result[\"type_ai\"] == 0: # and prob[0][index] >=0.3:\n# #ko tai che.\n# print (\"0\")\n# trash.send_go_trash()\n# else:\n# # Khong phan biet duoc rac nao.\n# print (\"Khong phan biet duoc rac nao.\")\n# trash.send_led(\"red\")\n# if 'id' in ai_result:\n# self.imagebk = ai_result[\"id\"]\n# ai_result[\"type_ai\"] = 2\n trash.send_led(\"blue\")\n #trash.enable_local_control() \n # if ai_result[\"type_ai\"] == 2 and 'id' in ai_result :\n # trash.disable_sensor_control()\n \n #Bam go_trash\n if message!=None and message[\"ID\"]==\"TRASH_BUTTON\" and message[\"Value\"]==2:\n print (\"user press button Trash\")\n trash.enable_sensor_control()\n message = None \n if self.imagebk !=None : \n ai_result = helpers.postData(API_POST_VERIFY,{\"image\":self.imagebk, \"type\":0 }, None , TOKEN )\n print(ai_result)\n self.imagebk = None \n\n if message!=None and message[\"ID\"]==\"RECYCLE_BUTTON\" and message[\"Value\"]==3:\n print (\"user press button RECYCLE_BUTTON\")\n trash.enable_sensor_control()\n message = None \n if self.imagebk !=None :\n ai_result = helpers.postData(API_POST_VERIFY,{\"image\":self.imagebk, \"type\":0 }, None , TOKEN )\n print(ai_result)\n self.imagebk = None \n del pil \n finally: \n print (\"finally stream\")\n self.stream.seek(0)\n self.stream.truncate()\n self.event.clear() \n with lock:\n pool.append(self)\n \n\nclass CameraServerTask(threading.Thread):\n def __init__(self):\n print (\"\"\"CameraServerTask\"\"\")\n threading.Thread.__init__ (self)\n\n def streams(self):\n global pool\n global lock \n while not done:\n with lock:\n if pool:\n processor = pool.pop()\n else:\n processor = None\n if processor:\n yield processor.stream\n processor.event.set()\n else:\n # When the pool is starved, wait a while for it to refill\n time.sleep(0.1)\n\n def run(self):\n ## Start Camera.\n global pool\n global lock \n with picamera.PiCamera() as camera:\n pool = [ImageProcessor()] # for i in range(4)]\n camera.resolution = (640, 480)\n camera.framerate = 10\n #camera.brightness = 60 \n time.sleep(2)\n camera.capture_sequence(self.streams(), use_video_port=True) \n \n print (\"run camera Service\")\n while pool:\n with lock:\n processor = pool.pop()\n processor.terminated = True\n processor.join() \n\n\n \n\n\ndef main(json_data, error):\n \n if error:\n return print (error)\n data = json_data['data']\n sensor = json_data['type'] if 'type' in json_data else None\n print( json_data) \n # global check_internet_connection\n # global message\n # if sensor == COMMANDS.CHECK_INTERNET_CONNECTION: \n # print (\"CHECK_INTERNET_CONNECTION\")\n # message={} \n # message[\"ID\"] = \"SCAN_WIFI_SSID\"\n # #cron_check_internet.reset()\n # #cron_check_internet.run() \n # else: \n # print (json_data) \n \nif __name__ == '__main__':\n # t = time.time() \n global message\n print( \"____init_____\") \n serverTask = TrashControlServerTask()\n serverTask.start() \n\n trash = TrashControlClientTask()\n trash.send_led(\"red\")\n\n # global init_state, wifi_info, PRODUCT_ID, TOKEN\n # init_state=0 \n\n CameraServer = CameraServerTask() \n CameraServer.start() \n wifi_info = helpers.read_file(SETTING_FILE) \n\n print (\"WIFI FILE INFO\")\n print (wifi_info)\n if wifi_info == None : \n message={}\n message[\"ID\"] = \"SCAN_WIFI_SSID\"\n trash.send_blink_led(\"red\",\"MS_300\")\n trash.send_open_cover_case() \n else: \n PRODUCT_ID = wifi_info[\"product_id\"]\n #TOKEN = wifi_info[\"token\"]\n\n if helpers.check_internet()==True:\n trash.send_led(\"blue\") \n print( \"Main _ service \")\n AutonomousService().run(main)\n \n","sub_path":"Software/ability/product_control/main_bu_server_capture.py","file_name":"main_bu_server_capture.py","file_ext":"py","file_size_in_byte":20240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"420936209","text":"'''\nSupport for YUM\n'''\n\nimport logging\nimport os\nimport re\nfrom collections import namedtuple\n\n\nlog = logging.getLogger(__name__)\n\ndef __virtual__():\n '''\n Confine this module to yum based systems\n '''\n # Work only on RHEL/Fedora based distros with python 2.6 or greater\n try:\n os_grain = __grains__['os']\n os_family = __grains__['os_family']\n os_major_version = int(__grains__['osrelease'].split('.')[0])\n except Exception:\n return False\n\n # Fedora <= 10 need to use this module\n if os_grain == 'Fedora' and os_major_version < 11:\n return 'pkg'\n else:\n # RHEL <= 5 and all variants need to use this module\n if os_family == 'RedHat' and os_major_version <= 5:\n return 'pkg'\n return False\n\n\ndef _parse_yum(arg):\n '''\n A small helper to parse yum output; returns a list of namedtuples\n '''\n cmd = 'yum -q {0}'.format(arg)\n out = __salt__['cmd.run_stdout'](cmd)\n YumOut = namedtuple('YumOut', ('name', 'version', 'status'))\n\n results = []\n\n for line in out.splitlines():\n if len(line.split()) == 3:\n namearchstr, pkgver, pkgstatus = line.split()\n pkgname = namearchstr.rpartition('.')[0]\n\n results.append(YumOut(pkgname, pkgver, pkgstatus))\n\n return results\n\n\ndef _list_removed(old, new):\n '''\n List the packages which have been removed between the two package objects\n '''\n pkgs = []\n for pkg in old:\n if pkg not in new:\n pkgs.append(pkg)\n return pkgs\n\n\ndef _parse_pkg_meta(path):\n '''\n Retrieve package name and version number from package metadata\n '''\n name = ''\n version = ''\n rel = ''\n result = __salt__['cmd.run_all']('rpm -qpi \"{0}\"'.format(path))\n if result['retcode'] == 0:\n for line in result['stdout'].split('\\n'):\n # Older versions of rpm command produce two-column output when run\n # with -qpi. So, regexes should not look for EOL after capture\n # group.\n if not name:\n m = re.match('^Name\\s*:\\s*(\\S+)',line)\n if m:\n name = m.group(1)\n continue\n if not version:\n m = re.match('^Version\\s*:\\s*(\\S+)',line)\n if m:\n version = m.group(1)\n continue\n if not rel:\n m = re.match('^Release\\s*:\\s*(\\S+)',line)\n if m:\n version = m.group(1)\n continue\n if rel: version += '-{0}'.format(rel)\n return name,version\n\n\ndef available_version(name):\n '''\n The available version of the package in the repository\n\n CLI Example::\n\n salt '*' pkg.available_version \n '''\n out = _parse_yum('list updates {0}'.format(name))\n return out[0].version if out else ''\n\n\ndef upgrade_available(name):\n '''\n Check whether or not an upgrade is available for a given package\n\n CLI Example::\n\n salt '*' pkg.upgrade_available \n '''\n return available_version(name) != ''\n\n\ndef version(name):\n '''\n Returns a version if the package is installed, else returns an empty string\n\n CLI Example::\n\n salt '*' pkg.version \n '''\n pkgs = list_pkgs()\n if name in pkgs:\n return pkgs[name]\n else:\n return ''\n\n\ndef list_pkgs():\n '''\n List the packages currently installed in a dict::\n\n {'': ''}\n\n CLI Example::\n\n salt '*' pkg.list_pkgs\n '''\n out = _parse_yum('list installed')\n return dict([(i.name, i.version) for i in out])\n\n\ndef list_upgrades():\n '''\n Check whether or not an upgrade is available for all packages\n\n CLI Example::\n\n salt '*' pkg.list_upgrades\n '''\n out = _parse_yum('check-update')\n return dict([(i.name, i.version) for i in out])\n\n\ndef refresh_db():\n '''\n Since yum refreshes the database automatically, this runs a yum clean,\n so that the next yum operation will have a clean database\n\n CLI Example::\n\n salt '*' pkg.refresh_db\n '''\n cmd = 'yum -q clean dbcache'\n __salt__['cmd.retcode'](cmd)\n return True\n\n\ndef install(name, refresh=False, repo='', skip_verify=False, source=None,\n **kwargs):\n '''\n Install the passed package\n\n name\n The name of the package to be installed\n\n refresh\n Clean out the yum database before executing\n\n repo\n Specify a package repository from which to install the package\n (e.g., ``yum --enablerepo=somerepo``)\n\n skip_verify\n Skip the GPG verification check (e.g., ``--nogpgcheck``)\n\n Return a dict containing the new package names and versions::\n\n {'': {'old': '',\n 'new': '']}\n\n CLI Example::\n\n salt '*' pkg.install \n '''\n\n if source is not None:\n if __salt__['config.valid_fileproto'](source):\n # Cached RPM from master\n pkg_file = __salt__['cp.cache_file'](source)\n pkg_type = 'remote'\n else:\n # RPM file local to the minion\n pkg_file = source\n pkg_type = 'local'\n pname,pversion = _parse_pkg_meta(pkg_file)\n if not pname:\n pkg_file = None\n if pkg_type == 'remote':\n log.error('Failed to cache {0}. Are you sure this path is '\n 'correct?'.format(source))\n elif pkg_type == 'local':\n if not os.path.isfile(source):\n log.error('Package file {0} not found. Are you sure this '\n 'path is correct?'.format(source))\n else:\n log.error('Unable to parse package metadata for '\n '{0}'.format(source))\n elif name != pname:\n pkg_file = None\n log.error('Package file {0} (Name: {1}) does not match the '\n 'specified package name ({2})'.format(source,\n pname,\n name))\n # Don't proceed if there was a problem with the package file\n if pkg_file is None: return {}\n\n cmd = 'yum -y {repo} {gpgcheck} install {pkg}'.format(\n repo='--enablerepo={0}'.format(repo) if repo else '',\n gpgcheck='--nogpgcheck' if skip_verify else '',\n pkg=pkg_file if source is not None else name,\n )\n\n if refresh: refresh_db()\n old = list_pkgs()\n __salt__['cmd.retcode'](cmd)\n new = list_pkgs()\n pkgs = {}\n for npkg in new:\n if npkg in old:\n if old[npkg] == new[npkg]:\n # no change in the package\n continue\n else:\n # the package was here before and the version has changed\n pkgs[npkg] = {'old': old[npkg],\n 'new': new[npkg]}\n else:\n # the package is freshly installed\n pkgs[npkg] = {'old': '',\n 'new': new[npkg]}\n return pkgs\n\n\ndef upgrade():\n '''\n Run a full system upgrade, a yum upgrade\n\n Return a dict containing the new package names and versions::\n\n {'': {'old': '',\n 'new': '']}\n\n CLI Example::\n\n salt '*' pkg.upgrade\n '''\n old = list_pkgs()\n cmd = 'yum -q -y upgrade'\n __salt__['cmd.retcode'](cmd)\n new = list_pkgs()\n pkgs = {}\n for npkg in new:\n if npkg in old:\n if old[npkg] == new[npkg]:\n # no change in the package\n continue\n else:\n # the package was here before and the version has changed\n pkgs[npkg] = {'old': old[npkg],\n 'new': new[npkg]}\n else:\n # the package is freshly installed\n pkgs[npkg] = {'old': '',\n 'new': new[npkg]}\n return pkgs\n\n\ndef remove(pkg):\n '''\n Remove a single package with yum remove\n\n Return a list containing the removed packages:\n\n CLI Example::\n\n salt '*' pkg.remove \n '''\n old = list_pkgs()\n cmd = 'yum -q -y remove ' + pkg\n __salt__['cmd.retcode'](cmd)\n new = list_pkgs()\n return _list_removed(old, new)\n\n\ndef purge(pkg):\n '''\n Yum does not have a purge, this function calls remove\n\n Return a list containing the removed packages:\n\n CLI Example::\n\n salt '*' pkg.purge \n '''\n return remove(pkg)\n\n","sub_path":"salt/modules/yumpkg5.py","file_name":"yumpkg5.py","file_ext":"py","file_size_in_byte":8669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177397639","text":"# -*- coding: utf-8 -*-\nfrom sklearn import svm, grid_search\n\ndef myScorer(estimator, features, labels):\n \"\"\"the scorer used by our 10-fold cross-validating classifier which optimizes for the final score specified by semeval twitter sentiment task\"\"\"\n return getFinalScore(estimator.predict(features), labels)\n\ndef trainClassifier(featuresOfTrainData, labelsOfTrainData):\n \"\"\"trains a linear svm classifier with a built-in 10-fold cross-validation\"\"\"\n parameters = {'C':[0.005, 0.01, 0.05, 0.1, 0.5, 1]}\n svc = svm.LinearSVC(class_weight='auto')\n clf = grid_search.GridSearchCV(svc, parameters, scoring=myScorer, n_jobs=8, cv=10)\n clf.fit(featuresOfTrainData, labelsOfTrainData)\n return clf\n\ndef getFinalScore(predictedLabels, correctLabels):\n \"\"\"returns the final score specified by semeval twitter sentiment task\"\"\"\n confusionMatrix = buildConfusionMatrix(predictedLabels, correctLabels)\n f1Positive = getF1(getPrecision('positive', confusionMatrix), getRecall('positive', confusionMatrix))\n f1Negative = getF1(getPrecision('negative', confusionMatrix), getRecall('negative', confusionMatrix))\n semEvalMakroF1 = (f1Negative+f1Positive)/2\n return semEvalMakroF1\n\ndef getPrecision(label, confusionMatrix):\n \"\"\"Calculates the precision of a given label using the confusionMatrix\n\n Parameters:\n label (str): the label to calculate the precision for\n confusionMatrix (dict): the confusionMatrix\n \n Returns: \n float: the precision value\n \"\"\"\n divisor = (confusionMatrix[label,'positive']+confusionMatrix[label,'neutral']+confusionMatrix[label,'negative'])\n return float(confusionMatrix[label, label]) / divisor if divisor>0 else 0\n\n\ndef getRecall(label, confusionMatrix):\n \"\"\"Calculates the recall of a given label using the confusionMatrix\n\n Parameters:\n label (str): the label to calculate the recall for\n confusionMatrix (dict): the confusionMatrix\n \n Returns: \n float: the recall value\n \"\"\"\n divisor = (confusionMatrix['positive', label]+confusionMatrix['neutral', label]+confusionMatrix['negative', label])\n return float(confusionMatrix[label, label]) / divisor if divisor>0 else 0\n\n\ndef getF1(precision, recall):\n \"\"\"Calculates the f1 score\n\n Parameters:\n precision (float): precision value\n recall (float): recall value\n \n Returns: \n float: the f1 score\n \"\"\"\n return 2*precision*recall/(precision+recall) if (precision+recall)>0 else 0\n\n\ndef buildConfusionMatrix(predictedLabels, correctLabels):\n \"\"\"Builds the confusionMatrix given predicted and correct labels\n\n Parameters:\n predictedLabels (list): labels resulted from the classifier\n correctLabels (list): the correct labels corresponding to the same indexes as predictedLabels\n \n Returns: \n dict: the confusion matrix\n \"\"\"\n confusionMatrix = {}\n confusionMatrix['positive', 'positive'] = 0\n confusionMatrix['positive', 'neutral'] = 0\n confusionMatrix['positive', 'negative'] = 0\n confusionMatrix['neutral', 'positive'] = 0\n confusionMatrix['neutral', 'neutral'] = 0\n confusionMatrix['neutral', 'negative'] = 0\n confusionMatrix['negative', 'positive'] = 0\n confusionMatrix['negative', 'neutral'] = 0\n confusionMatrix['negative', 'negative'] = 0\n for predictedLabel, correctLabel in zip(predictedLabels, correctLabels):\n confusionMatrix[predictedLabel,correctLabel]+=1\n return confusionMatrix\n\n\n","sub_path":"cas/sentiment analytics/Sentiment_analytics/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"12871616","text":"from collections import defaultdict\nfrom typing import Any, DefaultDict, Dict, List, Set\n\nfrom lamb.ebnf.ast import (BinaryExpressionNode, RuleNode, UnaryExpressionNode,\n VariableExpressionNode)\nfrom lamb.interaction.metric_printer import print_metric\nfrom lamb.utils.SymbolIdMapper import SymbolIdMapper\nfrom lamb.verification.predicate import get_predicate_for_rule\nfrom pysmt.shortcuts import And, Or, Bool, get_formula_size\nfrom pysmt.solvers.solver import Solver\n\n\ndef build_reachable_condition(start_var: str, rule_dict: Dict[str, List[RuleNode]],\n variables: Dict[str, Any], mapper: SymbolIdMapper, word_len: int, solver: Solver,\n nullable: Set[str]):\n exists_dict: DefaultDict[str, List[Any]] = defaultdict(list)\n\n for A, A_index in mapper.variable_items():\n for left in range(1, word_len + 1):\n for right in range(left, word_len + 1):\n ident_q_A = f'q${left}${right}${A_index}'\n condition_start = Bool(A == start_var and left == 1 and right == word_len)\n exists_dict[ident_q_A].append(condition_start)\n\n for A, A_index in mapper.variable_items():\n for left in range(1, word_len + 1):\n\n for right in range(left - 1, word_len + 1):\n for rule in rule_dict[A]:\n if isinstance(rule.expression, VariableExpressionNode):\n B = rule.expression.variable\n B_index = mapper.get_id_for_variable(B)\n ident_q_B = f'q${left}${right}${B_index}'\n exists_dict[ident_q_B].append(variables[f'q${left}${right}${A_index}'])\n elif isinstance(rule.expression, UnaryExpressionNode):\n assert isinstance(rule.expression.expr, VariableExpressionNode)\n B = rule.expression.expr.variable\n B_index = mapper.get_id_for_variable(B)\n ident_q_B = f'q${left}${right}${B_index}'\n exists_dict[ident_q_B].append(And(\n variables[f'q${left}${right}${A_index}'],\n get_predicate_for_rule(rule, variables, left, right)\n ))\n elif isinstance(rule.expression, BinaryExpressionNode):\n assert isinstance(rule.expression.expr1, VariableExpressionNode)\n assert isinstance(rule.expression.expr2, VariableExpressionNode)\n B, C = rule.expression.expr1.variable, rule.expression.expr2.variable\n B_index = mapper.get_id_for_variable(B)\n C_index = mapper.get_id_for_variable(C)\n if C in nullable:\n exists_dict[f'q${left}${right}${B_index}'].append(variables[f'q${left}${right}${A_index}'])\n for h in range(left - 1, right):\n cond_B = And(variables[f'q${left}${right}${A_index}'],\n variables[f'x${h + 1}${right}${C_index}'],\n get_predicate_for_rule(rule, variables, left, h + 1)\n if h != left - 1 else Bool(True))\n # /\\ for BinaryOp, constraints hold if any side is []\n exists_dict[f'q${left}${h}${B_index}'].append(cond_B)\n\n if B in nullable:\n exists_dict[f'q${left}${right}${C_index}'].append(variables[f'q${left}${right}${A_index}'])\n for h in range(left, right + 1):\n cond_C = And(variables[f'q${left}${right}${A_index}'],\n variables[f'x${left}${h}${B_index}'],\n get_predicate_for_rule(rule, variables, left, h + 1)\n if h != right else Bool(True))\n exists_dict[f'q${h + 1}${right}${C_index}'].append(cond_C)\n\n formula_size = 0\n for A, A_index in mapper.variable_items():\n for left in range(1, word_len + 1):\n for right in range(left, word_len + 1):\n ident_q = f'q${left}${right}${A_index}'\n cond_to_add = variables[ident_q].Implies(Or(exists_dict[ident_q]))\n formula_size += get_formula_size(cond_to_add)\n solver.add_assertion(cond_to_add)\n\n print_metric({'type': 'assertion_count', 'data': {\n 'name': 'sentence reachable', 'count': formula_size\n }})\n","sub_path":"lamb/verification/condition/sentence_reachable.py","file_name":"sentence_reachable.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584079399","text":"from flask import Flask, render_template, request, url_for, redirect\r\napp = Flask(__name__)\r\nimport json\r\nimport urllib.request, urllib.error, urllib.parse\r\nimport requests\r\nimport pprint\r\nfrom env import *\r\nfrom routes import *\r\napp.register_blueprint(routes)\r\n@app.route('/')\r\ndef get():\r\n try:\r\n import urllib.request\r\n with urllib.request.urlopen(dynamodburl) as dynamodb:\r\n dynamodbdata = dynamodb.read()\r\n except:\r\n dynamodbdata = 'Not Found'\r\n try:\r\n import urllib.request\r\n with urllib.request.urlopen('') as rds :\r\n rdsdata = rds.read()\r\n except:\r\n rdsdata = 'Not Found'\r\n try : \r\n client = MongoClient(mongourl,serverSelectionTimeoutMS = 2000)\r\n client.server_info()\r\n mongodata = 'Connected'\r\n except:\r\n mongodata = 'Not Found'\r\n return render_template('index.html',dynomodbstatus = dynamodbdata ,rdsstatus = rdsdata ,mongodb = mongodata)\r\n\r\n@app.route('/',methods = ['GET','POST'])\r\ndef post():\r\n if request.method == 'POST':\r\n if request.form['submit'] == 'submit':\r\n email = request.form['test']\r\n try:\r\n import urllib.request\r\n with urllib.request.urlopen(dynamodburl) as dynamodb:\r\n dynamodbdata = dynamodb.read()\r\n except:\r\n dynamodbdata = 'Not Found'\r\n try:\r\n import urllib.request\r\n with urllib.request.urlopen('') as rds :\r\n rdsdata = rds.read()\r\n except:\r\n rdsdata = 'Not Found'\r\n try : \r\n client = MongoClient(mongourl,serverSelectionTimeoutMS = 2000)\r\n client.server_info()\r\n mongodata = 'Connected'\r\n except:\r\n mongodata = 'Not Found'\r\n return render_template('index.html',data2 = email,dynomodbstatus = dynamodbdata ,rdsstatus = rdsdata ,mongodb = mongodata)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(port = 8000,debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211624318","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Neal Norwitz\n# Portions Copyright 2007 Google Inc.\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\n\"\"\"Run all the unittests.\"\"\"\n\ntry:\n # Python 3.x\n from io import StringIO\nexcept ImportError:\n # Python 2.x\n from StringIO import StringIO\n\nimport difflib\nimport os\nimport sys\n\nfrom cpp import ast\nfrom cpp import find_warnings\n\n\n# [(module, 'directory', 'input-file', 'expected-output-file')]\n# The tuples can have optional arguments after the expected output file.\n_GOLDEN_FILE_TESTS = [\n (ast, 'test', 'foo.h', 'foo.h.expected'),\n (find_warnings, 'test', 'foo.h', 'foo.h.expected-warnings'),\n (find_warnings, 'test', 'need-class.h', 'need-class.h.expected-warnings'),\n (find_warnings, 'test/define', 'd1.cc', 'd1.expected'),\n (find_warnings, 'test/define', 'd2.cc', 'd2.expected'),\n (find_warnings, 'test/define', 'd3.cc', 'd3.expected'),\n (find_warnings, 'test/define', 'd4.h', 'd4.expected'),\n (find_warnings, 'test/define', 'd5.h', 'd5.expected'),\n (find_warnings, 'test/define', 'd6.h', 'd6.expected'),\n (find_warnings, 'test/define', 'd7.h', 'd7.expected'),\n (find_warnings, 'test/define', 'd8.h', 'd8.expected'),\n ]\n\n\ndef DiffGoldenFile(test_type, test_name, output_lines, expected_file):\n expected_lines = open(expected_file).readlines()\n diffs = list(difflib.unified_diff(output_lines, expected_lines))\n if diffs:\n sys.__stdout__.write('%s %s failed. Diffs:\\n' % (test_type, test_name))\n for line in diffs:\n sys.__stdout__.write(line)\n return 1\n sys.__stdout__.write('%s %s passed\\n' % (test_type, test_name))\n return 0\n\n\ndef RunGoldenTests(generate_output):\n start_cwd = os.path.abspath(os.getcwd())\n exit_status = 0\n for record in _GOLDEN_FILE_TESTS:\n module, directory, input_file, expected_file = record[:4]\n # Capture stdout.\n sys.stdout = StringIO()\n try:\n # Setup directory and test name.\n os.chdir(os.path.join(start_cwd, directory))\n test_name = module.__name__\n\n # Run the test.\n module.main([test_name, input_file] + list(record[4:]))\n\n # Verify output.\n output = sys.stdout.getvalue()\n if generate_output:\n fp = open(expected_file, 'w+')\n fp.write(output)\n fp.close()\n output_lines = output.splitlines(True)\n exit_status = DiffGoldenFile(test_name, input_file,\n output_lines, expected_file)\n if exit_status != 0:\n # Stop after first failure.\n break\n finally:\n sys.stdout = sys.__stdout__\n return exit_status\n\n\ndef _RunCommand(args):\n try:\n # Support older versions: subprocess was added in 2.4.\n import subprocess\n p = subprocess.Popen(args, shell=False, close_fds=False,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out_fp = p.stdout\n err_fp = p.stderr\n status = p.wait()\n except ImportError:\n status = 0\n in_fp, out_fp, err_fp = os.popen3(args)\n in_fp.close()\n\n def GetAndPrintOutput(fp):\n output = fp.read()\n if not isinstance(output, str):\n # This should only happen in Python 3.0, where str is unicode str.\n output = str(output, 'ascii')\n fp.close()\n if output:\n print(output)\n return output\n\n return status, GetAndPrintOutput(out_fp), GetAndPrintOutput(err_fp)\n\n\ndef main(argv):\n dirname = os.path.abspath(os.path.dirname(argv[0]))\n test_dir = os.path.join(dirname, 'cpp')\n os.environ['PYTHONPATH'] = dirname\n exit_status = 0\n for f in os.listdir(test_dir):\n if f.endswith('_test.py'):\n args = [sys.executable, os.path.join(test_dir, f)]\n status, stdout, stderr = _RunCommand(args)\n if status or stderr:\n exit_status += 1\n if exit_status == 0:\n generate_golden_files = len(argv) > 1 and argv[1] == '--expected'\n exit_status = RunGoldenTests(generate_golden_files)\n return exit_status\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n","sub_path":"matlab_ext/code-miners/extern/cppclean/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"406344970","text":"import numpy as np\nimport tkinter as tk\nfrom tkinter import ttk\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import(\n\tFigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.figure import Figure\n#import matplotlib.animation as animation\nfrom matplotlib import style\nfrom matplotlib.patches import FancyArrowPatch\n\nfrom itertools import combinations, product\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.proj3d import proj_transform\n\nLARGE_FONT= (\"Verdana\", 12)\n\nclass SeaofBTCapp(tk.Tk):\n\n import numpy as np\nimport tkinter as tk\nfrom tkinter import ttk\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import(\n\tFigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.figure import Figure\n#import matplotlib.animation as animation\nfrom matplotlib import style\nfrom matplotlib.patches import FancyArrowPatch\n\nfrom itertools import combinations, product\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.proj3d import proj_transform\n\nLARGE_FONT= (\"Verdana\", 12)\n\nclass Vector_transform(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n \n tk.Tk.__init__(self, *args, **kwargs)\n\n # tk.Tk.iconbitmap(self, default=\"clienticon.ico\")\n tk.Tk.wm_title(self, \"Vector transformation app\")\n \n \n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand = True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n\n if graphImbedded :\n\n frame = graphImbedded(container, self)\n\n self.frames[graphImbedded] = frame\n\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n self.show_frame(graphImbedded)\n\n def show_frame(self, cont):\n\n frame = self.frames[cont]\n frame.tkraise()\n\n \n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\nclass graphImbedded(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n label = tk.Label(self, text=\"Graph Page!\", font=LARGE_FONT)\n label.pack(pady=10,padx=10)\n \n button1 = ttk.Button(self, text=\"translate\", command = lambda: controller.show_frame(graphImbedded))\n button1.pack()\n \n button2 = ttk.Button(self, text=\"rotate\", command = lambda: controller.show_frame(graphImbedded))\n button2.pack()\n \n button3 = ttk.Button(self, text=\"reflect\", command = lambda: controller.show_frame(graphImbedded))\n button3.pack()\n \n button4 = ttk.Button(self, text = \"stretch\", command = lambda: controller.show_frame(graphImbedded))\n button4.pack()\n \n \n fig = Figure(figsize=(5,5), dpi=100)\n canvas = FigureCanvasTkAgg(fig, master=self)\n canvas.draw()\n ax = fig.add_subplot(111, projection=\"3d\")\n\n\n r = [-1, 1]\n for s, e in combinations(np.array(list(product(r,r,r))), 2):\n if np.sum(np.abs(s-e)) == r[1]-r[0]:\n ax.plot3D(*zip(s,e), color=\"b\")\n ax.scatter([0],[0],[0],color=\"g\",s=100)\n \n \n vector = Arrow3D([1,1],[0.5,1],[0.3,1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"m\")\n vector_1 = Arrow3D([1,0],[0.5,0],[0.3,0], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"g\")\n vector_2= Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"c\")\n\n a = Arrow3D([0,0],[0,1],[0,0], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n b = Arrow3D([0,-1],[0,0],[0,0], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n c = Arrow3D([0,0],[0,0],[0,1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n d = Arrow3D([0,0],[0,0],[0,-1], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n e = Arrow3D([0,1],[0,0],[0,0], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n f = Arrow3D([0,0],[0,-1],[0,0], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n\n\n ax.add_artist(vector_1)\n ax.add_artist(vector_2)\n ax.add_artist(vector)\n ax.add_artist(a)\n ax.add_artist(b)\n ax.add_artist(c)\n ax.add_artist(d)\n ax.add_artist(e)\n ax.add_artist(f)\n \n \n\n \n\n toolbar = NavigationToolbar2Tk(canvas, self)\n toolbar.update()\n canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)\n\n\napp = Vector_transform()\napp.mainloop()\n\n","sub_path":"vector_transform.py","file_name":"vector_transform.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139252256","text":"from __future__ import unicode_literals\nfrom django.db import models\nfrom Utils import custom_fields as custom\nfrom Utils.data import serial\nfrom Utils.misc import namecase\nfrom Utils.security import getyear, gethist\nfrom Utils import supermodel as sm\nfrom django_mysql import models as sqlmod\nfrom datetime import datetime\n\n\nclass AddressManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(AddressManager, self).__init__('people.address')\nAddresses = AddressManager()\n\n\nclass FamilyManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(FamilyManager, self).__init__('people.family')\n\t\tself.fields = ['last','phone','email','phone_type']\n\t\tself.validations = [\n\t\t\tsm.Present('last' ,'Please enter the family surname, as used by the children.'),\n\t\t\tsm.Regular('last' ,r'^.{,30}$','This name is too long. The maximum is 30 characters.'),\n\t\t\tsm.Present('phone','Please enter the main family phone number.'),\n\t\t\tsm.Regular('phone',r'^$|^[ -.()/\\\\~]*(\\d[ -.()/\\\\~]*){10}$','Please enter a valid 10-digit phone number.'),\n\t\t\tsm.Present('email','Please enter an email address.'),\n\t\t\tsm.Regular('email',r'^$|(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)','Please enter a valid email address.'),\n\t\t]\n\tdef create(self, **kwargs):\n\t\tif 'last' in kwargs:\n\t\t\tkwargs['last'] = namecase(kwargs['last'])\n\t\t\tlas = kwargs['last'][:3].upper()\n\t\t\t# kwargs['hid'] = las + str(serial(self, 'hid', hid__startswith=las))\n\t\treturn super(FamilyManager, self).create(**kwargs)\n\tdef all_join_alpha(self):\n\t\tresult = []\n\t\tids = []\n\t\tfor year in gethist(0)[::-1]:\n\t\t\tfor family in self.filter(children__enrollment__course__year=year).order_by('last'):\n\t\t\t\tif family.id not in ids:\n\t\t\t\t\tids.append(family.id)\n\t\t\t\t\tresult.append(family)\n\t\tfor family in Families.all().exclude(id__in=ids):\n\t\t\tresult.append(family)\n\t\treturn result\nFamilies = FamilyManager()\n\n\nclass ParentManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(ParentManager, self).__init__('people.parent')\n\t\tself.fields = ['first','alt_last','sex','alt_phone','alt_email','phone_type']\n\t\tself.validations = [\n\t\t\tsm.Present('first','Please enter a first name or skip this parent'),\n\t\t\tsm.Regular('first',r'^.{,20}$','This name is too long. The maximum is 20 characters.'),\n\t\t\tsm.Regular('alt_last',r'^.{,30}$','This name is too long. The maximum is 30 characters.'),\n\t\t\tsm.Regular('alt_phone',r'^$|^[ -.()/\\\\~]*(\\d[ -.()/\\\\~]*){10}$','Please enter a valid 10-digit phone number.'),\n\t\t\tsm.Regular('alt_email',r'^$|(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)','Please enter a valid email address.'),\n\t\t]\nParents = ParentManager()\n\n\nclass StudentManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(StudentManager, self).__init__('people.student')\n\t\tself.fields = ['first','alt_last','alt_first','sex','birthday','grad_year','height','alt_phone','alt_email','tshirt']\n\t\tself.validations = [\n\t\t\tsm.Present('first','Please enter a first name.'),\n\t\t\tsm.Regular('first',r'^.{0,20}$','This name is too long. The maximum is 20 characters.'),\n\t\t\tsm.Regular('alt_last',r'^.{0,30}$','This name is too long. The maximum is 30 characters.'),\n\t\t\tsm.Regular('alt_first',r'^.{0,20}$','This name is too long. The maximum is 20 characters.'),\n\t\t\tsm.Present('sex','Please select a sex.'),\n\t\t\tsm.Present('birthday','Please enter a date of birth.'),\n\t\t\t# sm.Regular('birthday',r'^$|^\\d{4}-\\d{2}-\\d{2}$','Please enter the date as YYYY-MM-DD'),\n\t\t\tsm.Regular('alt_phone',r'^$|^[^\\d]*(\\d[^\\d]*){10}$','Please enter a valid 10-digit phone number, or leave blank to use family phone.'),\n\t\t\tsm.Regular('alt_email',r'^$|(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)','Please enter a valid email address, or leave blank to use family email.'),\n\t\t]\n\tdef create(self, **kwargs):\n\t\tif 'alt_last' in kwargs:\n\t\t\tkwargs['alt_last'] = namecase(kwargs['alt_last'])\n\t\treturn super(StudentManager, self).create(**kwargs)\n\tdef current(self, year=getyear()):\n\t\treturn self.filter(enrollment__course__year=year)\nStudents = StudentManager()\n\n\nclass NameClashManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(NameClashManager, self).__init__('people.nameclash')\n\tdef filter(self, **kwargs):\n\t\tif 'family' in kwargs:\n\t\t\tfamily = kwargs.pop('family')\n\t\t\tkwargs['last'] = family.last\n\t\treturn super(NameClashManager, self).filter(**kwargs)\n\tdef blanks(self, family):\n\t\treturn self.model.blanks(self.model(), family)\n\tdef calc(self, family, year=None):\n\t\tif hasattr(family,'last'):\n\t\t\tlast = family.last\n\t\telse:\n\t\t\tlast = family\n\t\tclashes = Families.filter(last=last)\n\t\tif year:\n\t\t\tclashes = clashes.filter(children__enrollment__course__year=year).distinct()\n\t\tif len(clashes) <= 1:\n\t\t\treturn 0\n\t\telse:\n\t\t\tfor tup in self.model.style_choices:\n\t\t\t\tnum = tup[0]\n\t\t\t\tstyle = tup[1]\n\t\t\t\tunique = set([])\n\t\t\t\tgood = True\n\t\t\t\tfor family in clashes:\n\t\t\t\t\tblanks = self.blanks(family)\n\t\t\t\t\tstyled = style.format(**blanks)\n\t\t\t\t\tif styled in unique:\n\t\t\t\t\t\tgood = False\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tunique.add(styled)\n\t\t\t\tif good:\n\t\t\t\t\treturn num\n\tdef fate(self, family, year):\n\t\tnum = self.calc(family,year)\n\t\tif num:\n\t\t\treturn self.create(last=family.last,year=year,style=num)\n\tdef universal(self, family):\n\t\tnum = self.calc(family)\n\t\treturn self.model.style_choices[num][1].format(**self.blanks(family))\nNameClashes = NameClashManager()\n\t\t\n\nclass UserManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(UserManager, self).__init__('people.user')\n\t\tself.fields = ['username','password','owner_type','owner_id']\n\t\tself.validations = [\n\t\t\tsm.Present('username','Please enter a username.'),\n\t\t\tsm.Unique(self,'username','This username is taken. Please select another.'),\n\t\t\t# sm.Regular('username', r'^[^@]*$', 'Username may not contain the @ symbol.'),\n\t\t\tsm.Present('password','Please enter a password'),\n\t\t\tsm.Regular('password', r'^$|^.{8,}$','Password is too short. It should be at least 8 characters.'),\n\t\t\tsm.Regular('password', r'^$|^[^$].*$','Password may not begin with a dollar sign ($).'),\n\t\t\tsm.Present('pw_confm','Please confirm your password'),\n\t\t\tsm.Confirm('pw_confm','password','Passwords do not match.')\n\t\t]\n\tdef isValid(self, data, **kwargs):\n\t\tif 'override_unique_username' in kwargs and kwargs['override_unique_username']:\n\t\t\tdel self.validations[1]\n\t\treturn super(UserManager, self).isValid(data, **kwargs)\n\tdef filter(self, **kwargs):\n\t\tif 'owner' in kwargs:\n\t\t\towner = kwargs.pop('owner')\n\t\t\tkwargs['owner_id'] = owner.id\n\t\t\tkwargs['owner_type'] = owner.__class__.__name__.title()\n\t\treturn super(UserManager, self).filter(**kwargs)\nUsers = UserManager()\n\nclass TeacherManager(sm.SuperManager):\n\tdef __init__(self):\n\t\tsuper(TeacherManager, self).__init__('people_teacher')\nTeachers = TeacherManager()","sub_path":"apps/people/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":6634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472018030","text":"#encoding:utf-8 \n'''\nCreated on 2018年6月4日\n\n@author: fxy16\n'''\nfrom MonitorApp.models import fim_pcl_stat\nimport io\n\ndef fim_pcl_stat_init():\n #获取FIM批处理状态数据集\n res = fim_pcl_stat.objects.filter(sys_name='FIM') \n suc_job = 0 \n undo_job = 0\n deal_job= 0 \n for r in res:\n #计算成功作业总数\n if r.job_stat == '2' :\n suc_job += 1\n elif r.job_stat == '1' :\n deal_job += 1 \n else :\n undo_job += 1 \n return suc_job,deal_job,undo_job\n\n#获取财管批处理结束标志作业记录数\ndef fim_get_bizdate():\n try:\n res = fim_pcl_stat.objects.all().get(job_name='send')\n except fim_pcl_stat.DoesNotExist:\n flg = 0\n else:\n if res.job_stat == '2':\n flg = 1\n else :\n flg = 0\n return flg\n\ndef get_fim_data():\n try:\n fim_info = fim_pcl_stat.objects.filter(sys_name='FIM').values_list(\"job_name\", \\\n \"job_stat\",\\\n \"start_time\", \\\n \"end_time\", \\\n \"etldt\" )\n except fim_pcl_stat.DoesNotExist:\n print(\"Get fim_pcl_stat Error!\")\n finally:\n if fim_info:\n x = len(fim_info[0])\n y = len(fim_info)\n fim_n_info = [['' for i in range(x)] for i in range(y)]\n #遍历进行转码\n for i in range(0,y):\n for j in range(0,x):\n if j == 1:\n if fim_info[i][j] == '0':\n fim_n_info[i][j] = '未开始'\n if fim_info[i][j] == '1':\n fim_n_info[i][j] = '执行中'\n if fim_info[i][j] == '2':\n fim_n_info[i][j] = '成功'\n else:\n fim_n_info[i][j] = fim_info[i][j]\n else:\n fim_n_info = [[0]*5]*1\n fim_n_info[0][0] = '批处理未开始'\n fim_n_info[0][1] = '批处理未开始' \n fim_n_info[0][2] = '批处理未开始' \n fim_n_info[0][3] = '批处理未开始' \n fim_n_info[0][4] = '批处理未开始' \n return fim_n_info","sub_path":"jsrcuMonitor/MonitorApp/fim_hz.py","file_name":"fim_hz.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"651676222","text":"import os as my_os\nimport time\ndef greeter():\n print (\"Welcome to the Arch Linux Package Backup Tool\")\n\ndef backup():\n start_time=time.time()\n number_of_total_packages=0\n number_of_packages_that_needed_to_be_backed_up=0\n for package in my_os.listdir(\"/var/cache/pacman/pkg\"):\n if package in my_os.listdir(\"/home/michael/Arch_packages/pkg\"):\n pass\n else:\n if package[-5:]==\".part\":\n print (\"Removing partial package {0}\".format(str(package)))\n my_os.system(\"sudo rm /var/cache/pacman/pkg/{0}\".format(str(package)))\n else:\n number_of_packages_that_needed_to_be_backed_up+=1\n print ('backing up {0}'.format(package))\n my_os.system(\"sudo cp /var/cache/pacman/pkg/{0} /home/michael/Arch_packages/pkg/{0}\".format(str(package)))\n number_of_total_packages+=1\n end_time=time.time()\n if number_of_packages_that_needed_to_be_backed_up==0:\n print(\"You have no packages to back up\")\n else:\n print (\"it took {0:5.2f} seconds to backup {1} new packages and go through a total of {2} packages\".format(float(end_time-start_time),int(number_of_packages_that_needed_to_be_backed_up),int(number_of_total_packages)))\n\ndef quit():\n print(\"Have a Good day\")\n\ndef main():\n greeter()\n backup()\n quit()\n\nmain()\n","sub_path":"Home Python Code/package_updater.py","file_name":"package_updater.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112236566","text":"from tkinter import *\r\n\r\nroot = Tk()\r\nroot.title(\"Calculator\")\r\n\r\nentry = Entry(root, width=50, borderwidth=5)\r\nentry.grid(row=0, column=0, columnspan=3, padx=30,pady=20)\r\n\r\ndef myCal(number):\r\n\tfirst = entry.get()\r\n\tentry.delete(0, END)\r\n\tentry.insert(0, str(first) + str(number))\r\n\r\ndef clear_button():\r\n\tentry.delete(0, END)\r\n\r\ndef add_button():\r\n\tfirst_number = entry.get()\r\n\tglobal f_number\r\n\tglobal math\r\n\tmath = \"addition\"\r\n\tf_number = int(first_number)\r\n\tentry.delete(0,END)\r\n\r\ndef subtract_button():\r\n\tfirst_number = entry.get()\r\n\tglobal f_number\r\n\tglobal math\r\n\tmath = \"substraction\"\r\n\tf_number = int(first_number)\r\n\tentry.delete(0,END)\r\n\r\ndef multiply_button():\r\n\tfirst_number = entry.get()\r\n\tglobal f_number\r\n\tglobal math\r\n\tmath = \"multiplication\"\r\n\tf_number = int(first_number)\r\n\tentry.delete(0,END)\r\n\r\ndef divide_button():\r\n\tfirst_number = entry.get()\r\n\tglobal f_number\r\n\tglobal math\r\n\tmath = \"division\"\r\n\tf_number = int(first_number)\r\n\tentry.delete(0,END)\t\r\n\r\ndef equal_button():\r\n\tsecond_number = entry.get()\r\n\tentry.delete(0, END)\r\n\r\n\tif math == \"addition\":\r\n\t\tentry.insert(0, f_number + int(second_number))\r\n\r\n\tif math == \"substraction\":\r\n\t\tentry.insert(0, f_number - int(second_number))\r\n\t\t\r\n\tif math == \"multiplication\":\r\n\t\tentry.insert(0, f_number * int(second_number))\r\n\r\n\tif math == \"division\":\r\n\t\tentry.insert(0, f_number / int(second_number))\t\r\n\r\n\r\nbutton_1 = Button(root, text=\"1\", padx=40, pady=20, command=lambda:myCal(1))\r\nbutton_2 = Button(root, text=\"2\", padx=40, pady=20, command=lambda:myCal(2))\r\nbutton_3 = Button(root, text=\"3\", padx=40, pady=20, command=lambda:myCal(3))\r\nbutton_4 = Button(root, text=\"4\", padx=40, pady=20, command=lambda:myCal(4))\r\nbutton_5 = Button(root, text=\"5\", padx=40, pady=20, command=lambda:myCal(5))\r\nbutton_6 = Button(root, text=\"6\", padx=40, pady=20, command=lambda:myCal(6))\r\nbutton_7 = Button(root, text=\"7\", padx=40, pady=20, command=lambda:myCal(7))\r\nbutton_8 = Button(root, text=\"8\", padx=40, pady=20, command=lambda:myCal(8))\r\nbutton_9 = Button(root, text=\"9\", padx=40, pady=20, command=lambda:myCal(9))\r\nbutton_0 = Button(root, text=\"0\", padx=40, pady=20, command=lambda:myCal(0))\r\nbutton_add = Button(root, text=\"+\", padx=39, pady=20, command=add_button)\r\nbutton_equal = Button(root, text=\"=\", padx=100, pady=20, bg=\"orange\",command=equal_button)\r\nbutton_clear= Button(root, text=\"AC\", padx=97, pady=20, fg=\"orange\" ,command=clear_button)\r\n\r\nbutton_subtract = Button(root, text=\"-\", padx=40, pady=20, command=subtract_button)\r\nbutton_multiply = Button(root, text=\"*\", padx=40, pady=20, command=multiply_button)\r\nbutton_divide = Button(root, text=\"/\", padx=40, pady=20, command=divide_button)\r\n\r\nbutton_1.grid(row=3, column=0)\r\nbutton_2.grid(row=3, column=1)\r\nbutton_3.grid(row=3, column=2)\r\n\r\nbutton_4.grid(row=2, column=0)\r\nbutton_5.grid(row=2, column=1)\r\nbutton_6.grid(row=2, column=2)\r\n\r\nbutton_7.grid(row=1, column=0)\r\nbutton_8.grid(row=1, column=1)\r\nbutton_9.grid(row=1, column=2)\r\n\r\nbutton_0.grid(row=4,column=0)\r\nbutton_multiply.grid(row=4 ,column=1)\r\nbutton_divide.grid(row=4 ,column=2)\r\nbutton_add.grid(row=5, column=0)\r\nbutton_equal.grid(row=5, column=1, columnspan=2)\r\n\r\nbutton_subtract.grid(row=6 ,column=0)\r\nbutton_clear.grid(row=6, column=1,columnspan=2)\r\n\r\n\r\nroot.mainloop()\t","sub_path":"Python_GUI/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17370740","text":"import os\r\nimport sys\r\nimport urllib.request\r\nimport json\r\nclient_id = \"\"\r\nclient_secret = \"\"\r\nencText = urllib.parse.quote(\"They keep their songs about real life issues(depression, insomnia, etc.)\") # 따옴표 안에 번역할 내용 넣음.\r\ndata = \"source=en&target=ko&text=\" + encText\r\nurl = \"https://openapi.naver.com/v1/papago/n2mt\"\r\nrequest = urllib.request.Request(url)\r\nrequest.add_header(\"X-Naver-Client-Id\",client_id)\r\nrequest.add_header(\"X-Naver-Client-Secret\",client_secret)\r\nresponse = urllib.request.urlopen(request, data=data.encode(\"utf-8\"))\r\nrescode = response.getcode()\r\nif(rescode==200):\r\n response_body = response.read()\r\n print(response_body.decode('utf-8'))\r\n data = response_body.decode('utf-8')\r\n data = json.loads(data) # 딕셔너리화\r\n translated_text = data['message']['result']['translatedText']\r\n print(\"번역된 내용 : \"+ translated_text)\r\nelse:\r\n print(\"Error Code:\" + rescode)\r\n","sub_path":"NaverPapagoNMT.py","file_name":"NaverPapagoNMT.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"39241664","text":"import argparse\nimport copy\nimport datetime\nimport email\nimport os\nimport posixpath\nimport re\nimport sys\nimport shutil\nimport zipfile\nimport zipimport\nfrom io import StringIO\nfrom os import path\nfrom pathlib import Path\nimport pkg_resources\nfrom pkg_resources import Distribution, EggMetadata, parse_version\nfrom wheel import wheelfile\nfrom wheel import pkginfo\nfrom distutils import dir_util\n\nimport mistune\nfrom mongoengine import connect\nfrom flask import current_app\n\nsys.path.append('.')\nfrom app.main.model.database import Test, User\nfrom app.main.config import get_config\nfrom app.main.util.get_path import get_back_scripts_root, get_user_scripts_root\nfrom app.main.model.database import Package\n\nMETADATA = 'METADATA'\nWHEEL_INFO = 'WHEEL'\nWHEEL_INFO_RE = re.compile(\n r\"\"\"^(?P(?P.+?)(-(?P\\d.+?))?)\n ((-(?P\\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?)\n \\.whl|\\.dist-info)$\"\"\",\n re.VERBOSE).match\nVERSION_CHECK = re.compile(r'(?P.*?)(?P\\s*(==|>=|<=|!=)\\s*)?(?P\\d.+?)?$').match\nMODULE_IMPORT = re.compile(r'^\\s*(import|from)\\s+(?P.+?)(#|$|\\s+import\\s+.+$)').match\n\ndef filter_kw(item):\n item = item.strip()\n if item.startswith('${') or item.startswith('@{') or item.startswith('&{'):\n item = item[2:]\n if not item.endswith('}'):\n current_app.logger.error('{ } mismatch for ' + item)\n else:\n item = item[0:-1]\n return item\n\ndef get_package_info(package):\n package = str(package)\n name, description, long_description = '', '', ''\n if package.endswith('.whl'):\n wf = wheelfile.WheelFile(package)\n ef = wf.open(posixpath.join(wf.dist_info_path, 'METADATA'))\n pkg_info = pkginfo.read_pkg_info_bytes(ef.read())\n name = pkg_info['Name']\n description = pkg_info['Summary']\n long_description = pkg_info.get_payload()\n ef.close()\n wf.close()\n if package.endswith('.egg'):\n with zipfile.ZipFile(package) as zf:\n with zf.open(posixpath.join('EGG-INFO', 'PKG-INFO')) as fp:\n value = fp.read().decode('utf-8')\n pkg_info = email.parser.Parser().parsestr(value)\n name = pkg_info['Name']\n description = pkg_info['Summary']\n long_description = pkg_info['Description']\n long_description = '\\n'.join((line.strip() for line in StringIO(long_description)))\n return name, description, long_description\n\ndef meet_version(versions, compare, version):\n \"\"\"\n versions must be sorted in ascending order\n \"\"\"\n assert(len(versions) > 0)\n if not compare:\n return version[0]\n\n ver = parse_version(version)\n if compare == '==':\n if version in versions:\n return version\n elif compare == '>':\n for v in versions:\n if parse_version(v) > ver:\n return v\n elif compare == '<':\n for v in reversed(versions, key=parse_version):\n if parse_version(v) < ver:\n return v\n elif compare == '>=':\n for v in versions:\n if parse_version(v) >= ver:\n return v\n elif compare == '<=':\n for v in reversed(versions, key=parse_version):\n if parse_version(v) <= ver:\n return v\n elif compare == '!=':\n for i, v in enumerate(versions):\n if v == version:\n versions.pop(i)\n break\n return versions[0] if len(versions) > 0 else None\n return None\n\ndef query_package(package_name, organization, team, type):\n package = Package.objects(py_packages=package_name, organization=organization, team=team, package_type=type).first()\n if not package:\n package = Package.objects(py_packages=package_name, organization=organization, team=None, package_type=type).first()\n if not package:\n package = Package.objects(py_packages=package_name, organization=None, team=None, package_type=type).first()\n if not package:\n return None\n return package\n\ndef get_package_requires(package, organization, team, type):\n if not package.endswith('.egg') or not zipfile.is_zipfile(package):\n current_app.logger.error(f'{package} is not an .egg file')\n return None\n packages = []\n dist = Distribution.from_filename(package, metadata=EggMetadata(zipimport.zipimporter(package)))\n for r in dist.requires():\n name, compare, version = VERSION_CHECK(str(r)).group('name', 'compare', 'version')\n package = Package.objects(py_packages=name, organization=organization, team=team, package_type=type).first()\n ver = meet_version(package.versions, compare, version) if package else None\n if not package or not ver:\n package = Package.objects(py_packages=name, organization=organization, team=None, package_type=type).first()\n ver = meet_version(package.versions, compare, version) if package else None\n if not package or not ver:\n package = Package.objects(py_packages=name, organization=None, team=None, package_type=type).first()\n ver = meet_version(package.versions, compare, version) if package else None\n if not package or not ver:\n current_app.logger.error(f'package {name} not found or version requirement not meet: {compare}{version}')\n return None\n packages.append((package, ver))\n return packages\n\n# TODO: rollback if failed in one step\ndef install_test_suite(package, user, organization, team, pypi_root, proprietary, version=None, new_package=True):\n if version is None:\n version = package.latest_version\n pkg_file = package.files[0]\n else:\n pkg_file = package.get_package_by_version(version)\n if not pkg_file:\n current_app.logger.error(f'package file not found for {package.name} with version {version}')\n return False\n pkg_file = pypi_root / package.package_name / pkg_file\n\n requires = get_package_requires(str(pkg_file), organization, team, type='Test Suite')\n if requires:\n for pkg, ver in requires:\n ret = install_test_suite(pkg, user, organization, team, pypi_root, proprietary, version=ver, new_package=False)\n if not ret:\n current_app.logger.error(f'Failed to install dependent package {package.name}')\n return False\n\n scripts_root = get_user_scripts_root(organization=organization, team=team)\n libraries_root = get_back_scripts_root(organization=organization, team=team)\n with zipfile.ZipFile(pkg_file) as zf:\n for f in zf.namelist():\n if f.startswith('EGG-INFO'):\n continue\n dirname = os.path.dirname(f)\n if os.path.exists(scripts_root / dirname):\n shutil.rmtree(scripts_root / dirname)\n if os.path.exists(libraries_root / dirname):\n shutil.rmtree(libraries_root / dirname)\n\n with zipfile.ZipFile(pkg_file) as zf:\n libraries = (f for f in zf.namelist() if not f.startswith('EGG-INFO') and '/scripts/' not in f)\n for l in libraries:\n zf.extract(l, libraries_root)\n scripts = [f for f in zf.namelist() if '/scripts/' in f]\n for s in scripts:\n zf.extract(s, scripts_root)\n for pkg_name in set((s.split('/', 1)[0] for s in scripts)):\n for f in os.listdir(scripts_root / pkg_name / 'scripts'):\n shutil.move(str(scripts_root / pkg_name / 'scripts' / f), scripts_root / pkg_name)\n db_update_test(scripts_root, os.path.join(pkg_name, f), user, organization, team, package, version)\n shutil.rmtree(scripts_root / pkg_name / 'scripts')\n package.modify(inc__download_times=1)\n return True\n\ndef db_update_test(scripts_dir, script, user, organization, team, package=None, version=None):\n if scripts_dir is None:\n return False\n if not script.endswith('.md'):\n return False\n\n basename = os.path.basename(script)\n dirname = os.path.dirname(script)\n test_suite = os.path.splitext(basename)[0]\n test = Test.objects(test_suite=test_suite, path=dirname, organization=organization, team=team).first()\n if not test:\n test = Test(path=dirname, author=user, organization=organization, team=team,\n test_suite=test_suite, package=package, package_version=version)\n test.create_date = datetime.datetime.utcnow()\n test.save()\n else:\n test.modify(package=package, package_version=version)\n\n ret = update_test_from_md(os.path.join(scripts_dir, script), test)\n if ret:\n test.update_date = datetime.datetime.utcnow()\n test.save()\n current_app.logger.critical(f'Update test suite for {script}')\n return True\n\ndef update_test_from_md(md_file, test):\n \"\"\"\n update test cases and variables for the test\n \"\"\"\n ret = False\n test_cases = []\n variables = {}\n with open(md_file, encoding='utf-8') as f:\n parser = mistune.BlockLexer()\n text = f.read()\n parser.parse(mistune.preprocessing(text))\n for t in parser.tokens:\n if t[\"type\"] == \"table\":\n table_header = t[\"header\"][0].lower()\n if table_header == 'test case' or table_header == 'test cases':\n for c in t[\"cells\"]:\n if not c[0] == '---':\n test_cases.append(c[0])\n break\n if table_header == 'variable' or table_header == 'variables':\n list_var = None\n for c in t[\"cells\"]:\n if c[0].startswith('#') or c[0].startswith('---'):\n continue\n if c[0].startswith('${'):\n list_var = None\n dict_var = None\n variables[filter_kw(c[0])] = c[1]\n elif c[0].startswith('@'):\n dict_var = None\n list_var = filter_kw(c[0])\n variables[list_var] = c[1:]\n elif c[0].startswith('...'):\n if list_var:\n variables[list_var].extend(c[1:])\n elif dict_var:\n for i in c[1:]:\n if not i:\n continue\n k, v = i.split('=')\n variables[dict_var][k] = v\n elif c[0].startswith('&'):\n list_var = None\n dict_var = filter_kw(c[0])\n variables[dict_var] = {}\n for i in c[1:]:\n if not i:\n continue\n k, v = i.split('=')\n variables[dict_var][k] = v\n else:\n current_app.logger.error('Unknown tag: ' + c[0])\n if test.test_cases != test_cases:\n test.test_cases = test_cases\n ret = True\n if test.variables != variables:\n test.variables = variables\n ret = True\n return ret\n\ndef find_modules(script):\n modules = []\n with open(script) as f:\n for line in f:\n if line.startswith('#'):\n continue\n m = MODULE_IMPORT(line)\n if m:\n module = m.group('module')\n mods = module.split(',')\n for m in mods:\n m = m.strip()\n modules.append(m.split('.', 1)[0])\n return modules\n\ndef find_dependencies(script, organization, team, package_type):\n ret = []\n modules = find_modules(script)\n for module in modules:\n tests = Test.objects(organization=organization, team=team)\n for test in tests:\n if test.package and module in test.package.py_packages:\n ret.append((test.package, test.package_version))\n break\n return ret\n\ndef find_pkg_dependencies(pypi_root, package, version, organization, team, package_type):\n pkg_file = pypi_root / package.package_name / package.get_package_by_version(version)\n requires = get_package_requires(str(pkg_file), organization, team, type='Test Suite')\n deps = [(package, version)]\n if requires:\n for pkg, version in requires:\n deps.extend(find_pkg_dependencies(pypi_root, pkg, version, organization, team, package_type))\n return deps\n\ndef get_internal_packages(package_path):\n with zipfile.ZipFile(package_path) as zf:\n packages = (f.split('/', 1)[0] for f in zf.namelist() if not f.startswith('EGG-INFO'))\n packages = set(packages)\n return list(packages)\n return []\n\ndef find_local_dependencies(scripts_root, script, organization, team):\n modules = find_modules(os.path.join(scripts_root, script))\n modules_dep = modules[:]\n ret = [os.path.splitext(script)[0].split('/', 1)[0]]\n for module in modules:\n tests = Test.objects(organization=organization, team=team)\n for test in tests:\n if test.package and module in test.package.py_packages:\n modules_dep.remove(module)\n for f in os.listdir(scripts_root):\n for module in modules_dep:\n f = os.path.splitext(f)[0]\n if f == module:\n ret.append(f)\n return ret\n\ndef repack_package(pypi_root, scripts_root, package, pkg_version, dest_root):\n unpack_root = os.path.join(dest_root, 'unpack')\n # os.mkdir(unpack_root)\n package_file = package.get_package_by_version(pkg_version)\n pkg_file = pypi_root / package.package_name / package_file\n with zipfile.ZipFile(pkg_file) as zf:\n zf.extractall(unpack_root)\n for py_pkg in package.py_packages:\n ret = dir_util.copy_tree(os.path.join(scripts_root, py_pkg), os.path.join(unpack_root, py_pkg))\n pkg_file = os.path.join(dest_root, package_file)\n leading_path = os.path.abspath(unpack_root)\n cwd_path = os.getcwd()\n leading_path = leading_path[len(cwd_path):]\n with zipfile.ZipFile(pkg_file, mode='w') as zf:\n for root, dirs, files in os.walk(unpack_root):\n for f in files:\n zf.write(os.path.join(root, f), arcname=os.path.join(root[len(leading_path):], f))\n return pkg_file\n\ndef generate_setup(src_dir, dst_dir, dependencies, project_name, version):\n packages = []\n py_modules = []\n\n for f in dependencies:\n src = os.path.join(src_dir, f)\n if os.path.isdir(src):\n packages.append(f)\n shutil.copytree(src, os.path.join(dst_dir, f))\n else:\n py_modules.append(f)\n shutil.copy(src + '.py', dst_dir)\n with open(os.path.join(dst_dir, 'setup.py'), 'w') as file:\n file.write(\n \"from setuptools import setup\\n\"\n \"setup(name=%r, version=%r, packages=%r, py_modules=%r)\\n\"\n % (project_name, version, packages, py_modules)\n )\n # with open(os.path.join(dst_dir, 'setup.py')) as file:\n # print(file.read())\n","sub_path":"webserver/task_runner/util/dbhelper.py","file_name":"dbhelper.py","file_ext":"py","file_size_in_byte":15349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"139185592","text":"\"\"\"\nSuppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one\nof '+', '−', '∗', or '/'. Given the root to such a tree, write a function to evaluate it.\n\nFor example, given the following tree:\n *\n / \\\n + +\n / \\ / \\\n3 2 4 5\nYou should return 45, as it is (3 + 2) * (4 + 5).\n\"\"\"\n\nfrom shared import TreeNode\nfrom operator import add, sub, mul, truediv\n\n\noperators = {'+': add, '-': sub, '*': mul, '/': truediv}\n\n\ndef evaluate_tree(root):\n left = root.left.val if isinstance(root.left.val, int) else evaluate_tree(root.left)\n right = root.right.val if isinstance(root.right.val, int) else evaluate_tree(root.right)\n return operators[root.val](left, right)\n\n\nassert evaluate_tree(\n TreeNode('*', TreeNode('+', TreeNode(3), TreeNode(2)), TreeNode('+', TreeNode(4), TreeNode(5)))\n) == 45\n","sub_path":"50/50.py","file_name":"50.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"625034629","text":"\"\"\"\nThis module contains tasks related to executing programs on the system.\n\"\"\"\n\nimport logging\nimport subprocess\nimport threading\nimport os\nimport ozawa\n\n\nclass Command(ozawa.Task):\n \"\"\"\n This task executes a series of arguments much like issuing a command in a console.\n\n Args:\n cmd_args (list): List of command-line arguments. The first would typically be the program eg. ``cp``, or\n ``docker``, followed by arguments for that program. Note that this does not support shell so you would have to\n call the shell as the first argument.\n\n Keyword Args:\n work_dir (str): The directory to run the command from.\n stdout_log_level (int): Defaults to :obj:`logging.INFO`.\n stderr_log_level (int): Defaults to :obj:`logging.ERROR`.\n\n .. note:: For more information regarding logging levels, see the official documentation_.\n\n .. _documentation: https://docs.python.org/3/library/logging.html#logging-levels\n\n Examples:\n Calling a program installed on the system::\n\n Command(['python', '-c', 'print(\"Hello, world!\")'])\n\n Using a shell like bash::\n\n Command(['bash', '-c', 'echo test > test.txt'], work_dir='/home/user')\n\n \"\"\"\n def __init__(self, cmd_args, work_dir=None, stdout_log_level=logging.INFO, stderr_log_level=logging.ERROR, **kwargs):\n super().__init__(**kwargs)\n if type(cmd_args) is not list:\n raise AttributeError(f'Expected cmd_args to be list, got {type(cmd_args)}')\n if len(cmd_args) < 1:\n raise AttributeError('Command requires at least one argument.')\n self.args = cmd_args\n self.work_dir = work_dir\n self.stdout_level = stdout_log_level\n self.stderr_level = stderr_log_level\n\n @staticmethod\n def _decode_byte_string(byte_string):\n string = byte_string.decode('utf-8')\n if string in ['\\r\\n']:\n return '>'\n return f'> {string.rstrip()}'\n\n def _stdout_handler(self, line):\n self.logger.log(self.stdout_level, self._decode_byte_string(line))\n\n def _stderr_handler(self, line):\n self.logger.log(self.stderr_level, self._decode_byte_string(line))\n\n @staticmethod\n def _proxy_lines(pipe, handler):\n with pipe:\n for line in iter(pipe.readline, b''):\n handler(line)\n\n def _command(self):\n with subprocess.Popen(self.args, cwd=self.work_dir,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1) as process:\n stdout_thread = threading.Thread(target=self._proxy_lines, args=[process.stdout, self._stdout_handler])\n stderr_thread = threading.Thread(target=self._proxy_lines, args=[process.stderr, self._stderr_handler])\n stdout_thread.start()\n stderr_thread.start()\n process.wait()\n stdout_thread.join()\n stderr_thread.join()\n if process.returncode != 0:\n self._failure_return_code = process.returncode\n self.raise_failure(f'Process terminated with non-zero return code.')\n\n def execute(self):\n self.logger.info(f'Calling args {self.args}.')\n try:\n self._command()\n except FileNotFoundError as e:\n self.raise_failure(f'Command \"{self.args[0]}\" not found.', cause=e)\n\n\nclass EnvironmentVariables(ozawa.Task):\n \"\"\"\n Set environment variables on the system for the current process.\n\n Args:\n variables (dict): Dictionary of ``variable:value`` pairs to set environment variables. A value of ``None`` will\n delete an environment variable.\n\n Example::\n\n EnvironmentVariables({'NEW_VAR': 'my new value', 'EXISTING_VAR': None})\n\n \"\"\"\n def __init__(self, variables, **kwargs):\n super().__init__(**kwargs)\n self.variables = variables\n\n @staticmethod\n def _set_variable(key, value):\n if value is None:\n os.environ.pop(key, None)\n else:\n os.environ[key] = value\n\n def _set_variables(self):\n for key in self.variables:\n self._set_variable(key, self.variables[key])\n\n def execute(self):\n self.logger.info(f'Setting variables {self.variables}.')\n self._set_variables()\n","sub_path":"ozawa/tasks/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"308524375","text":"# Copyright 2019 Google LLC\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# https://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\n\"\"\"Definitions of various standard energy functions.\"\"\"\n\nfrom functools import wraps, partial\n\nfrom typing import Callable, Tuple, TextIO, Dict, Any, Optional\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import ops\nfrom jax.tree_util import tree_map\nfrom jax import vmap\nimport haiku as hk\nfrom jax.scipy.special import erfc # error function\nfrom jax_md import space, smap, partition, nn, quantity, interpolate, util\n\nmaybe_downcast = util.maybe_downcast\n\n# Types\n\n\nf32 = util.f32\nf64 = util.f64\nArray = util.Array\n\nPyTree = Any\nBox = space.Box\nDisplacementFn = space.DisplacementFn\nDisplacementOrMetricFn = space.DisplacementOrMetricFn\n\nNeighborFn = partition.NeighborFn\nNeighborList = partition.NeighborList\n\n\n# Energy Functions\n\n\ndef simple_spring(dr: Array,\n length: Array=1,\n epsilon: Array=1,\n alpha: Array=2,\n **unused_kwargs) -> Array:\n \"\"\"Isotropic spring potential with a given rest length.\n\n We define `simple_spring` to be a generalized Hookian spring with\n agreement when alpha = 2.\n \"\"\"\n return epsilon / alpha * (dr - length) ** alpha\n\n\ndef simple_spring_bond(displacement_or_metric: DisplacementOrMetricFn,\n bond: Array,\n bond_type: Optional[Array]=None,\n length: Array=1,\n epsilon: Array=1,\n alpha: Array=2) -> Callable[[Array], Array]:\n \"\"\"Convenience wrapper to compute energy of particles bonded by springs.\"\"\"\n length = maybe_downcast(length)\n epsilon = maybe_downcast(epsilon)\n alpha = maybe_downcast(alpha)\n return smap.bond(\n simple_spring,\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n bond,\n bond_type,\n ignore_unused_parameters=True,\n length=length,\n epsilon=epsilon,\n alpha=alpha)\n\n\ndef soft_sphere(dr: Array,\n sigma: Array=1,\n epsilon: Array=1,\n alpha: Array=2,\n **unused_kwargs) -> Array:\n \"\"\"Finite ranged repulsive interaction between soft spheres.\n\n Args:\n dr: An ndarray of shape [n, m] of pairwise distances between particles.\n sigma: Particle diameter. Should either be a floating point scalar or an\n ndarray whose shape is [n, m].\n epsilon: Interaction energy scale. Should either be a floating point scalar\n or an ndarray whose shape is [n, m].\n alpha: Exponent specifying interaction stiffness. Should either be a float\n point scalar or an ndarray whose shape is [n, m].\n unused_kwargs: Allows extra data (e.g. time) to be passed to the energy.\n Returns:\n Matrix of energies whose shape is [n, m].\n \"\"\"\n\n dr = dr / sigma\n fn = lambda dr: epsilon / alpha * (f32(1.0) - dr) ** alpha\n\n if isinstance(alpha, int) or issubclass(type(alpha.dtype), jnp.integer):\n return jnp.where(dr < 1.0, fn(dr), f32(0.0))\n\n return util.safe_mask(dr < 1.0, fn, dr, f32(0.0))\n\n\ndef soft_sphere_pair(displacement_or_metric: DisplacementOrMetricFn,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=1.0,\n alpha: Array=2.0,\n per_particle: bool=False):\n \"\"\"Convenience wrapper to compute soft sphere energy over a system.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n alpha = maybe_downcast(alpha)\n return smap.pair(\n soft_sphere,\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n alpha=alpha,\n reduce_axis=(1,) if per_particle else None)\n\n\ndef soft_sphere_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: Box,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=1.0,\n alpha: Array=2.0,\n dr_threshold: float=0.2,\n per_particle: bool=False,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.OrderedSparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute soft spheres using a neighbor list.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n alpha = maybe_downcast(alpha)\n list_cutoff = jnp.max(sigma)\n dr_threshold = list_cutoff * maybe_downcast(dr_threshold)\n\n neighbor_fn = partition.neighbor_list(\n displacement_or_metric,\n box_size,\n list_cutoff,\n dr_threshold,\n fractional_coordinates=fractional_coordinates,\n format=format)\n energy_fn = smap.pair_neighbor_list(\n soft_sphere,\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n alpha=alpha,\n reduce_axis=(1,) if per_particle else None)\n\n return neighbor_fn, energy_fn\n\n\ndef lennard_jones(dr: Array,\n sigma: Array=1,\n epsilon: Array=1,\n **unused_kwargs) -> Array:\n \"\"\"Lennard-Jones interaction between particles with a minimum at sigma.\n\n Args:\n dr: An ndarray of shape [n, m] of pairwise distances between particles.\n sigma: Distance between particles where the energy has a minimum. Should\n either be a floating point scalar or an ndarray whose shape is [n, m].\n epsilon: Interaction energy scale. Should either be a floating point scalar\n or an ndarray whose shape is [n, m].\n unused_kwargs: Allows extra data (e.g. time) to be passed to the energy.\n Returns:\n Matrix of energies of shape [n, m].\n \"\"\"\n idr = (sigma / dr)\n idr = idr * idr\n idr6 = idr * idr * idr\n idr12 = idr6 * idr6\n # TODO(schsam): This seems potentially dangerous. We should do ErrorChecking\n # here.\n return jnp.nan_to_num(f32(4) * epsilon * (idr12 - idr6))\n\n\ndef lennard_jones_pair(displacement_or_metric: DisplacementOrMetricFn,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=1.0,\n r_onset: Array=2.0,\n r_cutoff: Array=2.5,\n per_particle: bool=False) -> Callable[[Array], Array]:\n \"\"\"Convenience wrapper to compute Lennard-Jones energy over a system.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n r_onset = maybe_downcast(r_onset) * jnp.max(sigma)\n r_cutoff = maybe_downcast(r_cutoff) * jnp.max(sigma)\n return smap.pair(\n multiplicative_isotropic_cutoff(lennard_jones, r_onset, r_cutoff),\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n reduce_axis=(1,) if per_particle else None)\n\n\ndef lennard_jones_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: Box,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=1.0,\n alpha: Array=2.0,\n r_onset: float=2.0,\n r_cutoff: float=2.5,\n dr_threshold: float=0.5,\n per_particle: bool=False,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.OrderedSparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute lennard-jones using a neighbor list.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n r_onset = maybe_downcast(r_onset) * jnp.max(sigma)\n r_cutoff = maybe_downcast(r_cutoff) * jnp.max(sigma)\n dr_threshold = jnp.max(sigma) * maybe_downcast(dr_threshold)\n\n neighbor_fn = partition.neighbor_list(\n displacement_or_metric,\n box_size,\n r_cutoff,\n dr_threshold,\n fractional_coordinates=fractional_coordinates,\n format=format)\n energy_fn = smap.pair_neighbor_list(\n multiplicative_isotropic_cutoff(lennard_jones, r_onset, r_cutoff),\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n reduce_axis=(1,) if per_particle else None)\n\n return neighbor_fn, energy_fn\n\n\ndef morse(dr: Array,\n sigma: Array=1.0,\n epsilon: Array=5.0,\n alpha: Array=5.0,\n **unused_kwargs) -> Array:\n \"\"\"Morse interaction between particles with a minimum at r0.\n Args:\n dr: An ndarray of shape [n, m] of pairwise distances between particles.\n sigma: Distance between particles where the energy has a minimum. Should\n either be a floating point scalar or an ndarray whose shape is [n, m].\n epsilon: Interaction energy scale. Should either be a floating point scalar\n or an ndarray whose shape is [n, m].\n alpha: Range parameter. Should either be a floating point scalar or an\n ndarray whose shape is [n, m].\n unused_kwargs: Allows extra data (e.g. time) to be passed to the energy.\n Returns:\n Matrix of energies of shape [n, m].\n \"\"\"\n U = epsilon * (f32(1) - jnp.exp(-alpha * (dr - sigma)))**f32(2) - epsilon\n # TODO(cpgoodri): ErrorChecking following lennard_jones\n return jnp.nan_to_num(jnp.array(U, dtype=dr.dtype))\n\ndef morse_pair(displacement_or_metric: DisplacementOrMetricFn,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=5.0,\n alpha: Array=5.0,\n r_onset: float=2.0,\n r_cutoff: float=2.5,\n per_particle: bool=False) -> Callable[[Array], Array]:\n \"\"\"Convenience wrapper to compute Morse energy over a system.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n alpha = maybe_downcast(alpha)\n return smap.pair(\n multiplicative_isotropic_cutoff(morse, r_onset, r_cutoff),\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n alpha=alpha,\n reduce_axis=(1,) if per_particle else None)\n\n\ndef morse_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: Box,\n species: Optional[Array]=None,\n sigma: Array=1.0,\n epsilon: Array=5.0,\n alpha: Array=5.0,\n r_onset: float=2.0,\n r_cutoff: float=2.5,\n dr_threshold: float=0.5,\n per_particle: bool=False,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.OrderedSparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute Morse using a neighbor list.\"\"\"\n sigma = maybe_downcast(sigma)\n epsilon = maybe_downcast(epsilon)\n alpha = maybe_downcast(alpha)\n r_onset = maybe_downcast(r_onset)\n r_cutoff = maybe_downcast(r_cutoff)\n dr_threshold = maybe_downcast(dr_threshold)\n\n neighbor_fn = partition.neighbor_list(\n displacement_or_metric,\n box_size,\n r_cutoff,\n dr_threshold,\n fractional_coordinates=fractional_coordinates,\n format=format)\n energy_fn = smap.pair_neighbor_list(\n multiplicative_isotropic_cutoff(morse, r_onset, r_cutoff),\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n ignore_unused_parameters=True,\n species=species,\n sigma=sigma,\n epsilon=epsilon,\n alpha=alpha,\n reduce_axis=(1,) if per_particle else None)\n\n return neighbor_fn, energy_fn\n\n\ndef gupta_potential(displacement, p, q, r_0n, U_n, A, cutoff):\n \"\"\"Gupta potential with default parameters for Au_55 cluster. Gupta\n potential was introduced by R. P. Gupta [1]. This potential uses parameters\n that were fit for bulk gold by Jellinek [2]. This particular implementation\n of the Gupta potential was introduced by Garzon and Posada-Amarillas [3].\n\n Args:\n displacement: Function to compute displacement between two positions.\n p: Gupta potential parameter of the repulsive term that was fitted for\n bulk gold.\n q: Gupta potential parameter of the attractive term that was fitted for\n bulk gold.\n r_0n: Parameter that determines the length scale of the potential. This\n value was particularly fit for gold clusters of size 55 atoms.\n U_n: Parameter that determines the energy scale, fit particularly for\n gold clusters of size 55 atoms.\n A: Parameter that was obtained using the cohesive energy of the fcc gold\n metal.\n cutoff: Pairwise interactions that are farther than the cutoff distance\n will be ignored.\n\n Returns:\n A function that takes in positions of gold atoms (shape [n, 3] where n is\n the number of atoms) and returns the total energy of the system in units\n of eV.\n\n [1] R.P. Gupta, Phys. Rev. B 23, 6265 (1981)\n [2] J. Jellinek, in Metal-Ligand Interactions, edited by N. Russo and\n D. R. Salahub (Kluwer Academic, Dordrecht, 1996), p. 325.\n [3] I. L. Garzon, A. Posada-Amarillas, Phys. Rev. B 54, 16 (1996)\n \"\"\"\n def _gupta_term1(r, p, r_0n, cutoff):\n \"\"\"Repulsive term in Gupta potential.\"\"\"\n within_cutoff = (r > 0) & (r < cutoff)\n term1 = jnp.exp(-1.0 * p * (r / r_0n - 1))\n return jnp.where(within_cutoff, term1, 0.0)\n\n def _gupta_term2(r, q, r_0n, cutoff):\n \"\"\"Attractive term in Gupta potential.\"\"\"\n within_cutoff = (r > 0) & (r < cutoff)\n term2 = jnp.exp(-2.0 * q * (r / r_0n - 1))\n return jnp.where(within_cutoff, term2, 0.0)\n\n def compute_fn(R):\n dR = space.map_product(displacement)(R, R)\n dr = space.distance(dR)\n first_term = A * jnp.sum(_gupta_term1(dr, p, r_0n, cutoff), axis=1)\n # Safe sqrt used in order to ensure that force calculations are not nan\n # when the particles are too widely separated at initialization\n # (corresponding to the case where the attractive term is 0.).\n attractive_term = jnp.sum(_gupta_term2(dr, q, r_0n, cutoff), axis=1)\n second_term = util.safe_mask(attractive_term > 0,\n jnp.sqrt, attractive_term)\n return U_n / 2.0 * jnp.sum(first_term - second_term)\n\n return compute_fn\n\n\nGUPTA_GOLD55_DICT = {\n 'p' : 10.15,\n 'q' : 4.13,\n 'r_0n' : 2.96,\n 'U_n' : 3.454,\n 'A' : 0.118428,\n}\n\ndef gupta_gold55(displacement,\n cutoff=8.0):\n gupta_gold_fn = gupta_potential(displacement,\n cutoff=cutoff,\n **GUPTA_GOLD55_DICT)\n def energy_fn(R, **unused_kwargs):\n return gupta_gold_fn(R)\n return energy_fn\n\ndef multiplicative_isotropic_cutoff(fn: Callable[..., Array],\n r_onset: float,\n r_cutoff: float) -> Callable[..., Array]:\n \"\"\"Takes an isotropic function and constructs a truncated function.\n\n Given a function f:R -> R, we construct a new function f':R -> R such that\n f'(r) = f(r) for r < r_onset, f'(r) = 0 for r > r_cutoff, and f(r) is C^1\n everywhere. To do this, we follow the approach outlined in HOOMD Blue [1]\n (thanks to Carl Goodrich for the pointer). We construct a function S(r) such\n that S(r) = 1 for r < r_onset, S(r) = 0 for r > r_cutoff, and S(r) is C^1.\n Then f'(r) = S(r)f(r).\n\n Args:\n fn: A function that takes an ndarray of distances of shape [n, m] as well\n as varargs.\n r_onset: A float specifying the distance marking the onset of deformation.\n r_cutoff: A float specifying the cutoff distance.\n\n Returns:\n A new function with the same signature as fn, with the properties outlined\n above.\n\n [1] HOOMD Blue documentation. Accessed on 05/31/2019.\n https://hoomd-blue.readthedocs.io/en/stable/module-md-pair.html#hoomd.md.pair.pair\n \"\"\"\n\n r_c = r_cutoff ** f32(2)\n r_o = r_onset ** f32(2)\n\n def smooth_fn(dr):\n r = dr ** f32(2)\n\n inner = jnp.where(dr < r_cutoff,\n (r_c - r)**2 * (r_c + 2 * r - 3 * r_o) / (r_c - r_o)**3,\n 0)\n\n return jnp.where(dr < r_onset, 1, inner)\n\n @wraps(fn)\n def cutoff_fn(dr, *args, **kwargs):\n return smooth_fn(dr) * fn(dr, *args, **kwargs)\n\n return cutoff_fn\n\n\ndef dsf_coulomb(r: Array,\n Q_sq: Array,\n alpha: Array=0.25,\n cutoff: float=8.0) -> Array:\n \"\"\"Damped-shifted-force approximation of the coulombic interaction.\"\"\"\n qqr2e = 332.06371 # Coulmbic conversion factor: 1/(4*pi*epo).\n\n cutoffsq = cutoff*cutoff\n erfcc = erfc(alpha*cutoff)\n erfcd = jnp.exp(-alpha*alpha*cutoffsq)\n f_shift = -(erfcc/cutoffsq + 2.0/jnp.sqrt(jnp.pi)*alpha*erfcd/cutoff)\n e_shift = erfcc/cutoff - f_shift*cutoff\n\n coulomb_en = qqr2e*Q_sq/r * (erfc(alpha*r) - r*e_shift - r**2*f_shift)\n return jnp.where(r < cutoff, coulomb_en, 0.0)\n\n\ndef bks(dr: Array,\n Q_sq: Array,\n exp_coeff: Array,\n exp_decay: Array,\n attractive_coeff: Array,\n repulsive_coeff: Array,\n coulomb_alpha: Array,\n cutoff: float,\n **unused_kwargs) -> Array:\n \"\"\"Beest-Kramer-van Santen (BKS) potential[1] which is commonly used to\n model silicas. This function computes the interaction between two\n given atoms within the Buckingham form[2], following the implementation\n from Ref. [3]\n\n Args:\n dr: An ndarray of shape [n, m] of pairwise distances between particles.\n Q_sq: An ndarray of shape [n, m] of pairwise product of partial charges.\n exp_coeff: An ndarray of shape [n, m] that sets the scale of the\n exponential decay of the short-range interaction.\n attractive_coeff: An ndarray of shape [n, m] for the coefficient of the\n attractive 6th order term.\n repulsive_coeff: An ndarray of shape [n, m] for the coefficient of the\n repulsive 24th order term, to prevent the ujnphysical fusion of atoms.\n coulomb_alpha: Damping parameter for the approximation of the long-range\n coulombic interactions (a scalar).\n cutoff: Cutoff distance for considering pairwise interactions.\n unused_kwargs: Allows extra data (e.g. time) to be passed to the energy.\n\n Returns:\n Matrix of energies of shape [n, m].\n\n [1] Van Beest, B. W. H., Gert Jan Kramer, and R. A. Van Santen. \"Force fields\n for silicas and aluminophosphates based on ab initio calculations.\" Physical\n Review Letters 64.16 (1990): 1955.\n [2] Carré, Antoine, et al. \"Developing empirical potentials from ab initio\n simulations: The case of amorphous silica.\" Computational Materials Science\n 124 (2016): 323-334.\n [3] Liu, Han, et al. \"Machine learning Forcefield for silicate glasses.\"\n arXiv preprint arXiv:1902.03486 (2019).\n \"\"\"\n energy = (dsf_coulomb(dr, Q_sq, coulomb_alpha, cutoff) + \\\n exp_coeff * jnp.exp(-dr / exp_decay) + \\\n attractive_coeff / dr ** 6 + repulsive_coeff / dr ** 24)\n return jnp.where(dr < cutoff, energy, 0.0)\n\n\ndef bks_pair(displacement_or_metric: DisplacementOrMetricFn,\n species: Array,\n Q_sq: Array,\n exp_coeff: Array,\n exp_decay: Array,\n attractive_coeff: Array,\n repulsive_coeff: Array,\n coulomb_alpha: Array,\n cutoff: float) -> Callable[[Array], Array]:\n \"\"\"Convenience wrapper to compute BKS energy over a system.\"\"\"\n Q_sq = maybe_downcast(Q_sq)\n exp_coeff = maybe_downcast(exp_coeff)\n exp_decay = maybe_downcast(exp_decay)\n attractive_coeff = maybe_downcast(attractive_coeff)\n repulsive_coeff = maybe_downcast(repulsive_coeff)\n\n return smap.pair(bks, displacement_or_metric,\n species=species,\n ignore_unused_parameters=True,\n Q_sq=Q_sq,\n exp_coeff=exp_coeff,\n exp_decay=exp_decay,\n attractive_coeff=attractive_coeff,\n repulsive_coeff=repulsive_coeff,\n coulomb_alpha=coulomb_alpha,\n cutoff=cutoff)\n\n\ndef bks_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: Box,\n species: Array,\n Q_sq: Array,\n exp_coeff: Array,\n exp_decay: Array,\n attractive_coeff: Array,\n repulsive_coeff: Array,\n coulomb_alpha: Array,\n cutoff: float,\n dr_threshold: float=0.8,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.OrderedSparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute BKS energy using a neighbor list.\"\"\"\n Q_sq = maybe_downcast(Q_sq)\n exp_coeff = maybe_downcast(exp_coeff)\n exp_decay = maybe_downcast(exp_decay)\n attractive_coeff = maybe_downcast(attractive_coeff)\n repulsive_coeff = maybe_downcast(repulsive_coeff)\n dr_threshold = maybe_downcast(dr_threshold)\n\n neighbor_fn = partition.neighbor_list(\n displacement_or_metric,\n box_size,\n cutoff,\n dr_threshold,\n fractional_coordinates=fractional_coordinates,\n format=format)\n\n energy_fn = smap.pair_neighbor_list(\n bks,\n space.canonicalize_displacement_or_metric(displacement_or_metric),\n species=species,\n ignore_unused_parameters=True,\n Q_sq=Q_sq,\n exp_coeff=exp_coeff,\n exp_decay=exp_decay,\n attractive_coeff=attractive_coeff,\n repulsive_coeff=repulsive_coeff,\n coulomb_alpha=coulomb_alpha,\n cutoff=cutoff)\n\n return neighbor_fn, energy_fn\n\n# BKS Potential Parameters.\n# Coefficients given in kcal/mol.\n\nCHARGE_OXYGEN = -0.977476019\nCHARGE_SILICON = 1.954952037\n\nBKS_SILICA_DICT = {\n 'Q_sq' : [[CHARGE_SILICON**2, CHARGE_SILICON*CHARGE_OXYGEN],\n [CHARGE_SILICON*CHARGE_OXYGEN, CHARGE_OXYGEN**2]],\n 'exp_coeff' : [[0, 471671.1243 ],\n [471671.1243, 23138.64826]],\n 'exp_decay' : [[1, 0.19173537],\n [0.19173537, 0.356855265]],\n 'attractive_coeff' : [[0, -2156.074422],\n [-2156.074422, -1879.223108]],\n 'repulsive_coeff' : [[78940848.06, 668.7557239],\n [668.7557239, 2605.841269]],\n 'coulomb_alpha' : 0.25,\n}\n\ndef _bks_silica_self(Q_sq: Array, alpha: Array, cutoff: float) -> Array:\n \"\"\"Function for computing the self-energy contributions to BKS.\"\"\"\n cutoffsq = cutoff * cutoff\n erfcc = erfc(alpha * cutoff)\n erfcd = jnp.exp(-alpha * alpha * cutoffsq)\n f_shift = -(erfcc / cutoffsq + 2.0 / jnp.sqrt(jnp.pi) * alpha * erfcd / cutoff)\n e_shift = erfcc / cutoff - f_shift * cutoff\n qqr2e = 332.06371 # kcal/mol coulmbic conversion factor: 1/(4*pi*epo)\n return -(e_shift / 2.0 + alpha / jnp.sqrt(jnp.pi)) * Q_sq * qqr2e\n\ndef bks_silica_pair(displacement_or_metric: DisplacementOrMetricFn,\n species: Array,\n cutoff: float=8.0):\n \"\"\"Convenience wrapper to compute BKS energy for SiO2.\"\"\"\n bks_pair_fn = bks_pair(displacement_or_metric,\n species,\n cutoff=cutoff,\n **BKS_SILICA_DICT)\n N_0 = jnp.sum(species==0)\n N_1 = jnp.sum(species==1)\n\n e_self = partial(_bks_silica_self, alpha=0.25, cutoff=cutoff)\n\n def energy_fn(R, **kwargs):\n return (bks_pair_fn(R, **kwargs) +\n N_0 * e_self(CHARGE_SILICON**2) +\n N_1 * e_self(CHARGE_OXYGEN**2))\n\n\n return energy_fn\n\n\ndef bks_silica_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: Box,\n species: Array,\n cutoff: float=8.0,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.OrderedSparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute BKS energy using neighbor lists.\"\"\"\n neighbor_fn, bks_pair_fn = bks_neighbor_list(\n displacement_or_metric,\n box_size,\n species,\n cutoff=cutoff,\n dr_threshold=0.8,\n fractional_coordinates=fractional_coordinates,\n format=format,\n **BKS_SILICA_DICT)\n N_0 = jnp.sum(species==0)\n N_1 = jnp.sum(species==1)\n\n e_self = partial(_bks_silica_self, alpha=0.25, cutoff=cutoff)\n\n def energy_fn(R, neighbor, **kwargs):\n return (bks_pair_fn(R, neighbor, **kwargs) +\n N_0 * e_self(CHARGE_SILICON ** 2) +\n N_1 * e_self(CHARGE_OXYGEN ** 2))\n\n return neighbor_fn, energy_fn\n\n# Stillinger-Weber Potential\ndef _sw_angle_interaction(gamma: float, sigma: float, cutoff: float,\n dR12: Array, dR13: Array) -> Array:\n \"\"\"The angular interaction for the Stillinger-Weber potential.\n This function is defined only for interaction with a pair of\n neighbors. We then vmap this function three times below to make\n it work on the whole system of atoms.\n Args:\n gamma: A scalar used to fit the angle interaction.\n sigma: A scalar that sets the distance scale between neighbors.\n cutoff: The cutoff beyond which the interactions are not\n considered. The default value should not be changed for the\n default SW potential.\n dR12: A d-dimensional vector that specifies the displacement\n of the first neighbor. This potential is usually used in three\n dimensions.\n dR13: A d-dimensional vector that specifies the displacement\n of the second neighbor.\n\n Returns:\n Angular interaction energy for one pair of neighbors.\n \"\"\"\n a = cutoff / sigma\n dr12 = space.distance(dR12)\n dr13 = space.distance(dR13)\n dr12 = jnp.where(dr12 < cutoff, dr12, 0)\n dr13 = jnp.where(dr13 < cutoff, dr13, 0)\n term1 = jnp.exp(gamma / (dr12 / sigma - a) + gamma / (dr13 / sigma - a))\n cos_angle = quantity.cosine_angle_between_two_vectors(dR12, dR13)\n term2 = (cos_angle + 1./3)**2\n within_cutoff = (dr12>0) & (dr13>0) & (jnp.linalg.norm(dR12-dR13)>1e-5)\n return jnp.where(within_cutoff, term1 * term2, 0)\nsw_three_body_term = vmap(vmap(vmap(\n _sw_angle_interaction, (0, None)), (None, 0)), 0)\n\n\ndef _sw_radial_interaction(sigma: float, B: float, cutoff: float, r: Array\n ) -> Array:\n \"\"\"The two body term of the Stillinger-Weber potential.\"\"\"\n a = cutoff / sigma\n p = 4\n term1 = (B * (r / sigma)**(-p) - 1.0)\n within_cutoff = (r > 0) & (r < cutoff)\n r = jnp.where(within_cutoff, r, 0)\n term2 = jnp.exp(1 / (r / sigma - a))\n return jnp.where(within_cutoff, term1 * term2, 0.0)\n\n\ndef stillinger_weber(displacement: DisplacementFn,\n sigma=2.0951,\n A=7.049556277,\n B=0.6022245584,\n lam=21.0,\n gamma=1.2,\n epsilon=2.16826,\n three_body_strength=1.0,\n cutoff=3.77118) -> Callable[[Array], Array]:\n \"\"\"Computes the Stillinger-Weber potential.\n\n The Stillinger-Weber (SW) potential [1] which is commonly used to model\n silicon and similar systems. This function uses the default SW parameters\n from the original paper. The SW potential was originally proposed to\n model diamond in the diamond crystal phase and the liquid phase, and is\n known to give ujnphysical amorphous configurations [2, 3]. For this reason,\n we provide a three_body_strength parameter. Changing this number to 1.5\n or 2.0 has been know to produce more physical amorphous phase, preventing\n most atoms from having more than four nearest neighbors. Note that this\n function currently assumes nearest-image-convention.\n\n Args:\n displacement: The displacement function for the space.\n sigma: A scalar that sets the distance scale between neighbors.\n A: A scalar that determines the scale of two-body term.\n B: A scalar that determines the scale of the 1 / r^p term.\n lam: A scalar that determines the scale of the three-body term.\n epsilon: A scalar that sets the total energy scale.\n gamma: A scalar used to fit the angle interaction.\n three_body_strength: A scalar that determines the relative strength\n of the angular interaction. Default value is 1.0, which works well\n for the diamond crystal and liquid phases. 1.5 and 2.0 have been used\n to model amorphous silicon.\n Returns:\n A function that computes the total energy.\n\n [1] Stillinger, Frank H., and Thomas A. Weber. \"Computer simulation of\n local order in condensed phases of silicon.\" Physical review B 31.8\n (1985): 5262.\n [2] Holender, J. M., and G. J. Morgan. \"Generation of a large structure\n (105 atoms) of amorphous Si using molecular dynamics.\" Journal of\n Physics: Condensed Matter 3.38 (1991): 7241.\n [3] Barkema, G. T., and Normand Mousseau. \"Event-based relaxation of\n continuous disordered systems.\" Physical review letters 77.21 (1996): 4358.\n \"\"\"\n two_body_fn = partial(_sw_radial_interaction, sigma, B, cutoff)\n three_body_fn = partial(_sw_angle_interaction, gamma, sigma, cutoff)\n three_body_fn = vmap(vmap(vmap(three_body_fn, (0, None)), (None, 0)))\n\n def compute_fn(R, **kwargs):\n d = partial(displacement, **kwargs)\n dR = space.map_product(d)(R, R)\n dr = space.distance(dR)\n first_term = util.high_precision_sum(two_body_fn(dr)) / 2.0 * A\n second_term = lam * util.high_precision_sum(three_body_fn(dR, dR)) / 2.0\n return epsilon * (first_term + three_body_strength * second_term)\n return compute_fn\n\n\ndef stillinger_weber_neighbor_list(\n displacement: DisplacementFn,\n box_size: float,\n sigma=2.0951,\n A=7.049556277,\n B=0.6022245584,\n lam=21.0,\n gamma=1.2,\n epsilon=2.16826,\n three_body_strength=1.0,\n cutoff=3.77118,\n fractional_coordinates: bool=False,\n format=partition.Dense\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Computes the Stillinger-Weber potential.\n\n The Stillinger-Weber (SW) potential [1] which is commonly used to model\n silicon and similar systems. This function uses the default SW parameters\n from the original paper. The SW potential was originally proposed to\n model diamond in the diamond crystal phase and the liquid phase, and is\n known to give ujnphysical amorphous configurations [2, 3]. For this reason,\n we provide a three_body_strength parameter. Changing this number to 1.5\n or 2.0 has been know to produce more physical amorphous phase, preventing\n most atoms from having more than four nearest neighbors. Note that this\n function currently assumes nearest-image-convention.\n\n Args:\n displacement: The displacement function for the space.\n sigma: A scalar that sets the distance scale between neighbors.\n A: A scalar that determines the scale of two-body term.\n B: A scalar that determines the scale of the 1 / r^p term.\n lam: A scalar that determines the scale of the three-body term.\n epsilon: A scalar that sets the total energy scale.\n gamma: A scalar used to fit the angle interaction.\n three_body_strength: A scalar that determines the relative strength\n of the angular interaction. Default value is 1.0, which works well\n for the diamond crystal and liquid phases. 1.5 and 2.0 have been used\n to model amorphous silicon.\n Returns:\n A function that computes the total energy.\n\n [1] Stillinger, Frank H., and Thomas A. Weber. \"Computer simulation of\n local order in condensed phases of silicon.\" Physical review B 31.8\n (1985): 5262.\n [2] Holender, J. M., and G. J. Morgan. \"Generation of a large structure\n (105 atoms) of amorphous Si using molecular dynamics.\" Journal of\n Physics: Condensed Matter 3.38 (1991): 7241.\n [3] Barkema, G. T., and Normand Mousseau. \"Event-based relaxation of\n continuous disordered systems.\" Physical review letters 77.21 (1996): 4358.\n \"\"\"\n two_body_fn = partial(_sw_radial_interaction, sigma, B, cutoff)\n three_body_fn = partial(_sw_angle_interaction, gamma, sigma, cutoff)\n\n dr_threshold = 0.5\n\n neighbor_fn = partition.neighbor_list(displacement,\n box_size,\n cutoff,\n dr_threshold,\n format=format)\n\n def compute_fn(R, neighbor, **kwargs):\n d = partial(displacement, **kwargs)\n mask = partition.neighbor_list_mask(neighbor)\n\n if neighbor.format is partition.Dense:\n _three_body_fn = vmap(vmap(vmap(three_body_fn, (0, None)), (None, 0)))\n dR = space.map_neighbor(d)(R, R[neighbor.idx])\n dr = space.distance(dR)\n first_term = util.high_precision_sum(two_body_fn(dr) * mask) / 2.0 * A\n mask_ijk = mask[:, None, :] * mask[:, :, None]\n second_term = lam * util.high_precision_sum(\n _three_body_fn(dR, dR) * mask_ijk) / 2.0\n else:\n raise NotImplementedError('Stillinger-Weber potential only implemented '\n 'with Dense neighbor lists.')\n\n return epsilon * (first_term + three_body_strength * second_term)\n return neighbor_fn, compute_fn\n\n\n\n# Embedded Atom Method\n\n\ndef load_lammps_eam_parameters(file: TextIO) -> Tuple[Callable[[Array], Array],\n Callable[[Array], Array],\n Callable[[Array], Array],\n float]:\n \"\"\"Reads EAM parameters from a LAMMPS file and returns relevant spline fits.\n\n This function reads single-element EAM potential fit parameters from a file\n in DYNAMO funcl format. In summary, the file contains:\n Line 1-3: comments,\n Line 4: Number of elements and the element type,\n Line 5: The number of charge values that the embedding energy is evaluated\n on (num_drho), interval between the charge values (drho), the number of\n distances the pairwise energy and the charge density is evaluated on (num_dr),\n the interval between these distances (dr), and the cutoff distance (cutoff).\n The lines that come after are the embedding function evaluated on num_drho\n charge values, charge function evaluated at num_dr distance values, and\n pairwise energy evaluated at num_dr distance values. Note that the pairwise\n energy is multiplied by distance (in units of eV x Angstroms). For more\n details of the DYNAMO file format, see:\n https://sites.google.com/a/ncsu.edu/cjobrien/tutorials-and-guides/eam\n Args:\n f: File handle for the EAM parameters text file.\n\n Returns:\n charge_fn: A function that takes an ndarray of shape [n, m] of distances\n between particles and returns a matrix of charge contributions.\n embedding_fn: Function that takes an ndarray of shape [n] of charges and\n returns an ndarray of shape [n] of the energy cost of embedding an atom\n into the charge.\n pairwise_fn: A function that takes an ndarray of shape [n, m] of distances\n and returns an ndarray of shape [n, m] of pairwise energies.\n cutoff: Cutoff distance for the embedding_fn and pairwise_fn.\n \"\"\"\n raw_text = file.read().split('\\n')\n if 'setfl' not in raw_text[0]:\n raise ValueError('File format is incorrect, expected LAMMPS setfl format.')\n temp_params = raw_text[4].split()\n num_drho, num_dr = int(temp_params[0]), int(temp_params[2])\n drho, dr, cutoff = float(temp_params[1]), float(temp_params[3]), float(\n temp_params[4])\n data = maybe_downcast([float(i) for i in raw_text[6:-1]])\n embedding_fn = interpolate.spline(data[:num_drho], drho)\n charge_fn = interpolate.spline(data[num_drho:num_drho + num_dr], dr)\n # LAMMPS EAM parameters file lists pairwise energies after multiplying by\n # distance, in units of eV*Angstrom. We divide the energy by distance below,\n distances = jnp.arange(num_dr) * dr\n # Prevent dividing by zero at zero distance, which will not\n # affect the calculation\n distances = jnp.where(distances == 0, f32(0.001), distances)\n pairwise_fn = interpolate.spline(\n data[num_dr + num_drho:num_drho + 2 * num_dr] / distances,\n dr)\n return charge_fn, embedding_fn, pairwise_fn, cutoff\n\n\ndef eam(displacement: DisplacementFn,\n charge_fn: Callable[[Array], Array],\n embedding_fn: Callable[[Array], Array],\n pairwise_fn: Callable[[Array], Array],\n axis: Optional[Tuple[int, ...]]=None) -> Callable[[Array], Array]:\n \"\"\"Interatomic potential as approximated by embedded atom model (EAM).\n\n This code implements the EAM approximation to interactions between metallic\n atoms. In EAM, the potential energy of an atom is given by two terms: a\n pairwise energy and an embedding energy due to the interaction between the\n atom and background charge density. The EAM potential for a single atomic\n species is often\n determined by three functions:\n 1) Charge density contribution of an atom as a function of distance.\n 2) Energy of embedding an atom in the background charge density.\n 3) Pairwise energy.\n These three functions are usually provided as spline fits, and we follow the\n implementation and spline fits given by [1]. Note that in current\n implementation, the three functions listed above can also be expressed by a\n any function with the correct signature, including neural networks.\n\n Args:\n displacement: A function that produces an ndarray of shape [n, m,\n spatial_dimension] of particle displacements from particle positions\n specified as an ndarray of shape [n, spatial_dimension] and [m,\n spatial_dimension] respectively.\n charge_fn: A function that takes an ndarray of shape [n, m] of distances\n between particles and returns a matrix of charge contributions.\n embedding_fn: Function that takes an ndarray of shape [n] of charges and\n returns an ndarray of shape [n] of the energy cost of embedding an atom\n into the charge.\n pairwise_fn: A function that takes an ndarray of shape [n, m] of distances\n and returns an ndarray of shape [n, m] of pairwise energies.\n axis: Specifies which axis the total energy should be summed over.\n\n Returns:\n A function that computes the EAM energy of a set of atoms with positions\n given by an [n, spatial_dimension] ndarray.\n\n [1] Y. Mishin, D. Farkas, M.J. Mehl, DA Papaconstantopoulos, \"Interatomic\n potentials for monoatomic metals from experimental data and ab initio\n calculations.\" Physical Review B, 59 (1999)\n \"\"\"\n metric = space.map_product(space.metric(displacement))\n\n def energy(R, **kwargs):\n dr = metric(R, R, **kwargs)\n total_charge = util.high_precision_sum(charge_fn(dr), axis=1)\n embedding_energy = embedding_fn(total_charge)\n pairwise_energy = util.high_precision_sum(smap._diagonal_mask(\n pairwise_fn(dr)), axis=1) / f32(2.0)\n return util.high_precision_sum(\n embedding_energy + pairwise_energy, axis=axis)\n\n return energy\n\n\ndef eam_from_lammps_parameters(displacement: DisplacementFn,\n f: TextIO) -> Callable[[Array], Array]:\n \"\"\"Convenience wrapper to compute EAM energy over a system.\"\"\"\n return eam(displacement, *load_lammps_eam_parameters(f)[:-1])\n\n\ndef eam_neighbor_list(\n displacement_or_metric: DisplacementOrMetricFn,\n box_size: float,\n charge_fn: Callable[[Array], Array],\n embedding_fn: Callable[[Array], Array],\n pairwise_fn: Callable[[Array], Array],\n cutoff: float,\n axis: Optional[Tuple[int, ...]]=None,\n fractional_coordinates: bool=True,\n format: partition.NeighborListFormat=partition.Sparse\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Interatomic potential as approximated by embedded atom model (EAM).\n\n This code implements the EAM approximation to interactions between metallic\n atoms. In EAM, the potential energy of an atom is given by two terms: a\n pairwise energy and an embedding energy due to the interaction between the\n atom and background charge density. The EAM potential for a single atomic\n species is often\n determined by three functions:\n 1) Charge density contribution of an atom as a function of distance.\n 2) Energy of embedding an atom in the background charge density.\n 3) Pairwise energy.\n These three functions are usually provided as spline fits, and we follow the\n implementation and spline fits given by [1]. Note that in current\n implementation, the three functions listed above can also be expressed by a\n any function with the correct signature, including neural networks.\n\n Args:\n displacement: A function that produces an ndarray of shape [n, m,\n spatial_dimension] of particle displacements from particle positions\n specified as an ndarray of shape [n, spatial_dimension] and [m,\n spatial_dimension] respectively.\n charge_fn: A function that takes an ndarray of shape [n, m] of distances\n between particles and returns a matrix of charge contributions.\n embedding_fn: Function that takes an ndarray of shape [n] of charges and\n returns an ndarray of shape [n] of the energy cost of embedding an atom\n into the charge.\n pairwise_fn: A function that takes an ndarray of shape [n, m] of distances\n and returns an ndarray of shape [n, m] of pairwise energies.\n axis: Specifies which axis the total energy should be summed over.\n\n Returns:\n A function that computes the EAM energy of a set of atoms with positions\n given by an [n, spatial_dimension] ndarray.\n\n [1] Y. Mishin, D. Farkas, M.J. Mehl, DA Papaconstantopoulos, \"Interatomic\n potentials for monoatomic metals from experimental data and ab initio\n calculations.\" Physical Review B, 59 (1999)\n \"\"\"\n metric = space.canonicalize_displacement_or_metric(displacement_or_metric)\n\n dr_threshold = 0.5\n\n neighbor_fn = partition.neighbor_list(displacement_or_metric,\n box_size,\n cutoff,\n dr_threshold,\n mask_self=False)\n\n def energy_fn(R, neighbor, **kwargs):\n mask = partition.neighbor_list_mask(neighbor)\n self_mask = partition.neighbor_list_mask(neighbor, mask_self=True)\n\n if neighbor.format is partition.Dense:\n dr = space.map_neighbor(metric)(R, R[neighbor.idx], **kwargs)\n total_charge = util.high_precision_sum(charge_fn(dr) * mask, axis=1)\n embedding_energy = embedding_fn(total_charge)\n pairwise_energy = util.high_precision_sum(pairwise_fn(dr) * self_mask,\n axis=1)\n elif neighbor.format is partition.Sparse:\n N = len(R)\n dr = space.map_bond(metric)(R[neighbor.idx[0]], R[neighbor.idx[1]],\n **kwargs)\n total_charge = ops.segment_sum(charge_fn(dr) * mask, neighbor.idx[0], N)\n embedding_energy = embedding_fn(total_charge)\n pairwise_energy = ops.segment_sum(pairwise_fn(dr) * self_mask,\n neighbor.idx[0], N)\n else:\n raise NotImplementedError('EAM potentail not implemented for '\n 'OrderedSparse neighbor lists.')\n\n return util.high_precision_sum(\n embedding_energy + pairwise_energy / 2.0, axis=axis)\n\n return neighbor_fn, energy_fn\n\n\ndef eam_from_lammps_parameters_neighbor_list(\n displacement: DisplacementFn,\n box_size, float,\n f: TextIO,\n axis=None,\n fractional_coordinates=True,\n ) -> Tuple[NeighborFn, Callable[[Array, NeighborList], Array]]:\n \"\"\"Convenience wrapper to compute EAM energy over a system.\"\"\"\n return eam_neighbor_list(displacement,\n box_size,\n *load_lammps_eam_parameters(f))\n\n\ndef behler_parrinello(displacement: DisplacementFn,\n species: Optional[Array]=None,\n mlp_sizes: Tuple[int, ...]=(30, 30),\n mlp_kwargs: Optional[Dict[str, Any]]=None,\n sym_kwargs: Optional[Dict[str, Any]]=None,\n per_particle: bool=False\n ) -> Tuple[nn.InitFn,\n Callable[[PyTree, Array], Array]]:\n if sym_kwargs is None:\n sym_kwargs = {}\n if mlp_kwargs is None:\n mlp_kwargs = {\n 'activation': jnp.tanh\n }\n\n sym_fn = nn.behler_parrinello_symmetry_functions(displacement,\n species,\n **sym_kwargs)\n\n @hk.without_apply_rng\n @hk.transform\n def model(R, **kwargs):\n embedding_fn = hk.nets.MLP(output_sizes=mlp_sizes+(1,),\n activate_final=False,\n name='BPEncoder',\n **mlp_kwargs)\n embedding_fn = vmap(embedding_fn)\n sym = sym_fn(R, **kwargs)\n readout = embedding_fn(sym)\n if per_particle:\n return readout\n return jnp.sum(readout)\n return model.init, model.apply\n\n\ndef behler_parrinello_neighbor_list(\n displacement: DisplacementFn,\n box_size: float,\n species: Optional[Array]=None,\n mlp_sizes: Tuple[int, ...]=(30, 30),\n mlp_kwargs: Optional[Dict[str, Any]]=None,\n sym_kwargs: Optional[Dict[str, Any]]=None,\n dr_threshold: float=0.5,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.Sparse\n ) -> Tuple[NeighborFn, nn.InitFn, Callable[[PyTree, Array, NeighborList],\n Array]]:\n if sym_kwargs is None:\n sym_kwargs = {}\n if mlp_kwargs is None:\n mlp_kwargs = {\n 'activation': jnp.tanh\n }\n\n cutoff_distance = 8.0\n if 'cutoff_distance' in sym_kwargs:\n cutoff_distance = sym_kwargs['cutoff_distance']\n\n neighbor_fn = partition.neighbor_list(\n displacement,\n box_size,\n cutoff_distance,\n dr_threshold,\n fractional_coordinates=fractional_coordinates,\n format=format)\n\n sym_fn = nn.behler_parrinello_symmetry_functions_neighbor_list(displacement,\n species,\n **sym_kwargs)\n\n @hk.without_apply_rng\n @hk.transform\n def model(R, neighbor, **kwargs):\n embedding_fn = hk.nets.MLP(output_sizes=mlp_sizes+(1,),\n activate_final=False,\n name='BPEncoder',\n **mlp_kwargs)\n embedding_fn = vmap(embedding_fn)\n sym = sym_fn(R, neighbor, **kwargs)\n readout = embedding_fn(sym)\n return jnp.sum(readout)\n return neighbor_fn, model.init, model.apply\n\n\nclass EnergyGraphNet(hk.Module):\n \"\"\"Implements a Graph Neural Network for energy fitting.\n\n This model uses a GraphNetEmbedding combined with a decoder applied to the\n global state.\n \"\"\"\n def __init__(self,\n n_recurrences: int,\n mlp_sizes: Tuple[int, ...],\n mlp_kwargs: Optional[Dict[str, Any]]=None,\n format: partition.NeighborListFormat=partition.Dense,\n name: str='Energy'):\n super(EnergyGraphNet, self).__init__(name=name)\n\n if mlp_kwargs is None:\n mlp_kwargs = {\n 'w_init': hk.initializers.VarianceScaling(),\n 'b_init': hk.initializers.VarianceScaling(0.1),\n 'activation': jax.nn.softplus\n }\n self._format = format\n self._graph_net = nn.GraphNetEncoder(n_recurrences,\n mlp_sizes,\n mlp_kwargs,\n format)\n self._decoder = hk.nets.MLP(output_sizes=mlp_sizes + (1,),\n activate_final=False,\n name='GlobalDecoder',\n **mlp_kwargs)\n\n def __call__(self, graph: nn.GraphsTuple) -> jnp.ndarray:\n output = self._graph_net(graph)\n output = jnp.squeeze(self._decoder(output.globals), axis=-1)\n if self._format is partition.Sparse:\n output = output[0]\n return output\n\n\ndef _canonicalize_node_state(nodes: Optional[Array]) -> Optional[Array]:\n if nodes is None:\n return nodes\n\n if nodes.ndim == 1:\n nodes = nodes[:, jnp.newaxis]\n\n if nodes.ndim != 2:\n raise ValueError(\n 'Nodes must be a [N, node_dim] array. Found {}.'.format(nodes.shape))\n\n return nodes\n\n\ndef graph_network(displacement_fn: DisplacementFn,\n r_cutoff: float,\n nodes: Optional[Array]=None,\n n_recurrences: int=2,\n mlp_sizes: Tuple[int, ...]=(64, 64),\n mlp_kwargs: Optional[Dict[str, Any]]=None\n ) -> Tuple[nn.InitFn,\n Callable[[PyTree, Array], Array]]:\n \"\"\"Convenience wrapper around EnergyGraphNet model.\n\n Args:\n displacement_fn: Function to compute displacement between two positions.\n r_cutoff: A floating point cutoff; Edges will be added to the graph\n for pairs of particles whose separation is smaller than the cutoff.\n nodes: None or an ndarray of shape `[N, node_dim]` specifying the state\n of the nodes. If None this is set to the zeroes vector. Often, for a\n system with multiple species, this could be the species id.\n n_recurrences: The number of steps of message passing in the graph network.\n mlp_sizes: A tuple specifying the layer-widths for the fully-connected\n networks used to update the states in the graph network.\n mlp_kwargs: A dict specifying args for the fully-connected networks used to\n update the states in the graph network.\n\n Returns:\n A tuple of functions. An `params = init_fn(key, R)` that instantiates the\n model parameters and an `E = apply_fn(params, R)` that computes the energy\n for a particular state.\n \"\"\"\n\n nodes = _canonicalize_node_state(nodes)\n\n @hk.without_apply_rng\n @hk.transform\n def model(R: Array, **kwargs) -> Array:\n N = R.shape[0]\n\n d = partial(displacement_fn, **kwargs)\n d = space.map_product(d)\n dR = d(R, R)\n\n dr_2 = space.square_distance(dR)\n\n if 'nodes' in kwargs:\n _nodes = _canonicalize_node_state(kwargs['nodes'])\n else:\n _nodes = jnp.zeros((N, 1), R.dtype) if nodes is None else nodes\n\n edge_idx = jnp.broadcast_to(jnp.arange(N)[jnp.newaxis, :], (N, N))\n edge_idx = jnp.where(dr_2 < r_cutoff ** 2, edge_idx, N)\n\n _globals = jnp.zeros((1,), R.dtype)\n\n net = EnergyGraphNet(n_recurrences, mlp_sizes, mlp_kwargs)\n return net(nn.GraphsTuple(_nodes, dR, _globals, edge_idx)) # pytype: disable=wrong-arg-count\n\n return model.init, model.apply\n\n\ndef graph_network_neighbor_list(\n displacement_fn: DisplacementFn,\n box_size: Box,\n r_cutoff: float,\n dr_threshold: float,\n nodes: Optional[Array]=None,\n n_recurrences: int=2,\n mlp_sizes: Tuple[int, ...]=(64, 64),\n mlp_kwargs: Optional[Dict[str, Any]]=None,\n fractional_coordinates: bool=False,\n format: partition.NeighborListFormat=partition.Sparse\n ) -> Tuple[NeighborFn, nn.InitFn, Callable[[PyTree, Array, NeighborList],\n Array]]:\n \"\"\"Convenience wrapper around EnergyGraphNet model using neighbor lists.\n\n Args:\n displacement_fn: Function to compute displacement between two positions.\n box_size: The size of the simulation volume, used to construct neighbor\n list.\n r_cutoff: A floating point cutoff; Edges will be added to the graph\n for pairs of particles whose separation is smaller than the cutoff.\n dr_threshold: A floating point number specifying a \"halo\" radius that we use\n for neighbor list construction. See `neighbor_list` for details.\n nodes: None or an ndarray of shape `[N, node_dim]` specifying the state\n of the nodes. If None this is set to the zeroes vector. Often, for a\n system with multiple species, this could be the species id.\n n_recurrences: The number of steps of message passing in the graph network.\n mlp_sizes: A tuple specifying the layer-widths for the fully-connected\n networks used to update the states in the graph network.\n mlp_kwargs: A dict specifying args for the fully-connected networks used to\n update the states in the graph network.\n fractional_coordinates: A boolean specifying whether or not the coordinates\n will be in the unit cube.\n format: The format of the neighbor list. See `partition.NeighborListFormat`\n for details. Only `Dense` and `Sparse` formats are accepted. If the `Dense`\n format is used, then the graph network is constructed using the JAX MD\n backend, otherwise Jraph is used.\n\n Returns:\n A pair of functions. An `params = init_fn(key, R)` that instantiates the\n model parameters and an `E = apply_fn(params, R)` that computes the energy\n for a particular state.\n \"\"\"\n\n nodes = _canonicalize_node_state(nodes)\n\n @hk.without_apply_rng\n @hk.transform\n def model(R, neighbor, **kwargs):\n N = R.shape[0]\n d = partial(displacement_fn, **kwargs)\n\n if 'nodes' in kwargs:\n _nodes = _canonicalize_node_state(kwargs['nodes'])\n else:\n _nodes = jnp.zeros((N, 1), R.dtype) if nodes is None else nodes\n\n _globals = jnp.zeros((1,), R.dtype)\n\n if format is partition.Dense:\n d = space.map_neighbor(d)\n R_neigh = R[neighbor.idx]\n dR = d(R, R_neigh)\n\n dr_2 = space.square_distance(dR)\n edge_idx = jnp.where(dr_2 < r_cutoff ** 2, neighbor.idx, N)\n graph = nn.GraphsTuple(_nodes, dR, _globals, edge_idx)\n else:\n d = space.map_bond(d)\n dR = d(R[neighbor.idx[0]], R[neighbor.idx[1]])\n if dr_threshold > 0.0:\n dr_2 = space.square_distance(dR)\n mask = dr_2 < r_cutoff ** 2 + 1e-5\n graph = partition.to_jraph(neighbor, mask)\n # TODO(schsam): It seems wasteful to recompute dR after we remask the\n # edges. If I can think of a clean way to get rid of this, I should.\n dR = d(R[graph.receivers], R[graph.senders])\n else:\n graph = partition.to_jraph(neighbor)\n\n graph = graph._replace(\n nodes=jnp.concatenate((_nodes,\n jnp.zeros((1,) + _nodes.shape[1:], R.dtype)),\n axis=0),\n edges=dR,\n globals=jnp.broadcast_to(_globals[:, None], (2, 1))\n )\n\n net = EnergyGraphNet(n_recurrences, mlp_sizes, mlp_kwargs, format)\n return net(graph) # pytype: disable=wrong-arg-count\n\n neighbor_fn = partition.neighbor_list(\n displacement_fn,\n box_size,\n r_cutoff,\n dr_threshold,\n mask_self=False,\n fractional_coordinates=fractional_coordinates,\n format=format)\n init_fn, apply_fn = model.init, model.apply\n\n return neighbor_fn, init_fn, apply_fn\n","sub_path":"jax_md/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":54409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"48120980","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 7 17:09:08 2019\r\n\r\n@author: William\r\n\"\"\"\r\nimport numpy as np\r\n\r\ninput_nodes = 4\r\noutput_nodes = 3\r\nmax_layers = 6\r\nmax_layers += 1 #1 more than the number of hidden layers\r\ninitial_nodes = 50\r\ninitial_nodes += 1\r\nmaximum_nodes = 500\r\ninitial_links = 200\r\ninitial_links += 1\r\nmaximum_links = maximum_nodes*(input_nodes+1+output_nodes)+input_nodes*output_nodes\r\n\r\nproportionality = 10.\r\n\r\nmin_link_change = 1\r\nmax_link_change = 5 #actually the range\r\nmax_link_change += 1\r\nmin_node_change = 1\r\nmax_node_change = 3 #actually the range\r\nmax_node_change += 1\r\n\r\nregular_layer_bias = 0.8\r\nin_out_layer_bias = 1-regular_layer_bias\r\n#input_layer_weights = in_out_layer_bias*input_nodes/(input_nodes+output_nodes)\r\n#output_layer_weights = in_out_layer_bias*output_nodes/(input_nodes+output_nodes)\r\n\r\nnumber_nets = 100\r\nrepeats = 1\r\nmax_steps = 4000 #2000 till gen 20\r\nsave_rate = 1\r\ncertain_parents = int(0.25*number_nets)\r\nrandom_parents = int((number_nets/2)-certain_parents)\r\nmax_fitness = np.pi*max_steps/2\r\n\r\n#drawing the net\r\nscreen_width = 1000\r\nscreen_height = 800\r\npixel_per_layer = screen_width/(max_layers+1)\r\nnode_radius = 10\r\nnode_width = 1\r\nlink_width = 1\r\n","sub_path":"MachineLearning/Will's work/Early Learning Processes/Gnarl Evolution Learning/settings_parametric_swing.py","file_name":"settings_parametric_swing.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"261327018","text":"\"\"\"\n ATRIBUTOS ETIQUETAS\n Peso | Ladra ¿Perro?\n --------------------------\n 3 | No No\n 5 | No No\n 7 | Si Si\n 9 | Si SI\n\"\"\"\n\nfrom sklearn.tree import DecisionTreeClassifier\n\natributos = [ [3,0], [5,0], [7,1], [9,1] ]\netiquetas = [ 0, 0, 1, 1 ]\n\nclasificador = DecisionTreeClassifier() # se crea una instancia del modelo\nentrenamiento = clasificador.fit(atributos, etiquetas) # se entrena el modelo con los atributos y las etiquetas\n\n# resultado = entrenamiento.predict( [[4,0]] )\nresultado = entrenamiento.predict( [[11,1]] )\nprint(resultado)\n","sub_path":"python/arbol-decision1.py","file_name":"arbol-decision1.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211594850","text":"import csv\nimport tool\nimport time\n\n\ndef which(i, confs):\n for item in confs:\n if item['index'] == i:\n return item\n\n\ndef run(file_path, orientation, item_confs, db):\n print(len(item_confs))\n if tool.equals_str(orientation, 'H') and len(item_confs) < 1:\n reader = csv.DictReader(open(file_path, 'r'))\n result = [row for row in reader]\n insert_to_db(result, db)\n\n if tool.equals_str(orientation, 'H') and len(item_confs) > 0:\n reader = csv.reader(open(file_path, 'r'))\n # 获取每一行\n rows = [row for row in reader]\n result = get_result(item_confs, rows)\n insert_to_db(result, db)\n\n if tool.equals_str(orientation, 'V'):\n reader = csv.reader(open(file_path, 'r'))\n # 获取每一行\n rows = [row for row in reader]\n lens = len([row[0] for row in rows])\n h_data = []\n for i in range(lens):\n data = [row[i] for row in rows]\n h_data.append(data)\n\n result = get_result(item_confs, h_data)\n insert_to_db(result, db)\n\n\ndef insert_to_db(result, db):\n if len(result) > 0:\n db.insert(result)\n print(result)\n\n\ndef get_result(item_confs, rows):\n confs = get_configs(item_confs)\n indexs = [item['index'] for item in confs]\n result = []\n keys = []\n for i in range(len(rows)):\n row = rows[i]\n if i == 0:\n keys = row\n else:\n item = {}\n for j in range(len(row)):\n if keys is not None and len(keys) > 0:\n item_conf = None\n if j in indexs:\n item_conf = which(j, confs)\n key = keys[j]\n key, value = get_format_value(key, item_conf, row[j])\n item[key] = value\n else:\n raise ValueError(\"the title can not be NOne\")\n result.append(item)\n return result\n\n\n# 获取格式化后的Value\ndef get_format_value(key, item, param):\n if item is None:\n return key, param\n\n formater = item.get('column_type', 'string')\n name = item.get('column_name')\n split_flag = item.get('split')\n\n if name is not None and len(name) > 0:\n key = name\n\n if tool.equals_str(formater, 'int', True):\n return key, int(param)\n elif tool.equals_str(formater, 'float', True):\n return key, float(param)\n elif tool.equals_str(formater, 'string', True):\n return key, param\n elif tool.equals_str(formater, 'date', True):\n return key, time.strftime(\"%Y-%m-%d\", time.strptime(param, \"%Y/%m/%d\"))\n elif tool.equals_str(formater, 'list', True):\n if split_flag is not None:\n return key, param.split(split_flag)\n else:\n raise ValueError('请输入分隔符')\n\n\n# 获取所有的配置信息\ndef get_configs(item_confs):\n confs = []\n for item_conf in item_confs:\n item = {}\n try:\n item['index'] = (int(item_conf['index']))\n item['column_name'] = item_conf.get('column_name')\n item['column_type'] = item_conf.get('column_type', 'string')\n item['split'] = item_conf.get('split', None)\n confs.append(item)\n except ValueError:\n raise ValueError('index must be integer 索引必须为数字')\n return confs\n","sub_path":"parser_csv.py","file_name":"parser_csv.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"540157088","text":"import cv2\nimport numpy as np\nfrom time import sleep\nimport math\n# from tracking import ITrackingCore\n\nclass TwoPointLine:\n def __init__(self, cv_line):\n self.x1, self.y1, self.x2, self.y2 = cv_line\n\n def reverse(self):\n self.x1, self.y1, self.x2, self.y2 = self.x2, self.y2, self.x1, self.y1\n\n\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n @staticmethod\n def from_line(line):\n return Vector((line.x2 - line.x1), (line.y2 - line.y1))\n\n def dot(self, other_vec):\n return self.x * other_vec.x + self.y * other_vec.y\n\n def norm(self):\n return (self.x ** 2 + self.y ** 2) ** 0.5\n\n def angle(self, other_vec):\n if abs(self.dot(other_vec)/(self.norm()*other_vec.norm())) > 1:\n return 0\n return math.acos(self.dot(other_vec)/(self.norm()*other_vec.norm())) * 180 / math.pi\n\n def add_vector(self, other_vec):\n return Vector((self.x + other_vec.x), (self.y + other_vec.y))\n\nclass Final:\n def __init__(self,img):\n self.img = img\n b,g,_ = cv2.split(img)\n self.yellow_frame = np.array(g) - np.array(b)\n\n def __inital_filter(self,line):\n minimal_dy = 40\n maximal_dx = 20\n if abs(line.x2 - line.x1) < maximal_dx and abs(line.y2 - line.y1) > minimal_dy:\n return True\n return False\n\n def __sub_score_core(self, x):\n return 1/(x**6 + 1)\n\n def __sub_score(self, value, centre, error_allowed):\n return self.__sub_score_core((value - centre) / error_allowed * 0.5)\n\n def __secondary_filter(self,line1,line2):\n if line1.y2 < line1.y1:\n line1.reverse()\n if line2.y2 < line2.y1:\n line2.reverse()\n vec_L = Vector.from_line(line1)\n vec_R = Vector.from_line(line2)\n # to check the color between the two lines are yello\n left,right = min(line1.x1,line2.x2),max(line1.x1,line2.x2)\n up,down = min(line1.y1,line2.y2),max(line1.y1,line2.y2)\n mean = np.mean(self.yellow_frame[left:right, up:down])\n total_score = 1\n total_score *= self.__sub_score(vec_L.angle(vec_R), 0, 10)\n total_score *= self.__sub_score(abs(line1.x1 - line2.x1),3,10)\n total_score *= self.__sub_score(mean,160,50)\n return total_score\n\n def filtering(self):\n origin = img = cv2.resize(self.img,(640,360),0)\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n _,_,v = cv2.split(hsv)\n blurred = cv2.GaussianBlur(v,(3,31),0)\n bw = 255 - np.array(blurred)\n bw = bw // 60 * 255\n edges = cv2.Canny(bw, 100, 300, apertureSize=5)\n # edges = cv2.dilate(edges, np.ones((3, 3), np.uint8))\n minLineLength, maxLineGap = 50, 150\n lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 20, None, minLineLength, maxLineGap)\n vertical_lines = []\n scores= {}\n for line in lines:\n line1 = TwoPointLine(line[0])\n if self.__inital_filter(line1):\n vertical_lines.append(line1)\n for line1 in vertical_lines:\n for line2 in vertical_lines:\n scores[self.__secondary_filter(line1,line2)] = (line1,line2)\n keylist = list(scores.keys())\n keylist.sort()\n final_line1,final_line2 = scores[keylist[-1]]\n final_line = TwoPointLine((\n int((final_line1.x1 + final_line2.x1)/2),\n int((final_line1.x2 + final_line2.x2)/2),\n int((final_line1.y1 + final_line2.y1)/2),\n int((final_line1.y2 + final_line2.y2)/2) ))\n\n cv2.line(edges, (final_line.x1, final_line.y1), (final_line.x2, final_line.y2), (0, 255, 0), 3)\n return origin, edges\n\nif __name__ == \"__main__\":\n for i in range(6,12):\n directory = \"/home/luo/Pictures/\"+str(i)+\".png\"\n img = cv2.imread(directory)\n t = Final(img)\n origin, edges = t.filtering()\n cv2.imshow(\"orign\",origin)\n cv2.imshow(\"edges\",edges)\n cv2.waitKey(0)\n sleep(3)\n cv2.destroyAllWindows()","sub_path":"python/libraries/opencv_python/core_gate.py","file_name":"core_gate.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"589481117","text":"\"\"\"\nScript to play a text-based version of Quasar from Mass Effect\n\nThe rules are explained in the specifications below. For the optimal strategy to\nmaximize your winnings, see\n\n https://masseffect.fandom.com/wiki/Quasar\n\nAuthor: Charles Smith\nDate: 05 January 2021\n\"\"\"\nimport random\nimport introcs\n\n\n# Do not touch these first two functions. They are finished for you.\ndef prompt(prompt,valid):\n \"\"\"\n Returns the choice from a given prompt.\n\n This function asks the user a question, and waits for a response. It checks\n if the response is valid against a list of acceptable answers. If it is not\n valid, it asks the question again. Otherwise, it returns the player's answer.\n\n Parameter prompt: The question prompt to display to the player\n Precondition: prompt is a string\n\n Parameter valid: The valid reponses\n Precondition: valid is a tuple of strings\n \"\"\"\n # Ask the question for the first time.\n response = input(prompt)\n\n # Continue to ask while the response is not valid.\n while not (response in valid):\n print('Invalid option. Choose one of '+str(valid))\n print()\n response = input(prompt)\n\n return response\n\n\ndef payout(bet,score):\n \"\"\"\n Returns the winnings for a game of quasar.\n\n Winnings are payout-bet. So winning your bet (on a score of 17) has a net of 0.\n\n Parameter bet: the number of credits bet\n Precondition: bet is an int > 0\n\n Parameter score: the quasar score\n Precondition: score is an int >= 0\n \"\"\"\n if score == 20:\n return bet\n elif score == 19:\n return round(0.5*bet)\n elif score == 18:\n return round(0.25*bet)\n elif score == 17:\n return 0\n elif score == 16:\n return round(-0.5*bet)\n elif score == 15:\n return round(-0.75*bet)\n\n # Everything else is a total loss\n return -bet\n\n\n# Complete these functions\ndef get_bet(credits):\n \"\"\"\n Returns the number of credits bet by the user.\n\n This function asks the user to make a bet\n\n Make a bet:\n\n If bet is not an integer, it responds with the error message\n\n The bet must be an integer.\n\n If bet is 0 or less, it responds with the error message\n\n The bet must be a positive integer.\n\n Finally, if bet is more than credits, it responds with the error message\n\n You do not have enough credits for that bet.\n\n It continues to ask for a bet until the user gives a valid answer.\n\n Parameter credits: the number of credits available to bet\n Precondition: credits is an int > 0\n \"\"\"\n loop = True\n while loop:\n value = input('Make a bet: ')\n try:\n bet = int(value)\n if bet <=0:\n print('The bet must be a positive integer.')\n elif bet > credits:\n print('You do not have enough credits for that bet.')\n else:\n loop = False\n except:\n print('The bet must be an integer.')\n\n return int(bet)\n\n\ndef session(bet):\n \"\"\"\n Returns the payout after playing a single session of quasar.\n\n The game starts by randomly choosing a number 1-8 and then displaying\n\n Your score is X.\n\n (where X is the number chosen). It then prompts the user with the following options:\n\n Choose (a) 4-7, (b) 1-8, or (s)top:\n\n If the user chooses 'a' or 'b', it picks a random number, adds it to the score,\n and then displays the score again. If the user chooses 's' OR the new score is\n 20 or more, the session is over.\n\n Once the session ends, if the user goes over 20, the function prints out\n\n You busted.\n\n However, if the user hits 20 exactly, the function prints out\n\n Quasar!\n\n Nothing extra is printed if the user is below 20.\n\n It then prints out\n\n You won X credits.\n\n or\n You lost X credits.\n\n as appropriate, where X is the payout (if X is 0, this is considered a win). When\n the session is done, the function returns the payout.\n\n Parameter bet: the number of credits bet\n Precondition: bet is an int > 0\n \"\"\"\n question = ('Choose (a) 4-7, (b) 1-8, or (s)top: ')\n valid = ('a', 'b', 's')\n score = random.randint(1,8)\n result = 0\n loop = True\n while loop:\n if score > 20:\n print('You busted.')\n print('You lost ' + str(bet) + ' credits.')\n result = payout(bet, score)\n loop = False\n elif score == 20:\n print('Quasar!')\n print('You won ' + str(bet) + ' credits.')\n result = payout(bet, score)\n loop = False\n else:\n print('Your score is ' + str(score) + '.')\n choice = prompt(question, valid)\n if choice == str('a'):\n score += random.randint(4,7)\n elif choice == str('b'):\n score += random.randint(1,8)\n elif choice == str('s'):\n result = payout(bet, score)\n if result >= 0:\n print('You won ' + str(result) + ' credits.')\n else:\n print('You lost ' + str(result*-1) + ' credits.')\n loop = False\n return result\n\n\ndef play(credits):\n \"\"\"\n Plays Quasar until the player quits or is broke.\n\n The game starts by announcing\n\n You have X credits.\n\n where X is the number of credits. It gets a bet from the user and plays a session\n of Quasar. When done, it adds the payout to the score and repeats the message above.\n\n If the user reaches 0 credits, the game is over. Otherwise, it asks\n\n Do you want to (c)ontinue or (p)ayout?\n\n If the user chooses 'c', the process repeats (get a bet, play a session, etc.)\n\n When done, the game prints\n\n You leave with X credits.\n\n assuming X > 0. However, if X is 0 it instead prints\n\n You went broke.\n\n Parameter credits: the number of credits available to bet\n Precondition: credits is an int > 0\n \"\"\"\n question = ('Do you want to (c)ontinue or (p)ayout? ')\n valid = ('c', 'p')\n result = 0\n loop = True\n print('You have ' + str(credits) + ' credits.')\n while loop:\n #print('You have ' + str(credits) + ' credits.')\n bet = get_bet(credits)\n result = session(bet)\n #print('You have ' + str(credits) + ' credits.')\n credits = credits + result\n if credits == 0:\n print('You have ' + str(credits) + ' credits.')\n print('You went broke.')\n loop = False\n else:\n print('You have ' + str(credits) + ' credits.')\n choice = prompt(question, valid)\n if choice == str('c'):\n print('You have ' + str(credits) + ' credits.')\n elif choice == str('p'):\n #print('You have ' + str(credits) + ' credits.')\n print('You leave with ' +str(credits) + ' credits.')\n loop = False\n\n# Script Code\n# DO NOT MODIFY BELOW THIS LINE\nif __name__ == '__main__':\n play(1000)\n","sub_path":"Using While Loops/Exercise4/quasar.py","file_name":"quasar.py","file_ext":"py","file_size_in_byte":7043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63457825","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nfrom actorCritic import Agent\nfrom actorCritic import ActorCritic\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v0')\n gamma = 0.92\n alpha = 0.0005\n layer1Dims = 512\n layer2Dims = 128\n layer3Dims = 128\n agent1Layer = Agent(gamma = gamma, alpha = alpha, inputDims = 4, numActions = 2, layer1Dims = layer1Dims)\n agent2Layer = Agent(gamma = gamma, alpha = alpha, inputDims = 4, numActions = 2, layer1Dims = layer1Dims, layer2Dims = layer2Dims)\n agent3Layer = Agent(gamma = gamma, alpha = alpha, inputDims = 4, numActions = 2, layer1Dims = layer1Dims, layer2Dims = layer2Dims, layer3Dims = layer3Dims)\n\n numEpisodes = 500\n\n fname = f\"FinalActorCritic_{alpha}_{gamma}_{layer1Dims}_{layer2Dims}_{layer3Dims}\"\n figure_file = fname + '.png'\n\n #### TRAINING AGENT WITH 1 HIDDEN LAYER\n episodes1Layer = np.zeros((numEpisodes, 2))\n for i in range(numEpisodes):\n done = False\n observation = env.reset()\n score = 0\n while not done:\n action = agent1Layer.chooseAction(observation)\n newObservation, reward, done, info = env.step(action)\n score += reward\n agent1Layer.learn(observation, reward, newObservation, done)\n observation = newObservation\n episodes1Layer[i, 0] = i\n episodes1Layer[i, 1] = score\n print(f\"agent: 1 Layer - \\t episode: {i},\\t score {score}\")\n\n #### TRAINING AGENT WITH 2 HIDDEN LAYERS\n episodes2Layer = np.zeros((numEpisodes, 2))\n for i in range(numEpisodes):\n done = False\n observation = env.reset()\n score = 0\n while not done:\n action = agent2Layer.chooseAction(observation)\n newObservation, reward, done, info = env.step(action)\n score += reward\n agent2Layer.learn(observation, reward, newObservation, done)\n observation = newObservation\n episodes2Layer[i, 0] = i\n episodes2Layer[i, 1] = score\n print(f\"agent: 2 Layer - \\t episode: {i},\\t score {score}\")\n\n #### TRAINING AGENT WITH 3 HIDDEN LAYERS\n episodes3Layer = np.zeros((numEpisodes, 2))\n for i in range(numEpisodes):\n done = False\n observation = env.reset()\n score = 0\n while not done:\n action = agent3Layer.chooseAction(observation)\n newObservation, reward, done, info = env.step(action)\n score += reward\n agent3Layer.learn(observation, reward, newObservation, done)\n observation = newObservation\n episodes3Layer[i, 0] = i\n episodes3Layer[i, 1] = score\n print(f\"agent: 3 Layer - \\t episode: {i},\\t score {score}\")\n\n env.close()\n\n #### CREATE RUNNING AVERAGES SO THE VALUES DON'T HAVE TOOOOO MUCH VARIANCE\n runningAvgs = np.zeros((numEpisodes,3))\n for i in range(len(runningAvgs)):\n print(i)\n runningAvgs[i,0] = np.mean(episodes1Layer[max(0, i-50):(i+1),1])\n runningAvgs[i,1] = np.mean(episodes2Layer[max(0, i-50):(i+1),1])\n runningAvgs[i,2] = np.mean(episodes3Layer[max(0, i-50):(i+1),1])\n\n #### GRAPH THE LINES\n plt.plot(episodes1Layer[:,0], runningAvgs[:,0], label = \"1 Layer Score\", color = \"#0A284B\")\n plt.plot(episodes2Layer[:,0], runningAvgs[:,1], label = \"2 Layer Score\", color = \"#235FA4\")\n plt.plot(episodes3Layer[:,0], runningAvgs[:,2], label = \"3 Layer Score\", color = \"#A691AE\")\n plt.title(f\"Reward Growth over {numEpisodes} Episodes\")\n plt.xlabel(\"Number of Episodes\")\n plt.ylabel(\"Reward\")\n plt.legend()\n plt.savefig(figure_file)\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"294840700","text":"from django.conf import settings\n\nfrom . import Action\nfrom data.handlers import CheckHandler, PaymentHandler\n\nimport sys\nimport json\nimport requests\n\nclass PayFine(Action):\n # Tip: When an offence is created for a driver, we can create an\n # entry in actors. This way, we can leave Neo as the final route instead\n # of changing to Zed temporarily as we're doing right now.\n\n def request_document_number(self):\n # Use document_number to get offence\n # Set method and action in session\n self.session.set_method_and_action(sys._getframe().f_code.co_name, action=self.__class__.__name__)\n return Action.response('Please provide document number without dashes:')\n\n def request_MM_network(self):\n # We need to take care of situations where driver has more than one offence.\n # Let's get ONE offence at this time.\n # Looks like driver would have to specify the document type so we\n # can know how to format. For now, all we have is licence formatting.\n document_number = self.message.strip()\n\n # Catch error and display message\n check = CheckHandler.get(document_number)\n if check is None:\n self.session.set_success()\n return Action.release(\"Offence not found.\")\n\n # Make payment record here. Set is_complete flag after payment process is complete\n PaymentHandler.create(self.session.get_or_create()[0], check)\n\n return Action.response('{} {}. {} {} GHS. {}'.format(\n 'Offence:', check.offence.short_description,\n 'Fine is', str(check.offence.fine_amount),\n 'Please select mobile money network:\\n\\n1. MTN\\n2. Airtel\\n3. Tigo\\n4. Vodafone'))\n\n def request_MM_number(self):\n network = self.message.strip()\n NETWORKS = {'1': 'mtn-gh', '2': 'airtel-gh', '3': 'tigo-gh', '4': 'vodafone-gh'}\n PaymentHandler.set_network(self.session.get_or_create()[0], NETWORKS[network])\n return Action.response('Please enter mobile money number:')\n\n def send_request(self):\n \"\"\"\n data = '{\"CustomerName\": \"Dayo Osikoya\", \"CustomerMsisdn\": \"233542751610\", \n \"CustomerEmail\": \"alwaysdeone@gmail.com\", \"Channel\": \"mtn-gh\", \"Amount\": 0.3, \n \"PrimaryCallbackUrl\": \"https://zed-cloned-deone.c9users.io/mm_response\", \n \"Description\": \"T Shirt\", \"ClientReference\": \"\"}'\n \"\"\"\n\n number = self.message.strip()\n payment = PaymentHandler.set_number(self.session.get_or_create()[0], number)\n\n customer_name = payment._check.driver_name\n customer_number = '233' + payment.mm_number[1:]\n channel = payment.mm_network\n amount = payment._check.offence.fine_amount\n callback_url = settings.PAYMENT_URL + str(payment.pk)\n description = payment._check.offence.short_description\n\n data = {}\n data['CustomerName'] = customer_name\n data['CustomerMsisdn'] = customer_number\n data['Channel'] = channel\n data['Amount'] = amount\n data['PrimaryCallbackUrl'] = callback_url\n data['Description'] = description\n\n data = json.dumps(data)\n\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Basic a2VhZGZubG06bmtremNjeWQ=',\n }\n url = 'https://api.hubtel.com/v1/merchantaccount/merchants/HM2102180017/receive/mobilemoney'\n\n # Set session success just before sending MM request\n self.session.set_success()\n\n # Send request\n response = requests.post(url, headers=headers, data=data)\n return Action.release('Please input PIN and approve transaction on MM phone.')","sub_path":"core/actions/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67105452","text":"# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\n\npath='/home/sronen/aws/s3/'\nloc_in=path+'bigpart'\nloc_out=path+'combined'\n\nwith open(loc_out,'wb') as out:\n\n for e, line in enumerate( open(loc_in) ):\n fields=line.strip().split(\"\\t\")\n out.write(fields[0]+\"\\t\"+fields[1]+\"\\t\"+(\"%.3f\" % float(fields[2]))+\"\\n\")\n \n\n\n","sub_path":"regular.py","file_name":"regular.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"652540752","text":"# %%\nimport nltk\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nfrom nltk.corpus import stopwords, treebank\nfrom nltk.stem import PorterStemmer\n\nimport re\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics._classification import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score\n\nimport gensim.downloader as api\n\n# %%\nnltk.download('punkt')\n\n# %%\ndata = 'All work and no play makes jack a dull boy'\n\n# %%\nprint(word_tokenize(data))\n\n# %%\nprint(sent_tokenize(\n 'I was going home. It was surprise!'\n))\n\n# %%\n\"\"\"\nНаибольший вклад в смысл предложения вносят слова, которые\nввстречаются не слишком часто и не слишком редко\n\"\"\"\n\n# %%\nnltk.download('stopwords') # слова, которые встречаются очень часто\n\n# %%\nstopWords = set(stopwords.words('english'))\n\n# %%\nlen(stopWords)\n\n# %%\nprint(stopWords)\n\n# %%\nres = [word for word in word_tokenize(data) if word not in stopWords]\n\n# %%\n# Пропал токен 'no'\nprint(res)\n\n# %%\n# Выделение корня слова\nwords = ['game', 'gaming', 'gamed', 'games', 'compacted']\n\n# %%\n# stemming не смотрит на контекст\nps = PorterStemmer()\nlist(map(ps.stem, words))\n\n# %%\n# Лемматизация (есть зависимомть от контекста)\nraw = \"\"\"\nDENNIS: Listen, strange women lying in ponds distributing swords \nis no basis for a system of government. Supreme executive power \nderives from a mandate from the masses, not from some farcical \naquatic ceremony.\n\"\"\"\ntokens = word_tokenize(raw)\n\n# %%\nnltk.download('wordnet')\n\n# %%\nwnl = nltk.WordNetLemmatizer()\nprint(list(map(wnl.lemmatize, tokens)))\n\n# %%\n# Можно указать часть речи слова\nwnl.lemmatize('is', 'v')\n\n# %%\n# Расставление частей речи словам в предложении\nnltk.download('averaged_perceptron_tagger')\n\n# %%\nsentences = nltk.sent_tokenize(data)\nfor sent in sentences:\n print(nltk.pos_tag(nltk.word_tokenize(sent)))\n\n# %%\n# Парсинг\nnltk.download('treebank')\n\n# %%\nt = treebank.parsed_sents('wsj_0001.mrg')[0]\nt.draw()\n\n# %%\n# Регулярные выражения\n# С помощью регулярных выражений можно искать,\n# заменять и сентезировать строки по шаблонам\nword = 'supercalifragilisticexpialidocious'\nre.findall('[aeiou]|super', word)\n\n# %%\nre.findall('\\d+', 'There is some numbers: 49 and 432')\n\n# %%\nre.sub('[,\\.?!]', ' ', 'How, to? split. text!').split()\n\n# %%\nre.sub('[^A-z]', ' ', 'I 123 can 45 play 67 football').split()\n\n# %%\n# nlp = en_core_web_sm.load()\n\n# %%\n# doc = nlp(\n# u'Apple is looking at buying U.K. startup for 1$ billion'\n# )\n\n# %%\n# for ent in doc.ents:\n# print(ent.text, ent.start_char, ent.end_char, ent.label_)\n\n# %%\nnewsgroups_train = fetch_20newsgroups(subset='train')\n\n# %%\nlist(newsgroups_train.target_names)\n\n# %%\nprint(newsgroups_train.filenames.shape)\n\n# %%\nprint(newsgroups_train.target.shape)\n\n# %%\ncats = ['alt.atheism', 'sci.space']\nnewsgroups_train = fetch_20newsgroups(\n subset='train', categories=cats\n)\n\n# %%\nprint(newsgroups_train.filenames.shape)\n\n# %%\nprint(newsgroups_train.data[0])\n\n# %%\nprint(newsgroups_train.target[:10])\n\n# %%\n# Векторизация с помощью TF-IDF\ncategories = [\n 'alt.atheism', 'talk.religion.misc',\n 'comp.graphics', 'sci.space'\n]\nnewsgroups_train = fetch_20newsgroups(\n subset='train', categories=categories\n)\n\n# %%\nvectorizer = TfidfVectorizer()\nvectors = vectorizer.fit_transform(newsgroups_train.data)\nprint(vectors.shape)\n\n# %%\nvectorizer = TfidfVectorizer(lowercase=False)\nvectors = vectorizer.fit_transform(newsgroups_train.data)\nprint(vectors.shape)\n\n# %%\nvectorizer = TfidfVectorizer(min_df=0.2)\nvectors = vectorizer.fit_transform(newsgroups_train.data)\nprint(vectors.shape)\n\n# %%\nvectorizer = TfidfVectorizer(max_df=0.9)\nvectors = vectorizer.fit_transform(newsgroups_train.data)\nprint(vectors.shape)\n\n# %%\nvector = vectors.todense()[1]\n\n# %%\nprint(vector)\n\n# %%\nprint(vectors[vector != 0].shape)\n\n# %%\nstopWords = set(stopwords.words('english'))\nwnl = nltk.WordNetLemmatizer()\n\n\n# %%\ndef preproc1(text):\n return ' '.join([\n wnl.lemmatize(word) for word in word_tokenize(\n text.lower()\n ) if word not in stopWords\n ])\n\n\n# %%\nvectorizer = TfidfVectorizer(\n max_features=1500, preprocessor=preproc1\n)\nvectors = vectorizer.fit_transform(newsgroups_train.data)\nprint(vectors.shape)\n\n# %%\n# Косинусная мера между векторами\ntype(vectors) # т.к. в этих векторах очень много нулей,\n # по умолчанию они записываются как sparce matrix\n\n# %%\nprint(newsgroups_train.target[:10])\n\n# %%\nnp.unique(newsgroups_train.target)\n\n# %%\ndense_vectors = vectors.todense()\nprint(dense_vectors.shape)\n\n\n# %%\ndef cosine_sim(v1, v2):\n return np.array(v1 @ v2.T / norm(v1) / norm(v2))[0][0]\n\n\n# %%\ncosine_sim(dense_vectors[1], dense_vectors[1])\n\n# %%\ncosines = []\nfor i in range(10):\n cosines.append(cosine_sim(\n dense_vectors[0], dense_vectors[i]\n ))\n\n# %%\n# [1, 3, 2, 0, 2, 0, 2, 1, 2, 1]\nprint(cosines) # самым близким оказался вектор из той же категории\n\n# %%\nsvc = svm.SVC()\n\n# %%\nX_train, X_test, y_train, y_test = train_test_split(\n dense_vectors, newsgroups_train.target, test_size=0.2\n)\n\n# %%\nprint(y_train.shape, y_test.shape)\n\n# %%\nsvc.fit(X_train, y_train)\n\n# %%\naccuracy_score(y_test, svc.predict(X_test))\n\n# %%\nsgd = SGDClassifier()\nsgd.fit(X_train, y_train)\naccuracy_score(y_test, sgd.predict(X_test))\n\n# %%\n# Классификация на основе embeddings\ncategories = [\n 'alt.atheism', 'talk.religion.misc',\n 'comp.graphics', 'sci.space'\n]\nnewsgroups_train = fetch_20newsgroups(\n subset='train', categories=categories\n)\n\n# %%\n# embeddings = api.load('glove-twitter-25')\nembeddings = api.load('glove-twitter-100')\n\n# %%\nprint(embeddings['fly'])\n\n\n# %%\ndef vectorize_sum(comment):\n embedding_dim = embeddings.vectors.shape[1]\n features = np.zeros([embedding_dim], dtype='float32')\n\n words = preproc1(comment).split()\n for word in words:\n if word in embeddings:\n features += embeddings[f'{word}']\n\n return features\n\n\n# %%\npreproc1('I can swim').split()\n\n# %%\nvectorize_sum('I can swim')\n\n# %%\nX_wv = np.stack([\n vectorize_sum(text) for text in newsgroups_train.data\n])\nprint(X_wv.shape)\n\n# %%\nX_train_wv, X_test_wv, y_train, y_test = train_test_split(\n X_wv, newsgroups_train.target, test_size=0.2\n)\n\n# %%\nprint(X_train_wv.shape, X_test_wv.shape)\n\n# %%\nwv_model = LogisticRegression().fit(X_train_wv, y_train)\n\n# %%\naccuracy_score(y_test, wv_model.predict(X_test_wv))\n","sub_path":"simple_w2v_1/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584245671","text":"'''\nCopyright (C) 2015 CG Cookie\nhttp://cgcookie.com\nhello@cgcookie.com\n\nCreated by Jonathan Denning, Jonathan Williamson, and Patrick Moore\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n'''\n\nimport bpy\nimport bgl\nimport blf\nimport bmesh\nfrom bpy_extras.view3d_utils import location_3d_to_region_2d, region_2d_to_vector_3d\nfrom bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_origin_3d\nfrom mathutils import Vector, Matrix, Quaternion\nfrom mathutils.bvhtree import BVHTree\n\nimport math\nimport os\nimport copy\nfrom itertools import chain\n\nfrom ..lib import common_utilities\nfrom ..lib.common_utilities import get_source_object, get_target_object, setup_target_object\nfrom ..lib.common_utilities import bversion, selection_mouse, showErrorMessage\nfrom ..lib.common_utilities import point_inside_loop2d, get_object_length_scale, dprint, frange\nfrom ..lib.common_utilities import ray_cast_region2d_bvh, invert_matrix\nfrom ..lib.common_drawing_bmesh import BMeshRender\nfrom ..lib.classes.profiler.profiler import Profiler\nfrom ..lib.classes.sketchbrush.sketchbrush import SketchBrush\nfrom ..lib.classes.bmeshcache.bmeshcache import BMeshCache\nfrom .. import key_maps\nfrom ..cache import mesh_cache, polystrips_undo_cache, object_validation, is_object_valid, write_mesh_cache, clear_mesh_cache\n\nfrom .polystrips_datastructure import Polystrips, GVert\n\n\nclass Polystrips_UI:\n def initialize_ui(self):\n self.is_fullscreen = False\n self.was_fullscreen = False\n if 'brush_radius' not in dir(Polystrips_UI):\n Polystrips_UI.brush_radius = 15\n \n def start_ui(self, context):\n self.settings = common_utilities.get_settings()\n self.keymap = key_maps.rtflow_user_keymap_generate()\n \n self.stroke_smoothing = 0.75 # 0: no smoothing. 1: no change\n \n self.mode_pos = (0, 0)\n self.cur_pos = (0, 0)\n self.mode_radius = 0\n self.action_center = (0, 0)\n self.action_radius = 0\n self.is_navigating = False\n self.sketch_curpos = (0, 0)\n self.sketch = []\n \n self.act_gvert = None # active gvert (operated upon)\n self.act_gedge = None # active gedge\n self.act_gpatch = None # active gpatch\n \n self.sel_gverts = set() # all selected gverts\n self.sel_gedges = set() # all selected gedges\n \n self.hov_gvert = None # gvert under mouse (hover)\n \n self.tweak_data = None\n\n self.post_update = True\n\n if context.mode == 'OBJECT':\n\n # Debug level 2: time start\n check_time = Profiler().start()\n\n self.obj_orig = get_source_object()\n self.mx = self.obj_orig.matrix_world\n is_valid = is_object_valid(self.obj_orig)\n if is_valid:\n pass\n \n else:\n clear_mesh_cache()\n polystrips_undo_cache = []\n me = self.obj_orig.to_mesh(scene=context.scene, apply_modifiers=True, settings='PREVIEW')\n me.update()\n bme = bmesh.new()\n bme.from_mesh(me)\n bvh = BVHTree.FromBMesh(bme)\n write_mesh_cache(self.obj_orig, bme, bvh)\n \n # Debug level 2: time end\n check_time.done()\n\n #Create a new empty destination object for new retopo mesh\n nm_polystrips = self.obj_orig.name + \"_polystrips\"\n self.dest_bme = bmesh.new()\n\n self.dest_obj = setup_target_object( nm_polystrips, self.obj_orig, self.dest_bme )\n\n self.extension_geometry = []\n self.snap_eds = []\n self.snap_eds_vis = []\n self.hover_ed = None\n\n elif context.mode == 'EDIT_MESH':\n self.obj_orig = get_source_object()\n self.mx = self.obj_orig.matrix_world\n is_valid = is_object_valid(self.obj_orig)\n \n if is_valid:\n pass\n \n else:\n clear_mesh_cache()\n polystrips_undo_cache = []\n me = self.obj_orig.to_mesh(scene=context.scene, apply_modifiers=True, settings='PREVIEW')\n me.update()\n \n bme = bmesh.new()\n bme.from_mesh(me)\n bvh = BVHTree.FromBMesh(bme)\n write_mesh_cache(self.obj_orig, bme, bvh)\n \n self.dest_obj = get_target_object()\n self.dest_bme = bmesh.from_edit_mesh(context.object.data)\n self.snap_eds = [] #EXTEND\n \n #self.snap_eds = [ed for ed in self.dest_bme.edges if not ed.is_manifold]\n region, r3d = context.region, context.space_data.region_3d\n dest_mx = self.dest_obj.matrix_world\n rv3d = context.space_data.region_3d\n \n #TODO snap_eds_vis? #careful with the 2 matrices. One is the source object mx, the other is the target object mx\n self.snap_eds_vis = [False not in common_utilities.ray_cast_visible_bvh([dest_mx * ed.verts[0].co, dest_mx * ed.verts[1].co], mesh_cache['bvh'], self.mx, rv3d) for ed in self.snap_eds]\n self.hover_ed = None\n\n # Hide any existng geometry so as to draw nicely via BmeshRender\n bpy.ops.mesh.hide(unselected=True)\n bpy.ops.mesh.hide(unselected=False)\n\n #for bmv in self.dest_bme.verts:\n # bmv.co = self.mx * bmv.co\n \n self.dest_xray = self.dest_obj.show_x_ray\n \n self.src_bmc = BMeshCache(self.obj_orig)\n\n self.scale = self.obj_orig.scale[0]\n self.length_scale = get_object_length_scale(self.obj_orig)\n # World stroke radius\n self.stroke_radius = 0.01 * self.length_scale\n # Screen_stroke_radius\n self.screen_stroke_radius = 20 # TODO, hook to settings\n\n self.sketch_brush = SketchBrush(context,\n self.settings,\n 0, 0, #event.mouse_region_x, event.mouse_region_y,\n Polystrips_UI.brush_radius, # settings.quad_prev_radius,\n mesh_cache['bvh'], self.mx,\n self.obj_orig.dimensions.length)\n\n self.polystrips = Polystrips(context, self.obj_orig, self.dest_obj)\n self.polystrips.extension_geometry_from_bme(self.dest_bme)\n \n if not self.is_fullscreen:\n was_fullscreen = len(context.screen.areas)==1\n if not was_fullscreen and self.settings.distraction_free:\n bpy.ops.screen.screen_full_area(use_hide_panels=True)\n self.is_fullscreen = True\n\n # Draw the existing bmesh geometry in our own style\n #target_bmesh, target_mx, source_bvh, source_mx\n self.tar_bmeshrender = BMeshRender(self.dest_bme, self.dest_obj.matrix_world, mesh_cache['bvh'], self.mx)\n\n context.area.header_text_set('Polystrips')\n \n def end_ui(self, context):\n if not self.was_fullscreen and self.settings.distraction_free:\n bpy.ops.screen.screen_full_area(use_hide_panels=True)\n self.is_fullscreen = False\n \n Polystrips_UI.brush_radius = self.sketch_brush.pxl_rad\n \n def cleanup(self, context, cleantype=''):\n '''\n remove temporary object\n '''\n dprint('cleaning up!')\n if cleantype == 'commit':\n pass\n\n elif cleantype == 'cancel':\n if context.mode == 'OBJECT' and not self.settings.target_object:\n context.scene.objects.unlink(self.dest_obj)\n self.dest_obj.data.user_clear()\n bpy.data.meshes.remove(self.dest_obj.data)\n bpy.data.objects.remove(self.dest_obj)\n elif context.mode == 'EDIT_MESH':\n bpy.ops.mesh.reveal()\n\n ###############################\n # undo functions\n \n def create_undo_snapshot(self, action):\n '''\n unsure about all the _timers get deep copied\n and if sel_gedges and verts get copied as references\n or also duplicated, making them no longer valid.\n '''\n\n repeated_actions = {'count', 'zip count'}\n\n if action in repeated_actions and len(polystrips_undo_cache):\n if action == polystrips_undo_cache[-1]['action']:\n dprint('repeatable...dont take snapshot')\n return\n\n polystrips_undo_cache.append({\n 'action': action,\n 'polystrips data': copy.deepcopy(self.polystrips),\n 'act_gvert': self.polystrips.gverts.index(self.act_gvert) if self.act_gvert else None,\n 'act_gedge': self.polystrips.gedges.index(self.act_gedge) if self.act_gedge else None,\n 'act_gpatch': self.polystrips.gpatches.index(self.act_gpatch) if self.act_gpatch else None,\n 'sel_gverts': [self.polystrips.gverts.index(gv) for gv in self.sel_gverts],\n 'sel_gedges': [self.polystrips.gedges.index(ge) for ge in self.sel_gedges],\n })\n\n if len(polystrips_undo_cache) > self.settings.undo_depth:\n polystrips_undo_cache.pop(0)\n\n def undo_action(self):\n if len(polystrips_undo_cache) == 0:\n return\n data = polystrips_undo_cache.pop()\n self.polystrips = data['polystrips data']\n self.act_gvert = self.polystrips.gverts[data['act_gvert']] if data['act_gvert'] is not None else None\n self.act_gedge = self.polystrips.gedges[data['act_gedge']] if data['act_gedge'] is not None else None\n self.act_gpatch = self.polystrips.gpatches[data['act_gpatch']] if data['act_gpatch'] is not None else None\n self.sel_gverts = set(self.polystrips.gverts[i] for i in data['sel_gverts'])\n self.sel_gedges = set(self.polystrips.gedges[i] for i in data['sel_gedges'])\n self.hov_gvert = None\n \n\n \n ###########################\n # mesh creation\n \n def create_mesh(self, context):\n self.settings = common_utilities.get_settings()\n verts,quads,non_quads = self.polystrips.create_mesh(self.dest_bme)\n\n mx = self.dest_obj.matrix_world\n imx = invert_matrix(mx)\n \n if 'EDIT' in context.mode: #self.dest_bme and self.dest_obj: #EDIT MODE on Existing Mesh\n mx2 = self.obj_orig.matrix_world\n imx2 = invert_matrix(mx2)\n\n else:\n #bm = bmesh.new() #now new bmesh is created at the start\n mx2 = Matrix(mx) # Matrix.Identity(4)\n imx2 = invert_matrix(mx2)\n\n self.dest_obj.update_tag()\n self.dest_obj.show_all_edges = True\n self.dest_obj.show_wire = True\n\n self.dest_obj.select = True\n context.scene.objects.active = self.dest_obj\n\n common_utilities.default_target_object_to_active()\n\n # check for symmetry and then add a mirror if needed\n if self.settings.symmetry_plane == 'x':\n if not self.dest_obj.modifiers:\n self.dest_obj.modifiers.new(type='MIRROR', name='Polystrips-Symmetry')\n self.dest_obj.modifiers['Polystrips-Symmetry'].use_clip = True\n else:\n for mod in self.dest_obj.modifiers:\n if mod.type == 'MIRROR':\n print('Mirror found! Skipping')\n break\n else:\n print(\"Let's add a new mirror mod\")\n self.dest_obj.modifiers.new(type='MIRROR', name='Polystrips-Symmetry')\n self.dest_obj.modifiers['Polystrips-Symmetry'].use_clip = True\n\n container_bme = bmesh.new()\n \n bmverts = [container_bme.verts.new(v) for v in verts]\n container_bme.verts.index_update()\n for q in quads: \n try:\n container_bme.faces.new([bmverts[i] for i in q])\n except ValueError as e:\n dprint('ValueError: ' + str(e))\n pass\n for nq in non_quads:\n container_bme.faces.new([bmverts[i] for i in nq])\n \n container_bme.faces.index_update()\n\n if 'EDIT' in context.mode: #self.dest_bme and self.dest_obj:\n bpy.ops.object.mode_set(mode='OBJECT')\n container_bme.to_mesh(self.dest_obj.data)\n bpy.ops.object.mode_set(mode = 'EDIT')\n #bmesh.update_edit_mesh(self.dest_obj.data, tessface=False, destructive=True)\n else:\n container_bme.to_mesh(self.dest_obj.data)\n \n self.dest_obj.show_x_ray = self.dest_xray\n \n self.dest_bme.free()\n container_bme.free()\n\n ###########################\n # fill function\n\n def fill(self, eventd):\n \n # GVert active\n if self.act_gvert:\n showErrorMessage('Not supported at the moment.')\n return\n lges = self.act_gvert.get_gedges()\n if self.act_gvert.is_ljunction():\n lgepairs = [(lges[0],lges[1])]\n elif self.act_gvert.is_tjunction():\n lgepairs = [(lges[0],lges[1]), (lges[3],lges[0])]\n elif self.act_gvert.is_cross():\n lgepairs = [(lges[0],lges[1]), (lges[1],lges[2]), (lges[2],lges[3]), (lges[3],lges[0])]\n else:\n showErrorMessage('GVert must be a L-junction, T-junction, or Cross type to use simple fill')\n return\n \n # find gedge pair that is not a part of a gpatch\n lgepairs = [(ge0,ge1) for ge0,ge1 in lgepairs if not set(ge0.gpatches).intersection(set(ge1.gpatches))]\n if not lgepairs:\n showErrorMessage('Could not find two GEdges that are not already patched')\n return\n \n self.sel_gedges = set(lgepairs[0])\n self.act_gedge = next(iter(self.sel_gedges))\n self.act_gvert = None\n \n lgpattempt = self.polystrips.attempt_gpatch(self.sel_gedges)\n if type(lgpattempt) is str:\n showErrorMessage(lgpattempt)\n return\n lgp = lgpattempt\n \n self.act_gvert = None\n self.act_gedge = None\n self.sel_gedges.clear()\n self.sel_gverts.clear()\n self.act_gpatch = lgp[0]\n \n for gp in lgp:\n gp.update()\n #self.polystrips.update_visibility(eventd['r3d'])\n\n\n\n ###########################\n # hover functions\n\n def hover_geom(self,eventd):\n mx,my = eventd['mouse'] \n rgn = eventd['context'].region\n r3d = eventd['context'].space_data.region_3d\n \n self.help_box.hover(mx, my)\n \n self.hov_gvert = None\n _,hit = ray_cast_region2d_bvh(rgn, r3d, (mx,my), mesh_cache['bvh'], self.mx, self.settings)\n hit_pos,hit_norm,_ = hit\n for gv in chain(self.polystrips.extension_geometry, self.polystrips.gverts):\n if gv.is_inner(): continue\n c0 = location_3d_to_region_2d(rgn, r3d, gv.corner0)\n c1 = location_3d_to_region_2d(rgn, r3d, gv.corner1)\n c2 = location_3d_to_region_2d(rgn, r3d, gv.corner2)\n c3 = location_3d_to_region_2d(rgn, r3d, gv.corner3)\n inside = point_inside_loop2d([c0,c1,c2,c3],Vector((mx,my)))\n if hit_pos: inside &= gv.is_picked(hit_pos, hit_norm)\n if inside:\n self.hov_gvert = gv\n break\n print('found hover gv')\n \n\n ##############################\n # picking function\n\n def pick(self, eventd):\n mx,my = eventd['mouse']\n rgn = eventd['context'].region\n r3d = eventd['context'].space_data.region_3d\n _,hit = ray_cast_region2d_bvh(rgn, r3d, (mx,my), mesh_cache['bvh'], self.mx, self.settings)\n hit_pos,hit_norm,_ = hit\n if not hit_pos:\n # user did not click on the object\n if not eventd['shift']:\n # clear selection if shift is not held\n self.act_gvert,self.act_gedge,self.act_gvert = None,None,None\n self.sel_gedges.clear()\n self.sel_gverts.clear()\n return ''\n\n if self.act_gvert or self.act_gedge:\n # check if user is picking an inner control point\n if self.act_gedge and not self.act_gedge.zip_to_gedge and not self.act_gedge.is_fromMesh():\n lcpts = [self.act_gedge.gvert1,self.act_gedge.gvert2]\n elif self.act_gvert:\n sgv = self.act_gvert\n lge = self.act_gvert.get_gedges()\n lcpts = [ge.get_inner_gvert_at(sgv) for ge in lge if ge and not ge.zip_to_gedge and not ge.is_fromMesh()] + [sgv]\n else:\n lcpts = []\n\n for cpt in lcpts:\n if not cpt.is_picked(hit_pos,hit_norm): continue\n self.act_gedge = None\n self.sel_gedges.clear()\n self.act_gvert = cpt\n self.sel_gverts = set([cpt])\n self.act_gpatch = None\n return ''\n \n # select gvert?\n for gv in self.polystrips.gverts:\n if gv.is_unconnected(): continue\n if not gv.is_picked(hit_pos,hit_norm): continue\n self.act_gedge = None\n self.sel_gedges.clear()\n self.sel_gverts.clear()\n self.act_gvert = gv\n self.act_gpatch = None\n return ''\n\n # select gedge?\n for ge in self.polystrips.gedges:\n if not ge.is_picked(hit_pos,hit_norm): continue\n self.act_gvert = None\n self.act_gedge = ge\n if not eventd['shift']:\n self.sel_gedges.clear()\n self.sel_gedges.add(ge)\n self.sel_gverts.clear()\n self.act_gpatch = None\n \n for ge in self.sel_gedges:\n if ge == self.act_gedge: continue\n self.sel_gverts.add(ge.gvert0)\n self.sel_gverts.add(ge.gvert3)\n \n return ''\n \n # Select patch\n for gp in self.polystrips.gpatches:\n if not gp.is_picked(hit_pos,hit_norm): continue\n self.act_gvert = None\n self.act_gedge = None\n self.sel_gedges.clear()\n self.sel_gverts.clear()\n self.act_gpatch = gp\n return ''\n \n if not eventd['shift']:\n self.act_gedge,self.act_gvert,self.act_gpatch = None,None,None\n self.sel_gedges.clear()\n self.sel_gverts.clear()\n\n ###########################################################\n # functions to convert beziers and gpencils to polystrips\n\n def create_polystrips_from_bezier(self, ob_bezier):\n data = ob_bezier.data\n mx = ob_bezier.matrix_world\n\n def create_gvert(self, mx, co, radius):\n p0 = mx * co\n r0 = radius\n n0 = Vector((0,0,1))\n tx0 = Vector((1,0,0))\n ty0 = Vector((0,1,0))\n return GVert(self.obj_orig,self.dest_obj, p0,r0,n0,tx0,ty0)\n\n for spline in data.splines:\n pregv = None\n for bp0,bp1 in zip(spline.bezier_points[:-1],spline.bezier_points[1:]):\n gv0 = pregv if pregv else self.create_gvert(mx, bp0.co, 0.2)\n gv1 = self.create_gvert(mx, bp0.handle_right, 0.2)\n gv2 = self.create_gvert(mx, bp1.handle_left, 0.2)\n gv3 = self.create_gvert(mx, bp1.co, 0.2)\n\n ge0 = GEdge(self.obj_orig, self.dest_obj, gv0, gv1, gv2, gv3)\n ge0.recalc_igverts_approx()\n ge0.snap_igverts_to_object()\n\n if pregv:\n self.polystrips.gverts += [gv1,gv2,gv3]\n else:\n self.polystrips.gverts += [gv0,gv1,gv2,gv3]\n self.polystrips.gedges += [ge0]\n pregv = gv3\n\n def create_polystrips_from_greasepencil(self):\n Mx = self.obj_orig.matrix_world\n gp = self.obj_orig.grease_pencil\n gp_layers = gp.layers\n # for gpl in gp_layers: gpl.hide = True\n strokes = [[(p.co,p.pressure) for p in stroke.points] for layer in gp_layers for frame in layer.frames for stroke in frame.strokes]\n self.strokes_original = strokes\n\n #for stroke in strokes:\n # self.polystrips.insert_gedge_from_stroke(stroke)\n\n\n\n","sub_path":"op_polystrips/polystrips_ui.py","file_name":"polystrips_ui.py","file_ext":"py","file_size_in_byte":21156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"284198304","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.http import HttpResponse\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n url(r'^$', 'home.views.index'),\n url(r'^contact/$', 'home.views.contact'),\n # url(r'^termeni/$', 'home.views.termeni'),\n\n url(r'^speakers/$', 'home.views.speakers'),\n url(r'^tournaments/$', 'home.views.tournaments'),\n url(r'^tournaments/heroes/$', 'home.views.tournaments_heroes'),\n url(r'^tournaments/counter-strike/$', 'home.views.tournaments_cs'),\n url(r'^tournaments/dota2/$', 'home.views.tournaments_dota'),\n url(r'^tournaments/hearthstone/$', 'home.views.tournaments_hearthstone'),\n url(r'^program/$', 'home.views.program'),\n url(r'^partners/$', 'home.views.partners'),\n url(r'^press/$', 'home.views.press'),\n url(r'^tickets/$', 'home.views.tickets'),\n\n url(r'^join/$', 'home.views.join'),\n\n url(r'^api/', include('api.urls')),\n\n # url(r'^login/$', 'people.views.custom_login'),\n # url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'people/login.html'}),\n # url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),\n # url(r'^join/$', 'people.views.join'),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^robots\\.txt$', lambda r: HttpResponse(\"User-agent: *\\nAllow: /\", content_type=\"text/plain\")),\n)\n\nfrom django.conf import settings\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n )","sub_path":"dotfair/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268350229","text":"\"\"\"\"image\"\n\nRevision ID: 0d1cf3dec27f\nRevises: a96d51e1001f\nCreate Date: 2016-07-13 14:29:09.538218\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '0d1cf3dec27f'\ndown_revision = 'a96d51e1001f'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('images', sa.Column('description', sa.String(length=256), nullable=True))\n op.add_column('images', sa.Column('owner_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'images', 'users', ['owner_id'], ['id'])\n op.drop_column('images', 'name')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('images', sa.Column('name', mysql.VARCHAR(length=64), nullable=True))\n op.drop_constraint(None, 'images', type_='foreignkey')\n op.drop_column('images', 'owner_id')\n op.drop_column('images', 'description')\n ### end Alembic commands ###\n","sub_path":"src/web/migrations/versions/20160713_0d1cf3dec27f_image.py","file_name":"20160713_0d1cf3dec27f_image.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538948762","text":"import multiprocessing\nimport threading\nfrom datetime import datetime\n\nimport joblib\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split, KFold, StratifiedShuffleSplit, StratifiedKFold, cross_validate\nfrom sklearn import metrics\nfrom sklearn.datasets import load_iris\nimport pandas\nimport numpy\nimport File\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\n# Import to get all file names of Algorithms Folder\nimport os\nfrom os import listdir\nimport importlib\n\nfrom shutil import copyfile, copy2\n\n# Import all Algorithms\n# from Algorithms import *\n\n# Descobrir o numero de parametros de uma funcao\nfrom inspect import signature\nfrom inspect import getfullargspec\n\nfrom os.path import basename\nimport File\nimport LogFile\nimport ProjectLogFile\nimport sklearn.externals\n\nimport GUI\nimport sys\n\n# IMPORT para abrir imagens\nfrom PIL import Image\n\n\nclass Classify:\n def __init__(self, master):\n # self.filePath = \"D:\\\\IPL\\\\4ano\\\\Projeto Informatico\\\\Projeto-Informatico_20_05_2021\\\\Projeto-Informatico_20_05_2021\\\\Projeto-Informatico\\\\ProjetoBom\\\\DataFileProjetoBom.csv\"\n # self.filePath = \"D:\\\\IPL\\\\4ano\\\\Projeto Informatico\\\\Projeto-Informatico_20_05_2021\\\\Projeto-Informatico_20_05_2021\\\\Projeto-Informatico\\\\ProjetoIntenso\\\\DataFileProjetoIntenso.csv\"\n # FilePath of Modified File used in Data Preparation side\n # self.filePath = start.GUI.getFilePath(master)\n self.filePath = None\n self.data = [[]]\n self.rows = []\n self.target = []\n self.target_column_index = None\n self.target_column_name = None\n self.file = None\n # List of Chosen Algorithms\n self.listOfChosenAlgorithms = []\n self.log = None\n # Project Folder Path used in Data Preparation Side\n # self.projectFolderPath = f\"{start.GUI.getProjectFilePath(master)}\"\n self.projectFolderPath = None\n self.iris = load_iris()\n # self.openFile(self.filePath)\n # Variavel para garantir que os modulos sao importados apenas uma vez\n self.modulosJaImportados = 0\n # Dicionario dos algoritmos e instancias a importar => : \n self.dictInstanciasAlgoritmos = {}\n # Dicionario dos algoritmos e funcoes a importar\n self.dictAlgoritmos = {}\n # Variavel para garantir que o ficheiro só é aberto uma vez\n self.ficheiroFoiAberto = 0\n # Lista de algoritmos instanciados\n self.listOfInstantiatedAlgorithms = {}\n # Dicionario dos resultados obtidos de acordo com os algoritmos escolhidos\n self.dictResultados = {}\n # Caminho completo do modelo selecionado pelo utilizador\n self.fullpathSelectedModel = None\n # Variavel para a thread\n self.running_thread = None\n # Variavel para verificar se existe thread ativa ou nao\n self.isThreadUp = False\n # Booleano para controlar se o utilizar ja deu START e ainda está à espera que a classificação termine\n self.isClassifying = False\n\n # ---------------------------|\n # Visual of our Classify tab |\n # ---------------------------|\n\n # Para fazer com que os FRAMES aumentem caso haja espaço disponivel\n master.grid_columnconfigure(0, weight=1)\n master.grid_columnconfigure(1, weight=1)\n master.grid_columnconfigure(2, weight=8)\n master.grid_rowconfigure(0, weight=2)\n master.grid_rowconfigure(1, weight=3)\n master.grid_rowconfigure(2, weight=3)\n master.grid_rowconfigure(3, weight=3)\n master.grid_rowconfigure(4, weight=2)\n\n # Algorithms Frame\n algorithmsFrame = LabelFrame(master, text=\"Algorithms\", background=\"gray69\")\n algorithmsFrame.grid(row=0, column=0, columnspan=3, padx=3, pady=3, sticky=E + W + N + S)\n algorithmsFrame.grid_columnconfigure(0, weight=1)\n\n # Frame para escolher algoritmos\n self.chooseAddAlgorithmFrane = Frame(algorithmsFrame, background=\"gray69\")\n self.chooseAddAlgorithmFrane.grid(row=0, column=0, pady=3)\n\n # Show List of All Algorithms of the Project\n self.varOflistOfAlgorithms = StringVar(self.chooseAddAlgorithmFrane)\n\n # Get all algorithms of the project\n self.listOfAlgorithms = []\n\n # Get all files of directory \"Algorithms\"\n entries = os.listdir('Algorithms')\n for entry in entries:\n # Para retirar o __py__cache\n if entry.endswith(\".py\"):\n # Append all filenames to the listOfAlgorithms\n self.listOfAlgorithms.append(os.path.splitext(entry)[0])\n\n # Create variable to be the first selected function\n self.varOflistOfAlgorithms.set(self.listOfAlgorithms[0])\n\n # Create dropdown where all algorithms will be placed\n self.dropdownAlgorithms = OptionMenu(self.chooseAddAlgorithmFrane, self.varOflistOfAlgorithms,\n *self.listOfAlgorithms)\n # Create dropdown menu with line functions\n self.dropdownAlgorithms.config(font=('Helvetica', 8), state=\"disabled\")\n self.dropdownAlgorithms.grid(row=0, column=0, columnspan=3, pady=3, padx=3)\n self.dropdownAlgorithms.grid_rowconfigure(0, weight=1)\n self.dropdownAlgorithms.grid_columnconfigure(0, weight=1)\n\n # Button to choose algorithms\n self.chooseAlgorithm = Button(self.chooseAddAlgorithmFrane, text=\"Choose Algorithms\",\n command=self.chosenAlgorithms)\n self.chooseAlgorithm.config(state=\"disabled\")\n self.chooseAlgorithm.grid(row=0, column=3, padx=3, pady=3)\n\n # Frame para adicionar um novo algoritmo ao programa\n addAlgorithmFrame = LabelFrame(master, text=\"Add New Algorithm\", background=\"gray69\")\n addAlgorithmFrame.grid(row=0, column=3, pady=3, padx=3, sticky=E + W + N + S)\n addAlgorithmFrame.grid_columnconfigure(0, weight=1)\n addAlgorithmFrame.grid_rowconfigure(0, weight=1)\n\n # Button to Add Algorithms to the APP\n self.addAlgorithm = Button(addAlgorithmFrame, text=\"Add New Algorithm\", command=self.addAlgorithms)\n self.addAlgorithm.config(state=\"disabled\")\n self.addAlgorithm.grid(row=0, column=0, pady=20, padx=20, sticky=E + W + N + S)\n '''\n # Button to Add New Algorithm to the APP\n # Creating a photoimage object to use image\n photo = PhotoImage(file=\"..\\\\Files\\\\icon.png\")\n img_label = Label(algorithmsFrame, image=photo, width=100, height=100)\n img_label.grid(row=0, column=1)\n '''\n\n self.nameAlgorithmFrame = Frame(algorithmsFrame, background=\"gray69\")\n self.nameAlgorithmFrame.grid(row=1, column=0, columnspan=3, pady=3, padx=3, sticky=E + W + N + S)\n self.nameAlgorithmFrame.grid_rowconfigure(0, weight=1)\n self.nameAlgorithmFrame.grid_columnconfigure(0, weight=1)\n\n # Label for all chosen algorithms\n self.nameAlgorithm = Label(self.nameAlgorithmFrame)\n self.nameAlgorithm.grid(row=0, column=0, columnspan=3, padx=3, pady=3, sticky=E + W + N + S)\n self.nameAlgorithm.grid_columnconfigure(0, weight=1)\n\n # Clear list of chosen algorithms button\n self.clearListOfAlgorithmsButton = Button(self.nameAlgorithmFrame, text=\"Clear Chosen Algorithms\",\n command=self.cleanChosenAlgorithms)\n self.clearListOfAlgorithmsButton.config(state=\"disabled\")\n self.clearListOfAlgorithmsButton.grid(row=0, column=3, padx=3, pady=3, sticky=E + W + N + S)\n\n # Train/Test Frame\n trainTestFrame = LabelFrame(master, text=\"Train Test\", background=\"gray69\")\n trainTestFrame.grid(row=1, column=0, columnspan=2, pady=3, padx=3, sticky=E + W + N)\n\n # Tkinter string variable\n # able to store any string value\n self.v = StringVar(master, \"1\")\n\n # Dictionary to create multiple buttons\n valuesTrainTest = {\"Use Training Set\": \"1\",\n \"Cross Validation\": \"2\",\n \"Stratified K-Fold\": \"3\",\n \"Percentage Split\": \"4\",\n \"K-Fold\": \"5\"\n }\n\n # Variable to increment rows\n rowIndex = 0\n\n # Loop is used to create multiple Radiobuttons\n # rather than creating each button separately\n for (text, value) in valuesTrainTest.items():\n Radiobutton(trainTestFrame, text=text, variable=self.v,\n value=value, command=self.activateEntry, background=\"gray69\").grid(row=rowIndex, column=0,\n columnspan=2, pady=3, padx=3,\n sticky=W)\n rowIndex += 1\n\n # Entries for Train/Test\n self.crossValidationEntry = Entry(trainTestFrame)\n self.crossValidationEntry.grid(row=1, column=3, pady=3, padx=3, sticky=E)\n self.crossValidationEntry.configure(state=\"disabled\")\n\n self.stratifiedKFoldEntry = Entry(trainTestFrame)\n self.stratifiedKFoldEntry.grid(row=2, column=3, pady=3, padx=3, sticky=E)\n self.stratifiedKFoldEntry.configure(state=\"disabled\")\n\n self.percentageSplitEntry = Entry(trainTestFrame, state=\"disabled\")\n self.percentageSplitEntry.grid(row=3, column=3, pady=3, padx=3, sticky=E)\n self.percentageSplitEntry.configure(state=\"disabled\")\n\n self.trainValidationTestEntry = Entry(trainTestFrame, state=\"disabled\")\n self.trainValidationTestEntry.grid(row=4, column=3, pady=3, padx=3, sticky=E)\n self.trainValidationTestEntry.configure(state=\"disabled\")\n\n # Classification Algorithm Frame\n classificationFrame = LabelFrame(master, text=\"Classify\", background=\"gray69\")\n classificationFrame.grid(row=2, rowspan=2, column=0, columnspan=2, pady=3, padx=3, sticky=E + W + N + S)\n # classificationFrame.grid_rowconfigure(0, weight=1)\n classificationFrame.grid_columnconfigure(0, weight=1)\n classificationFrame.grid_columnconfigure(1, weight=1)\n classificationFrame.grid_rowconfigure(1, weight=1)\n\n # Start Classification\n self.btnStart = Button(classificationFrame, text=\"Start\", command=self.startWithThread)\n self.btnStart.config(state=\"disabled\")\n self.btnStart.grid(row=0, column=0, pady=3, padx=3, sticky=E + W + N + S)\n\n # Stop Classification\n self.btnStop = Button(classificationFrame, text=\"Stop\", command=self.stop)\n self.btnStop.config(state=\"disabled\")\n self.btnStop.grid(row=0, column=1, pady=3, padx=3, sticky=E + W + N + S)\n\n # Output Frames\n self.outputFrame = LabelFrame(master, text=\"Output\", background=\"gray69\")\n self.outputFrame.grid(row=1, rowspan=5, column=2, columnspan=2, pady=3, padx=3, sticky=E + W + N + S)\n\n # treinoLabel = Label(outputFrame, text=\"Ola\")\n # treinoLabel.grid()\n\n # Notebook for TABS\n self.notebook = ttk.Notebook(self.outputFrame)\n # Place All Tabs on Screen\n self.notebook.pack(expand=1, fill=\"both\")\n\n # Importar as instancias dos algoritmos da pasta Algorithms\n self.importAlgorithmsInstanceDynamically()\n\n # ListBox para todos as classifações feitas\n self.lb_resultados = Listbox(classificationFrame, selectmode=\"multiple\")\n self.lb_resultados.grid(row=1, column=0, columnspan=2, padx=3, pady=3, sticky=E + W + N + S)\n self.lb_resultados.rowconfigure(1, weight=1)\n self.lb_resultados.columnconfigure(0, weight=1)\n\n # Botão para carregar os algortimos treinados\n self.btn_loadMetrics = Button(classificationFrame, text=\"Load Metrics\", command=self.loadMetrics)\n self.btn_loadMetrics.grid(row=2, column=0, pady=3, padx=3, sticky=E + W + N + S)\n\n # Botão para remover os algortimos treinados\n self.btn_removeClassification = Button(classificationFrame, text=\"Remove Metrics\", command=self.deleteMetrics)\n self.btn_removeClassification.grid(row=2, column=1, pady=3, padx=3, sticky=E + W + N + S)\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # --------------------------------------------------- COMPARE RESULTS ------------------------------------------------------------------\n # --------------------------------------------------------------------------------------------------------------------------------------\n\n # Frame para comparar resultados\n self.compareResultsFrame = LabelFrame(master, text=\"Compare Results\", background=\"gray69\")\n self.compareResultsFrame.grid(row=5, column=0, pady=3, padx=3, sticky=E + W + N + S)\n self.compareResultsFrame.grid_columnconfigure(0, weight=1)\n self.compareResultsFrame.grid_rowconfigure(0, weight=1)\n\n # Botao para mostrar o resultado obtido\n self.btn_showResult = Button(self.compareResultsFrame, text=\"Compare\", command=self.compareResults)\n self.btn_showResult.config(state=\"disabled\")\n self.btn_showResult.grid(row=0, column=0, columnspan=2, padx=3, pady=3, sticky=E + W + N + S)\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # --------------------------------------------------- SHOW GRAPHICS --------------------------------------------------------------------\n # --------------------------------------------------------------------------------------------------------------------------------------\n\n # Frame para visualizar graficos\n self.showPlotsFrame = LabelFrame(master, text=\"Visualize Plots\", background=\"gray69\")\n self.showPlotsFrame.grid(row=5, column=1, pady=3, padx=3, sticky=E + W + N + S)\n self.showPlotsFrame.grid_rowconfigure(0, weight=1)\n self.showPlotsFrame.grid_columnconfigure(0, weight=1) # Fazer com que a dropdown cresca caso haja espaco\n self.showPlotsFrame.grid_columnconfigure(1, weight=1) # Fazer com que o botao cresca caso haja espaco\n\n # Lista com os graficos que podem ser visualizados\n self.listOfPlots = StringVar(self.showPlotsFrame)\n self.listOfPlots.set(\"Confusion Matrix\") # Default Value\n\n # Criar a dropdown para escolher o grafico que se quer visualizar\n self.menuOfPlots = OptionMenu(self.showPlotsFrame, self.listOfPlots, \"Confusion Matrix\", \"ROC Curve\",\n \"Precision Recall Curve\")\n self.menuOfPlots.grid(row=0, column=0, pady=3, padx=3, sticky=E + W + N + S)\n\n # Criar o botao para selecionar o grafico a visualizar\n self.showPlot = Button(self.showPlotsFrame, text=\"Show Plots\", command=self.showPlots)\n self.showPlot.grid(row=0, column=1, pady=3, padx=3, sticky=E + W + N + S)\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # --------------------------------------------------- LOGS -----------------------------------------------------------------------------\n # --------------------------------------------------------------------------------------------------------------------------------------\n # Log Frame\n logFrame = LabelFrame(master, text=\"Log\", background=\"gray69\")\n logFrame.grid(row=6, column=0, columnspan=4, padx=3, pady=3, sticky=E + W + N + S)\n logFrame.grid_rowconfigure(0, weight=1)\n # logFrame.grid_columnconfigure(0, weight=1)\n logFrame.grid_columnconfigure(1, weight=1)\n\n # Buttons For Log Frame\n self.btn_log = Button(logFrame, text=\"Log\", height=2, width=5, command=self.showLogCommands)\n self.btn_log.config(state=\"disabled\")\n self.btn_log.grid(row=0, column=0, padx=3, pady=3, sticky=E + W + N + S)\n\n self.log_last_line = StringVar()\n self.label_log = Label(logFrame, width=200, height=2, textvariable=self.log_last_line)\n self.label_log.config(state=\"disabled\")\n self.label_log.grid(row=0, column=1, columnspan=2, padx=3, pady=3)\n\n # Criar Thread para ativar todos os botoes apos o utilizador selecionar um ficheiro\n thread = threading.Thread(target=self.activateButtons, args=())\n thread.daemon = True\n thread.start()\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # --------------------------------------------------- MODELS ---------------------------------------------------------------------------\n # --------------------------------------------------------------------------------------------------------------------------------------\n # Frame para carregar modelos e classificar com o modelo selecionado\n self.modelsFrame = LabelFrame(master, text=\"Models\", background=\"gray69\")\n self.modelsFrame.grid(row=4, column=0, columnspan=2, pady=3, padx=3, sticky=E + W + N + S)\n self.modelsFrame.grid_rowconfigure(0, weight=1)\n self.modelsFrame.grid_rowconfigure(1, weight=1)\n self.modelsFrame.grid_columnconfigure(0, weight=1)\n self.modelsFrame.grid_columnconfigure(1, weight=1)\n\n # Botao para carregar modelos\n self.btn_loadModel = Button(self.modelsFrame, text=\"Load Model\", command=self.loadModel)\n self.btn_loadModel.grid(row=0, column=0, pady=3, padx=3, sticky=E + W + N + S)\n\n # Botao para classificar com base no algoritmo selecionado\n self.btn_classifyWithModel = Button(self.modelsFrame, text=\"Classify\", command=self.classifyWithExistentModel)\n self.btn_classifyWithModel.grid(row=0, column=1, pady=3, padx=3, sticky=E + W + N + S)\n\n # Label que mostra o modelo selecionado\n self.label_model = Label(self.modelsFrame)\n self.label_model.grid(row=1, column=0, columnspan=2, pady=3, padx=3, sticky=E + W + N + S)\n\n # --------------------------------------------------------------------------------------------------------------------------------------\n # ----------------------------------------------------- TABS ---------------------------------------------------------------------------\n # --------------------------------------------------------------------------------------------------------------------------------------\n\n # Frame for\n\n # -----------------------------------------------------------------------------------------------------------------------------\n # ---------------- FUNCTIONS\n # -----------------------------------------------------------------------------------------------------------------------------\n\n # Activate All Buttons\n def activateButtons(self):\n # Enquanto o nome do ficheiro for NONE, damos return\n # Quando o nome do ficheiro se alterar, activamos os botoes\n # -----------------------------------------------------------------------------------------------------------------------\n # Enquanto o nome do ficheiro for NONE, damos return\n while self.filePath == None:\n pass\n\n # Quando o nome do ficheiro se alterar, activamos os botoes\n self.dropdownAlgorithms.config(state=\"normal\")\n self.chooseAlgorithm.config(state=\"normal\")\n self.addAlgorithm.config(state=\"normal\")\n self.clearListOfAlgorithmsButton.config(state=\"normal\")\n self.btnStart.config(state=\"normal\")\n self.btnStop.config(state=\"normal\")\n self.btn_showResult.config(state=\"normal\")\n self.btn_log.config(state=\"normal\")\n self.label_log.config(state=\"normal\")\n\n # Activate Specific Entries for Classification\n def activateEntry(self):\n # Inactive all Entries\n if self.v.get() == \"1\":\n self.crossValidationEntry.configure(state='disabled')\n self.percentageSplitEntry.configure(state='disabled')\n self.stratifiedKFoldEntry.configure(state='disabled')\n self.trainValidationTestEntry.configure(state='disabled')\n\n # Activate CrossValidation Entry\n elif self.v.get() == \"2\":\n self.crossValidationEntry.configure(state='normal')\n self.percentageSplitEntry.configure(state='disabled')\n self.stratifiedKFoldEntry.configure(state='disabled')\n self.trainValidationTestEntry.configure(state='disabled')\n\n # Activate Stratified K-Fold Entry\n elif self.v.get() == \"3\":\n self.crossValidationEntry.configure(state='disabled')\n self.percentageSplitEntry.configure(state='disabled')\n self.stratifiedKFoldEntry.configure(state='normal')\n self.trainValidationTestEntry.configure(state='disabled')\n\n # Activate Percentage Split Entry\n elif self.v.get() == \"4\":\n self.crossValidationEntry.configure(state='disabled')\n self.percentageSplitEntry.configure(state='normal')\n self.stratifiedKFoldEntry.configure(state='disabled')\n self.trainValidationTestEntry.configure(state='disabled')\n\n # Activate Train-Validation-Test Entry\n else:\n self.crossValidationEntry.configure(state='disabled')\n self.percentageSplitEntry.configure(state='disabled')\n self.stratifiedKFoldEntry.configure(state='disabled')\n self.trainValidationTestEntry.configure(state='normal')\n\n def chosenAlgorithms(self):\n # Ver o algoritmo escolhido\n # Adicionar o algoritmo a uma lista com todos os algoritmos guardados\n self.listOfChosenAlgorithms.append(self.varOflistOfAlgorithms.get())\n\n # Guardar o nome do algoritmo\n self.varOflistOfAlgorithms.get()\n\n # Buscar o caminho da pasta dos algoritmos\n myPath = f\"Algorithms\"\n # PARA TODOS OS ALGORITMOS DA PASTA ALGORITMOS\n for algoritmo in listdir(myPath):\n algoritmoSemExtensao = os.path.splitext(algoritmo)[0]\n # Verificar se o algoritmo escolhido é igual a um dos algoritmos daquela diretoria\n if self.varOflistOfAlgorithms.get() == algoritmoSemExtensao:\n # Criar uma signature\n sig = signature(self.dictInstanciasAlgoritmos[self.varOflistOfAlgorithms.get()])\n # Descobrir o numero de parametros que a funcao precisa\n params = sig.parameters\n lig = getfullargspec(self.dictInstanciasAlgoritmos[self.varOflistOfAlgorithms.get()])\n # Caso o construtor do algoritmo escolhido tenha atributos\n if len(params) > 0:\n # Variavel para contar quantas entries vao ser criadas\n countEntries = 0\n\n # Criar uma window que passe os valores necessarios ao algoritmo escolhido\n self.window = Toplevel()\n self.window.resizable(False, False)\n\n # Criar uma lista de parametros vazia que vai guardar todos os parametros inseridos pelo utilizador\n self.listOfFunctionParameters = []\n\n # Linhas onde os inputs vao ficar\n rows = 0\n\n # Criar os inputs dinamicamente para os valores pedidos pelo algoritmo\n for parametro in params:\n if countEntries < len(params):\n # Criar label para dizer o que o user tem de selecionar\n label = Label(self.window, text=f\"{parametro}: \")\n label.grid(row=rows, column=0, pady=3, padx=3)\n\n # Criar o input\n entry = Entry(self.window)\n entry.grid(row=rows, column=1, pady=3, padx=3)\n\n # Aumentar a variavel que dita em que linha os inputs vao ser apresentados\n rows += 1\n self.listOfFunctionParameters.append(entry)\n countEntries += 1\n\n # Mostrar o parametro selecionado\n\n finish = Button(self.window, text=\"Finish\", command=lambda: self.instantiateAlgorithm(\n self.dictInstanciasAlgoritmos[self.varOflistOfAlgorithms.get()]))\n finish.grid(row=rows, column=0)\n\n else:\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[self.varOflistOfAlgorithms.get()]] = \\\n self.dictInstanciasAlgoritmos[self.varOflistOfAlgorithms.get()]\n\n '''\n if algoritmoSemExtensao == \"KNN\":\n # Criar uma window que passe os valores necessários ao algoritmo escolhido\n self.window = Toplevel()\n self.window.resizable(False, False)\n\n self.neigbhoors = Entry(self.window)\n self.neigbhoors.pack(side=LEFT)\n\n finish = Button(self.window, text=\"Finish\", command=lambda: self.instantiateAlgorithm(self.neigbhoors.get()))\n finish.pack(side=RIGHT)\n else:\n pass\n '''\n else:\n # Aceder ao algoritmo utilizado dinamicamente\n pass\n\n # Lista de algoritmos sem as plicas\n without_single_quotes = \"[{0}]\".format(', '.join(map(str, self.listOfChosenAlgorithms)))\n\n # Adicionar os algoritmos selecionados à label abaixo\n self.nameAlgorithm = Label(self.nameAlgorithmFrame, text=f\"{without_single_quotes[1:-1]}\")\n self.nameAlgorithm.grid(row=0, column=0, columnspan=3, padx=3, pady=3, sticky=E + W + N + S)\n self.nameAlgorithm.grid_columnconfigure(0, weight=1)\n\n def instantiateAlgorithm(self, algoritmo):\n for item in self.listOfFunctionParameters:\n # Criar uma instancia daquele algoritmo\n self.listOfInstantiatedAlgorithms[algoritmo] = algoritmo(item.get())\n self.window.destroy()\n\n def cleanChosenAlgorithms(self):\n # for algoritmos in self.listOfAlgorithms:\n self.listOfChosenAlgorithms = []\n\n # Limpar a label que tem a lista de algoritmos selecionados\n self.nameAlgorithm = Label(self.nameAlgorithmFrame, text=\"\")\n self.nameAlgorithm.grid(row=0, column=0, columnspan=3, padx=3, pady=3, sticky=E + W + N + S)\n self.nameAlgorithm.grid_columnconfigure(0, weight=1)\n\n # falta conseguir criar um array 2d com os valores das celulas da tabela, tirando a coluna target,\n # que tem de ficar a parte\n\n def openFile(self, filePath):\n targetColumn = []\n self.file = File.File()\n self.file.openDataFile(filePath)\n self.log = LogFile.LogFile(self.projectFolderPath)\n # column_name_line = self.file.getLine(0)\n for i in range(1, self.file.fileNumLines):\n # columns = self.file.getLine(i)\n line = self.file.getLine(i)\n targetColumn = numpy.append(targetColumn, line.pop(self.target_column_index))\n self.rows = numpy.append(self.rows, line)\n # self.data = numpy.append(self.data, self.file.getLine(i))\n self.rows = numpy.reshape(self.rows, (self.file.fileNumLines - 1, self.file.fileNumColumns - 1))\n self.target = targetColumn\n\n # Function which add tabs according to the number of chosen algorithms\n def addTabs(self, algorithm, configs, resultado):\n # Get current timestamp para meter no nome do ficheiro das metricas e para apresentar na listbox\n # now = datetime.now()\n current_timestamp = resultado[1] # now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n # separar timestamp\n data = current_timestamp.split(\"_\", 3)\n dataFinal = data[0] + \"-\" + data[1] + \"-\" + data[2]\n horario = data[3].replace(\"_\", \":\")\n timestamp = dataFinal + \" \" + horario\n\n current_timestamp_listbox = timestamp\n\n # Tabs For Results\n # Creation of the space where we all tabs will be placed\n self.tab = Frame(self.notebook)\n self.notebook.add(self.tab, text=f\"{current_timestamp_listbox} - {algorithm}\")\n\n # Add information to the TAB\n # Create Text Box\n results = Text(self.tab)\n results.pack(expand=1, fill=\"both\")\n\n\n # Criar um ficheiro que vai guardar todas as configurações relacionadas ao algoritmo utilizado\n config_results_file = open(f\"{self.projectFolderPath}\\\\Results\\\\Metrics_{current_timestamp}_{algorithm}.txt\",\n \"a\")\n\n # Linha para dizer que aqui vao ficar as configuracoes escolhidas pelo utilizador\n results.insert(INSERT, \"Configurações: \\n\")\n # Escrever no ficheiro que guarda as configurações\n config_results_file.write(\"Configurações: \\n\")\n\n # Lista de configuracoes a serem apresentadas na text box e escritas no ficheiro\n for config in configs.keys():\n # Escrever na textBox a config\n results.insert(INSERT, config + \": \")\n results.insert(INSERT, configs[config])\n results.insert(INSERT, \"\\n\")\n\n # Escrever no ficheiro a config\n config_results_file.write(config + \": \")\n config_results_file.write(str(configs[config]))\n config_results_file.write(\"\\n\")\n try:\n for parameter in resultado[2].keys():\n # Escrever linha na textBox\n results.insert(INSERT, parameter + \": \")\n results.insert(INSERT, resultado[2][parameter])\n results.insert(INSERT, \"\\n\")\n\n # Escrever linha no ficheiro\n config_results_file.write(parameter + \": \")\n config_results_file.write(str(resultado[2][parameter]))\n config_results_file.write(\"\\n\")\n except:\n pass\n\n # Deixar uma linha em Branco Entre as configuracoes e o resultado do algoritmo\n results.insert(INSERT, \"\\n\")\n # Deixar uma linha em Branco Entre as configuracoes e o resultado do algoritmo no ficheiro\n config_results_file.write(\"\\n\")\n\n # Linha para dizer que aqui vao ficar os resultados do algoritmo\n results.insert(INSERT, \"Métricas: \\n\")\n # Escrever no ficheiro a indicacao das metricas obtidas\n config_results_file.write(\"Métricas: \\n\")\n\n\n # Metricas e resultados a serem apresentados na text box e escritas no ficheiro\n for item in resultado[0].keys():\n # Escrever linha na textBox\n results.insert(INSERT, item + \": \")\n results.insert(INSERT, resultado[0][item])\n results.insert(INSERT, \"\\n\")\n\n # Escrever linha no ficheiro\n config_results_file.write(item + \": \")\n config_results_file.write(str(resultado[0][item]))\n config_results_file.write(\"\\n\")\n\n # Fechar o ficheiro que foi usado para guardar os resultados\n config_results_file.close()\n\n # Adicionar um key:value com os resultados\n self.dictResultados[f\"{current_timestamp_listbox} - {algorithm}\"] = config_results_file\n\n # Limpar a lista de resultados e reescrever a lista\n # Percorrer os resultados e inserir o nome da key na listbox\n self.lb_resultados.delete(0, END)\n for key_resultado in self.dictResultados.keys():\n # Inserir na listbox o value da key atual\n self.lb_resultados.insert(END, key_resultado)\n\n # Place All Tabs on Screen\n self.notebook.pack(expand=1, fill=\"both\")\n\n # Classificação terminada com sucesso\n self.log.logActions(\"Classification ended with success\")\n\n # Function which add algorithms to the project\n def addAlgorithms(self):\n # MessageBox which shows some alerts\n messagebox.showinfo(\"Add Algorithm Alerts\", \"\"\" Addition of algorithms needs to follow some rules: \n \\n\\t 1. Name of function needs to be equal to the name the algorithm (It's case sensitive!)\n \\n\\t 2. Code of the function needs to be similar to the code that will be presented next.\n \\n\\t 3. File added needs to be .py.\"\"\")\n\n # Window with a template of how definition of function should be\n window = Toplevel()\n window.resizable(True, True)\n\n # Label With Some Infos\n lbInfos = Label(window, text=\"Here is an example of one algorithm thats exists on program.\"\n \"Copy function above and make necessary changes to use your own algorithm.\")\n lbInfos.pack(pady=10, padx=10)\n\n # TextBox With Template of Function\n txtBox = Text(window, height=10, width=10)\n\n # Function Presented as Template\n function = \"\"\"import joblib\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn import metrics\n\n# IMPORT do messagebox\nfrom tkinter import messagebox\n\n# IMPORT do timestamp\nfrom datetime import datetime\n\n# IMPORT para apresentar graficos\n# É preciso instalar um package\nimport matplotlib.pyplot as plt\nimport scikitplot as skplt\n\n\n# IMPORT para a janela que vai mostrar o grafico\nfrom tkinter import *\nfrom tkinter import ttk\n\n# IMPORT para abrir imagens\nfrom PIL import Image\n\nclass LR:\n def __init__(self):\n pass\n\n def LR(self, projectFolderPath, X_train, X_test, y_train, y_test):\n #X_train, X_test, y_train, y_test = train_test_split(rows, target, test_size=test_size)\n lr = LogisticRegression()\n\n # TRY\n # Fazer o fit\n try:\n lr.fit(X_train, y_train)\n # Abrir uma mensagem de erro a dizer que nao foi possivel fazer o fit\n except:\n messagebox.showerror(\"Error\", \"Verify number of classes of target column\")\n return\n\n\n y_pred = lr.predict(X_test)\n\n # Get current timestamp\n now = datetime.now()\n current_timestamp = now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n # Create a file with model\n joblib.dump(lr, f'{projectFolderPath}\\\\Models\\\\LRmodel_{current_timestamp}.pkl')\n\n acc = metrics.accuracy_score(y_test, y_pred)\n f1 = metrics.f1_score(y_test, y_pred, average='macro')\n precision = metrics.precision_score(y_test, y_pred, average='macro')\n recall = metrics.recall_score(y_test, y_pred, average='macro')\n logLoss = metrics.log_loss(y_test, y_pred)\n rocAuc = metrics.roc_auc_score(y_test, y_pred, average='macro')\n confusionMatrix = metrics.confusion_matrix(y_test, y_pred)\n\n # Create dictionary with METRICS\n dictionary = {\n \"Accuracy Score\": \"{0:.2f}\".format(acc),\n \"F1 Score\": \"{0:.2f}\".format(f1),\n \"Precision\": \"{0:.2f}\".format(precision),\n \"Recall\": \"{0:.2f}\".format(recall),\n \"Log Loss\": \"{0:.2f}\".format(logLoss),\n \"Roc AUC\": \"{0:.2f}\".format(rocAuc),\n \"Confusion Matrix\": f\"\\n {confusionMatrix}\"\n }\n\n #-----------------------------------------------------------------------------------------------------------\n # --------------------------------------------- GRAPHS -----------------------------------------------------\n # ----------------------------------------------------------------------------------------------------------\n # Construir o grafico da metrica ROC Curve\n metrics.plot_roc_curve(lr, X_test, y_test)\n # Guardar o grafico\n plt.savefig(f'{projectFolderPath}\\\\Plots\\\\LRmodel_{current_timestamp}_ROCCurve.png')\n\n # Construir o grafico da CONFUSION MATRIX\n metrics.plot_confusion_matrix(lr, X_test, y_test)\n # Guardar o grafico\n plt.savefig(f'{projectFolderPath}\\\\Plots\\\\LRmodel_{current_timestamp}_ConfusionMatrix.png')\n\n # Construir o grafico da metrica PRECISION RECALL\n metrics.plot_precision_recall_curve(lr, X_test, y_test)\n plt.savefig(f'{projectFolderPath}\\\\Plots\\\\LRmodel_{current_timestamp}_PrecisionRecallCurve.png')\n\n\n return dictionary, current_timestamp\n # write in the log file\n # self.log.logActions(f\"Logistic Regression aplied\")\n\n \"\"\"\n\n # Show txtBox on Window\n txtBox.pack(expand=1, fill=\"both\", padx=10, pady=10)\n\n # Insert function on txtBox\n txtBox.insert(END, function)\n\n # Button to add algorithm\n btnAddAlgorithm = Button(window, text=\"Add Algorithm\", command=self.add)\n btnAddAlgorithm.pack(anchor=\"s\", side=RIGHT, pady=10, padx=10)\n\n def addFilePathProjectFolderPath(self, filePath, projectFolderPath):\n self.filePath = filePath\n self.projectFolderPath = projectFolderPath\n # Quando o projeto for criado ou reaberto\n # o self.log vai ficar com o log.txt\n self.log = LogFile.LogFile(self.projectFolderPath)\n\n # Funcao para receber a target column e o index\n def setTargetColumn(self, targetColumm, target_column_index):\n self.target_column_name = targetColumm\n self.target_column_index = target_column_index\n\n def startWithThread(self):\n if self.target_column_index == None:\n messagebox.showerror(\"Error\", \"Choose target column first\")\n return\n # Verificar se ja existe uma thread a correr\n if self.isClassifying == True:\n messagebox.showinfo(\"Classification in progress\", \"Classification in progress. \\nWait until classification process terminates to start a new classification!\")\n return\n else:\n # Variavel para controlar que a thread ja está a correr\n self.isClassifying = True\n\n # Variavel para depois matar a thread\n self.isThreadUp = True\n\n # Criar thread e iniciar a thread com a funcao START()\n self.running_thread = threading.Thread(target=self.start)\n self.running_thread.daemon = True\n self.running_thread.start()\n\n\n\n def start(self):\n if self.listOfChosenAlgorithms == []:\n messagebox.showerror(\"Error\", \"Choose at least one algorithm\")\n return\n\n # Verificar se o ficheiro ja foi aberto\n if self.ficheiroFoiAberto == 0:\n try:\n # Open file to start playing with algorithms\n self.openFile(self.filePath)\n except:\n messagebox.showerror(\"Error\", \"Something went wrong when trying to classification\")\n # Fechar o ficheiro\n self.file.close()\n\n # Retirar o self.rows e o self.target\n self.rows = []\n self.target = []\n\n self.isClassifying = False\n return\n\n # Alterar a variavel para mostrar que o ficheiro ja está aberto\n self.ficheiroFoiAberto = 1\n\n # Ver o dicionario com os algoritmos e respetivas funcoes\n\n # Classificar o dataset passando por todos os algoritmos selecionados pelo utilizador\n for alg in self.listOfChosenAlgorithms:\n # Chamar a funcao que lê o tipo de Train Test escolhido e corre a funcao correspondente aos algoritmos selecionados\n self.readTrainTestSplit(alg)\n\n # Verificar se o botao STOP foi clicado\n if self.isThreadUp == False:\n break\n\n # Fechar o ficheiro\n self.file.close()\n\n # Passar a variavel do self.ficheiroFoiAberto para 0\n self.ficheiroFoiAberto = 0\n\n # Retirar o self.rows e o self.target\n self.rows = []\n self.target = []\n\n # Booleano para dizer que a classificação terminou\n self.isClassifying = False\n\n\n # Apresentar mensagem a dizer que a classificação terminou\n # messagebox.showinfo(\"Classification Ended\", \"Classification of data with chosen algorithms has finished with success.\")\n\n # Parar a classificação\n def stop(self):\n # Passar a variavel que garante que a classificação está a decorrer\n # para False\n self.isThreadUp = False\n\n # Avisar que a classificação foi parada\n messagebox.showinfo(\"Classification Stopped\",\n \"Classification of data was stopped. You might wait until the last algorithm \"\n \"finishes the classification.\")\n\n #############################################################################\n ########################### SPLIT DATA #####################################\n #############################################################################\n def allData(self, algoritmo):\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.rows, self.target, random_state=0)\n\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"Use Training Set\",\n \"Coluna Target\": self.target_column_name # self.target\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: Cross Validation\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # Adicionar os resultados\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"Error\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n def splitDataKFold(self, n_splits, algoritmo):\n kf = KFold(n_splits=n_splits)\n for train_index, test_index in kf.split(self.rows):\n self.X_train, self.X_test, self.y_train, self.y_test = self.rows[train_index], self.rows[test_index], \\\n self.target[\n train_index], self.target[test_index]\n\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"K-Fold\",\n \"Numero de Splits\": n_splits,\n \"Coluna Target\": self.target_column_name # self.target\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: K-Fold\")\n self.log.logActions(f\"Number Of Splits Used: {n_splits}\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](algoritmo, self.projectFolderPath,self.X_train, self.X_test, self.y_train, self.y_test))\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n def splitDataStratifiedSplit(self, n_splits, algoritmo):\n ss = StratifiedShuffleSplit(n_splits=n_splits)\n for train_index, test_index in ss.split(self.rows, self.target):\n self.X_train, self.X_test, self.y_train, self.y_test = self.rows[train_index], self.rows[test_index], \\\n self.target[\n train_index], self.target[test_index]\n # self.trainKnn(X_train, X_test, y_train, y_test)\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"Stratified Split\",\n \"Numero de Splits\": n_splits,\n \"Coluna Target\": self.target_column_name # self.target\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: Stratified Split\")\n self.log.logActions(f\"Number Of Splits Used: {n_splits}\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # Adicionar resultados\n # self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](algoritmo, self.projectFolderPath, self.X_train, self.X_test, self.y_train, self.y_test))\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n def splitDataPercentage(self, test_size, algoritmo):\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.rows, self.target,\n test_size=test_size)\n # self.addTabs(\"KNN Percentage\", Algorithms.KNN.KNN.KNN(self.knnInstance, self.projectFolderPath, self.X_train, self.X_test,self.y_train, self.y_test))\n # self.trainKnn(X_train, X_test, y_train, y_test)\n\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"Percentage Split\",\n \"Test Size\": test_size,\n \"Coluna Target\": self.target_column_name\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: Percentage Split\")\n self.log.logActions(f\"Test Size Used: {test_size}\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # Chamada à funcao que vai adicionar os resultados da classificacao do algoritmo às tabs\n # Recebe varios parametros\n # 1º => Nome do algoritmo\n # 2º => Lista de configuracoes utilizadas\n # 3º => Algoritmo escolhido pelo utilizador\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n def splitDataStratifiedKFold(self, n_splits, algoritmo):\n skf = StratifiedKFold(n_splits=n_splits)\n for train_index, test_index in skf.split(self.rows, self.target):\n self.X_train, self.X_test, self.y_train, self.y_test = self.rows[train_index], self.rows[test_index], \\\n self.target[\n train_index], self.target[test_index]\n\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"Stratified K-Fold\",\n \"Numero de Splits\": n_splits,\n \"Coluna Target\": self.target_column_name # self.target\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: Stratified K-Fold\")\n self.log.logActions(f\"Number Of Splits Used: {n_splits}\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](algoritmo, self.projectFolderPath, self.X_train, self.X_test, self.y_train, self.y_test))\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # Cross Validation\n def crossValidation(self, test_size, algoritmo):\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.rows, self.target,\n test_size=test_size, random_state=0)\n\n dictionary = {\n \"Algoritmo Utilizado\": algoritmo,\n \"Método de Divisão de Dados Utilizado\": \"Cross Validation\",\n \"Test Size\": test_size,\n \"Coluna Target\": self.target_column_name # self.target\n }\n\n try:\n # Inserir linhas no ficheiro de log\n self.log.logActions(f\"Classification started!\")\n self.log.logActions(f\"Used Algorithm: {algoritmo}\")\n self.log.logActions(f\"Division Method Used: Cross Validation\")\n self.log.logActions(f\"Test Size Used: {test_size}\")\n self.log.logActions(f\"Column Target Used: {self.target_column_name}\")\n self.log.logActions(\"Classification in progress...\")\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n self.addTabs(f\"{algoritmo}\", dictionary, self.dictAlgoritmos[algoritmo](\n self.listOfInstantiatedAlgorithms[self.dictInstanciasAlgoritmos[algoritmo]], self.projectFolderPath,\n self.X_train, self.X_test, self.y_train, self.y_test))\n\n\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong with classification\")\n self.log.logActions(\"Error occurred during classification. Classification terminated.\")\n # Apresentar a ultima linha do log.txt na label\n self.showLastCommand()\n\n # Activate Specific Entries for Classification\n def readTrainTestSplit(self, algoritmo):\n # Classificar o dataset com todos os dados\n if self.v.get() == \"1\":\n try:\n self.allData(algoritmo)\n except:\n messagebox.showerror(\"ERROR\", \"Something went wrong!\")\n\n # Activate CrossValidation Entry\n elif self.v.get() == \"2\":\n try:\n test_size = float(self.crossValidationEntry.get())\n self.crossValidation(test_size, algoritmo)\n except:\n messagebox.showerror(\"ERROR\", \"Specify how you want to divide data. Use percentual values\")\n\n # Activate Stratified K-Fold Entry\n elif self.v.get() == \"3\":\n try:\n split = int(self.stratifiedKFoldEntry.get())\n self.splitDataStratifiedKFold(split, algoritmo)\n except:\n messagebox.showerror(\"ERROR\", \"Specify how you want to divide data. Use integer values\")\n\n # Activate Percentage Split Entry\n elif self.v.get() == \"4\":\n try:\n testSize = float(self.percentageSplitEntry.get())\n self.splitDataPercentage(testSize, algoritmo)\n except:\n messagebox.showerror(\"ERROR\", \"Specify how you want to divide data. Use percentual values\")\n\n # Activate Train-Validation-Test Entry\n else:\n try:\n # Para ja está a utilizar o Data K Fold\n n_splits = int(self.trainValidationTestEntry.get())\n self.splitDataKFold(n_splits, algoritmo)\n except:\n messagebox.showerror(\"ERROR\", \"Specify how you want to divide data. Use integer values\")\n\n def importAlgorithmsInstanceDynamically(self):\n # Importar os modulos apenas na primeira vez que clicamos no botao START\n if self.modulosJaImportados == 0:\n # Passar a variavel que garante que os modulos ja foram importados para 1 para que nao voltem a ser importados\n self.modulosJaImportados = 1\n # Importar todos os modulos e funcoes existentes na pasta Algorithms\n # Lista de todos os algoritmos para dar import\n listOfAlgorithmsToImport = []\n\n # Dicionario dos algoritmos e funcoes a importar => : \n # self.dictAlgoritmos = {}\n\n # Caminho da pasta onde estao todos os algoritmos\n myPath = f\"Algorithms\"\n\n # Limpar cache por causa dos imports dinamicos\n importlib.invalidate_caches()\n\n # PARA TODOS OS ALGORITMOS DA PASTA ALGORITMOS\n for algoritmo in listdir(myPath):\n # Caso o ficheiro encontrado na pasta dos Algorithms acabe em '.py'\n if algoritmo.endswith(\".py\"):\n # Retirar o '.py' do ficheiro do algoritmo\n algoritmoSemExtensao = os.path.splitext(algoritmo)[0]\n # Adicionar o algoritmo à listOfAlgorithmsToImport\n listOfAlgorithmsToImport.append(algoritmoSemExtensao)\n # Importar o modulo correspondente ao algoritmo encontrado\n module = importlib.import_module(\"Algorithms.\" + str(algoritmoSemExtensao))\n # Adicionar ao dicionario o nome do algoritmo e a instancia correspondente a esse algoritmo\n # 'algoritmoSemExtensao' : Algorithms.algoritmoSemExtensao.algoritmoSemExtensao\n self.dictInstanciasAlgoritmos[algoritmoSemExtensao] = getattr(module, algoritmoSemExtensao)\n # Adicionar ao dicionario o nome do algoritmo e a funcao correspondente a esse algoritmo\n funcao = getattr(module, algoritmoSemExtensao)\n self.dictAlgoritmos[algoritmoSemExtensao] = getattr(funcao, algoritmoSemExtensao)\n\n #############################################################################\n\n # Adicionar um novo algoritmo ao projeto\n def add(self):\n # Open FileDialog to choose algorithm to add\n addAlgorithmPY = filedialog.askopenfilename(initialdir=\"Documentos\", title=\"Open File\",\n filetypes=((\"PY Files\", \"*.py\"),))\n\n # Adicionar um novo algoritmo ao projeto\n dir_name = 'Algorithms'\n\n # Nome do ficheiro adicionado sem o caminho completo\n filename = os.path.basename(addAlgorithmPY)\n\n for algoritmoNaPasta in listdir(dir_name):\n if algoritmoNaPasta == filename:\n messagebox.showerror(\"Invalid Algorithm\", \"There is a algorithm file with same name on program\")\n return\n\n # Copiar o novo algoritmo para a pasta dos Algorithms\n copy2(addAlgorithmPY, dir_name)\n\n # Dar Import do novo algoritmo inserido\n # Caso o ficheiro encontrado na pasta dos Algorithms acabe em '.py'\n if addAlgorithmPY.endswith(\".py\"):\n # Retirar o '.py' do ficheiro do algoritmo\n algoritmoSemExtensao = os.path.splitext(filename)[0]\n # Importar o modulo correspondente ao algoritmo encontrado\n module = importlib.import_module(\"Algorithms.\" + str(algoritmoSemExtensao))\n # Adicionar ao dicionario o nome do algoritmo e a instancia correspondente a esse algoritmo\n # 'algoritmoSemExtensao' : Algorithms.algoritmoSemExtensao.algoritmoSemExtensao\n self.dictInstanciasAlgoritmos[algoritmoSemExtensao] = getattr(module, algoritmoSemExtensao)\n # Adicionar ao dicionario o nome do algoritmo e a funcao correspondente a esse algoritmo\n funcao = getattr(module, algoritmoSemExtensao)\n self.dictAlgoritmos[algoritmoSemExtensao] = getattr(funcao, algoritmoSemExtensao)\n\n # Reescrever a listBox dos algoritmos\n self.rewriteAlgorithmListBox()\n\n # Dizer que o algoritmo foi adicionado com sucesso\n messagebox.showinfo(\"Algorithm Added With Success\",\n f\"Algorithm {algoritmoSemExtensao} added to the program with success\")\n\n # Adicionar nova linha ao ficheiro de log\n # a dizer que o algoritmo foi inserio\n self.log.logActions(f\"Algorithm {algoritmoSemExtensao} added to the program\")\n\n # Reescrever a label do log com a nova linha de log\n self.showLastCommand()\n\n # Reescrever a lista de Algoritmos que se pode selecionar apos a insercao de um novo algoritmo\n def rewriteAlgorithmListBox(self):\n # Get all algorithms of the project\n self.listOfAlgorithms = []\n\n # Get all files of directory \"Algorithms\"\n entries = os.listdir('Algorithms')\n for entry in entries:\n # Para retirar o __py__cache\n if entry.endswith(\".py\"):\n # Append all filenames to the listOfAlgorithms\n self.listOfAlgorithms.append(os.path.splitext(entry)[0])\n\n # Create variable to be the first selected function\n self.varOflistOfAlgorithms.set(self.listOfAlgorithms[0])\n\n # Create dropdown where all algorithms will be placed\n self.dropdownAlgorithms = OptionMenu(self.chooseAddAlgorithmFrane, self.varOflistOfAlgorithms,\n *self.listOfAlgorithms)\n # Create dropdown menu with line functions\n self.dropdownAlgorithms.config(font=('Helvetica', 8), state=\"normal\")\n self.dropdownAlgorithms.grid(row=0, column=0, columnspan=2, pady=3, padx=3)\n self.dropdownAlgorithms.grid_rowconfigure(0, weight=1)\n self.dropdownAlgorithms.grid_columnconfigure(0, weight=1)\n\n\n # Abrir uma janela com os resultados gravados\n def compareResults(self):\n # Verify if any algorithm was selected\n if not self.lb_resultados.curselection():\n messagebox.showerror(\"Error\", \"Please select at least 2 classifications from the list\")\n return\n else:\n pass\n\n # Create new Window\n top = Toplevel()\n top.resizable(True, True)\n\n # Create A Frame\n tableFrame = LabelFrame(top, text=\"Table\", background=\"gray69\")\n\n # Destroy everything inside of Frame\n for widget in tableFrame.winfo_children():\n widget.destroy()\n\n # Make frame appear in window\n tableFrame.pack(expand=1, fill=\"both\")\n\n tv1 = ttk.Treeview(tableFrame)\n tv1.place(relheight=1, relwidth=1) # set the height and width of the widget to 100% of its container (frame1).\n\n treescrolly = Scrollbar(tableFrame, orient=\"vertical\",\n command=tv1.yview) # command means update the yaxis view of the widget\n treescrollx = Scrollbar(tableFrame, orient=\"horizontal\",\n command=tv1.xview) # command means update the xaxis view of the widget\n tv1.configure(xscrollcommand=treescrollx.set,\n yscrollcommand=treescrolly.set) # assign the scrollbars to the Treeview Widget\n treescrollx.pack(side=\"bottom\", fill=\"x\") # make the scrollbar fill the x axis of the Treeview widget\n treescrolly.pack(side=\"right\", fill=\"y\") # make the scrollbar fill the y axis of the Treeview widget\n\n lista_colunas = []\n lista_colunas.append(\"Métricas/Algoritmos\")\n for item in self.lb_resultados.curselection():\n lista_colunas.append(self.lb_resultados.get(item))\n\n tv1[\"column\"] = list(lista_colunas)\n tv1[\"show\"] = \"headings\"\n for column in tv1[\"columns\"]:\n tv1.column(column, anchor=\"center\")\n tv1.heading(column, text=column) # let the column heading = column name\n\n # Criar uma lista com os valores todos de uma linha\n metrica_acc = [\"Accuracy-Score\"]\n metrica_f1 = [\"F1-Score\"]\n metrica_precision = [\"Precision\"]\n metrica_recall = [\"Recall\"]\n metrica_log = [\"Log-Loss\"]\n metric_auc = [\"ROC-AUC\"]\n lista_metricas = []\n lista_metricas.append(metrica_acc)\n lista_metricas.append(metrica_f1)\n lista_metricas.append(metrica_precision)\n lista_metricas.append(metrica_recall)\n lista_metricas.append(metrica_log)\n lista_metricas.append(metric_auc)\n\n # Percorrer todos os items selecionados na listBox\n for item in self.lb_resultados.curselection():\n # Buscar o resultado selecionado da lista\n selectedResult = self.lb_resultados.get(item)\n # Fazer a divisao do resultado escolhido para conseguir ir buscar o ficheiro certo\n timestamp_data = selectedResult.split(\"-\")\n timestamp_horario = selectedResult.split(\":\")\n # Descobrir o dia\n day = timestamp_data[0]\n # Descobrir o mes\n month = timestamp_data[1]\n # Descobrir o ano\n year = timestamp_data[2]\n year = year.split(\" \")\n year = year[0]\n # Descobrir a hora\n hour = timestamp_horario[0]\n hour = hour.split(\" \")\n hour = hour[1]\n # Descobrir o minuto\n minute = timestamp_horario[1]\n # Separar os segundos do algoritmo\n second = timestamp_horario[2]\n second = second.split(\" - \")\n # Descobrir o algoritmo usado\n algoritmo = second[1]\n # Descobrir o segundo\n second = second[0]\n # Obter a data correta e conforme o ficheiro guardado\n selectedResult = f\"{day}_{month}_{year}_{hour}_{minute}_{second}_{algoritmo}\"\n # Abrir o ficheiro relacionado com o resultado obtido para leitura\n f = open(f\"{self.projectFolderPath}\\\\Results\\\\Metrics_{selectedResult}.txt\", \"r\")\n\n # Lista com todas as linhas\n all_lines = f.readlines()\n\n line_number = 0\n for line in all_lines:\n if line == '\\n':\n line_sem_valor = line_number\n line_number += 1\n else:\n line_number += 1\n\n # Configurações para mudar a cor de fundo das linhas da treeview\n for line in range(line_sem_valor + 2, len(all_lines)-3):\n result = all_lines[line].split(\": \")\n lista_metricas[line - (line_sem_valor + 2)].append(result[1])\n\n f.close()\n\n for line in range(len(lista_metricas)):\n # Inserir a linha completa na tabela\n tv1.insert('','end',values=lista_metricas[line]) # inserts each list into the treeview. For parameters see https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.insert\n\n # Show PLOTS\n def showPlots(self):\n # Garantir que está um algoritmo classificado da listbox selecionado\n # Buscar e guardar o grafico selecionado pelo utilizador\n # Buscar e guardar o algoritmo classificado presente na listbox\n # Procurar pelo grafico do algoritmo selecionado na pasta Plots\n # Apresentar o grafico encontrado numa nova janela\n # -----------------------------------------------------------------------\n # Garantir que está um algoritmo classificado da listbox selecionado\n selection = self.lb_resultados.curselection()\n if not selection:\n messagebox.showerror(\"Error\", \"Please select one of the classified algorithms of the list on the left side\")\n return\n else:\n # Buscar e guardar o grafico selecionado pelo utilizador\n selectedPlot = self.listOfPlots.get()\n # Remover os espaços que vêm da dropdown\n selectedPlot = selectedPlot.replace(\" \", \"\")\n\n # Buscar e guardar o algoritmo classificado presente na listbox\n for item in selection:\n algorithm = self.lb_resultados.get(item)\n\n # Separar o resultado do item em várias partes para conseguir aceder ao grafico que se pretende\n timestamp = algorithm.split(\" \")\n algorithm = timestamp[3]\n # Separar a data\n timestamp_data = timestamp[0]\n timestamp_data = timestamp_data.split(\"-\")\n # Descobrir o dia\n day = timestamp_data[0]\n # Descobrir o mes\n month = timestamp_data[1]\n # Descobrir o ano\n year = timestamp_data[2]\n\n # Separar o horario\n timestamp_horario = timestamp[1]\n timestamp_horario = timestamp_horario.split(\":\")\n # Descobrir a hora\n hour = timestamp_horario[0]\n # Descobrir o minuto\n minute = timestamp_horario[1]\n # Descobrir o segundo\n second = timestamp_horario[2]\n\n # Timestamp completo do ficheio\n result = f\"{day}_{month}_{year}_{hour}_{minute}_{second}\"\n\n # Abrir o ficheiro com o grafico correspondente ao algoritmo escolhido\n plot_file = Image.open(f\"{self.projectFolderPath}\\\\Plots\\\\{algorithm}model_{result}_{selectedPlot}.png\")\n plot_file.show()\n\n # Show log commands\n def showLogCommands(self):\n # Abrir o ficheiro log.txt para leitura\n # Criar uma nova janela\n # Colocar uma text box na nova janela\n # Copiar o texto do ficheiro log.txt para essa text box\n # Passar o estado da text box para disabled, de modo a que nao seja possivel escrever ou apagar\n # Fechar o ficheiro log.txt\n # ---------------------------------------------------------------------------------------------\n # Abrir o ficheiro log.txt para leitura\n logfile = open(f\"{self.projectFolderPath}\\\\log.txt\", \"r\")\n\n # Criar uma nova janela\n window = Toplevel()\n window.resizable(True, True)\n\n # Colocar uma text box na nova janela\n textbox = Text(window)\n textbox.pack(fill=BOTH, expand=1, pady=10, padx=10)\n\n # Copiar o texto do ficheiro log.txt para essa text box\n textbox.insert(INSERT, logfile.read())\n\n # Passar o estado da text box para disabled\n textbox.config(state=DISABLED)\n\n # Fechar o ficheiro log.txt\n logfile.close()\n\n # Show on label the last log command\n def showLastCommand(self):\n # Abrir o ficheiro log.txt para leitura\n # Ler a ultima linha do ficheiro log.txt\n # Colocar a ultima linha na label ao lado do botao de LOG\n # Fechar o ficheiro log.txt\n # -------------------------------------------------------------------------------\n # Abrir o ficheiro log.txt para leitura\n logfile = open(f\"{self.projectFolderPath}\\\\log.txt\", \"r\")\n\n # Ler a ultima linha do ficheiro log.txt\n lines = logfile.read().splitlines()\n last_line = lines[-1]\n\n # Colocar a ultima linha na label ao lado do botao de LOG\n self.log_last_line.set(last_line)\n\n # Fechar o ficheiro log.txt\n logfile.close()\n\n # Load Model Function\n def loadModel(self):\n model = filedialog.askopenfilename(initialdir=f\"{self.projectFolderPath}\", title=\"Choose Model\", filetypes=(\n (\"PKL Files\", \"*.pkl\"),))\n modelName = os.path.basename(model)\n modelNameSemExtensao = os.path.splitext(modelName)[0]\n\n # Caminho completo do modelo selecionado\n self.fullpathSelectedModel = model\n\n # Apresentar o nome do modelo selecionado na label\n self.label_model[\"text\"] = modelNameSemExtensao\n\n # Escrever no ficheiro de log a escolha do modelo\n self.log.logActions(f\"Model {modelNameSemExtensao} loaded\")\n\n self.showLastCommand()\n\n def classifyWithExistentModel(self):\n # Verificar se o utilizador ja escolheu um modelo\n if self.fullpathSelectedModel == None:\n messagebox.showerror(\"Error\", \"Choose model first\")\n return\n else:\n pass\n\n if self.ficheiroFoiAberto == 0:\n # Open file to start playing with algorithms\n self.openFile(self.filePath)\n # Alterar a variavel para mostrar que o ficheiro ja está aberto\n self.ficheiroFoiAberto = 1\n else:\n pass\n\n\n modelName = os.path.basename(self.fullpathSelectedModel)\n modelNameSemExtensao = os.path.splitext(modelName)[0]\n\n try:\n # Buscar o caminho completo\n lr = joblib.load(self.fullpathSelectedModel)\n y_pred = lr.predict(self.rows)\n\n # Criar um novo ficheiro e passar o resultado obtido apos a classificacao\n fileRefernce = open(f\"{self.projectFolderPath}\\\\Results\\\\Classified_{modelNameSemExtensao}.txt\", 'a+')\n\n\n for item in y_pred:\n fileRefernce.write(item + '\\n')\n\n # Fechar o ficheiro\n fileRefernce.close()\n\n # Escrever no ficheiro de log\n self.log.logActions(f\"Classification with model {modelNameSemExtensao} finished with success.\")\n\n # Apresentar mensagem a dizer que a classificaçao correu bem\n messagebox.showinfo(\"Classification Done\", \"Classification finished with success!\")\n\n # Fechar o ficheiro\n self.file.close()\n\n # Passar a variavel do self.ficheiroFoiAberto para 0\n self.ficheiroFoiAberto = 0\n\n # Retirar o self.rows e o self.target\n self.rows = []\n self.target = []\n\n\n except:\n # Apresentar mensagem caso dê erro\n messagebox.showerror(\"Error\",\n f\"Something went wrong when trying to classify with loaded model: {modelNameSemExtensao}\")\n\n # Escrever no ficheiro de logs que deu erro\n self.log.logActions(f\"Erro ao tentar classificar com o model carregado: {modelNameSemExtensao}\")\n\n # Fechar o ficheiro\n self.file.close()\n\n # Passar a variavel do self.ficheiroFoiAberto para 0\n self.ficheiroFoiAberto = 0\n\n # Retirar o self.rows e o self.target\n self.rows = []\n self.target = []\n\n self.showLastCommand()\n\n\n def loadMetrics(self):\n metric = filedialog.askopenfilename(initialdir=f\"{self.projectFolderPath}\", title=\"Choose Model\", filetypes=(\n (\"TXT Files\", \"*.txt\"),))\n metricName = os.path.basename(metric)\n metricNameSemExtensao = os.path.splitext(metricName)[0]\n\n # Caminho completo da metrica selecionada\n self.fullpathSelectedModel = metric\n\n # Fazer a divisao do resultado escolhido para conseguir ir buscar o ficheiro certo\n timestamp_data = metricNameSemExtensao.split(\"_\")\n # Descobrir o dia\n day = timestamp_data[1]\n # Descobrir o mes\n month = timestamp_data[2]\n # Descobrir o ano\n year = timestamp_data[3]\n # Descobrir a hora\n hour = timestamp_data[4]\n # Descobrir o minuto\n minute = timestamp_data[5]\n # Separar os segundos do algoritmo\n second = timestamp_data[6]\n # Descobrir o algoritmo usado\n algoritmo = timestamp_data[7]\n # Descobrir o segundo\n # Obter a data correta e conforme o ficheiro guardado\n selectedResult = f\"{day}-{month}-{year} {hour}:{minute}:{second} - {algoritmo}\"\n\n self.lb_resultados.insert(END, selectedResult)\n\n\n # Creation of the space where we all tabs will be placed\n self.tab = Frame(self.notebook)\n self.notebook.add(self.tab, text=f\"{selectedResult}\")\n\n results = Text(self.tab)\n results.pack(expand=1, fill=\"both\")\n\n file = open(metric, \"r\")\n\n for line in (file.readlines()):\n results.insert(INSERT, line.strip())\n results.insert(INSERT, '\\n')\n\n\n def deleteMetrics(self):\n sel = self.lb_resultados.curselection()\n for name in sel:\n del self.dictResultados[f\"{self.lb_resultados.index(name)}\"]\n\n for index in sel[::-1]:\n self.lb_resultados.delete(index)\n\n lista_separadores = list(self.notebook.winfo_children())\n\n for index in sel[::-1]:\n for item in range(len(lista_separadores)):\n if index == item:\n lista_separadores[index].destroy()\n","sub_path":"NEW/Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":75664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436997425","text":"\"\"\" Project Euler, Problem 7.\n Find the 10001th prime.\"\"\"\n\nprint(prime(10001))\n\ndef prime(n):\n \"\"\"Prints the nth prime.\"\"\"\n counter = 0\n for i in prime_gen():\n counter += 1\n if counter == n:\n return i \n \ndef prime_gen():\n \"\"\"Instantiates a list of primes up to a large number.\"\"\"\n limit = int(1e+7)\n prim_flags = [True]*limit\n prim_flags[0] = prim_flags[1] = False\n \n for (i, isprime) in enumerate(prim_flags):\n if isprime:\n yield i\n for n in range(i*i, limit, i): # Mark factors non-prime\n prim_flags[n] = False\n \n \n \n \n \n \n \n \n \n\n","sub_path":"7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10723927","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport logging\nimport os\nimport json\nimport sqlite3\nimport contextlib\nimport requests\n\n\nDB_PATH = 'db.sqlite3'\nTABLE_NAME = 'novels'\n\n\nclass WebNovelUpdateNotifierPipeline(object):\n def __init__(self, settings, *args, **kwargs):\n super(WebNovelUpdateNotifierPipeline, self).__init__(*args, **kwargs)\n\n self.slack_url = settings.get('SLACK_URL')\n self.slack_channel = settings.get('SLACK_CHANNEL')\n self.slack_bot_name = settings.get('SLACK_BOT_NAME')\n self.slack_bot_icon = settings.get('SLACK_BOT_ICON')\n\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(settings = crawler.settings)\n\n\n def process_item(self, item, spider):\n if self.novel_exists(item):\n if self.is_updated(item):\n self.update_novel(item)\n self.notify_slack(item)\n else:\n self.insert_novel(item)\n\n return item\n\n\n @contextlib.contextmanager\n def open_db(self):\n db = sqlite3.connect(\n os.path.join(os.getcwd(), DB_PATH))\n\n cursor = db.cursor()\n cursor.execute(\n f'CREATE TABLE IF NOT EXISTS {TABLE_NAME}(\\\n id INTEGER PRIMARY KEY AUTOINCREMENT, \\\n domain TEXT NOT NULL, \\\n novel_id TEXT NOT NULL, \\\n title TEXT NOT NULL, \\\n author TEXT, \\\n latest_url TEXT NOT NULL, \\\n updated_at DATE \\\n );')\n\n try:\n yield db\n finally:\n db.close()\n\n\n def insert_novel(self, item):\n with self.open_db() as db:\n db.execute(\n f'INSERT INTO {TABLE_NAME} (domain, novel_id, title, author, latest_url, updated_at) VALUES (?, ?, ?, ?, ?, ?)', (\n item['domain'],\n item['novel_id'],\n item['title'],\n item['author'],\n item['latest_url'],\n item['updated_at'],\n )\n )\n db.commit()\n logging.info(f'Insert {item}')\n\n\n def update_novel(self, item):\n with self.open_db() as db:\n db.execute(\n f'UPDATE {TABLE_NAME} SET title=?, author=?, latest_url=?, updated_at=? WHERE domain=? AND novel_id=?',\n (item['title'], item['author'], item['latest_url'], item['updated_at'], item['domain'], item['novel_id'],)\n )\n db.commit()\n logging.info(f'Update {item}')\n\n\n def novel_exists(self, item):\n with self.open_db() as db:\n cursor = db.execute(\n f'SELECT * FROM {TABLE_NAME} WHERE domain=? AND novel_id=?',\n (item['domain'], item['novel_id'],)\n )\n return True if cursor.fetchone() else False\n\n\n def is_updated(self, item):\n with self.open_db() as db:\n cursor = db.execute(\n f'SELECT * FROM {TABLE_NAME} WHERE domain=? AND novel_id=?',\n (item['domain'], item['novel_id'],)\n )\n \n return cursor.fetchone()[5] != item['latest_url']\n\n\n def notify_slack(self, item):\n fields = []\n fields += [{'title': 'Author', 'value': item['author'], 'short': True}]\n fields += [{'title': 'Updated', 'value': item['updated_at'].strftime('%Y/%m/%d %H:%M'), 'short': True}]\n \n attachments = [{'fallback': f'{item[\"title\"]} is updated', 'title': item['title'], 'title_link': item['latest_url'], 'fields': fields}]\n\n payload = {'username': self.slack_bot_name, 'icon_emoji': self.slack_bot_icon, 'attachments': attachments}\n\n if self.slack_channel:\n payload['channel'] = self.slack_channel\n\n requests.post(self.slack_url, json.dumps(payload))\n","sub_path":"app/web_novel_update_notifier/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"470171281","text":"# coding=utf-8\nfrom keras import Input, Model\nfrom keras.layers import Embedding, Conv1D, Dropout, MaxPooling1D, Flatten, merge, Dense, LSTM, Bidirectional\n\nimport globalvar as gl\nfrom preprocess.data_preprocessor import preprocess,generateWord2VectorMatrix,loadEmbeddingsIndex\n\n#全局变量\n\n\n\ngl.set_train_rela_files(\"train_case_rela.txt\")\ngl.set_train_ques_file(\"train_case_ques.txt\")\ngl.set_train_label_file(\"train_case_label.txt\")\ngl.set_test_rela_files(\"test_case_rela.txt\")\ngl.set_test_ques_file(\"test_case_ques.txt\")\ngl.set_test_label_file(\"test_case_label.txt\")\ngl.set_preprocessWordVector_files(\"TencentPreTrain.txt\")\ngl.set_preprocessWordVector_path(\"/data/zjy/\")\ngl.set_MAX_NB_WORDS(30)\ngl.set_EMBEDDING_DIM(200)\ngl.set_LSTM_DIM(150)\n\ntrain_rela_files=gl.get_train_rela_files()\ntrain_ques_file=gl.get_train_ques_file()\ntrain_label_file=gl.get_train_label_file()\ntest_rela_files=gl.get_test_rela_files()\ntest_ques_file=gl.get_test_ques_file()\ntest_label_file=gl.get_test_label_file()\npreprocessWordVector_files=gl.get_preprocessWordVector_files()\npreprocessWordVector_path=gl.get_preprocessWordVector_path()\nMAX_NB_WORDS=gl.get_MAX_NB_WORDS()\nEMBEDDING_DIM=gl.get_EMBEDDING_DIM()\nLSTM_DIM=gl.get_LSTM_DIM()\n\ngl.set_NUM_FILTERS(150)\ngl.set_filter_sizes([1,3,5])\n\nNUM_FILTERS = gl.get_NUM_FILTERS()\nfilter_sizes = gl.get_filter_sizes()\n\n\n#预处理\n\n\n\nques_train, rela_train,label_train, ques_test, rela_test, label_test,wd_idx=preprocess(train_rela_files,train_ques_file,train_label_file,test_rela_files,test_ques_file,test_label_file)\nembedding_index=loadEmbeddingsIndex(preprocessWordVector_path,preprocessWordVector_files)\nembedding_matrix=generateWord2VectorMatrix(embedding_index,wd_idx)\n#model\nrelation_maxlen= gl.get_relation_maxlen()\nques_maxlen= gl.get_ques_maxlen()\ntweet_relation = Input(shape=(relation_maxlen,))\ntweet_ques = Input(shape=(ques_maxlen,))\n\nDROPOUT_RATE=0.1\n\n\n\nrelation_embedding_layer = Embedding(len(wd_idx) + 1, EMBEDDING_DIM, input_length=relation_maxlen, weights=[embedding_matrix], trainable=True)(tweet_relation)\n\n\nlstm_relation=Bidirectional(LSTM(LSTM_DIM, activation='tanh', return_sequences=True),merge_mode='concat')(relation_embedding_layer)\nlstm_relation = Dropout(DROPOUT_RATE)(lstm_relation)\n\n\nrelation_conv1 = Conv1D(128, 3, activation='tanh')(lstm_relation)\nrelation_drop_1 = Dropout(DROPOUT_RATE)(relation_conv1)\nrelation_max_1 = MaxPooling1D(relation_maxlen-3+1)(relation_drop_1)\nrelation_conv2 = Conv1D(128, 1, activation='tanh')(relation_max_1)\nrelation_drop_2 = Dropout(DROPOUT_RATE)(relation_conv2)\nrelation_dmax_2 = MaxPooling1D(1)(relation_drop_2)\n#conv2 = Conv1D(128, 3, activation='tanh')(max_1)\n#max_2 = MaxPooling1D(3)(conv2)\nrelation_out_1 = Flatten()(relation_dmax_2)\n#out_1 = LSTM(128)(max_1)\n#question\nquestion_embedding_layer = Embedding(len(wd_idx) + 1, EMBEDDING_DIM, input_length=ques_maxlen, weights=[embedding_matrix], trainable=True)(tweet_ques)\n\nlstm_question=Bidirectional(LSTM(LSTM_DIM, activation='tanh', return_sequences=True),merge_mode='concat')(question_embedding_layer)\nlstm_question = Dropout(DROPOUT_RATE)(lstm_question)\n\n\nquestion_conv1 = Conv1D(128, 3, activation='tanh')(lstm_question)\nquestion_drop_1 = Dropout(DROPOUT_RATE)(question_conv1)\nquestion_max_1 = MaxPooling1D(ques_maxlen-3+1)(question_drop_1)\nquestion_conv2 = Conv1D(128, 1, activation='tanh')(question_max_1)\nquestion_drop_2 = Dropout(DROPOUT_RATE)(question_conv2)\nquestion_dmax_2 = MaxPooling1D(1)(question_drop_2)\n#conv2 = Conv1D(128, 3, activation='tanh')(max_1)\n#max_2 = MaxPooling1D(3)(conv2)\nquestion_out_1 = Flatten()(question_dmax_2)\n#out_1 = LSTM(128)(max_1)\n\n\nmerged_vector = merge([relation_out_1, question_out_1], mode='concat') # good\ndense_1 = Dense(128,activation='relu')(merged_vector)\ndense_2 = Dense(128,activation='relu')(dense_1)\ndense_3 = Dense(128,activation='relu')(dense_2)\n\npredictions = Dense(1, activation='sigmoid')(dense_3)\n#predictions = Dense(len(labels_index), activation='softmax')(merged_vector)\n\nmodel = Model(input=[tweet_relation, tweet_ques], output=predictions)\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit([rela_train,ques_train], label_train, nb_epoch=10,batch_size=20,verbose=1,shuffle=True)\njson_string = model.to_json() # json_string = model.get_config()\nopen('my_model_architecture.json','w').write(json_string)\nmodel.save_weights('my_model_weights.h5')\n\nscore = model.evaluate([rela_train,ques_train], label_train, verbose=0)\nprint('train score:', score[0])\nprint('train accuracy:', score[1])\nscore = model.evaluate([rela_test, ques_test], label_test, verbose=0)\nprint('Test score:', score[0])\nprint('Test accuracy:', score[1])\na = model.predict([rela_test,ques_test])\n\nprint('Predicted:')\nfor lines in a:\n for line in lines:\n print(line)","sub_path":"model/lstm_cnn.py","file_name":"lstm_cnn.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"223920595","text":"from django import urls\nfrom django.contrib.auth.models import User\nimport pytest\n\nimport pghistory.middleware\nimport pghistory.tests.models as test_models\nimport pghistory.tracking\n\n\n@pytest.mark.django_db\ndef test_post(client):\n \"\"\"Tests a post to a test URL with the middleware enabled\n\n The user created and set as the request user in the view.\n It should still be tracked in the history context\n \"\"\"\n assert not User.objects.exists()\n client.post(urls.reverse('test_view'))\n\n assert User.objects.count() == 1\n assert test_models.SnapshotModel.objects.count() == 1\n assert test_models.SnapshotModelSnapshot.objects.count() == 1\n\n user = User.objects.get()\n assert (\n test_models.SnapshotModelSnapshot.objects.get().pgh_context.metadata[\n 'user'\n ]\n == user.id\n )\n\n\ndef test_middleware(rf, mocker):\n \"\"\"\n Verifies pghistory context is tracked during certain requests\n with middleware in pghistory.middleware\n \"\"\"\n\n def get_response(request):\n return getattr(pghistory.tracking._tracker, 'value', None)\n\n resp = pghistory.middleware.HistoryMiddleware(get_response)(\n rf.get('/get/url/')\n )\n # No tracking should be happening since this is a GET request\n assert resp is None\n\n # A POST request will initiate the tracker\n resp = pghistory.middleware.HistoryMiddleware(get_response)(\n rf.post('/post/url/')\n )\n assert resp.metadata == {'url': '/post/url/', 'user': None}\n\n # Authenticated users will be tracked\n request = rf.post('/post/url2/')\n request.user = mocker.Mock(id=3)\n resp = pghistory.middleware.HistoryMiddleware(get_response)(request)\n assert resp.metadata == {'url': '/post/url2/', 'user': 3}\n","sub_path":"pghistory/tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"188953257","text":"import urllib.request, urllib.parse, urllib.error\nimport json\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter -')\ndata = urllib.request.urlopen(url, context = ctx).read()\ndata = json.loads(data)\n\ncount = 0;\nfor comment in data['comments']:\n\tcount = count + int(comment['count'])\nprint(count)\n\n","sub_path":"Using Python to Access Web Data/Assignment6-1.py","file_name":"Assignment6-1.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241893167","text":"#!/usr/bin/env python3\n\nimport os\nfrom collections import Counter\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n# return dict\ndef read(filename):\n if not filename:\n print('Error: invalid file name')\n return None\n filename=filename.strip()\n if filename[0] == '~':\n filename = os.path.expanduser(filename)\n if not os.path.isfile(filename):\n return None\n file = open(filename, 'r')\n\n for line in file:\n line = line.strip()\n if not line:\n continue\n yield line\n\ndef open_file(filename,mode='r'):\n if not filename:\n print('Error: invalid file name')\n return None\n filename=filename.strip()\n if filename[0] == '~':\n filename = os.path.expanduser(filename)\n if mode == 'r' and not os.path.isfile(filename):\n return None\n return open(filename, mode)\n\ndef imprime_saidas():\n infile = open('../data/spam_train.txt','r')\n outfile = open('saidas.log','w')\n for line in infile:\n outfile.write(line[0]+'\\n')\n infile.close()\n outfile.close()\n\ndef main(infilename,outfilename):\n infile = open_file(infilename)\n outfile = open_file(outfilename, 'w')\n\n try:\n T = int(infile.readline())\n except:\n print('error converting string to int')\n sys.exit(1)\n # print(T)\n i = 1\n for line in infile:\n word = line.strip()\n # print(line)\n out = ''\n end = 'A'\n for letter in word:\n # print(letter)\n if end > letter:\n out += letter\n else:\n out = letter + out\n end = out[0]\n # print('Case #',end='')\n # print(i,end='')\n # print(':', out)\n outfile.write('Case #' + str(i) + ': ' + out + '\\n')\n i += 1\n\n\n\nif __name__ == '__main__':\n infilename = ''\n outfilename = ''\n if len(sys.argv) > 1:\n infilename = sys.argv[1]\n else:\n print('usage:', sys.argv[0], 'filename_input [filename_output]')\n sys.exit(1)\n if len(sys.argv) > 2:\n outfilename = sys.argv[2]\n # print('outfile:', outfilename)\n main(infilename,outfilename)\nelse:\n pass\n","sub_path":"codes/CodeJamCrawler/16_1_1_neat/16_1_1_gagarin_main.py","file_name":"16_1_1_gagarin_main.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649583435","text":"# Make a class function of vehicles\r\nclass Vehicle:\r\n # Make a counter of passing cars through toll gates.\r\n Car=0\r\n # Make a counter of passing buses through toll gates.\r\n Bus=0\r\n # Make a counter of passing trucks through toll gates.\r\n Truck=0\r\n # Define a function to initialize class Vehicle.\r\n def __init__(self,vehicle):\r\n self.vehicle=vehicle\r\n # Define a function to add number of vehicle whether it is car, bus, or truck.\r\n def addVehicle(self,vehicle):\r\n if vehicle == \"car\" or vehicle == \"Car\":\r\n self.Car += 1\r\n return self.Car\r\n elif vehicle == \"bus\" or vehicle == \"Bus\":\r\n self.Bus += 1\r\n return self.Bus\r\n elif vehicle == \"truck\" or vehicle == \"Truck\":\r\n self.Truck += 1\r\n return self.Truck\r\n# Make a class function of location which inherits class Vehicle\r\nclass Location(Vehicle):\r\n # Define a function to initialize class Location and inherit class Vehicle\r\n def __init__(self,name,vehicle,Cprice,Bprice,Tprice):\r\n super().__init__(vehicle)\r\n self.Cprice = float(Cprice)\r\n self.Bprice = float(Bprice)\r\n self.Tprice = float(Tprice)\r\n self.name = str(name)\r\n # Define a function to get fee based on 3 category of vehicles such as cars, buses, and trucks.\r\n def getPrice(self,type):\r\n if type == \"car\" or type == \"Car\":\r\n return self.Cprice\r\n elif type == \"bus\" or type == \"Bus\":\r\n return self.Bprice\r\n elif type == \"truck\" or type == \"Truck\":\r\n return self.Tprice\r\n # Define a function to get name of location\r\n def getName(self):\r\n return self.name\r\n # Define a function to get value of car's fee\r\n def getCar_price(self):\r\n return float(self.Cprice)\r\n # Define a function to get value of bus's fee\r\n def getBus_price(self):\r\n return float(self.Bprice)\r\n # Define a function to get value of truck's fee\r\n def getTruck_price(self):\r\n return float(self.Tprice)\r\n# Make an object of class Location that inherit class Vehicle\r\nT = Location(\"Meruya\",\"\",6000.0,8000.0,10000.0)\r\n\r\n# Make a variable of True statement\r\nisInput = True\r\n#As long as statement is True, it will run until it reaches False statement.\r\nwhile isInput:\r\n print(\"======PT. Jasa Marga======\")\r\n print(\"Welcome to Toll Gate {}\".format(T.getName()))\r\n print(\"Category of Vehicle:\\n1.Car: Rp. {}\\n2.Bus: Rp. {}\\n3.Truck: Rp.{}\".format(T.getCar_price(),\r\n T.getBus_price(),\r\n T.getTruck_price()))\r\n # Variable for inputting 1 vehicle based on its category.\r\n Fee=input(\">\")\r\n T.addVehicle(Fee)\r\n T.getPrice(Fee)\r\n # print fee based on its vehicle category.\r\n print(\"Fee: {}\".format(T.getPrice(Fee)))\r\n print(\"Is there any vehicle? Y/N\")\r\n # Variable for answer yes or no.\r\n answer = input(\">\")\r\n # When answer is equal to \"N\" or \"n\", it will show how many cars, buses, and trucks and sum all fees.\r\n if answer == \"N\" or answer == \"n\":\r\n # when isInput becomes False, it will stop running.\r\n isInput = False\r\n # when answer is equal to \"Y\" or \"y\", it will return to start point again.\r\n elif answer == \"Y\" or answer == \"y\":\r\n isInput = True\r\n","sub_path":"Toll Payment System/Toll Payment version 1.py","file_name":"Toll Payment version 1.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"649632299","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport time\nimport atexit\nimport random\nimport telepot\n\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17, GPIO.OUT)\n\nBOT_API_KEY = ''\n\nwhy = ['Because', 'Why not?']\nbla = ['Hmm...']\n\n# Open the log file\nlog = open('log.txt', 'a')\n\n\ndef add_log(message, response):\n\n log.write('<< {0}\\n'.format(message))\n log.write('>>> {0}\\n'.format(response))\n\n\ndef save_and_exit():\n GPIO.cleanup()\n log.close()\n\n# Close log file at exit\natexit.register(save_and_exit)\n\n\ndef get_response(message):\n\n message = message.lower()\n\n response = 'Ok'\n\n if 'why' in message and '?' in message:\n response = random.choice(why)\n elif message == 'time':\n response = datetime.datetime.now().strftime(\"%A, %d %B %Y %I:%M %p\")\n elif message == '/ledon':\n GPIO.output(17, True)\n elif message == '/ledoff':\n GPIO.output(17, False)\n else:\n response = random.choice(bla)\n\n add_log(message, response)\n return response\n\n\ndef handle(msg):\n\n chat_id = msg['chat']['id']\n command = msg['text']\n\n print('Got: %s' % command)\n\n bot.sendMessage(chat_id, get_response(command))\n\n\nbot = telepot.Bot(BOT_API_KEY)\nbot.message_loop(handle)\nprint('Listening ...')\n\nwhile 1:\n time.sleep(10)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137778407","text":"\"\"\"Train NNs ensemble members for a given salient's submodel \r\n\r\nExample:\r\n $ python src/models/salient/train_keras.py salient_fri_20170201 -n 50 -s 0 -r contest \r\n\r\nAttributes:\r\n batch_size (int): number of training examples used in one iteration during \r\n the training of each NN ensemble member.\r\n train_ratio (float): train-validation split ratio used for each NN ensemble member.\r\n save_models (bool): if True, save the weights of the trained NNs.\r\n window_size (int): size of the sliding window over the data. If set to 10, \r\n the NN's input feature vector consists of a concatenation of the prior 10 weeks of data.\r\n\r\nPositional args:\r\n submodel_name: string consisting of the ground truth variable ids used for training and the date of the last training example\r\n a submodel_name consists of a concatenation of 3 strings, one of each of the category below:\r\n ground truth variables : \"salient_fri\"\r\n end_date: \"20170201\"\r\n\r\nNamed args:\r\n --n_random_models (-n): number of NN ensemble members to be trained (default: 50)\r\n --start_id (-s): id of the first NN to be trained as part of the n_random_models NNs (default: 0).\r\n This id can be set to a different value if the training is to be picked up from a paused/interrupted ensemble training.\r\n --region (-r): string consisting of the spatial region on which to train the model; \r\n either 'us' to use U.S. continental bounding box for the output data\r\n or 'contest' to use the frii contest region bounding box (default)\r\n or 'east' to use the east region (U.S. minus contest latlons).\r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport json\r\nimport keras\r\nimport random\r\nimport pickle\r\nimport numpy as np\r\nfrom datetime import datetime\r\nimport argparse\r\nfrom argparse import ArgumentParser\r\nfrom keras import backend as K\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom subseasonal_toolkit.utils.models_util import Logger\r\nfrom subseasonal_toolkit.utils.general_util import printf, make_directories\r\nfrom subseasonal_toolkit.models.salient.salient_util import dir_train_data, dir_train_results, val_i_error, mkdir_p\r\n\r\n\r\nbatch_size = 128\r\ntrain_ratio = .89\r\nsave_models = True\r\nwindow_size = 10\r\n\r\n\r\ndef mean_loss_i(i):\r\n \"\"\"returns the mean loss for a single training example of a keras NN model.\r\n\r\n Args:\r\n i: index of training example of a keras NN model.\r\n\r\n Returns:\r\n loss value for the ith training example.\r\n\r\n \"\"\"\r\n def i_error(y_true, y_pred):\r\n start = i*514\r\n end = (i+1)*514\r\n y_true = y_true[...,start:end]\r\n y_pred = y_pred[...,start:end]\r\n err = K.abs(y_true - y_pred)\r\n return K.mean(err)\r\n return i_error\r\n\r\ndef generate_windows(x):\r\n \"\"\"generates a sliding window over the data of length window_size.\r\n\r\n Args:\r\n x: array of input features used the NN\r\n\r\n Returns:\r\n reshaped array of input features so that each example is a concatenation of the past 10 weeks of data.\r\n\r\n \"\"\"\r\n\r\n result = []\r\n for i in range(x.shape[0]-window_size):\r\n result.append(x[i:i+window_size, ...])\r\n return np.stack(result)\r\n\r\ndef reshape_data(x, y):\r\n \"\"\"Example function with PEP 484 type annotations.\r\n\r\n Args:\r\n x: array of input features used by the NN.\r\n y: array of output features used by the NN.\r\n\r\n Returns:\r\n x: reshaped array of input features to use a concatenation of data over past 10 weeks for every training example.\r\n y: reshaped array of output features used by the NN.\r\n\r\n \"\"\"\r\n x = generate_windows(x)\r\n # Truncate first few y values since there aren't enough preceding weeks to predict on.\r\n y = y[window_size:,...]\r\n # Shuffle data \r\n indices = np.random.permutation(x.shape[0])\r\n x = x[indices,...]\r\n y = y[indices,...]\r\n return x, y\r\n\r\ndef compile_input(submodel_name, n_weeks_predict=[3,4,5,6], i_time=False, region='contest'):\r\n \"\"\"Example function with PEP 484 type annotations.\r\n\r\n Args:\r\n submodel_name (str): string consisting of the ground truth variable \r\n ids used for training and the date of the last training example.\r\n n_weeks_predict (list): list of weeks over which output is averaged. \r\n Each network in the ensemble provides a prediction \r\n for the average temperature and accumulated rainfall at \r\n at 3, 4, 5, and 6 weeks into the future (default: [3, 4, 5, 6]).\r\n i_time (bool): if True, include time vector as an input feature (default: False).\r\n region (str): string consisting of spatial region used for output data, \r\n either 'contest', 'east' or 'us' (default: 'contest').\r\n\r\n Returns:\r\n input_data: array of input features used to train the NNs.\r\n output_data_all: array of output features used to train the NNs.\r\n\r\n \"\"\"\r\n if region == 'contest':\r\n num_of_gc = 514\r\n elif region == 'east':\r\n num_of_gc = 348\r\n elif region == 'us':\r\n num_of_gc = 862\r\n \r\n # Get the end date of the training dataset and training data directory\r\n end_date = submodel_name[-8:]\r\n \r\n # Load date data\r\n end_date = datetime.strptime(end_date, '%Y%m%d')\r\n date_data_file = os.path.join(dir_train_data, \"date.pickle\")\r\n date_vectors = pickle.load(open(date_data_file, 'rb'))\r\n date_vectors = [datetime(d[0].astype(object).year, d[0].astype(object).month, d[0].astype(object).day) for d in date_vectors ]\r\n date_vectors = sorted([d for d in date_vectors if d<=end_date])\r\n last_i = len(date_vectors)\r\n\r\n \r\n # load sst data\r\n sst_data_file = os.path.join(dir_train_data, \"sst.pickle\")\r\n sst_vectors = pickle.load(open(sst_data_file, 'rb'))\r\n \r\n # load time data\r\n time_data_file = os.path.join(dir_train_data, \"time.pickle\")\r\n time_vectors = pickle.load(open(time_data_file, 'rb'))\r\n time_vectors = np.reshape(time_vectors,(time_vectors.shape[0],1))\r\n\r\n # load precipitation data\r\n location_precip_file = os.path.join(dir_train_data, \"precip.pickle\")\r\n precip_data = pickle.load(open(location_precip_file, 'rb'))\r\n precip_data = precip_data.T\r\n\r\n # load temperature data\r\n location_temp_file = os.path.join(dir_train_data, \"temp.pickle\")\r\n temp_data = pickle.load(open(location_temp_file, 'rb'))\r\n temp_data = temp_data.T\r\n\r\n # make precip data only as long as temp data\r\n precip_data = precip_data[:temp_data.shape[0],:]\r\n\r\n # Ensure same length vectors and standardize sst data\r\n sst_vectors = sst_vectors[:precip_data.shape[0],:]\r\n sst_vectors = (sst_vectors - np.amin(sst_vectors)) * 1./(np.amax(sst_vectors) - np.amin(sst_vectors))\r\n data_min, data_max = np.amin(sst_vectors), np.amax(sst_vectors)\r\n\r\n\r\n # Ensure same length vectors for time, precip and temp vectors \r\n time_vectors = time_vectors[:precip_data.shape[0],:]\r\n precip_input = precip_data[:precip_data.shape[0],:]\r\n temp_input = temp_data[:temp_data.shape[0],:]\r\n\r\n # Standardize pecip and temp data \r\n precip_input = (precip_input - np.amin(precip_input)) * 1./(np.amax(precip_input) - np.amin(precip_input))\r\n temp_input = (temp_input - np.amin(temp_input)) * 1./(np.amax(temp_input) - np.amin(temp_input))\r\n\r\n #concatenate weeks to predict for all data \r\n max_weeks_predict = np.amax(n_weeks_predict)\r\n # Can't use the last weeks because there wouldn't be enough data to predict.\r\n sst_vectors = sst_vectors[:-max_weeks_predict, ...]\r\n data_length = sst_vectors.shape[0] \r\n time_vectors = time_vectors[:-max_weeks_predict, ...]\r\n precip_input = precip_input[:-max_weeks_predict, ...]\r\n temp_input = temp_input[:-max_weeks_predict, ...]\r\n \r\n\r\n # compile input data\r\n input_data = sst_vectors \r\n if i_time:\r\n input_data = np.concatenate((input_data, time_vectors), axis=1)\r\n\r\n # compile output precip data\r\n precip_data_all = np.zeros((data_length,precip_data.shape[1],len(n_weeks_predict))) # (t,loc,wk)\r\n for i in range(len(n_weeks_predict)):\r\n week = n_weeks_predict[i]\r\n # offset precip data\r\n precip_data_all[:,:,i] = precip_data[week-1:-(1+max_weeks_predict-week),:] # (t,loc,wk)\r\n precip_data_all = np.rollaxis(precip_data_all,2,1) # (t,wk,loc)\r\n precip_data_all = precip_data_all.reshape(precip_data_all.shape[0],-1) # (t,wkloc)\r\n\r\n # compile output temp data\r\n temp_data_all = np.zeros((data_length,temp_data.shape[1],len(n_weeks_predict))) # (t,loc,wk)\r\n for i in range(len(n_weeks_predict)):\r\n week = n_weeks_predict[i]\r\n # offset temp data\r\n temp_data_all[:,:,i] = temp_data[week-1:-(1+max_weeks_predict-week),:] # (t,loc,wk)\r\n temp_data_all = np.rollaxis(temp_data_all,2,1) # (t,wk,loc)\r\n temp_data_all = temp_data_all.reshape(temp_data_all.shape[0],-1) # (t,wkloc)\r\n \r\n output_data_all = np.concatenate((precip_data_all, temp_data_all), axis=1)\r\n \r\n\r\n #adjust for end date, i.e., last training date \r\n input_data = input_data[:last_i]\r\n output_data_all = output_data_all[:last_i]\r\n\r\n return input_data, output_data_all\r\n\r\ndef train(x, y, activation='lrelu', epochs=200, units=300, depth=3, region='contest'):\r\n \"\"\"Example function with PEP 484 type annotations.\r\n\r\n Args:\r\n x (float): array of input features used to train the NNs.\r\n y (float): array of output features used to train the NNs.\r\n epochs (int): number of epochs (i.e., one cycle through the full training\r\n dataset) used to train the NNs (default: 200).\r\n units (int): number of units in each layer of the NN (default: 300).\r\n depth (int): number of layers in the NN (default: 3).\r\n region (str): string consisting of spatial region used for output data, \r\n either 'contest', 'east' or 'us' (default: 'contest').\r\n\r\n Returns:\r\n model (keras squential model object): trained NN model weights.\r\n history (keras history object): training history of the NN, including metrics dictionary.\r\n val_metrics (numpy array): mean loss for each output feature.\r\n\r\n \"\"\"\r\n if region == 'contest':\r\n num_of_gc = 514\r\n elif region == 'east':\r\n num_of_gc = 348\r\n elif region == 'us':\r\n num_of_gc = 862\r\n # Set up number of metrics to be used\r\n N_metrics = int(y.shape[1]/num_of_gc)\r\n metrics_vector = '['\r\n for i in range(N_metrics):\r\n metrics_vector += 'mean_loss_i('+str(i)+')'\r\n if i < N_metrics-1:\r\n metrics_vector += ', '\r\n metrics_vector += ']'\r\n\r\n # Set up lrelu usage\r\n lrelu = False\r\n if activation == 'lrelu':\r\n lrelu = True\r\n activation = 'linear'\r\n\r\n num_weeks = x.shape[0]\r\n\r\n x_train = x[:int(train_ratio*num_weeks),...]\r\n x_test = x[int(train_ratio*num_weeks):-13,...]\r\n y_train = y[:int(train_ratio*num_weeks),...]\r\n y_test = y[int(train_ratio*num_weeks):-13,...]\r\n\r\n # Setup keras sequential model\r\n model = Sequential()\r\n model.add(Dense(units, input_shape=x_train.shape[1:], activation=activation))\r\n if lrelu:\r\n model.add(LeakyReLU(alpha=.2))\r\n model.add(Flatten())\r\n model.add(Dropout(0.25))\r\n\r\n for i in range(depth-2):\r\n model.add(Dense(units, activation=activation))\r\n if lrelu:\r\n model.add(LeakyReLU(alpha=.2))\r\n model.add(Dropout(0.25))\r\n\r\n model.add(Dense(y_train.shape[1], activation='linear'))\r\n model.add(LeakyReLU(alpha=.05))\r\n \r\n \r\n # Compile keras sequential model\r\n adam_opt = keras.optimizers.Adam(lr=0.005, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.01)\r\n model.compile(loss=keras.losses.mean_absolute_error, optimizer=adam_opt)\r\n\r\n # Fit keras sequential model\r\n history = model.fit(x_train, y_train,\r\n batch_size=batch_size,\r\n epochs=epochs,\r\n verbose=0,\r\n #callbacks=[tbCallBack],\r\n validation_data=(x_test, y_test),\r\n shuffle=False)\r\n\r\n # Track validation metrics\r\n val_prediction = model.predict(x_test)\r\n val_metrics = np.zeros(N_metrics)\r\n for i in range(N_metrics):\r\n val_metrics[i] = val_i_error(y_test, val_prediction, i)\r\n\r\n return model, history, val_metrics\r\n\r\n\r\ndef main():\r\n \r\n # input arguments\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"pos_vars\",nargs=\"*\") # submodel_name\r\n parser.add_argument(\"--n_random_models\", \"-n\", default=50)\r\n parser.add_argument(\"--start_id\", \"-s\", default=0)\r\n parser.add_argument('--region', '-r', default='contest')\r\n \r\n # Assign variables\r\n args = parser.parse_args()\r\n submodel_name = args.pos_vars[0] # \"salient_fri_20170201\"\r\n n_random_models = int(args.n_random_models)\r\n start_id = int(args.start_id)\r\n region = args.region \r\n \r\n #weights directory\r\n in_dir_weights = os.path.join(dir_train_results, submodel_name, f\"{region}_{submodel_name}\")\r\n make_directories(in_dir_weights)\r\n \r\n # Create logs and histories\r\n for dir_name in [\"logs\", \"checkpoints\", \"histories\", \"histories_detailed\"]:\r\n mkdir_p(os.path.join(in_dir_weights, dir_name))\r\n log_file = (os.path.join(in_dir_weights, \"logs\", f\"training_{start_id}_to_{start_id+n_random_models-1}.log\"))\r\n Logger(log_file, 'w') # 'w' overwrites previous log\r\n \r\n\r\n # Define weeks to predict\r\n n_weeks_predict = [3,4,5,6]\r\n activations = ['elu', 'lrelu'] # ['relu', 'linear', 'tanh', 'sigmoid', 'elu', 'lrelu']\r\n\r\n # Create lists for ensemble members' models and histories\r\n histories = []\r\n models = []\r\n \r\n # Train NN ensemble\r\n for i in range(n_random_models):\r\n f_template = os.path.join(in_dir_weights, \"checkpoints\", f\"tmp_k_model_{i+start_id}_time\")\r\n if os.path.isfile(f\"{f_template}1.h5\") or os.path.isfile(f\"{f_template}0.h5\"):\r\n print('Skipping model ' + str(i+start_id))\r\n continue\r\n \r\n print('Training model ' + str(i+start_id))\r\n\r\n # Compile input and output data\r\n input_set = random.randint(0,1)\r\n input_data, output_data = compile_input(submodel_name, n_weeks_predict, i_time=bool(input_set), region = region)\r\n\r\n # Setup NN's architecture specifications\r\n activation = activations[random.randint(0,len(activations)-1)]\r\n units = random.randint(100,600)\r\n layers = random.randint(3,7)\r\n epochs = random.randint(100,500)\r\n\r\n # Format input and output data to use a sliding window of 10 weeks over the data\r\n x, y = reshape_data(input_data, output_data)\r\n # Train keras sequential NN\r\n model, history, val_metrics = train(x, y,\r\n activation=activation,\r\n units=units,\r\n depth=layers,\r\n epochs=epochs\r\n )\r\n \r\n # Track history of NN model\r\n history_i = {\r\n \"region\": region,\r\n \"submodel_name\": submodel_name,\r\n \"index\": i+start_id,\r\n \"i_time\": input_set,\r\n \"activation\": activation,\r\n \"units\": units,\r\n \"layers\": layers,\r\n \"epochs\": epochs,\r\n \"loss\": history.history[\"loss\"][-1],\r\n \"val_loss\": history.history[\"val_loss\"][-1],\r\n \"val_metrics\": list(val_metrics)\r\n }\r\n histories.append(history_i)\r\n print(history_i)\r\n\r\n # Setup model and history saving paths.\r\n model_name = os.path.join(in_dir_weights, \"checkpoints\", f\"tmp_k_model_{i+start_id}_time{input_set}.h5\")\r\n history_name = os.path.join(in_dir_weights, \"histories\", f\"tmp_k_model_{i+start_id}_time{input_set}.pickle\")\r\n history_detailed_name = os.path.join(in_dir_weights, \"histories_detailed\", f\"tmp_k_model_{i+start_id}_time{input_set}.pickle\")\r\n \r\n # Save model's weights, history and detailed history \r\n if save_models:\r\n model.save(model_name)\r\n with open(history_name, \"wb\") as out_file:\r\n pickle.dump(history.history, out_file)\r\n with open(history_detailed_name, \"w\") as out_file:\r\n json.dump(history_i, out_file)\r\n \r\n printf(f\"\\nAll results\")\r\n [printf(item) for item in histories]\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"subseasonal_toolkit/models/salient/train_keras.py","file_name":"train_keras.py","file_ext":"py","file_size_in_byte":16656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"471179282","text":"from fastapi import FastAPI, Response, Request\r\nfrom fastapi.responses import HTMLResponse\r\nfrom fastapi.staticfiles import StaticFiles\r\nfrom fastapi.templating import Jinja2Templates\r\nimport requests_async as requests\r\nimport os\r\nfrom random import choice\r\nimport base64\r\n\r\n\r\napp = FastAPI()\r\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\r\ntemplates = Jinja2Templates(directory=\"templates\")\r\n\r\ndef parsePath():\r\n dirs = path.split('/')\r\n return dirs\r\n\r\ndef createPath(path):\r\n root = 'cache'\r\n full_path = os.path.join(root,'/'.join(path.split('/')[0:-1]))\r\n if not os.path.isfile(full_path):\r\n os.makedirs(full_path,exist_ok=True)\r\n \r\ndef writeToCache(path,bytes_data):\r\n createPath(path)\r\n root = 'cache'\r\n path = os.path.join(root,path)\r\n if not os.path.isfile(path):\r\n open(path,'wb').write(bytes_data)\r\n\r\ndef readSizeCache(path):\r\n root = 'cache'\r\n return os.stat(os.path.join(root,path)).st_size\r\n\r\ndef parseContentRange(header_data):\r\n byte_range = header_data.split(\"/\")[0].split(\"-\")\r\n start = int(byte_range[0].strip().replace('bytes ',''))\r\n end = int(byte_range[1].strip())\r\n return start, end\r\n \r\ndef readFromCache(path,start,end):\r\n root = 'cache'\r\n f = open(os.path.join(root,path),'rb')\r\n f.seek(start)\r\n data = f.read(end-start)\r\n return data\r\n\r\ndef getProxies():\r\n response = requests.get(\"https://actproxy.com/proxy-api/01808179c14f0ae3a22778c483f1aae9_12957-30342?format=json&userpass=true\")\r\n list_proxies = response.json()\r\n return(choice(list_proxies).split(\";\"))\r\n\r\nasync def httpxProxy(path,headers):\r\n url = f\"http://s3.eu-central-1.wasabisys.com/eu.minhpg.com/{path}\"\r\n proxy = await requests.get(url)\r\n return proxy\r\n\r\nasync def httpxM3u8Proxy(path,headers):\r\n url = decodeBase64(path)\r\n proxy = await requests.get(url)\r\n return proxy\r\n\r\n\r\ndef responseReadCache(response,headers,path):\r\n if 'content-range' in headers:\r\n start, end = parseContentRange(headers['content-range'])\r\n size = readSizeCache(path)\r\n response.body = readFromCache(path,start,end)\r\n response.status_code = 206\r\n else:\r\n start = 0\r\n end = readSizeCache(path)\r\n size = end\r\n response.body = readFromCache(path,0,end)\r\n response.status_code = 200\r\n\r\n headers = {\r\n 'Access-Control-Allow-Origin' : '*',\r\n 'content-type' : 'binary/octet-stream', \r\n 'content-range' : 'bytes {}-{}/{}'.format(str(start),str(end),str(size)),\r\n 'cache' : 'HIT',\r\n 'server' : 'minhpg.com'\r\n }\r\n for i in headers.keys():\r\n response.headers[i] = headers[i]\r\n return response\r\n\r\ndef handleErrorProxy(proxy,response):\r\n response.body = proxy.content\r\n headers = {\r\n 'Access-Control-Allow-Origin' : '*',\r\n 'cache' : 'ERROR',\r\n 'server' : 'minhpg.com'\r\n }\r\n for i in headers.keys():\r\n response.headers[i] = headers[i]\r\n response.status_code = proxy.status_code\r\n return response\r\n\r\ndef extractBaseUrl(url):\r\n components = url.split('/')\r\n for i in components:\r\n if 'm3u8' in i:\r\n components.pop(components.index(i))\r\n return '/'.join(components)\r\n\r\ndef m3u8Parser(content,baseurl):\r\n new_playlist = []\r\n lines = content.split('\\n')\r\n for i in lines:\r\n if 'm3u8' in i:\r\n new_playlist.append('/proxy/'+generateBase64(i))\r\n elif 'ts' in i:\r\n if 'http' in i:\r\n new_playlist.append('/proxy/'+generateBase64(i))\r\n else:\r\n new_playlist.append('/proxy/'+generateBase64(baseurl+'/'+i))\r\n else:\r\n new_playlist.append(i)\r\n return '\\n'.join(new_playlist)\r\n\r\nasync def proxy(request,response,path):\r\n headers = request.headers\r\n root='cache'\r\n if not os.path.isfile(os.path.join(root,path)):\r\n proxy = await httpxProxy(path,dict(headers))\r\n if proxy.status_code == 200:\r\n writeToCache(path,proxy.content)\r\n response = responseReadCache(response,headers,path)\r\n else:\r\n response = handleErrorProxy(proxy,response)\r\n else:\r\n response = responseReadCache(response,headers,path)\r\n return response\r\n\r\nasync def proxy_m3u8(request,response,path):\r\n url = path\r\n path = generateBase64(path)\r\n headers = request.headers\r\n root='cache'\r\n if not os.path.isfile(os.path.join(root,path)):\r\n proxy = await httpxM3u8Proxy(path,dict(headers))\r\n if proxy.status_code == 200:\r\n if 'm3u8' in url:\r\n baseurl = extractBaseUrl(url)\r\n data = m3u8Parser(proxy.text,baseurl)\r\n response.body = bytes(data,\"UTF-8\")\r\n response.status_code = 200\r\n headers = {\r\n 'Access-Control-Allow-Origin' : '*',\r\n 'content-type' : 'application/vnd.apple.mpegurl', \r\n 'cache' : 'MISS',\r\n 'server' : 'minhpg.com'\r\n }\r\n for i in headers.keys():\r\n response.headers[i] = headers[i] \r\n else:\r\n writeToCache(path,proxy.content)\r\n response = responseReadCache(response,headers,path)\r\n else:\r\n response = handleErrorProxy(proxy,response)\r\n else:\r\n response = responseReadCache(response,headers,path)\r\n return response\r\n\r\n@app.get(\"/player/{path:path}\", response_class=HTMLResponse)\r\nasync def player(request: Request, path: str):\r\n return templates.TemplateResponse(\"gapo.html\", {\"request\": request, \"hd\": '/proxy/'+generateBase64(path),\"type\":'m3u8'})\r\n\r\n\r\n@app.get(\"/proxy/{path:path}\")\r\nasync def _proxy_playlist(path: str, response: Response, request: Request):\r\n try:\r\n path = decodeBase64(path)\r\n response = await proxy_m3u8(request,response,path)\r\n except Exception as exception:\r\n response.headers['server'] = 'minhpg.com'\r\n return {'error':str(exception)}\r\n return response\r\n\r\n@app.get(\"/{path:path}\")\r\nasync def _proxy(path: str, response: Response, request: Request):\r\n try:\r\n response = await proxy(request,response,path)\r\n except Exception as exception:\r\n response.headers['server'] = 'minhpg.com'\r\n return {'error':str(exception)}\r\n return response\r\n\r\n\r\ndef generateBase64(string):\r\n return base64.b64encode(bytes(string, 'utf-8')).decode(\"utf-8\")\r\n\r\ndef decodeBase64(string):\r\n return base64.b64decode(bytes(string, 'utf-8')).decode(\"utf-8\")","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362323226","text":"\"\"\"\n api_util.py\n ~~~~~~\n Created By : Pankaj Suthar\n\"\"\"\nfrom resourceprovider import ResourceProvider\n\nfrom src.exception.application_exception import ApplicationException\n\n\nclass APIUtil:\n \"\"\"API Util is utility to verify basic request parameters\"\"\"\n\n @staticmethod\n def is_content_type_application_json(request):\n \"\"\"Verify Content-Type in request. It should be application/json\"\"\"\n # Logger\n logger = ResourceProvider.get_resource(\"logger\")\n is_verify, header = True, None\n try:\n header = request.content_type\n if header != 'application/json':\n if header != 'application/json; charset=UTF-8':\n is_verify = False\n except Exception as ex:\n logger.error(\"Unable to Verify Content-Type. EXCEPTION [{}]\".format(ex))\n\n if not is_verify:\n logger.error(\n \"Invalid Content-Type header. Found = [ {} ], required [ application/json ]\".format(\n header))\n raise ApplicationException(message=\"Required Header [ application/json ]\", status_code=400)\n else:\n logger.info(\"Content-Type Verified.\")\n","sub_path":"src/util/api_util.py","file_name":"api_util.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"364508975","text":"# 1450 Number of Students Doing Homework at a Given Time\nclass Solution(object):\n def busyStudent(self, startTime, endTime, queryTime):\n \"\"\"\n :type startTime: List[int]\n :type endTime: List[int]\n :type queryTime: int\n :rtype: int\n \"\"\"\n tally = 0\n for i in range(len(startTime)):\n tally += (queryTime >= startTime[i]) and (queryTime <= endTime[i])\n return tally\n","sub_path":"easy/1450.py","file_name":"1450.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"303576201","text":"import matplotlib\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.tree import DecisionTreeClassifier\r\n\r\n# 加载数据集\r\n# 鸢尾花(iris)数据集\r\n# 数据集内包含 3 类共 150 条记录,每类各 50 个数据,\r\n# 每条记录都有 4 项特征:花萼长度、花萼宽度、花瓣长度、花瓣宽度,\r\n# 可以通过这4个特征预测鸢尾花卉属于(iris-setosa, iris-versicolour, iris-virginica)中的哪一品种。\r\n# 这里只取前100条记录,两项特征,两个类别。\r\ndef create_data():\r\n iris = load_iris()\r\n df = pd.DataFrame(iris.data, columns=iris.feature_names)\r\n df['label'] = iris.target\r\n df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']\r\n data = np.array(df.iloc[:100, [0, 1, -1]])\r\n for i in range(len(data)):\r\n if data[i,-1] == 0:\r\n data[i,-1] = -1\r\n # print(data)\r\n return data[:,:2], data[:,-1]\r\n\r\n# adaboost实现\r\n\"\"\"\r\n1.初始化训练数据的权值分布,n个训练样本数据,那么每一个训练样本最开始时都赋予相同的权值,w1=1/n\r\n2.训练弱分类器hi。如果某个训练样本点,被弱分类器hi准确地分类,那么在构造下一个训练集中,它对应的权值要减小;\r\n 如果某个训练样本点被错误分类,那么它的权值就应该增大。\r\n 权值更新过的样本集被用于训练下一个分类器,整个训练过程如此迭代地进行下去\r\n3.将各个训练得到的弱分类器组合成一个强分类器,加大分类误差率小的弱分类器的权重 \r\n 保证误差率低的弱分类器在最终分类器中占的权重较大,否则较小\r\n\"\"\"\r\nclass Adaboost:\r\n def __init__( self, x, y ,lr):\r\n self.x = x\r\n self.y = y\r\n self.lr = lr # 学习率\r\n self.classifiers = [] # 子分类器集合\r\n self.alphas = [] # 子分类器权值\r\n self.num_samples = len(self.x) # 样本个数\r\n self.weights = np.array( [1/self.num_samples] * self.num_samples ) # 数据权重\r\n\r\n def addClassifier(self, classifier=DecisionTreeClassifier(max_depth=1)):\r\n\r\n classifier.fit( self.x, self.y ,sample_weight=self.weights) # 训练子分类器\r\n y_predict = classifier.predict(self.x) # 子分类器预测\r\n\r\n error_rate = np.sum( (y_predict != self.y) * self.weights ) / np.sum(self.weights) # 计算加权错误率\r\n alpha = 0.5 * self.lr * np.log( (1 - error_rate) / error_rate ) # 计算alpha\r\n\r\n self.weights *= np.exp( -alpha * y_predict * self.y)\r\n self.weights /= np.sum(self.weights) # 更新数据权重\r\n\r\n self.classifiers.append(classifier) # 收集子分类器\r\n self.alphas.append(alpha) # 收集alpha\r\n\r\n \"\"\"\r\n 求出预测值\r\n \"\"\"\r\n def predict(self, x):\r\n y_predict = np.zeros([len(x)]).astype(\"float\")\r\n for classifier, alpha in zip(self.classifiers, self.alphas):\r\n y_predict += alpha * classifier.predict(x)\r\n y_predict = np.sign(y_predict)\r\n return y_predict\r\n\r\n def plot(self):\r\n y_predict = self.predict(self.x) # 子分类器预测\r\n error_rate = np.sum(y_predict != self.y)/self.num_samples # 算精度\r\n print(error_rate,self.num_samples)\r\n fig = plt.figure(figsize=(5, 4), dpi=140)\r\n\r\n xmin, xmax = np.min(self.x[:,0]-0.5, axis=0), np.max(self.x[:,0]+0.5, axis=0) # 算xy轴界限\r\n ymin, ymax = np.min(self.x[:,1]-0.5, axis=0), np.max(self.x[:,1]+0.5, axis=0)\r\n\r\n test_X,test_Y = np.mgrid[xmin:xmax:200j, ymin:ymax:200j ] #生成网络采样点\r\n grid_test = np.stack((test_X.flat,test_Y.flat) ,axis=1) #测试点\r\n #print(grid_test)\r\n grid_hat = self.predict(grid_test) # 预测分类值\r\n #print(grid_hat)\r\n grid_hat = grid_hat.reshape(test_X.shape) # 使之与输入的形状相同\r\n\r\n ax = fig.add_subplot(1, 1, 1)\r\n\r\n # 为了可以成功显示汉字\r\n matplotlib.pyplot.rcParams['font.sans-serif']=['SimHei']\r\n matplotlib.pyplot.rcParams['axes.unicode_minus'] = False\r\n\r\n ax.set( title='鸢尾花两个特征实现Adaboost分类(iter_num:{},error_rate:{})'.format( len(self.alphas), error_rate ))\r\n ax.set_xlim(xmin, xmax)\r\n ax.set_ylim(ymin, ymax)\r\n\r\n cm_light=matplotlib.colors.ListedColormap(['#DA70D6', '#8B0000', '#00CED1']) # 配置颜色\r\n ax.pcolormesh(test_X, test_Y, grid_hat, cmap=cm_light) # 预测值的显示\r\n ax.scatter(self.x[self.y==-1][:, 0], self.x[self.y==-1][:, 1], marker='o')\r\n ax.scatter(self.x[self.y==1][:, 0], self.x[self.y==1][:, 1], marker='x') # 训练点的散点图\r\n plt.show()\r\n\r\n\r\nx, y = create_data()# 构造数据\r\nmodel = Adaboost(x, y, lr=0.6)\r\nfor i in range(50):\r\n model.addClassifier(classifier=DecisionTreeClassifier(max_depth=1))\r\ny_predict = model.predict(x)\r\nmodel.plot() # 画出结果图\r\n","sub_path":"adaboost_wxc.py","file_name":"adaboost_wxc.py","file_ext":"py","file_size_in_byte":5059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232864781","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 4 13:10:36 2018\r\n\r\n@author: student\r\n\"\"\"\r\n#%%\r\n\r\nprint('''\r\nWELCOME TO \r\n \r\n | | /\\ |\\ | _____ |\\ /| /\\ |\\ |\r\n | | / \\ | \\ | | | \\ / | / \\ | \\ |\r\n |-----| | | | \\ | | ___ | \\/ | | | | \\ |\r\n | | |----| | \\ | | | | | |----| | \\ |\r\n | | | | | \\| |____| | | | | | \\|\r\n \r\n ''')\r\n\r\n\r\n\r\nvowels=['a','e','i','o','u','A','E','I','O','U']\r\nword=input('HELLO USER---------ASK SOMEONE TO ENTER A SUPER TOUGH WORD FOR YOU ')\r\nl=len(word)\r\nl1=list(word)\r\nl2=list(word)\r\nfor i in range(l):\r\n if word[i] not in vowels:\r\n l1[i]='_'\r\nprint(l1)\r\n\r\n\r\n\r\n\r\nhang0=''' __________\r\n '''\r\nhang1=''' \r\n__________\r\n |\r\n\r\n '''\r\nhang2='''\r\n__________\r\n |\r\n O\r\n '''\r\nhang3='''\r\n__________\r\n |\r\n O\r\n |\r\n |\r\n ''' \r\nhang4='''\r\n__________\r\n |\r\n O\r\n /|\\\\\r\n |\r\n '''\r\nhang5='''\r\n__________\r\n |\r\n O\r\n /|\\\\\r\n |\r\n / \\\\\r\n '''\r\nman='''\r\n__________\r\n\r\n\r\n\r\n\r\n O\r\n /|\\\\\r\n |\r\n / \\\\\r\n '''\r\n\r\nfor d in range(60):\r\n print()\r\n\r\n\r\nn=''\r\nfor i in l1:\r\n n=n+' '+i\r\nprint(\"WELCOME PLAYER-----GUESS THIS WORD TO SAVE THE MAN\",n) \r\nprint(man)\r\n\r\n\r\n\r\nwrong=0\r\n\r\nm=''\r\nwhile wrong<5 and '_' in l1:\r\n f=input('PRESS w TO GUESS THE ENTIRE WORD OR l TO GUESS A SINGLE LETTER ')\r\n if f=='w' or f=='W':\r\n wordd=input('ENTER A WORD ')\r\n if wordd==word:\r\n wrong=1\r\n break\r\n else:\r\n wrong=5\r\n \r\n else:\r\n letter=str(input('ENTER A LETTER '))\r\n n=''\r\n if letter in l2:\r\n ind=l2.index(letter)\r\n l1[ind]=letter\r\n print()\r\n \r\n for z in range(5):\r\n lll=l2[ind+1:]\r\n if letter in lll:\r\n ind1=lll.index(letter)\r\n ind=ind1+ind+1\r\n l1[ind]=letter\r\n \r\n else:\r\n wrong=wrong+1\r\n print('SORRY PLAYER-----LETTER IS ABSENT ')\r\n print()\r\n m=m+letter\r\n print()\r\n print()\r\n for j in l1:\r\n n=n+' '+j\r\n print(n)\r\n print('NUMBER OF WRONG ATTEMPTS=',wrong)\r\n print('WRONG LETTERS=',m)\r\n print()\r\n if wrong==0:\r\n print(hang0)\r\n elif wrong==1:\r\n print(hang1)\r\n elif wrong==2:\r\n print(hang2)\r\n elif wrong==3:\r\n print(hang3)\r\n elif wrong==4:\r\n print(hang4)\r\nif wrong==5: \r\n print()\r\n print(hang5)\r\n print(\"GAME OVER-----WRONG GUESS-----YOU KILLED THE MAN---THE WORD IS\",word)\r\n print(hang5)\r\nelse:\r\n print('CONGRATULATIONS PLAYER-----YOU GUESSED IT RIGHT AND SAVED THE MAN----THE WORD IS',word) \r\n print(man)\r\n \r\n#%%\r\n \r\n #%%\r\nn=int(input('enter'))\r\nfor i in range(n):\r\n print('bye')\r\n","sub_path":"hangman FINAL -ASHUTOSH.py","file_name":"hangman FINAL -ASHUTOSH.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382933961","text":"import os\nimport sys\n\n# first argument = regex to pngfiles\n# e.g. path/snapshot_%03d.png\n# second argument = output name\n# e.g. path/out.mp4\n\nplaySpeed = 0.25\n\n\npathToPNG = sys.argv[1]\npathToOutput = sys.argv[2]\nif os.access(pathToOutput,os.F_OK):\n os.remove(pathToOutput)\n\nos.system(\"avconv -i \"+pathToPNG+\" -b 15000000 -flags mv4 -r 32 -vf setpts=\"+str(1.0/playSpeed)+\"*PTS \"+pathToOutput)\n","sub_path":"bachelorthesis/evaluation/code/movie_from_pngs.py","file_name":"movie_from_pngs.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79900120","text":"from ..dissector import Dissector\nimport socket\n\nclass IPv4(Dissector):\n\n\tprotocol_name = \"Internet Protocol version 4 (IPv4)\"\n\tprotocol_id = \"ipv4\"\n\tparent_protocols = ['eth','wifi']\n\n\tdef _isValid(self, packet):\n\t\tisValid = False\n\t\ttry:\n\t\t\tp = packet['data']\n\t\t\tisValid = ord(p[0]) >> 4 == 0x04\n\t\texcept:\n\t\t\tpass\n\t\treturn isValid\n\n\tdef _process(self, packet):\n\t\tp = packet['data']\n\t\treturn {\n\t\t\t'protocol': ord(p[9]),\n\t\t\t'src': socket.inet_ntoa(p[12:16]),\n\t\t\t'dst': socket.inet_ntoa(p[16:20]),\n\t\t\t'payload': (20, len(p))\n\t\t}\n","sub_path":"core/dissectors/layer2/ipv4.py","file_name":"ipv4.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331343920","text":"from django.db import connection\nfrom django.test import Client\nfrom myapp.models import Rol\nfrom unittest import TestCase\nfrom urllib.parse import urlencode\nfrom .test_login import LoginTest\nimport json\n\nclass RolTest(TestCase):\n\n # Autenticación\n loginObj = LoginTest()\n token = loginObj.test()\n\n # Cabeceras generales\n headers = {\n 'HTTP_AUTHORIZATION': 'Bearer ' + token\n }\n\n client = Client(**headers)\n\n # Listado\n def list(self, cantidad):\n\n response = self.client.get('/roles/list/')\n\n cantidadRoles = len(json.loads(response.content)['roles'])\n\n self.assertEqual(cantidadRoles, cantidad)\n\n if cantidad > 4:\n self.update()\n\n # Eliminación de los proyectos en la base de datos\n def clean(self):\n\n with connection.cursor() as cursor:\n query = \"DELETE FROM v1.roles \" \\\n \"WHERE rolid != '628acd70-f86f-4449-af06-ab36144d9d6a' \" \\\n \"AND rolid != '53ad3141-56bb-4ee2-adcf-5664ba03ad65' \" \\\n \"AND rolid != '0be58d4e-6735-481a-8740-739a73c3be86' \" \\\n \"AND rolid != '8945979e-8ca5-481e-92a2-219dd42ae9fc';\"\n\n cursor.execute(query)\n\n self.store()\n\n # Almacenamiento\n def store(self):\n\n data = {\n 'rolname': 'Test',\n 'roldescripcion': 'Test'\n }\n\n response = self.client.post('/roles/store/',\n urlencode(data),\n content_type='application/x-www-form-urlencoded')\n\n self.assertEqual(response.status_code, 201)\n\n self.list(5)\n\n # Actualización\n def update(self):\n\n # Obtener la decisión almacenada anteriormente\n rol = Rol.objects.get(rolname='Test')\n\n data = {\n 'rolname': 'Test a',\n 'roldescripcion': 'Test a'\n }\n\n response = self.client.post('/roles/' + str(rol.rolid),\n urlencode(data),\n content_type='application/x-www-form-urlencoded')\n\n self.assertEqual(response.status_code, 200)\n\n self.delete()\n\n # Eliminación\n def delete(self):\n # Obtener el proyecto modificado anteriormente\n rol = Rol.objects.get(rolname='Test a')\n\n response = self.client.delete('/roles/delete/' + str(rol.rolid))\n\n self.assertEqual(response.status_code, 200)\n\n self.list(4)\n\n # Prueba\n def test(self):\n\n self.clean()","sub_path":"myapp/tests/test_rol.py","file_name":"test_rol.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"549954721","text":"#Script to run the SkinCancerDetection Prototype.\n#General\nimport numpy as np\nimport os\n\n#Model\n#from tensorflow.keras.models import load_model \n\n#Camera\nimport cv2\nimport matplotlib.pyplot as plt\nimport screeninfo\n\nimport time\n\n\n#Process flow. \nimport threading\nimport RPi.GPIO as IO\n\ndef Load_Model(model_name):\n global My_Model\n My_Model = load_model(model_name)\n\ndef Button_On_Interrupt(pin):\n if(Taking_Picture == True):\n global Picture_Taken\n Picture_Taken = True\n global Another_Picture\n Another_Picture = True\n #Inable more button pushes. \n buttonEventPushed.set()\n\n\ndef Display_FeedBack(diagnosis):\n #After prediction. Display information about the predicted skin leision. \n print(\"Diagnosis: \", diagnosis)\n \ndef Display_img_fullscreen(filename, name=\"test\"):\n _img_arr = cv2.imread(filename, cv2.COLOR_BGR2RGB)\n cv2.imshow(name, _img_arr)\n cv2.waitKey(1)\n \ndef Display_Black_Screen(width, height):\n print('BLACK SCREEN')\n \n newScreen = np.zeros((height, width), dtype=np.float32)\n \n window_name = 'test'\n cv2.imshow(window_name, newScreen)\n cv2.waitKey(1)\n \n\ndef Preprocess_Image(filename = None, x = 256, y = 192):\n #Preprocess and image to correct format for the model to consume.\n print('preprocess') \n _img_arr = cv2.imread(filename, cv2.COLOR_BGR2RGB)\n _img_arr = cv2.cvtColor(_img_arr, cv2.COLOR_BGR2RGB)\n new_arr = cv2.resize(_img_arr, (x, y))\n\n new_arr = np.array(new_arr)\n return new_arr\n\ndef Generate_Model_Output(model, filename):\n #Parameters: model, image name. \n input_data = Preprocess_Image(filename)\n\n prediction = model.predict(x = input_data.reshape(1, 192, 256, 3))\n\n pred_arr = prediction[0]\n print(pred_arr)\n max_index = np.argmax(pred_arr)\n print(max_index)\n\n cat_data = {\n 'df' : 1,\n 'nv' : 2, \n 'mel' : 3, \n 'bkl' : 4, \n 'bcc' : 5, \n 'akiec' : 6, \n 'vasc' : 0\n }\n rtn_df = None\n for df in cat_data: \n if cat_data[df] == max_index:\n rtn_df = df\n break\n \n #Return the type of skin leision. \n return rtn_df\n\n#Global variables. \nTimeOut = False\nTaking_Picture = False\nPicture_Taken = False\n\nload_model_this_time = False\nif __name__ == '__main__':\n #Test image. Debug.\n filename = 'ISIC_0024306.png'\n\n print(\"Starting.\")\n print(\"Model load...\") \n mod_name = '3sc35-084.hdf5'\n My_Model = None\n #loader_thread = threading.Thread(name = 'loader_thread', \n # target=Load_Model, args=(mod_name,))\n #loader_thread.start()\n if(load_model_this_time):\n My_Model = load_model('3sc35-084.hdf5')\n\n #GPIO Button Set up. \n print('rasp button set up')\n buttonPin = 21\n IO.setmode(IO.BCM)\n IO.setwarnings(False) \n IO.setup(buttonPin, IO.IN,pull_up_down=IO.PUD_UP)\n IO.add_event_detect(buttonPin, IO.FALLING, bouncetime=200)\n IO.add_event_callback(buttonPin, Button_On_Interrupt)\n buttonEventPushed = threading.Event()\n\n #Time out vars. \n delay = 20\n delay_retake_pict = 10\n img_counter = None\n cam = None\n screen = screeninfo.get_monitors()[0]\n width, height = screen.width, screen.height\n window_name = 'test'\n cv2.namedWindow(\"test\", cv2.WND_PROP_FULLSCREEN)\n cv2.moveWindow(window_name, screen.x - 1, screen.y - 1)\n cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n \n \n Display_Black_Screen(width, height)\n Display_Black_Screen(width, height)\n try:\n print('Start loop')\n while True:\n \n #Wait for button to be clicked to turn on the device. \n print('Waiting for button to turn on device.....')\n while not buttonEventPushed.wait():\n print('Press Button')\n \n print('BLACK SCREEN DOWN')\n \n img_count = 0 \n now = time.time()\n TimeOut = False\n \n \n \n cam = cv2.VideoCapture(0) \n\n #Reset button to take picture\n Taking_Picture = True\n buttonEventPushed = threading.Event()\n img_name = None\n \n while True:\n #Turn on display.\n ret, frame = cam.read()\n cv2.imshow(window_name, frame) \n print('CAMERA SCREEN ONE')\n if not ret:\n break\n \n k = cv2.waitKey(1)\n\n if(time.time() > now + delay):\n TimeOut = True\n \n if(TimeOut):\n Display_Black_Screen(width, height)\n break\n \n if(Picture_Taken):\n print('PICTURE TAKEN')\n Picture_Taken = False\n GO_ON = False\n img_count += 1 \n img_name = \"image_{}.png\".format(img_count)\n cv2.imwrite(img_name, frame)\n Display_img_fullscreen(img_name)\n #Waiting for model to load.\n #print('waiting for model to load')\n #loader_thread.join()\n #print('Model has been loaded')\n #Picture has been taken. Now Process the picture. \n diagnosis = \"good\"\n time.sleep(2)\n if(load_model_this_time):\n diagnosis = Generate_Model_Output(My_Model, img_name)\n \n #TODO take in frame maybe. \n Display_FeedBack(diagnosis)\n \n #Reset timeout. \n now = time.time()\n TimeOut = False\n Another_Picture = False\n print('hold pic inner loop')\n while True:\n if(time.time() > now + delay_retake_pict):\n TimeOut = True\n \n if(TimeOut):\n Display_Black_Screen(width, height)\n break\n \n if(Another_Picture):\n break \n print('out of pic inner loop')\n Another_Picture = False\n Picture_Taken = False\n if(TimeOut):\n Display_Black_Screen(width, height)\n break\n \n \n\n \n cam.release()\n #Reset Button. \n Taking_Picture = False\n buttonEventPushed = threading.Event()\n Display_Black_Screen(width, height)\n except:\n if(cam != None):\n cam.release()\n cv2.destroyAllWindows()\n \n \n \n","sub_path":"skinCancerDetection.py","file_name":"skinCancerDetection.py","file_ext":"py","file_size_in_byte":6944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"146687323","text":"import tensorflow as tf\nimport numpy as np\n\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n\n Weights = tf.Variable(tf.random_normal([in_size, out_size], name='Weights'))\n\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='biases')\n\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n\n return outputs\n\n\n## 定義要練習的資料\nx_data = np.linspace(-1,1,300)[:,np.newaxis]\nnoise = np.random.normal(0, 0.05, x_data.shape)\ny_data = np.square(x_data) - 0.5 + noise\n\n## 定義要訓練的資料\nx_train = tf.placeholder(tf.float32, [None, 1], name='x_input')\ny_train = tf.placeholder(tf.float32, [None, 1], name='y_input')\n\n## 定義隱藏層\nHidden_Layer1 = add_layer(x_train, 1, 10, activation_function=tf.nn.relu)\n## 定義輸出層\nOutput_Layer = add_layer(Hidden_Layer1, 10, 1, activation_function=None)\n\n## 計算誤差值\nloss = tf.reduce_mean(tf.reduce_sum(\n tf.square(y_train - Output_Layer), reduction_indices=[1]), name='loss')\n\n## 定義訓練步驟\ntrain_step = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n\n for i in range(1001):\n sess.run(train_step,\n feed_dict={x_train:x_data, y_train:y_data})\n if(i % 50 == 0):\n print(sess.run(loss,\n feed_dict={x_train:x_data, y_train:y_data}))\n\n\n\n","sub_path":"Notes/Tensorflow_Python_Test/morvanzhou/11.bulid a neural network.py","file_name":"11.bulid a neural network.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131874290","text":"import sys\nimport os\nimport pytest\nfrom rasterstats.utils import (stats_to_csv, bbox_to_pixel_offsets,\n get_percentile, remap_categories)\nfrom rasterstats import zonal_stats\nfrom rasterstats.utils import VALID_STATS\n\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nDATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\nraster = os.path.join(DATA, 'slope.tif')\n\n\ndef test_csv():\n polygons = os.path.join(DATA, 'polygons.shp')\n stats = zonal_stats(polygons, raster, stats=\"*\")\n csv = stats_to_csv(stats)\n assert csv.split()[0] == ','.join(sorted(VALID_STATS + ['__fid__']))\n\n\ndef test_categorical_csv():\n polygons = os.path.join(DATA, 'polygons.shp')\n categorical_raster = os.path.join(DATA, 'slope_classes.tif')\n stats = zonal_stats(polygons, categorical_raster, categorical=True)\n csv = stats_to_csv(stats)\n assert csv.split()[0] == \"1.0,2.0,5.0,__fid__\"\n\n\ndef test_bbox_offbyone():\n # Make sure we don't get the off-by-one error in calculating src offset\n rgt = (-4418000.0, 250.0, 0.0, 4876500.0, 0.0, -250.0)\n geom_bounds = [4077943.9961, -3873500.0, 4462000.0055, -3505823.7582]\n rshape = (37000, 35000)\n so = bbox_to_pixel_offsets(rgt, geom_bounds, rshape)\n assert so[1] + so[3] == rshape[1]\n\n # Another great example\n # based on https://github.com/perrygeo/python-raster-stats/issues/46\n rgt = (151.2006, 0.025, 0.0, -25.4896, 0.0, -0.025)\n geom_bounds = [153.39775866026284, -28.903022885889843,\n 153.51344076545288, -28.80117672778147]\n rshape = (92, 135)\n # should only be 5 pixels wide, not 6 due to rounding errors\n assert bbox_to_pixel_offsets(rgt, geom_bounds, rshape) == (87, 132, 5, 3)\n\n\ndef test_get_percentile():\n assert get_percentile('percentile_0') == 0.0\n assert get_percentile('percentile_100') == 100.0\n assert get_percentile('percentile_13.2') == 13.2\n\n with pytest.raises(ValueError):\n get_percentile('percentile_101')\n\n with pytest.raises(ValueError):\n get_percentile('percentile_-1')\n\n with pytest.raises(ValueError):\n get_percentile('percentile_foobar')\n\n\ndef test_remap_categories():\n feature_stats = {1: 22.343, 2: 54.34, 3: 987.5}\n category_map = {1: 'grassland', 2: 'forest'}\n new_stats = remap_categories(category_map, feature_stats)\n assert 1 not in new_stats.keys()\n assert 'grassland' in new_stats.keys()\n assert 3 in new_stats.keys()\n\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88808190","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------\n# Copyright 2016-2017 ARM Limited or its affiliates\n#\n# SPDX-License-Identifier: Apache-2.0\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 json, logging, binascii\nfrom builtins import bytes\nfrom manifesttool.v1.verify import main as verify_v1\n\nLOG = logging.getLogger(__name__)\n\ndef skipAhead(code):\n rc = 0\n if code == 0x81:\n rc = 1\n if code == 0x82:\n rc = 2\n if code == 0x83:\n rc = 3\n if code == 0x83:\n rc = 4\n return rc\n\ndef main(options):\n LOG.debug(\"Attempting to determine manifest version...\")\n # 32 bytes is currently sufficient to detect the manifest type.\n headerData = bytes(options.input_file.read(32))\n options.input_file.seek(0)\n # In both cases, the manifest starts with a DER SEQUENCE tag.\n if headerData[0] != 0x30:\n LOG.critical(\"input file is not a manifest.\")\n return 1\n # skip past the length\n pos = 2 + skipAhead(headerData[1])\n\n version = None\n # For version 1, the first object in the SEQUENCE should be another SEQUENCE\n if headerData[pos] == 0x30:\n version = 1\n # For version 2+, a CMS wrapper is used, so the tag should be an OID tag\n if headerData[pos] == 0x06:\n version = 2\n\n if version == None:\n LOG.critical(\"No recognized manifest format found.\")\n return 1\n\n # For now, we will assume that 2+ means 2.\n parser = {\n 1 : verify_v1\n }.get(version, None)\n if not parser:\n LOG.critical(\"Unrecognized manifest version.\")\n return 1\n return parser(options)\n","sub_path":"manifesttool/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645512389","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\n# 所有网络类要继承nn.Module\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__() # 调用父类构造函数\n self.conv1 = nn.Conv2d(1, 20, 5, 1) # (in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)\n self.conv2 = nn.Conv2d(20, 50, 5, 1) # 这一层的in_channels正好是上一层的out_channels\n self.fc1 = nn.Linear(4*4*50, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2) # kernel_size=2, stride=2,pooling之后的大小除以2\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4*4*50) # 展开成 (z, 4*4*50),其中z是通过自动推导得到的,所以这里设置为-1,这里相当于展开成行向量,便于后续全连接\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return F.log_softmax(x, dim=1) # log_softmax 即 log(softmax(x));dim=1对行进行softmax,因为上面x.view展开成行向量了,log_softmax速度和数值稳定性都比softmax好一些\n \ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train() # 告诉pytorch,这是训练阶段 https://stackoverflow.com/a/51433411/2468587\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad() # 每个batch的梯度重新累加\n output = model(data)\n loss = F.nll_loss(output, target) # 这里的nll_loss就是Michael Nielsen在ch3提到的log-likelihood cost function,配合softmax使用,batch的梯度/loss要求均值mean\n loss.backward() # 求loss对参数的梯度dw\n optimizer.step() # 梯度下降,w'=w-η*dw\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef test(args, model, device, test_loader):\n model.eval() # 告诉pytorch,这是预测(评价)阶段\n test_loss = 0\n correct = 0\n with torch.no_grad(): # 预测时不需要误差反传,https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/19615/2\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss,预测时的loss求sum,L54再求均值\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef plot1digit(data_loader):\n\n import numpy as np\n import matplotlib.pyplot as plt\n\n examples = enumerate(data_loader)\n batch_idx, (Xs, ys) = next(examples) # 读取到的是一个batch的所有数据\n\n X=Xs[0].numpy()[0] # Xs[0]取出batch中的第一个数据,由tensor转换为numpy,因为pytorch tensor的格式是[channel, height, width],所以最后[0]取出其第一个通道的[h,w]\n y=ys[0].numpy() # y没有通道,就一个标量值\n\n np.savetxt('../../../fig/%d.csv'%y, X, delimiter=',')\n \n plt.imshow(X, cmap='Greys') # or 'Greys_r'\n plt.savefig('../../../fig/%d.png'%y)\n plt.show()\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\n parser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n \n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transforms.Compose([ # https://discuss.pytorch.org/t/can-some-please-explain-how-the-transforms-work-and-why-normalize-the-data/2461/3\n transforms.ToTensor(), # 把[0,255]的(H,W,C)的图片转换为[0,1]的(channel,height,width)的图片\n transforms.Normalize((0.1307,), (0.3081,)) # 进行z-score标准化,这两个数分别是MNIST的均值和标准差\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.test_batch_size, shuffle=True, **kwargs)\n\n # plot1digit(train_loader)\n\n model = Net().to(device)\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n\n for epoch in range(1, args.epochs + 1):\n train(args, model, device, train_loader, optimizer, epoch)\n test(args, model, device, test_loader)\n\n if (args.save_model):\n torch.save(model.state_dict(),\"mnist_cnn.pt\")\n \nif __name__ == '__main__':\n main()\n","sub_path":"src/pytorch/mnist/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145534591","text":"import requests\nimport json\nimport time\nimport datetime\nimport webbrowser\nimport os\nimport sys\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport urllib\nfrom urllib.parse import urlparse\n#from utilities import print_active_function_name,print_result,print_request_result,print_return\nfrom openbanking_utilities_module import log_process_start,log_process_finish,log_process_input_param,log_process_result,log_process_value\nfrom openbanking_utilities_module import log_process_section_start,log_process_section_finish,log_http_request_result,log_process_error\nfrom openbanking_configuration_module import get_configuration,get_configuration_param\nfrom openbanking_globals import *\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\ndef boc_get_parameters(api):\n process='get_parameters'\n log_process_start(process)\n\n bankCodeName='bankofcyprus'\n ts = time.time()\n currentTimeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')\n\n bankID=get_configuration_param('bankID',master_configuration,bankCodeName)\n bankName=get_configuration_param('bankName',master_configuration,bankCodeName)\n redirect_uri=get_configuration_param('redirect_uri',master_configuration,bankCodeName)\n app_name=get_configuration_param('application_name',master_configuration,bankCodeName)\n client_id=get_configuration_param('client_id',master_configuration,bankCodeName)\n client_secret=get_configuration_param('client_secret',master_configuration,bankCodeName)\n api_uri=get_configuration_param('api_uri',master_configuration,bankCodeName)\n journeyId=get_configuration_param('journeyId',master_configuration,bankCodeName)\n originSourceId=get_configuration_param('originSourceId',master_configuration,bankCodeName)\n originChannelId=get_configuration_param('originChannelId',master_configuration,bankCodeName)\n originDeptId=get_configuration_param('originDeptId',master_configuration,bankCodeName)\n originUserId=get_configuration_param('originUserId',master_configuration,bankCodeName)\n originEmployeeId=get_configuration_param('originEmployeeId',master_configuration,bankCodeName)\n originTerminalId=get_configuration_param('originTerminalId',master_configuration,bankCodeName)\n correlationId=get_configuration_param('correlationId',master_configuration,bankCodeName)\n lang=get_configuration_param('lang',master_configuration,bankCodeName)\n tppId=get_configuration_param('tppId',master_configuration,bankCodeName)\n\n functionRequest = 'GET'\n if api=='get_access_token':\n endpoint = 'df-boc-org-sb/sb/psd2/oauth2/token'\n elif api=='get_authorization_token':\n endpoint = 'df-boc-org-sb/sb/psd2/oauth2/token'\n elif api=='get_subscriptionId':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/subscriptions'\n elif api=='get_subscription_details':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/subscriptions/{}'\n elif api=='update_subscription':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/subscriptions/{}'\n elif api=='get_account_subscriptions':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/subscriptions/accounts/{}'\n elif api=='delete_subscription':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/subscriptions/{}'\n functionRequest = 'DELETE'\n elif api=='get_customerConsent':\n endpoint = 'https://sandbox-apis.bankofcyprus.com/df-boc-org-sb/sb/psd2/oauth2/authorize'\n elif api=='get_subscription_Accounts':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/accounts'\n elif api=='get_subscription_Customers':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/customers'\n elif api=='get_Accounts_List':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/accounts'\n elif api=='get_account_details':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/accounts/{}'\n elif api=='get_account_transactions':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/accounts/{}/statement'\n elif api=='get_account_balances':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/accounts/{}/balance'\n elif api=='get_payments':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/accounts/{}'\n elif api=='payment_initiate':\n endpoint = 'df-boc-org-sb/sb/jwssignverifyapi/sign'\n elif api=='payment_create':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments'\n elif api=='payment_checkfunds':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/fundAvailability'\n functionRequest = 'POST'\n elif api=='payment_authorize':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/{}/authorize'\n elif api=='get_payment_details':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/{}'\n functionRequest = 'GET'\n elif api=='get_payment_status':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/{}/status'\n functionRequest = 'GET'\n elif api=='delete_payment':\n endpoint = 'df-boc-org-sb/sb/psd2/v1/payments/{}'\n functionRequest = 'DELETE'\n else:\n endpoint = 'df-boc-org-sb/????????????????'\n \n log_process_value('api',api)\n log_process_value('endpoint',endpoint)\n\n params={\n 'bankCodeName' :bankCodeName\n ,'bankID' :bankID \n ,'bankName' :bankName\n ,'app_Name' :app_name\n ,'client_id' :client_id\n ,'client_secret' :client_secret\n ,'redirect_uri' :redirect_uri\n ,'api' :api\n ,'api_uri' :api_uri\n ,'endpoint' :endpoint\n ,'function' :functionRequest\n ,'tppId' :tppId\n ,'journeyId' :journeyId\n ,'originSourceId' :originSourceId\n ,'originChannelId' :originChannelId\n ,'originDeptId' :originDeptId\n ,'originUserId' :originUserId\n ,'originEmployeeId' :originEmployeeId\n ,'originTerminalId' :originTerminalId\n ,'correlationId' :correlationId\n ,'lang' :lang\n ,'currentTimeStamp' :datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')\n ,'debuglevel_one' :debuglevel_one\n ,'debuglevel_two' :debuglevel_two\n ,'debuglevel_three' :debuglevel_three\n }\n log_process_result('api_params',params)\n\n log_process_finish()\n return params\n\ndef boc_prepare_request_standard(access_token,subscriptionId,api_params,url_parameter=''):\n process='prepare_standard_request'\n log_process_start(process)\n\n headers = {\n 'content-type': 'application/json',\n 'accept': 'application/json',\n #'app_name': api_params['app_Name'],\n 'journeyId': api_params['journeyId'],\n #'originSourceId': api_params['originSourceId'], \n #'originChannelId': api_params['originChannelId'],\n #'originDeptId': api_params['originDeptId'],\n #'originUserId': api_params['originUserId'],\n #'originEmployeeId':api_params['originEmployeeId'],\n #'originTerminalId': api_params['originTerminalId'],\n #'correlationId': api_params['correlationId'],\n #'lang': api_params['lang'],\n 'tppId': api_params['tppId'],\n 'timeStamp': api_params['currentTimeStamp'],\n #'Authorization': 'Bearer {}'.format(access_token),\n #'subscriptionId': subscriptionId,\n #'lang': ''\n }\n #print('headers=',headers)\n #print('--------')\n #params = params_standard.copy()\n if subscriptionId:\n if subscriptionId!='':\n header_subscriptionId={'subscriptionId': subscriptionId}\n headers.update(header_subscriptionId)\n if access_token:\n if access_token!='':\n header_token={'Authorization': 'Bearer {}'.format(access_token)}\n headers.update(header_token)\n if api_params['originSourceId'] !='':\n headers.update({'originSourceId': api_params['originSourceId']})\n if api_params['originUserId'] !='':\n headers.update({'originUserId': api_params['originUserId']})\n if api_params['originEmployeeId'] !='':\n headers.update({'originEmployeeId': api_params['originEmployeeId']})\n if api_params['originChannelId'] !='':\n headers.update({'originChannelId': api_params['originChannelId']})\n if api_params['originDeptId'] !='':\n headers.update({'originDeptId': api_params['originDeptId']})\n if api_params['originChannelId'] !='':\n headers.update({'originChannelId': api_params['originChannelId']})\n if api_params['originTerminalId'] !='':\n headers.update({'originTerminalId': api_params['originTerminalId']})\n if api_params['correlationId'] !='':\n headers.update({'correlationId': api_params['correlationId']})\n if api_params['lang'] !='':\n headers.update({'lang': api_params['lang']})\n if api_params['lang'] !='':\n headers.update({'lang': api_params['lang']})\n\n log_process_result('headers',headers)\n\n params = {\n 'client_id': api_params['client_id'],\n 'client_secret': api_params['client_secret'],\n }\n log_process_result('params',params)\n\n url=api_params['api_uri']+api_params['endpoint'].format(url_parameter)\n log_process_result('api_url',url)\n\n request_params={\n 'headers' :headers\n ,'parameters' :params\n ,'url' :url\n }\n log_process_result('request_params',request_params)\n\n log_process_finish()\n return request_params\n \n\n################################################################\n### access tokens ###\n################################################################\ndef boc_get_access_token():\n api='get_access_token'\n log_process_start(api)\n\n access_token=''\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard('','',api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n headers = {\n 'accept': 'application/json'\n }\n payload = {\n 'grant_type': 'client_credentials',\n 'client_id': api_params['client_id'],\n 'client_secret': api_params['client_secret'],\n 'scope': 'TPPOAuth2Security'\n }\n r = requests.post(api_url,data=payload,headers=headers)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n access_token=None\n error_text=r.text\n error_code=1\n else:\n access_token = response['access_token'] \n\n log_process_result('access_token',access_token)\n log_process_finish()\n return access_token\n\ndef boc_get_authorization_token(access_token,authorization_code):\n api='get_authorization_token'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,'',api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.post(api_url,headers=headers,params=params)\n headers = {\n 'accept': 'application/json'\n }\n payload = {\n 'code': authorization_code,\n 'client_id': api_params['client_id'],\n 'client_secret': api_params['client_secret'],\n 'grant_type': 'authorization_code',\n 'scope': 'UserOAuth2Security'\n }\n\n r = requests.post(api_url,headers=headers,data=payload)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n authorization_token=None\n error_text=r.text\n error_code=1\n else:\n authorization_token = response['access_token'] \n\n log_process_result('authorization_token',authorization_token)\n\n log_process_finish()\n return authorization_token\n\n################################################################\n### subscription apis ###\n################################################################\ndef boc_get_subscription_details(access_token,subscriptionId): \n api='get_subscription_details'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,'',api_params,subscriptionId)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if api_params['debuglevel_two']>0:\n print(r.status_code,r.json())\n\n #print(r.header)\n #print(r.data)\n\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n\n log_process_finish()\n return response\n\ndef boc_get_subscription_selectedAccounts(access_token,subscriptionId): ###even if pending\n api='get_subscription_selectedAccounts'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n subscription_details=boc_get_subscription_details(access_token,subscriptionId)\n \n if not subscription_details:\n error_text=r.text\n error_code=1\n acts=[] #None\n else:\n acts=subscription_details[0]['selectedAccounts']\n \n log_process_finish()\n return acts\n\ndef boc_get_subscription_Accounts(access_token,subscriptionId): \n api='get_subscription_Accounts'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n #print(r.status_code,r.json())\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=[] #None\n \n log_process_finish()\n return response\n\ndef boc_get_subscription_Customers(access_token,subscriptionId): \n api='get_subscription_Customers'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n #print(r.status_code,r.json())\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=[] #None\n \n log_process_finish()\n return response\n\ndef boc_delete_subscription(access_token,subscriptionId):\n api='delete_subscription'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,'',api_params,subscriptionId)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.delete(api_url,headers=headers,params=params)\n reply_code=r.status_code\n #response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n response = {\"message\":\"subscription \"+subscriptionId+\" not found\"}\n else:\n #fix: when 200 to return text message as json\n response = {\"message\":\"OK-subscription \"+subscriptionId+\" Deleted\"}\n log_process_finish()\n return response\n################################################################\n### accounts apis ###\n################################################################\ndef boc_list_accounts(access_token,subscriptionId): \n api='get_Accounts_List'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n if debuglevel_two>0:\n print('---api_url---',api_url)\n print('---headers---',headers)\n print('---params---',params)\n\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n \n if debuglevel_three>0:\n print(r.status_code,r.text)\n \n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\n\ndef boc_get_account_details(access_token, subscriptionId, account_id):\n api='get_account_details'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,account_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\ndef boc_get_account_balances(access_token, subscriptionId, account_id):\n api='get_account_balances'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,account_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\ndef boc_get_account_transactions(access_token, subscriptionId, account_id,sdate='',edate='',ntrans=9999):\n api='get_account_transactions'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,account_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params_standard=request_params['parameters']\n params_transactions = {\n 'startDate': '01/01/2010'\n ,'endDate': '31/12/2018'\n ,'maxCount': ntrans\n }\n params = params_standard.copy()\n params.update(params_transactions)\n\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\ndef boc_get_account_subscriptions(access_token,account_id):\n api='get_account_subscriptions'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,'',api_params,account_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=[]\n log_process_finish()\n return response\n################################################################\n### payments apis ###\n################################################################\ndef boc_payment_fundsavailability(access_token,subscriptionId,payment):\n api='payment_checkfunds'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n\n paymentData=json.dumps(payment)\n\n r = requests.post(api_url,headers=headers,params=params,data=paymentData)\n reply_code=r.status_code\n response = r.json()\n\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n else:\n response=1\n \n log_process_finish()\n return response\n\ndef boc_get_payments(access_token, subscriptionId,accountId):\n api='get_payments'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,accountId)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\n\n\ndef boc_get_payment_status(access_token,subscriptionId,payment_id):\n api='get_payment_status'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,payment_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n if not r.status_code == requests.codes.ok:\n raise Exception(r.text)\n payments = r.json()\n #res=print_result('payment_status=',payments)\n log_process_finish()\n return payments\n\ndef boc_delete_payment(access_token,subscriptionId,payment_id):\n api='delete_payment'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,payment_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.delete(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n log_process_finish()\n return response\n\ndef boc_get_payment_details(access_token,subscriptionId,payment_id):\n api='get_payment_details'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,payment_id)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n r = requests.get(api_url,headers=headers,params=params)\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n #payment_details = r.json()\n #res=print_result('payment_details=',payment_details)\n log_process_finish()\n return response\n################################################################\n### create payment apis ###\n################################################################\ndef boc_payment_initiate(access_token, subscriptionId, DBaccountId ,CRaccountId,Amount,Currency,Details):\n api='payment_initiate'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n params.update({'subscriptionId': subscriptionId}) \n\n paym = {\n \"debtor\":{\"bankId\":\"\",\"accountId\":DBaccountId},\n \"creditor\":{\"bankId\":\"\",\"accountId\":CRaccountId,\"name\":\"zorbas\",\"address\":\"athalassas\"},\n \"transactionAmount\":{\"amount\":Amount,\"currency\":Currency,\"currencyRate\":\"\"},\n \"paymentDetails\":Details,\n \"endToEndId\":\"\",\n \"terminalId\":\"\",\n \"branch\":\"\",\n \"executionDate\":\"\",\n \"valueDate\":\"\",\n #\"RUB\":{\"voCode\":\"lezeidne\",\"BIK\":\"ublepipunzokcevjozejkedhanticew\",\"INN\":\"topajimpopcuvirobil\",\"correspondentAccount\":\"6226014357403233\"}\n #\"totalDebitAmount\":{\"amount\":Amount,\"currency\":Currency,\"currencyRate\":\"\"},\n \"refNumber\":\"123456789\"\n }\n\n paymentRequest=json.dumps(paym)\n #the reverse is: paym=json.loads(paymentRequest)\n\n if api_params['debuglevel_two']>0:\n print('url-----',api_url)\n print('params----',params)\n print('headers---',headers)\n print('data------',paymentRequest)\n\n \n r = requests.post(api_url,headers=headers,params=params,data=paymentRequest)\n #print(r)\n #reply_code=r.status_code\n #response = r.json()\n if api_params['debuglevel_two']>0:\n print('results---',r.status_code,r.text)\n \n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n else:\n response = r.json()\n #{\n #'payload': '...',\n #'signatures': [\n # {'protected': 'eyJhbGciOiJSUzI1NiJ9''signature': '...'}\n #]\n #}\n payload = response['payload']\n #res=print_result('payload=',payload)\n signatures = response['signatures']\n #res=print_result('signatures=',signatures)\n log_process_finish()\n return response\n\ndef boc_payment_create(access_token, subscriptionId, payload):\n api='payment_create'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n params.update({'subscriptionId': subscriptionId}) \n\n paymentData=json.dumps(payload)\n #res=print_result('paymentLoad=',paymentData)\n #paymentData=payLoad\n #print('@@@@@',payLoad)\n #print('@@@@@',signature)\n if api_params['debuglevel_two']>0:\n print('url-----',api_url)\n print('params----',params)\n print('headers---',headers)\n print('data------',paymentData)\n \n r = requests.post(api_url,headers=headers,params=params,data=paymentData)\n if api_params['debuglevel_two']>0:\n print('results---',r.status_code,r.text)\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n else:\n response = r.json()\n payment = r.json()\n #{\n # \"authCodeNeeded\": true,\n # \"payment\": {\n # \"paymentId\": \"PmtId000001_1518607567498\",\n # \"transactionTime\": \"1511779237\",\n # \"status\": {\n # \"code\": \"PNDG\",\n # \"description\": [\n # \"Payment in pending status\"\n # ],\n # \"refNumber\": \"CYP12345\"\n # },\n # \"debtor\": {\n # \"bankId\": \"\",\n # \"accountId\": \"351012345671\"\n # },\n # \"creditor\": {\n # \"bankId\": \"\",\n # \"accountId\": \"351092345672\",\n # \"name\": null,\n # \"address\": null\n # },\n # \"transactionAmount\": {\n # \"amount\": 3.55,\n # \"currency\": \"EUR\",\n # \"currencyRate\": \"string\"\n # },\n # \"charges\": null,\n # \"totalCharges\": \"1100.00\",\n # \"endToEndId\": \"string\",\n # \"paymentDetails\": \"test sandbox \",\n # \"terminalId\": \"string\",\n # \"branch\": \"\",\n # \"RUB\": null,\n # \"executionDate\": \"14/02/2018\",\n # \"valueDate\": \"14/02/2018\",\n # \"totalDebitAmount\": null\n # }\n #}\n paymAuthNeeded=payment['authCodeNeeded']\n paym=payment['payment']\n paymentId=paym['paymentId']\n\n log_process_finish()\n return response\n\ndef boc_payment_authorize(access_token, subscriptionId, paymentId,authorization_code):\n api='payment_authorize'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,subscriptionId,api_params,paymentId)\n api_url=request_params['url']\n headers=request_params['headers']\n params=request_params['parameters']\n params.update({'subscriptionId': subscriptionId}) \n\n auth = {\"transactionTime\": api_params['currentTimeStamp'],\"authCode\": authorization_code}\n authData=json.dumps(auth)\n if api_params['debuglevel_two']>0:\n print('url-----',api_url)\n print('params----',params)\n print('headers---',headers)\n print('data------',authData)\n \n r = requests.post(api_url,headers=headers,params=params,data=authData)\n reply_code=r.status_code\n if api_params['debuglevel_two']>0:\n print('results---',r.status_code,r.text)\n\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n paymStatus=r.text\n else:\n #response = r.json()\n #{\n # \"code\": \"CLPT\",\n # \"description\": [\n # \" The transaction has passed all validations and was successfully posted in bank systems\"\n # ],\n # \"refNumber\": \"1524485123473408\"\n #}\n reply_code=r.status_code\n response = r.json()\n paymStatus=response['code']\n paymRefNum=response['refNumber']\n paymStatusDesc=response['description']\n log_process_finish()\n return response\n\ndef boc_make_payment(access_token,subscriptionId,DBaccountId,CRaccountId,Amount,Currency,Details):\n api='make_payment'\n log_process_start(api)\n\n paymentId=None \n api_params=boc_get_parameters(api)\n paym={'bankId':'?','accountId':DBaccountId,'transaction':{'amount':Amount,'currency':Currency,'currencyRate':''}}\n \n fundsavail=boc_payment_fundsavailability(access_token,subscriptionId,paym)\n if fundsavail != 1:\n return None\n\n signature=boc_payment_initiate(access_token, subscriptionId, DBaccountId ,CRaccountId,Amount,Currency,Details)\n if not signature:\n return None\n \n payment=boc_payment_create(access_token, subscriptionId, signature)\n if not payment:\n return None\n \n if api_params['debuglevel_three']>0:\n print('payment---',payment)\n\n paymAuthNeeded=payment['authCodeNeeded']\n paym=payment['payment']\n paymentId=paym['paymentId']\n paymstatus=paym['status']\n paymentRefNum=paymstatus['refNumber']\n paymentStatusCode=paymstatus['code']\n paymentStatusDesc=paymstatus['description'][0]\n\n if api_params['debuglevel_two']>0:\n print('paymAuthNeeded=',paymAuthNeeded)\n print('paymentId=',paymentId)\n print('paymentRefNum=',paymentRefNum)\n print('paymentStatusCode=',paymentStatusCode)\n print('paymentStatusDesc=',paymentStatusDesc)\n\n## if paymAuthNeeded==True:\n## result=boc_payment_authorize(access_token, subscriptionId, paymentId)\n## print(result)\n## if result:\n## paymentStatusCode=result['code']\n## paymRefNum=result['refNumber']\n## paymStatusDesc=result['description']\n## print('paymentStatusCode=',paymentStatusCode)\n## print('paymStatusDesc=',paymStatusDesc)\n## print('paymRefNum=',paymRefNum)\n## else:\n## print('@@@ERROR-not authorized')\n## else:\n## print('paymentId=',paymentId)\n## print('paymentRefNum=',paymentRefNum)\n## print('paymentStatusCode=',paymentStatusCode)\n## print('paymentStatusDesc=',paymentStatusDesc)\n\n log_process_finish()\n return payment\n\ndef boc_authorize_payment(access_token,subscriptionId,paymentId):\n api='authorize_payment'\n\n api_params=boc_get_parameters(api)\n result='?'\n payment_status=boc_get_payment_status(access_token,subscriptionId,paymentId)\n #payment_details=boc_get_payment_details(access_token,subscriptionId,paymentId)\n statusCode=payment_status['status']['code']\n #print(statusCode)\n if statusCode!='PNDG':\n result='this payment is not PNDG'\n else:\n msg=\"enter the OTP for payment id {paymentID}:\".format(paymentID=paymentId)\n authorization_code = input(msg)\n\n authorization_result=boc_payment_authorize(access_token,subscriptionId,paymentId,authorization_code)\n print('authorization_result=',authorization_result)\n \n if authorization_result:\n paymStatus=authorization_result['code']\n paymRefNum=authorization_result['refNumber']\n paymStatusDesc=authorization_result['description']\n print('paymStatus=',paymStatus)\n print('paymStatusDesc=',paymStatusDesc[0])\n print('paymRefNum=',paymRefNum)\n result=json.dumps(paymStatus)+'-'+json.dumps(paymStatusDesc)+'-'+json.dumps(paymRefNum)\n else:\n result='ERROR-not authorized:'+error_text\n \n log_process_finish()\n return result \n\n\n################################################################\n### create subscription apis ###\n################################################################\ndef boc_get_subscriptionId(access_token,SubscriptionRequest): \n api='get_subscriptionId'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(access_token,'',api_params)\n api_url=request_params['url']\n headers=request_params['headers']\n headers.update({'app_name': api_params['app_Name']})\n params=request_params['parameters']\n r = requests.post(api_url,headers=headers,params=params,data=SubscriptionRequest)\n reply_code=r.status_code\n response = r.json()\n if not((r.status_code == requests.codes.ok) or (r.status_code == 201)):\n error_text=r.text\n error_code=1\n response=None\n subscriptionId=None\n else:\n subscriptionId = response['subscriptionId']\n log_process_finish()\n return subscriptionId\ndef boc_get_customer_Consent(subscriptionId):\n api='get_customerConsent'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n\n url=api_params['endpoint']+\"?\"\n url=url+\"response_type=code\"\n url=url+\"&redirect_uri=\"+api_params['redirect_uri']\n url=url+\"&scope=UserOAuth2Security\"\n url=url+\"&client_id=\"+api_params['client_id']\n url=url+\"&subscriptionid=\"+subscriptionId\n\n webbrowser.open(url, new=0)\n log_process_finish()\n return 1\n\ndef boc_update_subscription(subscriptionId,authorization_token,authorization_code,subscription_options): \n api='update_subscription'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n request_params=boc_prepare_request_standard(authorization_token,'',api_params,subscriptionId)\n api_url=request_params['url']\n if api_params['debuglevel_three']>0:\n print('url-----',api_url)\n params=request_params['parameters']\n params.update({'subscriptionId': subscriptionId}) \n if api_params['debuglevel_three']>0:\n print('params----',params)\n\n headers=request_params['headers']\n if api_params['debuglevel_three']>0:\n print('headers---',headers)\n if api_params['debuglevel_three']>0:\n print('data------',subscription_options)\n \n r = requests.patch(api_url,headers=headers,params=params,data=subscription_options)\n if api_params['debuglevel_three']>0:\n print(r,r.json())\n\n reply_code=r.status_code\n response = r.json()\n if not r.status_code == requests.codes.ok:\n error_text=r.text\n error_code=1\n response=None\n updateStatus=None\n else:\n updateStatus=response['status']\n\n log_process_finish()\n return updateStatus\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef wait_for_authorization():\n process='wait_for_user_authorization'\n log_process_start(process)\n\n authorization_code=None\n codefile = r'''c:\\users\\user\\documents\\code.txt'''\n try:\n os.remove(codefile)\n except:\n x=1\n n=0\n #print(n,'waiting....')\n while n<120:\n if ((n % 10) == 0):\n print(n,'waiting....')\n \n time.sleep(1) # Delay for 1 sec\n n=n+1\n #runServer()\n ok=0\n try:\n thefile = open(codefile, 'r')\n ok=1\n except:\n ok=0\n if ok==1:\n authorization_code=thefile.read()\n thefile.close\n print('---code_received---',authorization_code+'<--')\n n=99999 \n\n log_process_finish()\n return authorization_code\n#=====================================================\ndef boc_create_subscription(SubscriptionData): \n api='new_subscription'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n\n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n\n subscription_options=json.loads(SubscriptionData)\n SubscriptionData=json.dumps(subscription_options)\n\n subscriptionId=boc_get_subscriptionId(access_token,SubscriptionData)\n if not subscriptionId:\n print('ERROR:',error_text)\n return subscriptionId\n \n boc_get_customer_Consent(subscriptionId)\n authorization_code=wait_for_authorization()\n if not authorization_code:\n error_text='authorization NOT received'\n print('ERROR:',error_text)\n subscriptionId=None\n return subscriptionId\n\n if api_params['debuglevel_two']>0:\n print('subscriptionId=', subscriptionId)\n print('authorization_code=', authorization_code)\n \n #access_token=boc_get_access_token()\n authorization_token=boc_get_authorization_token(access_token,authorization_code)\n if not authorization_token:\n #raise Exception(error_text)\n print('ERROR:',error_text)\n SubscriptionDetails=boc_get_subscription_details(access_token,subscriptionId)\n accounts_list=SubscriptionDetails[0]['selectedAccounts']\n print ('selected_accounts=',accounts_list)\n subscriptionId=None\n return subscriptionId\n \n if api_params['debuglevel_two']>0:\n print('authorization_token=', authorization_token)\n\n SubscriptionDetails=boc_get_subscription_details(access_token,subscriptionId)\n selected_accounts=SubscriptionDetails[0]['selectedAccounts']\n accounts_options=SubscriptionDetails[0]['accounts']\n payments_options=SubscriptionDetails[0]['payments']\n if api_params['debuglevel_three']>0:\n print ('')\n print ('selected_accounts=',selected_accounts)\n print ('accounts_options=',accounts_options)\n print ('payments_accounts=',payments_options)\n \n NewSubscriptionData = \"{\\\"selectedAccounts\\\":\"+json.dumps(selected_accounts)+\",\\\"accounts\\\":\"+json.dumps(accounts_options)+\",\\\"payments\\\":\"+json.dumps(payments_options)+\"}\"\n subscriptionData=json.loads(NewSubscriptionData)\n subscription_options=json.dumps(subscriptionData)\n #subscription_options=json.dumps(\"{\\\"selectedAccounts\\\":[{\\\"accountId\\\":\\\"351012345671\\\"}],\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":64.36,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":96.08}}\")\n #subscription_options=json.dumps(\"{\\\"selectedAccounts\\\":[{\\\"accountId\\\":\\\"351012345671\\\"},{\\\"accountId\\\":\\\"351012345673\\\"},{\\\"accountId\\\":\\\"351012345674\\\"}],\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":64.36,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":96.08}}\")\n #less accounts ---subscription_options=json.dumps(\"{\\\"selectedAccounts\\\":[{\\\"accountId\\\":\\\"351012345671\\\"},{\\\"accountId\\\":\\\"351012345673\\\"}],\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":64.36,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":96.08}}\")\n\n if api_params['debuglevel_two']>0:\n print('')\n print('subscription_options=',subscription_options)\n \n subscription_status=boc_update_subscription(subscriptionId,authorization_token,authorization_code,subscription_options)\n if not subscription_status:\n print('error:',error_text)\n subscriptionId=None\n #raise Exception(error_text)\n else: \n if api_params['debuglevel_two']>0:\n print('subscription_status=', subscription_status)\n \n log_process_finish()\n return subscriptionId\n\ndef clear_pending_subscriptions(accounts):\n api='clear_pending_subscriptions'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n customer_subscriptions=[]\n customer_accounts=set([])\n access_token=boc_get_access_token()\n a=0\n deleted=0\n for account_id in accounts:\n a=a+1\n #print('@@@customer account@@@',a,'account_id=',account_id,'-----')\n subscriptions=boc_get_account_subscriptions(access_token,account_id)\n if subscriptions:\n n=0\n for subscription in subscriptions:\n n=n+1\n subscription_id=subscription['subscriptionId']\n subscription_status=subscription['status']\n if subscription_status=='pending':\n res=boc_delete_subscription(access_token, subscription_id)\n if api_params['debuglevel_two']>0:\n print (res)\n deleted=deleted+1\n msg='{} pending subscriptions deleted'.format(deleted)\n log_process_finish()\n return msg\n\ndef clear_all_subscriptions(accounts):\n api='clear_active_subscriptions'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n customer_subscriptions=[]\n customer_accounts=set([])\n access_token=boc_get_access_token()\n a=0\n deleted=0\n for account_id in accounts:\n a=a+1\n #print('@@@customer account@@@',a,'account_id=',account_id,'-----')\n subscriptions=boc_get_account_subscriptions(access_token,account_id)\n if subscriptions:\n n=0\n for subscription in subscriptions:\n n=n+1\n subscription_id=subscription['subscriptionId']\n subscription_status=subscription['status']\n #if subscription_status=='pending':\n res=boc_delete_subscription(access_token, subscription_id)\n if api_params['debuglevel_two']>0:\n print (res)\n deleted=deleted+1\n msg='{} subscriptions deleted'.format(deleted)\n log_process_finish()\n return msg\n\ndef get_customer_subscriptions(accounts,resultoption=''):\n api='get_customer_subscriptions'\n log_process_start(api)\n\n api_params=boc_get_parameters(api)\n customer_subscriptions=set([])\n customer_accounts=set([])\n customer_subscriptionsaccountsxref=set([])\n access_token=boc_get_access_token()\n a=0\n for account_id in accounts:\n a=a+1\n #print('@@@customer account@@@',a,'account_id=',account_id,'-----')\n subscriptions=boc_get_account_subscriptions(access_token,account_id)\n if subscriptions:\n #n=0\n #for subscription in subscriptions:\n # n=n+1\n # subscription_id=subscription['subscriptionId']\n # subscription_status=subscription['status']\n # subscription_accounts=boc_get_subscription_selectedAccounts(access_token,subscription_id)\n # #print(' ',a,account_id,n,subscription_id,subscription_status,len(subscription_accounts))\n n=0\n for subscription in subscriptions:\n n=n+1\n subscription_id=subscription['subscriptionId']\n subscription_status=subscription['status']\n customer_subscriptions.add(subscription_id)\n subscription_accounts=boc_get_subscription_selectedAccounts(access_token,subscription_id)\n #print(' ',a,account_id,n,subscription_id,subscription_status,len(subscription_accounts))\n an=0\n for account in subscription_accounts:\n an=an+1\n #print(' ',a,n,an,'acct=',account['accountId'])\n customer_accounts.add(account['accountId'])\n xref=account['accountId']+'-->'+subscription_id+'-->'+subscription_status\n customer_subscriptionsaccountsxref.add(xref)\n \n if api_params['debuglevel_three']>0:\n print('#1#customer_accounts:')\n #print('#1#customer_accounts=',customer_accounts)\n n=0\n for account in sorted(customer_accounts):\n n=n+1\n print(' ',n,account)\n\n #print('#2#customer_subscriptions=',customer_subscriptions)\n print('#2#customer_subscriptions:')\n n=0\n for subscriptionid in sorted(customer_subscriptions):\n n=n+1\n #print(' ',n,subscriptionid)\n\n #print('#3#customer_subscriptionsaccountsxref=',customer_subscriptionsaccountsxref)\n print('#3#customer_subscriptionsaccountsxref:')\n n=0\n for xref in sorted(customer_subscriptionsaccountsxref):\n n=n+1\n #print(' ',n,xref)\n\n log_process_finish()\n\t\n if resultoption=='subscriptions': \n return customer_subscriptions\n if resultoption=='accounts': \n return customer_accounts\n if resultoption=='xref': \n return customer_subscriptionsaccountsxref\n\n return customer_subscriptions\n\ndef check_subscriptions():\n process='check_subscriptions'\n log_process_start(process)\n ok=1\n errors=[]\n global master_configuration\n master_configuration=get_configuration()\n banks=get_configuration_param('customer_banks',master_configuration,'')\n log_process_value('banks',banks)\n for bankCodeName in banks:\n res=configuration_check(bankCodeName)\n if res != 'OK':\n error_text='ERROR:'+res\n log_process_error(error_text)\n errors.append(error_text)\n ok=0\n \n if ok==1:\n result='OK'\n else:\n result=json.dumps(errors)\n \n log_process_result('result',result)\n log_process_finish()\n return result\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\ndef configuration_check(bankCodeName):\n process='configuration_check'\n log_process_start(process)\n log_process_input_param('bankCodeName',bankCodeName)\n #::::::::::::::::::::::::::::::::::::\n log_process_section_start('prologue')\n global master_configuration\n cif=get_configuration_param('cif',master_configuration,bankCodeName)\n payments_subscriptionID=get_configuration_param('subscription_payments',master_configuration,bankCodeName)\n accounts_subscriptionID=get_configuration_param('subscription_accounts',master_configuration,bankCodeName)\n accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n log_process_section_finish()\n #::::::::::::::::::::::::::::::::::::\n if not accounts_subscriptionID:\n log_process_section_start('no_accounts_subscriptionID')\n\n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n \n SubscriptionRequest=\"{\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":false},\\\"payments\\\":{\\\"limit\\\":0.00,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":0.00}}\"\n subsID=boc_create_subscription(SubscriptionRequest)\n if subsID:\n log_process_value('new accounts subscription:', subsID)\n accounts=[]\n subscription_accounts=boc_get_subscription_Accounts(access_token,subsID)\n log_process_value('subscription_accounts=',subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n accountId=account['accountId']\n log_process_value(' ',a,accountId)\n accounts.add(accountId)\n \n acccountsList=json.dumps(accounts)\n log_process_value('accounts_accounts=',accountsList)\n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_accounts',subsID)\n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_accounts_accounts',accountsList)\n master_configuration=get_configuration()\n if not master_configuration:\n error_text='ERROR: can not retrieve master_configuration'\n log_process_error(error_text)\n #raise Exception(error_text)\n\n accounts_subscriptionID=get_configuration_param('subscription_accounts',master_configuration,bankCodeName)\n accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n log_process_section_finish()\n #::::::::::::::::::::::::::::::::::::\n if not payments_subscriptionID:\n log_process_section_start('no_payments_subscriptionID')\n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n\n\n SubscriptionRequest=\"{\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":1000.00,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":100.00}}\"\n subsID=boc_create_subscription(SubscriptionRequest)\n if subsID:\n log_process_value('new payments subscription:', subsID)\n accounts=[]\n subscription_accounts=boc_get_subscription_Accounts(access_token,subsID)\n log_process_value('subscription_accounts=',subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n accountId=account['accountId']\n print(' ',a,accountId)\n accounts.add(accountId)\n\n acccountsList=json.dumps(accounts)\n log_process_value('payments_accounts=',accountsList)\n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_payments',subsID)\n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_payments_accounts',acccountsList)\n master_configuration=get_configuration()\n if not master_configuration:\n error_text='ERROR: can not retrieve master_configuration'\n log_process_error(error_text)\n #raise Exception(error_text)\n\n payments_subscriptionID=get_configuration_param('subscription_payments',master_configuration,bankCodeName)\n payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n log_process_section_finish()\n #::::::::::::::::::::::::::::::::::::\n if not accounts_accounts:\n log_process_section_start('no_accounts')\n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n\n subsID=accounts_subscriptionID\n if subsID:\n accounts=[]\n subscription_accounts=boc_get_subscription_Accounts(access_token,subsID)\n log_process_value('subscription_accounts=',subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n accountId=account['accountId']\n print(' ',a,accountId)\n accounts.append(accountId)\n\n acccountsList=json.dumps(accounts) \n log_process_value('accounts_accounts=',acccountsList)\n \n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_accounts_accounts',acccountsList)\n master_configuration=get_configuration()\n if not master_configuration:\n error_text='ERROR: can not retrieve master_configuration'\n log_process_error(error_text)\n #raise Exception(error_text)\n\n accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n log_process_section_finish()\n #::::::::::::::::::::::::::::::::::::\n if not payments_accounts:\n log_process_section_start('no_payments_accounts')\n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n subsID=payments_subscriptionID\n if subsID:\n accounts=[]\n subscription_accounts=boc_get_subscription_Accounts(access_token,subsID)\n log_process_value('subscription_accounts=',subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n accountId=account['accountId']\n print(' ',a,accountId)\n accounts.append(accountId)\n\n acccountsList=json.dumps(accounts) \n log_process_value('payment_accounts=',acccountsList)\n update_customer_configuration(bankCodeName,'customer_subscriptions','subscription_payments_accounts',acccountsList)\n master_configuration=get_configuration()\n if not master_configuration:\n error_text='ERROR: can not retrieve master_configuration'\n log_process_error(error_text)\n #raise Exception(error_text)\n\n payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n log_process_section_finish()\n\n #::::::::::::::::::::::::::::::::::::\n log_process_section_start('epilogue')\n cif=get_configuration_param('cif',master_configuration,bankCodeName)\n payments_subscriptionID=get_configuration_param('subscription_payments',master_configuration,bankCodeName)\n accounts_subscriptionID=get_configuration_param('subscription_accounts',master_configuration,bankCodeName)\n accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n\n log_process_value('cif=',cif)\n log_process_value('payments_subscriptionID=',payments_subscriptionID)\n log_process_value('payments_accounts=',payments_accounts)\n log_process_value('accounts_subscriptionID=',accounts_subscriptionID)\n log_process_value('accounts_accounts=',accounts_accounts)\n\n if payments_subscriptionID and payments_accounts and accounts_subscriptionID and accounts_accounts:\n result='OK'\n else:\n result='missing subscriptions for bank '+bankCodeName \n log_process_section_finish()\n #::::::::::::::::::::::::::::::::::::\n\n log_process_result('result',result)\n log_process_finish()\n return result\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n##################################################\n##################################################\n##################################################\n##################################################\n##################################################\n##################################################\n##################################################\n##################################################\nif __name__ == '__main__':\n bankCodeName='bankofcyprus'\n #environment='development'\n debuglevel_one=0\n debuglevel_two=0\n debuglevel_three=0\n debuglevel_four=0\n response=''\n error_code=0\n error_text=''\n reply_code=0\n\n master_configuration=get_configuration()\n if not master_configuration:\n error_text='ERROR: can not retrieve master_configuration'\n raise Exception(error_text)\n #debuglevel_one=1\n #access_token=boc_get_access_token()\n #if not access_token:\n # raise Exception(error_text)\n\n res=check_subscriptions()\n if res != 'OK':\n error_text='ERROR:'+res\n raise Exception(error_text)\n sys.exit(0)\n\n payments_subscriptionID=get_configuration_param('subscription_payments',master_configuration,bankCodeName)\n accounts_subscriptionID=get_configuration_param('subscription_accounts',master_configuration,bankCodeName)\n accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n if debuglevel_three>=0:\n print('=================')\n print(bankCodeName,'payments_subscriptionID=',payments_subscriptionID)\n print(bankCodeName,'payments_accounts=',payments_accounts)\n print(bankCodeName,'accounts_subscriptionID=',accounts_subscriptionID)\n print(bankCodeName,'accounts_accounts=',accounts_accounts)\n print('=================')\n \n #access_token=boc_get_access_token()\n #if not access_token:\n # raise Exception(error_text)\n print('ALL OK - PROCEED')\n\n \n access_token=boc_get_access_token()\n if not access_token:\n raise Exception(error_text)\n\n if 1==1:\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(' accounts');\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n subscription_accounts=boc_list_accounts(access_token,accounts_subscriptionID)\n print(subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n accountID=account['accountId']\n print(' ',a,accountID)\n \n account_details=boc_get_account_details(access_token,accounts_subscriptionID,accountID)\n print(' ','account_details=',account_details)\n\n account_balances=boc_get_account_balances(access_token,accounts_subscriptionID,accountID)\n print(' ','account_balances=',account_balances)\n\n account_transactions=boc_get_account_transactions(access_token,accounts_subscriptionID,accountID)\n print(' ','account_transactions=',account_transactions)\n \n if 1==2:\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(' create subscriptions');\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n\n #res=get_customer_subscriptions(my_accounts)\n #print('1---customer subscriptions=',res)\n msg=clear_pending_subscriptions(my_accounts)\n print(msg)\n #msg=clear_all_subscriptions(my_accounts)\n #print(msg)\n\n SubscriptionRequest=\"{\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":64.36373117,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":96.08441354}}\"\n #subscription_options=json.loads(SubscriptionRequest)\n #SubscriptionRequest=json.dumps(subscription_options)\n subsID=boc_create_subscription(SubscriptionRequest)\n if subsID:\n print('new subscription:', subsID)\n \n res=get_customer_subscriptions(my_accounts)\n print('customer subscriptions=',res)\n sys.exit(0)\n\n if 1==2:\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(' subscriptions');\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n subscriptionId='Subid000001-1532955588265'\n subscription_details=boc_get_subscription_details(access_token,subscriptionId)\n print('subscription_details=',subscription_details)\n #sys.exit(0)\n##\n## subscriptionId='Subid000001-1532936259944'\n## res=boc_delete_subscription(access_token, subscriptionId)\n## print (res)\n##\n## subscriptionId='Subid000001-1532594181330'\n## res=boc_delete_subscription(access_token, subscriptionId)\n## print (res)\n##\n## my_accounts=['351012345671','351092345672','351012345673','351012345674','351012345675']\n## msg=clear_pending_subscriptions(my_accounts)\n## print(msg)\n\n SubscriptionRequest=\"{\\\"accounts\\\":{\\\"transactionHistory\\\":true,\\\"balance\\\":true,\\\"details\\\":true,\\\"checkFundsAvailability\\\":true},\\\"payments\\\":{\\\"limit\\\":64.36373117,\\\"currency\\\":\\\"EUR\\\",\\\"amount\\\":96.08441354}}\"\n subsID=boc_create_subscription(SubscriptionRequest)\n if subsID:\n print('new subscription:', subsID)\n\n subscriptions=get_customer_subscriptions(my_accounts,'subscriptions')\n #print('customer_subscriptions=',get_customer_subscriptions(my_accounts,'subscriptions'))\n n=0\n for subscriptionId in subscriptions:\n n=n+1\n subscription_details=boc_get_subscription_details(access_token,subscriptionId)\n print(n,'subscription_details=',subscription_details)\n\n \n #print('customer_accounts=',get_customer_subscriptions(my_accounts,'accounts'))\n #print('customer_accounts_xref=',get_customer_subscriptions(my_accounts,'xref'))\n\n sys.exit(0) ##stop run\n \n if 1==2:\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(' accounts');\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n account_id='351012345671'\n subscription_Id=None\n subscriptions=boc_get_account_subscriptions(access_token,account_id)\n n=0\n for subscription in subscriptions:\n n=n+1\n subscription_id=subscription['subscriptionId']\n subscription_status=subscription['status']\n print(n,subscription_id,subscription_status)\n\n if subscription_id:\n subscription_accounts=boc_list_accounts(access_token,subscription_id)\n print(subscription_accounts)\n a=0\n for account in subscription_accounts:\n a=a+1\n account_Id=account['accountId']\n print(' ',n,a,account_Id)\n \n account_details=boc_get_account_details(access_token, subscription_id, account_Id)\n print(' ','account_details=',account_details)\n\n account_balances=boc_get_account_balances(access_token, subscription_id, account_Id)\n print(' ','account_balances=',account_balances)\n\n account_transactions=boc_get_account_transactions(access_token, subscription_id, account_Id)\n print(' ','account_transactions=',account_transactions)\n\n if 1==2:\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print(' payments');\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')\n## payments_subscriptionID=get_configuration_param('subscription_payments',master_configuration,bankCodeName)\n## accounts_subscriptionID=get_configuration_param('subscription_accounts',master_configuration,bankCodeName)\n## accounts_accounts=get_configuration_param('subscription_accounts_accounts',master_configuration,bankCodeName)\n## payments_accounts=get_configuration_param('subscription_payments_accounts',master_configuration,bankCodeName)\n\n subscription_accounts=boc_list_accounts(access_token,payments_subscriptionID)\n #print(subscription_accounts)\n #sys.exit(0)\n allPayments=[]\n a=0\n for account in subscription_accounts:\n #print('====',account)\n \n a=a+1\n accountID=account['accountId']\n #print(' ',a,accountID)\n \n payments=boc_get_payments(access_token,payments_subscriptionID,accountID)\n if payments:\n for payment in payments:\n allPayments.append(payment)\n \n n=0\n for payment in allPayments:\n n=n+1\n paymentID=payment['paymentId']\n DBaccountID=payment['debtor']['accountId']\n CRaccountID=payment['creditor']['accountId']\n CRaccountName=payment['creditor']['name']\n paymentRefNum=payment['status']['refNumber']\n paymentStatusCode=payment['status']['code']\n paymentStatusDesc=payment['status']['description'][0]\n\n #paystatus=payment['status']\n #print(n,payment_Id)\n\n #payment_delete=boc_delete_payment(access_token,payments_subscriptionID,paymentID)\n #print(n,'payment_delete=',payment_delete)\n\n #payment_details=boc_get_payment_details(access_token,payments_subscriptionID,paymentID)\n #print(n,'payment_details=',payment_details)\n\n #payment_authorize=boc_payment_authorize(access_token, payments_subscriptionID,paymentID)\n #print(n,'payment_authorize=',payment_authorize)\n\n\n print(n,paymentID,paymentStatusCode,paymentRefNum,DBaccountID,CRaccountID)\n #print(n,'paymentRefNum=',paymentRefNum)\n #print(n,'paymentStatusCode=',paymentStatusCode)\n #print(n,'paymentStatusDesc=',paymentStatusDesc)\n \n print('-----------------')\n #sys.exit(0)\n\n paymentID=None\n DBaccountId='351012345671'\n CRaccountId='351092345672'\n Amount=12.23\n Currency='EUR'\n Details='pay zorbas'\n payment=boc_make_payment(access_token,payments_subscriptionID,DBaccountId,CRaccountId,Amount,Currency,Details)\n if not payment:\n print(error_text)\n else:\n paymAuthNeeded=payment['authCodeNeeded']\n paymentID=payment['payment']['paymentId']\n paymstatus=payment['payment']['status']\n paymentRefNum=payment['payment']['status']['refNumber']\n paymentStatusCode=payment['payment']['status']['code']\n paymentStatusDesc=payment['payment']['status']['description'][0]\n print(paymentStatusCode)\n \n payment_status=boc_get_payment_status(access_token,payments_subscriptionID,paymentID)\n payment_details=boc_get_payment_details(access_token,payments_subscriptionID,paymentID)\n\n print('paymAuthNeeded=',paymAuthNeeded)\n print('paymentID=',paymentID)\n print('paymentRefNum=',paymentRefNum)\n print('paymentStatusCode=',paymentStatusCode)\n print('paymentStatusDesc=',paymentStatusDesc)\n print('-----------------')\n if paymentID:\n res=boc_authorize_payment(access_token,payments_subscriptionID,paymentID)\n print('####payment result####',res)\n print('-----------------')\n \n","sub_path":"ganimedes/myApp/openbanking_services/openbanking_services_BankofCyprus/openbanking_services_BankofCyprus.py","file_name":"openbanking_services_BankofCyprus.py","file_ext":"py","file_size_in_byte":68651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"322495957","text":"# Copyright 2013 Evan Hazlett and contributors.\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.\nfrom tastypie import fields\nfrom tastypie.resources import Resource\nfrom tastypie.bundle import Bundle\nfrom tastypie.authorization import Authorization\nfrom tastypie.authentication import (ApiKeyAuthentication,\n SessionAuthentication, MultiAuthentication)\nfrom containers.models import Container, Host\nfrom hosts.api import HostResource\nfrom django.contrib.auth.models import User\nfrom shipyard import utils\n\ndef get_containers():\n valid_container_ids = [x.container_id for x in Host.get_all_containers()]\n return Container.objects.filter(container_id__in=valid_container_ids)\n\nclass ContainerResource(Resource):\n container_id = fields.CharField(attribute='container_id')\n description = fields.CharField(attribute='description')\n meta = fields.DictField(attribute='get_meta')\n is_running = fields.BooleanField(attribute='is_running')\n host = fields.ToOneField(HostResource, attribute='host')\n protected = fields.BooleanField(attribute='protected')\n\n class Meta:\n resource_name = 'containers'\n authorization = Authorization()\n authentication = MultiAuthentication(\n ApiKeyAuthentication(), SessionAuthentication())\n list_allowed_methods = ['get', 'post']\n detail_allowed_methods = ['get', 'post', 'delete']\n\n def detail_uri_kwargs(self, bundle_or_obj):\n kwargs = {}\n if isinstance(bundle_or_obj, Bundle):\n kwargs['pk'] = bundle_or_obj.obj.id\n else:\n kwargs['pk'] = bundle_or_obj.id\n return kwargs\n\n def get_object_list(self, request):\n containers = get_containers()\n return containers\n\n def obj_get_list(self, request=None, **kwargs):\n return self.get_object_list(request)\n\n def obj_get(self, request=None, **kwargs):\n # TODO: refactor Container to use a Manager to automatically\n # update container metadata\n id = kwargs.get('pk')\n c = Container.objects.get(id=id)\n # refresh metadata\n c.host._load_container_data(c.container_id)\n # re-run query to get new data\n c = Container.objects.get(id=id)\n return c\n\n def obj_create(self, bundle, request=None, **kwargs):\n \"\"\"\n Override obj_create to launch containers and return metadata\n\n \"\"\"\n # HACK: get host id -- this should probably be some type of\n # reverse lookup from tastypie\n host_urls = bundle.data.get('hosts')\n # remove 'hosts' from data and pass rest to create_container\n del bundle.data['hosts']\n # launch on hosts\n for host_url in host_urls:\n host_id = host_url.split('/')[-2]\n host = Host.objects.get(id=host_id)\n data = bundle.data\n c_id, status = host.create_container(**data)\n bundle.obj = Container.objects.get(\n container_id=utils.get_short_id(c_id))\n bundle = self.full_hydrate(bundle)\n return bundle\n\n def obj_delete(self, request=None, **kwargs):\n id = kwargs.get('pk')\n c = Container.objects.get(id=id)\n h = c.host\n h.destroy_container(c.container_id)\n\n def obj_delete_list(self, request=None, **kwargs):\n for c in Container.objects.all():\n h = c.host\n h.destroy_container(c.container_id)\n","sub_path":"containers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"516078483","text":"\"\"\"Image utils.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cv2\nimport io\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\nimport scipy.ndimage as ndimage\nimport tensorflow as tf\n\n\nface_cascade = cv2.CascadeClassifier(\n \"../app/Avatar/data/models/haarcascade_frontalface_alt.xml\")\n\n\ndef pad_or_crop_image(image, padding, mode):\n \"\"\"Pad or crop an annotated image.\"\"\"\n p_pad = [(max(p[0], 0), max(p[1], 0)) for p in padding]\n n_pad = [(max(-p[0], 0), max(-p[1], 0)) for p in padding]\n min_p = [p[0] for i, p in enumerate(n_pad)]\n max_p = [image.shape[1-i]-p[1] for i, p in enumerate(n_pad)]\n image = image[min_p[1]:max_p[1], min_p[0]:max_p[0]]\n image = np.pad(image, [p_pad[1], p_pad[0], (0, 0)], mode)\n return image\n\n\ndef crop_image(image, labels, bbox):\n \"\"\"Crop an annotated image.\"\"\"\n image_w = image.shape[1]\n image_h = image.shape[0]\n pad_x = (bbox[2] // 4) - bbox[0], (bbox[0] + bbox[2] * 5 // 4) - image_w\n pad_y = (bbox[3] // 4) - bbox[1], (bbox[1] + bbox[3] * 5 // 4) - image_h\n image = pad_or_crop_image(image, (pad_x, pad_y), \"reflect\")\n labels = labels + np.array([[pad_x[0], pad_y[0]]])\n return image, labels\n\n\ndef scale_image(image, labels, size):\n \"\"\"Scale an annotated image.\"\"\"\n zoom = np.array([size, size]) / np.array([image.shape[0], image.shape[1]])\n image = ndimage.interpolation.zoom(image, [zoom[0], zoom[1], 1])\n labels = labels * zoom\n return image, labels\n\n\ndef crop_and_scale_image(image, labels, bbox, size):\n \"\"\"Crop and scale an annotated image.\"\"\"\n image, labels = crop_image(image, labels, bbox)\n image, labels = scale_image(image, labels, size)\n return image, labels\n\n\ndef overlap(bbox1, bbox2):\n \"\"\"Compute the overlap beween two boxes.\"\"\"\n tl = np.maximum(bbox1[0:2], bbox2[0:2])\n br = np.minimum(bbox1[0:2] + bbox1[2:4], bbox2[0:2] + bbox2[2:4])\n size = br - tl\n ratio = float(np.prod(size)) / np.prod(bbox1[2:4])\n return ratio\n\n\ndef detect_face(image, labels, min_overlap=0.8):\n \"\"\"Detect face.\"\"\"\n cv2.ocl.setUseOpenCL(False)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(\n gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))\n center = labels.mean(axis=0).astype(np.int)\n size = np.int((labels.max(axis=0) - labels.min(axis=0)).mean())\n size = np.array([size, size])\n pos = center - size // 2\n init_face = np.concatenate((pos, size))\n sel_face = init_face\n detected = False\n for face in faces:\n cur_overlap = overlap(init_face, face)\n if cur_overlap > min_overlap:\n sel_face = face\n min_overlap = cur_overlap\n detected = True\n print([\"Not detected\", \"Detected\"][detected])\n return sel_face.astype(np.int)\n\n\ndef encode_image(data, format=\"png\"):\n \"\"\"Encodes a numpy array to string.\"\"\"\n im = PIL.Image.fromarray(data)\n buf = io.BytesIO()\n data = im.save(buf, format=format)\n buf.seek(0)\n return buf.getvalue()\n\n\ndef decode_image(data):\n \"\"\"Decode the given image to a numpy array.\"\"\"\n buf = io.BytesIO(data)\n im = PIL.Image.open(buf)\n data = np.array(im.getdata()).reshape([im.height, im.width, -1])\n return data\n\n\ndef visualize(image, labels):\n \"\"\"Visualize image.\"\"\"\n plt.figure(figsize=(16, 12))\n plt.imshow(image)\n plt.plot(labels[:, 0], labels[:, 1], \".\")\n plt.axis(\"off\")\n plt.show()\n","sub_path":"common/image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250661507","text":"from sklearn import metrics as mets\nfrom algorithm import RF\nfrom supportfunc import load,split,Proc,Imp\nimport os\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef display(accinfo, yr, result_metric=[]):\n if (len(result_metric) > 0):\n print('\\naccinfo for yr {}:'.format(yr))\n for metric in result_metric:\n if type(accinfo[metric]) == dict:\n print('{}={:.2f}, std={:.2f}'.format(metric,\n accinfo[metric]['mean'], accinfo[metric]['std']))\n elif type(accinfo[metric]) == str:\n print(accinfo[metric])\n elif isinstance(accinfo[metric], float):\n print('{}={:.2f}'.format(metric, accinfo[metric]))\n else:\n print('{} cannot be printed.'.format(metric))\n\n plt.figure(yr)\n plt.title('roc curve yr {}'.format(yr))\n plt.plot((0, 1), (0, 1), ls='--', c='k')\n if type(accinfo['roc_curve']['fpr']) == list:\n for fpr, tpr in zip(accinfo['roc_curve']['fpr'],accinfo['roc_curve']['tpr']):\n plt.plot(fpr, tpr)\n else:\n plt.plot(accinfo['roc_curve']['fpr'], accinfo['roc_curve']['tpr'])\n plt.xlabel('False positive rate')\n plt.ylabel('True positive rate')\n\ndef trainfunc(yr):\n tmpX, tmpY = load(yr)\n trainX, trainY, testX, testY = split(tmpX, tmpY,0.1)\n accinfo,algo,proc,imp = trainrun(trainX, trainY, testX, testY)\n with open(os.getcwd() + \"/model/{}_algo\".format(str(yr)),\"wb\") as f:\n \tpickle.dump(algo,f)\n with open(os.getcwd() + \"/model/{}_proc\".format(str(yr)),\"wb\") as f:\n pickle.dump(proc,f)\n with open(os.getcwd() + \"/model/{}_imp\".format(str(yr)),\"wb\") as f:\n pickle.dump(imp,f)\n display(accinfo, yr,result_metric=['classification_report', 'log_loss', 'accuracy', 'roc_auc'])\n\ndef trainrun(trainX, trainY, testX, testY):\n process = Proc()\n trainX = process.fittran(trainX)\n testX = process.tran(testX)\n imp = Imp()\n trainX = imp.fittran(trainX)\n testX = imp.tran(testX)\n parameters = {\"n_estimators\": 100, \"min_samples_split\": 2,\"min_samples_leaf\": 1,\"min_weight_fraction_leaf\": 0.0,\n \t\t\t \"warm_start\": False,\"criterion\": 'entropy',\"bootstrap\": False,\"oob_score\": False,\"max_features\": 'auto',\n \t\t\t \"max_depth\": None,\"max_leaf_nodes\": None,\"class_weight\": None }\n\n RFalgo = RF(**parameters)\n\n accinfo = dict()\n accinfo['fit_info'] = RFalgo.fit(trainX, trainY)\n predresult = RFalgo.algopredict(testX)\n pred = np.argmax(predresult, axis=1)\n accinfo['log_loss'] = mets.log_loss(testY, predresult[:, 1])\n accinfo['accuracy'] = mets.accuracy_score(testY, pred)\n accinfo['recall'] = mets.recall_score(testY, pred, labels=[0, 1])\n accinfo['precision'] = mets.precision_score(testY, pred, labels=[0, 1])\n fpr, tpr, thresholds = mets.roc_curve(testY, predresult[:, 1])\n accinfo['roc_curve'] = {'fpr': fpr, 'tpr': tpr, 'thresholds': thresholds}\n accinfo['roc_auc'] = mets.auc(fpr, tpr)\n accinfo['classification_report'] = mets.classification_report(testY,pred, labels=[0, 1])\n return accinfo,RFalgo,process,imp\n\n\nif __name__ == '__main__':\n\tnp.random.seed(52)\n\tfor yr in [1,2,3,4,5]:\n\t\ttrainfunc(yr)\n\tplt.show()\n","sub_path":"algo/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458248709","text":"\"\"\"\nReinforcement learning maze example.\nBall: explorer.\nBlack Triangle: hells [reward = -1].\nYellow rectangle: paradise [reward = +1].\nAll other states: ground [reward = 0].\n\"\"\"\n\nimport numpy as np\nimport time\nimport tkinter as tk\n\nUNIT = 50\nWORLD_H = 5\nWORLD_W = 10\n\n\nclass JumpJumpWorld(tk.Tk, object):\n def __init__(self):\n super(JumpJumpWorld, self).__init__()\n self.actions = ['Up', 'Left', 'Right']\n self.n_actions = len(self.actions)\n self.title('JumpJumpWorld')\n self.geometry('{0}x{1}'.format(WORLD_W * UNIT, WORLD_H * UNIT))\n self._build_world()\n\n def _build_world(self):\n self.canvas = tk.Canvas(self, bg='white', height=WORLD_H * UNIT, width=WORLD_W * UNIT)\n self.canvas.create_line(0,240,500,240)\n origin = np.array([22.5, 220])\n self.player = {\"Center\": origin, \"Body\": None, \"Gravity\": False}\n self.player[\"Body\"] = self.canvas.create_oval(self.player[\"Center\"][0] - 20, self.player[\"Center\"][1] - 20,\n self.player[\"Center\"][0] + 20, self.player[\"Center\"][1] + 20,\n fill='red')\n\n self.obstacle = {\"Center\": np.array([230, 220]), \"Body\": None}\n self.obstacle[\"Body\"] = self.canvas.create_rectangle(self.obstacle[\"Center\"][0] - 20,\n self.obstacle[\"Center\"][1] - 20,\n self.obstacle[\"Center\"][0] + 20,\n self.obstacle[\"Center\"][1] + 20,\n fill='black')\n\n self.finishBox = {\"Center\": np.array([477.5, 220]), \"Body\": None}\n self.finishBox[\"Body\"] = self.canvas.create_rectangle(self.finishBox[\"Center\"][0] - 20,\n self.finishBox[\"Center\"][1] - 20,\n self.finishBox[\"Center\"][0] + 20,\n self.finishBox[\"Center\"][1] + 20,\n fill='light green')\n self.canvas.pack()\n\n def reset(self):\n self.update()\n time.sleep(0.5)\n self.canvas.delete(self.player[\"Body\"])\n self.player[\"Body\"] = self.canvas.create_oval(self.player[\"Center\"][0] - 20, self.player[\"Center\"][1] - 20,\n self.player[\"Center\"][0] + 20, self.player[\"Center\"][1] + 20,\n fill='red')\n return self.canvas.coords(self.player[\"Body\"])\n\n def move(self, action):\n player_position = self.canvas.coords(self.player[\"Body\"])\n base_action = np.array([0, 0])\n\n if action is 0: # Up\n if player_position[1] > UNIT:\n base_action[1] -= 20\n elif action is 1: # Right\n if player_position[0] < (WORLD_W - 1) * UNIT:\n base_action[0] += 20\n elif action is 2:\n if player_position[0] > UNIT:\n base_action[0] -= 20\n\n\n self.canvas.move(self.player[\"Body\"], base_action[0], base_action[1])\n next_player_position = self.canvas.coords(self.player[\"Body\"])\n\n if next_player_position == self.canvas.coords(self.finishBox[\"Body\"]):\n reward = 1\n done = True\n next_player_position = 'terminal'\n\n elif next_player_position == self.canvas.coords(self.obstacle[\"Body\"]):\n reward = -1\n done = True\n next_player_position = 'terminal'\n\n else:\n reward = 0\n done = False\n\n return next_player_position, reward, done\n\n def render(self):\n time.sleep(0.1)\n self.update()\n\n\ndef update():\n for t in range(10):\n s = env.reset()\n while True:\n env.render()\n a = 0\n s, r, done = env.move(a)\n if done:\n break\n\nif __name__ == '__main__':\n env = JumpJumpWorld()\n env.after(100, update)\n env.mainloop()","sub_path":"my_world.py","file_name":"my_world.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109921287","text":"import time\nfrom concurrent.futures import Future, wait\nfrom dataclasses import dataclass\nfrom threading import RLock, current_thread, main_thread\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport pytest\n\nfrom napari.components import Dims\nfrom napari.components._layer_slicer import _LayerSlicer\nfrom napari.layers import Image, Points\nfrom napari.layers._data_protocols import Index, LayerDataProtocol\nfrom napari.types import DTypeLike\n\n\"\"\"\nCases to consider\n- single + multiple layers that supports async (all of layers do support async)\n- single + multiple layers that don't support async (all of layers do not support async)\n- mix of layers that do and don't support async\n\nBehaviors we want to test:\nscheduling logic of the slicer (and not correctness of the slice response value)\n\n- for layers that support async, the slice task should not be run on the main\n thread (we don't want to block the calling)\n- for layers that do not support async, slicing should always be done once\n the method returns\n- slice requests should be run on the main thread\n- pending tasks are cancelled (at least when the new task will slice all\n layers for the pending task)\n\nThe fake request, response, and layers exist to give structure against which to\ntest (class instances and attributes) and to remain isolated from the existing\ncodebase. They represent what will become real classes in the codebase which\nhave additional methods and properties that don't currently exist.\n\nRun all tests with:\npytest napari/components/_tests/test_layer_slicer.py -svv\n\"\"\"\n\n\n@dataclass(frozen=True)\nclass FakeSliceResponse:\n id: int\n\n\n@dataclass(frozen=True)\nclass FakeSliceRequest:\n id: int\n lock: RLock\n\n def __call__(self) -> FakeSliceResponse:\n assert current_thread() != main_thread()\n with self.lock:\n return FakeSliceResponse(id=self.id)\n\n\nclass FakeAsyncLayer:\n def __init__(self):\n self.slice_count = 0\n self.lock = RLock()\n\n def _make_slice_request(self, dims) -> FakeSliceRequest:\n assert current_thread() == main_thread()\n self.slice_count += 1\n return FakeSliceRequest(id=self.slice_count, lock=self.lock)\n\n def _slice_dims(self, *args, **kwargs) -> None:\n self.slice_count += 1\n\n\nclass FakeSyncLayer:\n def __init__(self):\n self.slice_count: int = 0\n\n def _slice_dims(self, *args, **kwargs) -> None:\n self.slice_count += 1\n\n\nclass LockableData:\n \"\"\"A wrapper for napari layer data that blocks read-access with a lock.\n\n This is useful when testing async slicing with real napari layers because\n it allows us to control when slicing tasks complete.\n \"\"\"\n\n def __init__(self, data: LayerDataProtocol):\n self.data = data\n self.lock = RLock()\n\n @property\n def dtype(self) -> DTypeLike:\n return self.data.dtype\n\n @property\n def shape(self) -> Tuple[int, ...]:\n return self.data.shape\n\n def __getitem__(\n self, key: Union[Index, Tuple[Index, ...], LayerDataProtocol]\n ) -> LayerDataProtocol:\n with self.lock:\n return self.data[key]\n\n def __len__(self):\n return len(self.data)\n\n\n@pytest.fixture()\ndef layer_slicer():\n layer_slicer = _LayerSlicer()\n yield layer_slicer\n layer_slicer.shutdown()\n\n\ndef test_slice_layers_async_with_one_async_layer_no_block(layer_slicer):\n layer = FakeAsyncLayer()\n\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n assert future.result()[layer].id == 1\n\n\ndef test_slice_layers_async_with_multiple_async_layer_no_block(layer_slicer):\n layer1 = FakeAsyncLayer()\n layer2 = FakeAsyncLayer()\n\n future = layer_slicer.slice_layers_async(\n layers=[layer1, layer2], dims=Dims()\n )\n\n assert future.result()[layer1].id == 1\n assert future.result()[layer2].id == 1\n\n\ndef test_slice_layers_async_emits_ready_event_when_done(layer_slicer):\n layer = FakeAsyncLayer()\n event_result = None\n\n def on_done(event):\n nonlocal event_result\n event_result = event.value\n\n layer_slicer.events.ready.connect(on_done)\n\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n actual_result = future.result()\n\n assert actual_result is event_result\n\n\ndef test_slice_layers_async_with_one_sync_layer(layer_slicer):\n layer = FakeSyncLayer()\n assert layer.slice_count == 0\n\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n assert layer.slice_count == 1\n assert future.result() == {}\n\n\ndef test_slice_layers_async_with_multiple_sync_layer(layer_slicer):\n layer1 = FakeSyncLayer()\n layer2 = FakeSyncLayer()\n assert layer1.slice_count == 0\n assert layer2.slice_count == 0\n\n future = layer_slicer.slice_layers_async(\n layers=[layer1, layer2], dims=Dims()\n )\n\n assert layer1.slice_count == 1\n assert layer2.slice_count == 1\n assert not future.result()\n\n\ndef test_slice_layers_async_with_mixed_layers(layer_slicer):\n layer1 = FakeAsyncLayer()\n layer2 = FakeSyncLayer()\n assert layer1.slice_count == 0\n assert layer2.slice_count == 0\n\n future = layer_slicer.slice_layers_async(\n layers=[layer1, layer2], dims=Dims()\n )\n\n assert layer1.slice_count == 1\n assert layer2.slice_count == 1\n assert future.result()[layer1].id == 1\n assert layer2 not in future.result()\n\n\ndef test_slice_layers_async_lock_blocking(layer_slicer):\n dims = Dims()\n layer = FakeAsyncLayer()\n\n assert layer.slice_count == 0\n with layer.lock:\n blocked = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert not blocked.done()\n\n assert blocked.result()[layer].id == 1\n\n\ndef test_slice_layers_async_multiple_calls_cancels_pending(layer_slicer):\n dims = Dims()\n layer = FakeAsyncLayer()\n\n with layer.lock:\n blocked = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n pending = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert not pending.running()\n layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert not blocked.done()\n\n assert pending.cancelled()\n\n\ndef test_slice_layers_mixed_allows_sync_to_run(layer_slicer):\n \"\"\"ensure that a blocked async slice doesn't block sync slicing\"\"\"\n dims = Dims()\n layer1 = FakeAsyncLayer()\n layer2 = FakeSyncLayer()\n with layer1.lock:\n blocked = layer_slicer.slice_layers_async(layers=[layer1], dims=dims)\n layer_slicer.slice_layers_async(layers=[layer2], dims=dims)\n assert layer2.slice_count == 1\n assert not blocked.done()\n\n assert blocked.result()[layer1].id == 1\n\n\ndef test_slice_layers_mixed_allows_sync_to_run_one_slicer_call(layer_slicer):\n \"\"\"ensure that a blocked async slice doesn't block sync slicing\"\"\"\n dims = Dims()\n layer1 = FakeAsyncLayer()\n layer2 = FakeSyncLayer()\n with layer1.lock:\n blocked = layer_slicer.slice_layers_async(\n layers=[layer1, layer2], dims=dims\n )\n\n assert layer2.slice_count == 1\n assert not blocked.done()\n\n assert blocked.result()[layer1].id == 1\n\n\ndef test_slice_layers_async_with_multiple_async_layer_with_all_locked(\n layer_slicer,\n):\n \"\"\"ensure that if only all layers are locked, none continue\"\"\"\n dims = Dims()\n layer1 = FakeAsyncLayer()\n layer2 = FakeAsyncLayer()\n\n with layer1.lock, layer2.lock:\n blocked = layer_slicer.slice_layers_async(\n layers=[layer1, layer2], dims=dims\n )\n assert not blocked.done()\n\n assert blocked.result()[layer1].id == 1\n assert blocked.result()[layer2].id == 1\n\n\ndef test_slice_layers_async_task_to_layers_lock(layer_slicer):\n \"\"\"ensure that if only one layer has a lock, the non-locked layer\n can continue\"\"\"\n dims = Dims()\n layer = FakeAsyncLayer()\n\n with layer.lock:\n task = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert task in layer_slicer._layers_to_task.values()\n\n assert task.result()[layer].id == 1\n assert task not in layer_slicer._layers_to_task\n\n\ndef test_slice_layers_exception_main_thread(layer_slicer):\n \"\"\"Exception is raised on the main thread from an error on the main\n thread immediately when the task is created.\"\"\"\n\n class FakeAsyncLayerError(FakeAsyncLayer):\n def _make_slice_request(self, dims) -> FakeSliceRequest:\n raise RuntimeError('_make_slice_request')\n\n layer = FakeAsyncLayerError()\n with pytest.raises(RuntimeError, match='_make_slice_request'):\n layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n\ndef test_slice_layers_exception_subthread_on_result(layer_slicer):\n \"\"\"Exception is raised on the main thread from an error on a subthread\n only after result is called, not upon submission of the task.\"\"\"\n\n @dataclass(frozen=True)\n class FakeSliceRequestError(FakeSliceRequest):\n def __call__(self) -> FakeSliceResponse:\n assert current_thread() != main_thread()\n raise RuntimeError('FakeSliceRequestError')\n\n class FakeAsyncLayerError(FakeAsyncLayer):\n def _make_slice_request(self, dims) -> FakeSliceRequestError:\n return FakeSliceRequestError(id=self.slice_count, lock=self.lock)\n\n layer = FakeAsyncLayerError()\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n done, _ = wait([future], timeout=5)\n assert done, 'Test future did not complete within timeout.'\n with pytest.raises(RuntimeError, match='FakeSliceRequestError'):\n future.result()\n\n\ndef test_wait_until_idle(layer_slicer, single_threaded_executor):\n dims = Dims()\n layer = FakeAsyncLayer()\n\n with layer.lock:\n slice_future = layer_slicer.slice_layers_async(\n layers=[layer], dims=dims\n )\n _wait_until_running(slice_future)\n # The slice task has started, but has not finished yet\n # because we are holding the layer's slicing lock.\n assert len(layer_slicer._layers_to_task) > 0\n # We can't call wait_until_idle on this thread because we're\n # holding the layer's slice lock, so submit it to be executed\n # on another thread and also wait for it to start.\n wait_future = single_threaded_executor.submit(\n layer_slicer.wait_until_idle\n )\n _wait_until_running(wait_future)\n\n wait_future.result()\n assert len(layer_slicer._layers_to_task) == 0\n\n\ndef _wait_until_running(future: Future):\n while not future.running():\n time.sleep(0.01)\n\n\ndef test_layer_slicer_force_sync_on_sync_layer(layer_slicer):\n layer = FakeSyncLayer()\n\n with layer_slicer.force_sync():\n assert layer_slicer._force_sync\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n assert layer.slice_count == 1\n assert future.result() == {}\n assert not layer_slicer._force_sync\n\n\ndef test_layer_slicer_force_sync_on_async_layer(layer_slicer):\n layer = FakeAsyncLayer()\n\n with layer_slicer.force_sync():\n assert layer_slicer._force_sync\n future = layer_slicer.slice_layers_async(layers=[layer], dims=Dims())\n\n assert layer.slice_count == 1\n assert future.result() == {}\n\n\ndef test_slice_layers_async_with_one_3d_image(layer_slicer):\n np.random.seed(0)\n data = np.random.rand(8, 7, 6)\n lockable_data = LockableData(data)\n layer = Image(data=lockable_data, multiscale=False)\n dims = Dims(\n ndim=3,\n ndisplay=2,\n range=((0, 8, 1), (0, 7, 1), (0, 6, 1)),\n current_step=(2, 0, 0),\n )\n\n with lockable_data.lock:\n future = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert not future.done()\n\n layer_result = future.result()[layer]\n np.testing.assert_equal(layer_result.data, data[2, :, :])\n\n\ndef test_slice_layers_async_with_one_3d_points(layer_slicer):\n \"\"\"ensure that async slicing of points does not block\"\"\"\n np.random.seed(0)\n num_points = 100\n data = np.rint(2.0 * np.random.rand(num_points, 3))\n layer = Points(data=data)\n\n # Note: We are directly accessing and locking the _data of layer. This\n # forces a block to ensure that the async slicing call returns\n # before slicing is complete.\n lockable_internal_data = LockableData(layer._data)\n layer._data = lockable_internal_data\n dims = Dims(\n ndim=3,\n ndisplay=2,\n range=((0, 3, 1), (0, 3, 1), (0, 3, 1)),\n current_step=(1, 0, 0),\n )\n\n with lockable_internal_data.lock:\n future = layer_slicer.slice_layers_async(layers=[layer], dims=dims)\n assert not future.done()\n","sub_path":"napari/components/_tests/test_layer_slicer.py","file_name":"test_layer_slicer.py","file_ext":"py","file_size_in_byte":12648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418264422","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/breno/Envs/djangoplus/lib/python3.7/site-packages/djangoplus/ui/components/utils/forms.py\n# Compiled at: 2019-04-13 15:22:11\n# Size of source mod 2**32: 966 bytes\nfrom djangoplus.ui.components import forms\nfrom djangoplus.ui.components.utils import MultiScheduleTable, ScheduleTable\n\nclass ScheduleTableForm(forms.Form):\n values = forms.CharField(label='Values', widget=(forms.widgets.HiddenInput()))\n\n def __init__(self, *args, **kwargs):\n schedule = kwargs.get('initial', {}).pop('schedule', [])\n kwargs['initial']['values'] = ''\n (super().__init__)(*args, **kwargs)\n form_prefix = self.prefix and '{}-'.format(self.prefix) or None\n self.component = MultiScheduleTable(schedule, (self.request), title='Horários', form_prefix=form_prefix)\n\n def clean_values(self):\n values = self.cleaned_data['values']\n cleaned_values = []\n if values:\n for value in values.split('|'):\n i, interval = value.split('::')\n cleaned_values.append((ScheduleTable.WEEK_DAYS[(int(i) - 1)], interval))\n\n return cleaned_values","sub_path":"pycfiles/djangoplus-0.0.98.tar/forms.cpython-37.py","file_name":"forms.cpython-37.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403344686","text":"import unittest\nfrom city_functions import mesto\n\nclass NamesTestCase(unittest.TestCase):\n def test_mesto(self):\n format_city = mesto('odessa', 'ukraine')\n self.assertEqual(format_city, 'Odessa, Ukraine')\n\n def test_mesto_with_population(self):\n format_city = mesto('odessa', 'ukraine', '900 000')\n self.assertEqual(format_city, 'Odessa, Ukraine - population is 900 000')\n\nunittest.main()","sub_path":"Book_Python/test_city_functions.py","file_name":"test_city_functions.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"368736583","text":"'''\n\nCopyright 2017 Ewan Mellor\n\nChanges authored by Hadi Esiely:\nCopyright 2018 The Johns Hopkins University Applied Physics Laboratory LLC.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\ncontributors may be used to endorse or promote products derived from this\nsoftware without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nWHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\nOTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n'''\n\nfrom datetime import datetime\nimport errno\nimport os\n\nimport phonenumbers\n\n\ndef do_callback(handler, f, *args):\n cb = getattr(handler, f.__name__, None)\n if cb is None:\n return None\n return cb(*args)\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as err:\n if err.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\ndef normalize_phone_number(s):\n if not s:\n return None\n\n # Note that we're assuming USA phone numbers here, unless the user\n # starts the number with a +.\n country = None if s[0] == '+' else 'US'\n no = phonenumbers.parse(s, country)\n if not phonenumbers.is_valid_number(no):\n return None\n else:\n return phonenumbers.format_number(\n no, phonenumbers.PhoneNumberFormat.E164)\n\n\ndef printable_phone_number(s):\n if not s:\n return ''\n\n # Note that we're assuming USA here, but this shouldn't matter, because\n # s should already be in E.164 format.\n no = phonenumbers.parse(s, 'US')\n if not phonenumbers.is_valid_number(no):\n return s\n\n # We're checking for +1 here, but this simply means that non-US numbers\n # will have the international prefix.\n fmt = (phonenumbers.PhoneNumberFormat.NATIONAL if no.country_code == 1\n else phonenumbers.PhoneNumberFormat.INTERNATIONAL)\n return phonenumbers.format_number(no, fmt)\n\n\ndef rm_f(filename):\n try:\n os.remove(filename)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n\ndef utcnow_str():\n return datetime.utcnow().isoformat('T')\n\n\ndef timestamp_filename(ts, ext):\n return '%s.%s' % (ts.replace(':', '.'), ext)\n","sub_path":"holonet-web/holonet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103519669","text":"import db_connector\nfrom stock_model import StockPrediction\nfrom sector_model import SectorPrediction, write_result_to_database, write_result_to_excel\nimport pandas as pd\nfrom datetime import datetime\nimport sys, os\nimport tensorflow as tf\nimport numpy as np\nfrom numpy.random import RandomState\nimport math\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelBinarizer\nimport argparse\nimport re\nfrom pathlib import Path\nimport traceback\nimport pickle\nimport hashlib\nimport csv\n\nimport logging\nlogger = logging.getLogger(\"forecast\")\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s')\nlogging.root.setLevel(level=logging.INFO)\nlogger.info(\"Running %s\" % ' '.join(sys.argv))\n\n\n###########################################################################################################\n###########################################################################################################\n###########################################################################################################\n\n\ndef get_argparser():\n parser = argparse.ArgumentParser(add_help=True)\n parser.add_argument('--experiment_id', type=int, action='store', dest='experiment_id',\n help='id of experiment_id in the database')\n parser.add_argument('--pred_start_date', type=str, action='store', dest='pred_start_date',\n help='Start date of the prediction (include) under format YYYY-MM-DD')\n parser.add_argument('--pred_end_date', type=str, action='store', dest='pred_end_date',\n help='End date of the prediction (include) under format YYYY-MM-DD')\n\n args = parser.parse_args()\n \n return args \n\n\n \n\nif __name__ == \"__main__\":\n when_run = datetime.now()\n args = get_argparser()\n\n train_start_date_str = '2011-04-01'\n train_end_date_str = '2018-08-21'\n\n train_start_date = datetime.strptime(train_start_date_str, '%Y-%m-%d').date()\n train_end_date = datetime.strptime(train_end_date_str, '%Y-%m-%d').date()\n \n pred_start_date = datetime.strptime(args.pred_start_date, '%Y-%m-%d').date()\n pred_end_date = datetime.strptime(args.pred_end_date, '%Y-%m-%d').date() \n\n\n df = db_connector.query_ml_results_summary_table(id=args.experiment_id)\n assert df.shape[0] == 1\n dict_exp_settings = df.to_dict(orient='records')[0]\n\n\n dict_params = {}\n for pair in dict_exp_settings[\"training_parameters\"].split(\",\"):\n var_name, var_val = pair.split(\"=\")\n var_name = var_name.strip()\n try:\n if \".\" in var_val:\n var_val = float(var_val)\n else:\n var_val = int(var_val)\n except:\n continue\n \n dict_params[var_name] = var_val\n \n sector_name, model_type, n_classes, threshold_change, threshold_change_extreme, n_lags, future_n_lags = \\\n dict_exp_settings[\"sector\"], dict_params[\"model_type\"], dict_params[\"n_classes\"], dict_params[\"threshold_change\"], dict_params[\"threshold_change_extreme\"], dict_params[\"n_lags\"], dict_params[\"future_n_lags\"]\n #print(sector_name)\n para_str = \"_\".join([sector_name, str(model_type), str(n_classes), str(threshold_change), str(threshold_change_extreme), str(n_lags), str(future_n_lags)])\n saved_model_dir = dict_exp_settings[\"file_name_of_trained_model\"]\n #log_file_path = \"{}_eval_{}_{}.log\".format(saved_model_dir, pred_start_date, pred_end_date)\n\n manual_features = dict_exp_settings[\"training_features\"]\n manual_features = manual_features[manual_features.index('['):] \n manual_features = manual_features.replace(\"'options_f0_0', 'options_f0_1', 'options_f1_0', 'options_f1_1'\", \"'options'\")\n print(manual_features)\n \n #####################\n if manual_features:\n import ast\n manual_features = ast.literal_eval(manual_features)\n logger.info(\"manual_features ({}) = {}\".format(len(manual_features), manual_features))\n \n '''\n list_economic_indicators = [\"$A191RL1Q225SBEA\", \"$USEPUINDXD\", \"$DPRIME\", \"$DEXCHUS\", \"$DEXJPUS\",\n \"$CPFF\", \"$HOUST\", \"$LNU02000000\", \"$DCOILWTICO\", \n \"$UNEMPLOY\", \"$DFF\", \"$economic_conf\"]\n '''\n test_metrics_results_dict = None\n test_confusion_results_dict = None\n test_otherresults_dict = None\n\n try:\n #list_economic_indicators = db_connector.retrieve_list_interested_economic_indicators(update_frequency = [\"daily\"], observation_start = train_start_date, observation_end = pred_end_date)\n #list_economic_indicators = db_connector.retrieve_list_interested_economic_indicators_2()\n list_economic_indicators = db_connector.retrieve_list_interested_economic_indicators(observation_start = train_start_date, observation_end = train_end_date)\n list_economic_indicators += ['kilowattusage']\n list_economic_indicators = list(sorted(list_economic_indicators))\n \n list_insider_transactions = [\"insider_buy_amount_of_shares\", \"insider_sell_amount_of_shares\", \"insider_deltabuysell_amount_of_shares\"]\n list_stock_metrics = [\"dilutedeps\", \"debttoequity\", \"pricetoearningsgrowth\", \"cashpersharepercent\"]\n list_googletrend = [\"googletrend\"]\n list_ta_indicators = []#[\"OBV\", \"AD\", \"ADOSC\"]\n list_other_indicators = [\"options\"]\n \n\n \n if manual_features:\n unknown_features = [f for f in manual_features if f not in list_economic_indicators + list_insider_transactions + list_stock_metrics + list_googletrend + list_ta_indicators + list_other_indicators]\n logger.error(\"unknown_features ({}) = {}\".format(len(unknown_features), unknown_features))\n \n list_economic_indicators = [f for f in list_economic_indicators if f in manual_features]\n list_insider_transactions = [f for f in list_insider_transactions if f in manual_features]\n list_stock_metrics = [f for f in list_stock_metrics if f in manual_features]\n list_googletrend = [f for f in list_googletrend if f in manual_features]\n list_ta_indicators = [f for f in list_ta_indicators if f in manual_features]\n list_other_indicators = [f for f in list_other_indicators if f in manual_features]\n \n logger.info(\"list_economic_indicators ({}) = {}\".format(len(list_economic_indicators), list_economic_indicators))\n logger.info(\"list_insider_transactions ({}) = {}\".format(len(list_insider_transactions), list_insider_transactions))\n logger.info(\"list_stock_metrics ({}) = {}\".format(len(list_stock_metrics), list_stock_metrics))\n logger.info(\"list_googletrend ({}) = {}\".format(len(list_googletrend), list_googletrend))\n logger.info(\"list_ta_indicators ({}) = {}\".format(len(list_ta_indicators), list_ta_indicators))\n logger.info(\"list_other_indicators ({}) = {}\".format(len(list_other_indicators), list_other_indicators))\n \n list_features = list_economic_indicators + list_insider_transactions + list_stock_metrics + list_googletrend + list_ta_indicators + list_other_indicators\n #str_hash_features = get_hashvalue(list_features)\n #saved_model_dir = \"{}_{}\".format(saved_model_dir, str_hash_features)\n \n sector_model = SectorPrediction(sector_name=sector_name, model_type=model_type,\n n_classes=n_classes, threshold_change=threshold_change, threshold_change_extreme=threshold_change_extreme,\n n_lags=n_lags, future_n_lags=future_n_lags, saved_model_dir=saved_model_dir,\n list_economic_indicators=list_economic_indicators, list_insider_transactions=list_insider_transactions, list_stock_metrics=list_stock_metrics, \n list_googletrend=list_googletrend, list_ta_indicators=list_ta_indicators, list_other_indicators=list_other_indicators)\n \n \n logger.info(\"Predict data:\")\n sector_model.create_model(True, True)\n sector_model.load_model()\n Y_pred, pred_probY, df_X = sector_model.run_predict(pred_start_date, pred_end_date)\n df_X[\"Y_pred\"] =Y_pred\n df_X[\"Y_pred_prob\"] = pred_probY\n pred_df = df_X[[\"stock_quote\", \"Y_pred\", \"Y_pred_prob\"]]\n \n out_csv_file = \"realtime/{}_{}_{}_{}.csv\".format(args.experiment_id, sector_name, args.pred_start_date, args.pred_end_date)\n logger.info(\"Write the prediction to csv file: {}\".format(out_csv_file))\n pred_df.to_csv(out_csv_file)\n \n # Write to standard output csv format of hedge fund\n pred_df[\"date\"] = pred_df.index\n care_df = pred_df[pred_df[\"Y_pred\"]==\"Up\"]\n stock_exchange_df = db_connector.query_stock_exchange_field(care_df[\"stock_quote\"].values.tolist())\n stock_exchange_df = stock_exchange_df[[\"ticker\", \"stock_exchange\"]]\n care_df = pd.merge(care_df, stock_exchange_df, left_on='stock_quote', right_on='ticker')\n care_df[\"Action\"] = \"BUY\"\n care_df[\"Quantity\"] = 100\n care_df[\"Symbol\"] = care_df[\"stock_quote\"] \n care_df[\"SecType\"] = \"STK\"\n care_df[\"Exchange\"] = care_df[\"stock_exchange\"]\n care_df[\"Currency\"] = \"USD\"\n care_df[\"TimeInForce\"] = \"OPG\"\n care_df[\"OrderType\"] = \"MKT\"\n care_df[\"BasketTag\"] = \"inferfund1\"\n care_df[\"Account\"] = \"U2642827\"\n care_df[\"OrderRef\"] = care_df[\"date\"]\n \n \n care_df = care_df[[\"Action\", \"Quantity\", \"Symbol\", \"SecType\", \"Exchange\", \"Currency\", \"TimeInForce\", \"OrderType\", \"BasketTag\", \"Account\", \"OrderRef\"]]\n out_csv_file = \"realtime/hedgefundformat_{}_{}_{}_{}.csv\".format(args.experiment_id, sector_name, args.pred_start_date, args.pred_end_date)\n logger.info(\"Write the prediction to csv file: {}\".format(out_csv_file))\n care_df.to_csv(out_csv_file, index=False) \n \n except Exception as e:\n logger.error(str(e))\n print(traceback.format_exc())\n\n logger.info(\"Finished.\")\n \n \n \n ","sub_path":"python/stock_model/sector_model_load_predict.py","file_name":"sector_model_load_predict.py","file_ext":"py","file_size_in_byte":10196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244868176","text":"import torch, os, sys, pdb, math\nfrom torch.nn import functional as F\nimport numpy as np\nimport itertools\nfrom numpy.random import RandomState\n\ndef debug_memory():\n import collections, gc, resource, torch\n print('maxrss = {}'.format(\n resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))\n tensors = collections.Counter((str(o.device), o.dtype, tuple(o.shape))\n for o in gc.get_objects()\n if torch.is_tensor(o))\n for line in tensors.items():\n print('{}\\t{}'.format(*line))\n pdb.set_trace()\n\ndef al_method_grad(mod, w, x_cand, avail_cands, args, c):\n if w is None:\n tuned_w = mod.parameters()\n else:\n tuned_w = w\n\n #dists = np.ones((cand_data.shape[0], target_data.shape[0]))\n #for i in range(cand_data.shape[0]):\n # for j in range(target_data.shape[0]):\n # dists[i, j] = torch.norm(cand_data[i] - target_data[j]).item()\n\n\n grad_ests = []\n for i in range(len(avail_cands)): #x_cand.shape[0]):\n grad_ests.append(0.0)\n\n with torch.no_grad():\n logits = mod(x_cand, vars = tuned_w, bn_training=False)\n original_ests = F.softmax(logits, dim=1).argmax(dim=1)\n for i in range(100):\n cand_ests = mod(x_cand, vars = tuned_w, bn_training=False, dropout_rate=args.dropout_rate) \n for j in range(len(avail_cands)): #x_cand.shape[0]):\n if c: #classification\n loss = F.cross_entropy(cand_ests[avail_cands[j]].unsqueeze(0), original_ests[avail_cands[j]].unsqueeze(0))\n else:\n loss = F.mse_loss(cand_ests[avail_cands[j]], original_ests[avail_cands[j]])\n grad = torch.autograd.grad(loss, tuned_w, retain_graph=True)\n norm = 0.0\n for layer in grad:\n norm += (layer.data.norm(2).item()**2.0) \n grad_ests[j] += math.sqrt(norm)\n\n '''labeled_cands = np.setdiff1d(range(cand_data.shape[0]), avail_cand_idx)\n max_min_dists = []\n C = list(itertools.combinations(avail_cand_idx, req_count))\n for i in range(len(C)):\n x = C[i]\n min_dists = []\n for pt in range(target_data.shape[0]):\n min_dist = np.inf\n for exp_cands in np.concatenate([labeled_cands, x]):\n min_dist = min(min_dist, dists[exp_cands, pt])\n min_dists.append(min_dist)\n max_min_dists.append([x, max(min_dists)])\n idx1 = np.argmin(np.array(max_min_dists)[:,1])\n\n pdb.set_trace()\n exp_grads = [dropout_ests[d[0][0]] for d in max_min_dists]\n\n idx = np.argmax(np.array(exp_grads))'''\n return avail_cands[np.argmax(np.array(grad_ests))] # max_min_dists[idx][0]\n\ndef al_method_learned(mod, tuned_w, cand_data, avail_cand_idx, update=False):\n if update:\n w = tuned_w\n else:\n w = mod.parameters()\n raw_comps, comps = [], []\n diffs = []\n for i in range(cand_data.shape[0]):\n c = []\n for j in range(cand_data.shape[0]):\n if i == j:\n continue\n c.append(cand_data[i] - cand_data[j])\n diffs.append(torch.stack(c))\n diffs = torch.cat(diffs)\n ests = mod(diffs, vars = w, bn_training=True)[:,-1]\n split_ests = torch.split(ests, cand_data.shape[0]-1)\n comps = [torch.sum(torch.sign(split_ests[i])).item() for i in range(cand_data.shape[0])]\n raw_comps = [torch.sum(split_ests[i]).item() for i in range(cand_data.shape[0])]\n #comps.append(torch.sum(torch.sign(ests)).item())\n #raw_comps.append(torch.sum(ests).item())\n idxs = np.argsort(np.array(comps))\n raw_idxs = np.argsort(np.array(raw_comps))\n return idxs\n #for i in idxs:\n # if i in avail_cand_idx:\n # return i\n \n\ndef al_method_dropout(mod, tuned_w, cand_data, avail_cand_idx, args):\n if tuned_w is None:\n tuned_w = mod.parameters()\n x_cand = cand_data\n dropout_ests = []\n for i in range(cand_data.shape[0]):\n dropout_ests.append([])\n #for i in range(1000):\n for i in range(100):\n cand_ests = mod(x_cand, vars = tuned_w, bn_training=True, dropout_rate=args.dropout_rate) \n\n for j in range(cand_data.shape[0]):\n dropout_ests[j].append(cand_ests[j].cpu().detach().numpy())\n variances = []\n for i in avail_cand_idx: #dropout_ests:\n ests = np.stack(dropout_ests[i])\n mean = np.mean(ests,axis=0)\n dist = 0.0\n for c in dropout_ests[i]:\n dist += np.sum((c - mean)**2.0)\n variances.append(dist/len(dropout_ests[i]))\n idx = np.argmax(variances)\n return avail_cand_idx[idx] # max_min_dists[idx][0]\n\ndef al_method_k_centers(mod, tuned_w, cand_data, avail_cand_idx, target_data, dist_metric=\"output\"):\n if tuned_w is None:\n tuned_w = mod.parameters()\n x_cand = cand_data\n x_tgt = target_data\n cand_ests = mod(x_cand, vars = tuned_w, bn_training=False)\n tgt_ests = mod(x_tgt, vars = tuned_w, bn_training=False)\n dists = np.ones((cand_data.shape[0], target_data.shape[0]))\n out_dists = np.ones((cand_data.shape[0], target_data.shape[0]))\n in_dists = np.ones((cand_data.shape[0], target_data.shape[0]))\n for i in range(cand_data.shape[0]):\n for j in range(target_data.shape[0]):\n in_dists[i, j] = torch.norm(cand_data[i] - target_data[j])\n out_dists[i, j] = torch.norm(cand_ests[i] - tgt_ests[j])\n if dist_metric == \"output\":\n dists[i, j] = out_dists[i,j]\n elif dist_metric == \"input_output\":\n dists[i, j] = out_dists[i,j] * in_dists[i,j]\n elif dist_metric == \"input\":\n dists[i, j] = in_dists[i,j]\n\n labeled_cands = np.setdiff1d(range(cand_data.shape[0]), avail_cand_idx)\n max_min_dists = []\n for x in avail_cand_idx:\n min_dists = []\n for pt in range(target_data.shape[0]):\n min_dist = np.inf\n for exp_cands in np.concatenate([labeled_cands, [x]]):\n min_dist = min(min_dist, dists[exp_cands, pt])\n min_dists.append(min_dist)\n max_min_dists.append([x, max(min_dists)])\n idx = np.argmin(np.array(max_min_dists)[:,1])\n #idx = np.argmin(np.array(max_min_dists)[:,1])\n return avail_cand_idx[idx] # max_min_dists[idx][0]\n\nclass QuerySelector():\n def __init__(self):\n self.query_order = None\n self.order_idx = 0\n self.rand = RandomState(222)\n self.query_order = []\n\n def all_queries(self, cands, k):\n orderings = [np.random.permutation(cands) for _ in range(10)]\n queries = []\n for o in orderings:\n queries.append([cands[i] for i in o])\n return queries\n\n def next_order(self):\n self.order_idx += 1\n if self.order_idx >= len(self.query_order):\n return False\n return True\n\n def query(self, args, net, w, cands, avail_cands, targets, k, method, classification):\n if method == \"random\":\n if len(self.query_order) == 0:\n self.query_order = self.all_queries(avail_cands, k)\n s = self.query_order[self.order_idx].pop(0)\n if method == \"output_space\":\n s = al_method_k_centers(net, w, cands, avail_cands, targets, dist_metric=\"output\")\n if method == \"input_space\":\n s = al_method_k_centers(net, w, cands, avail_cands, targets, dist_metric=\"input\")\n if method == \"input_output\":\n s = al_method_k_centers(net, w, cands, avail_cands, targets, dist_metric=\"input_output\")\n if method == \"dropout\":\n s = al_method_dropout(net, w, cands, avail_cands, args)\n if method == \"gaussian\":\n s = al_method_gaussian(net, w, cands)\n if method == \"gradient\":\n s = al_method_grad(net, w, cands, avail_cands, args, classification)\n if method == \"learned\":\n if len(self.query_order) == 0:\n self.query_order = list(al_method_learned(net, w, cands, avail_cands))\n s = self.query_order.pop(0)\n #for q in self.query_order:\n # if q in avail_cands:\n # return q\n return s\n\n","sub_path":"forked_stock/active.py","file_name":"active.py","file_ext":"py","file_size_in_byte":8118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"68867948","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport stat\nimport config as cfg\nfrom os.path import join\n\n__all__ = ( 'logfiles', )\n# сборка пакета. добавить имена которые будут экспортироваться в пакет\n\nLOGFILE_MASK = re.compile( r'''\n ^ # from start of string\n ([\\w\\d]+) # log name any alphanumeric\n (?:\\.log)? # log ext may be\n (\\.\\d+)? # log count number may be\n (?:\\.gz)? # log compressed may be\n $ # to end of string\n ''', re.VERBOSE )\n\ndef logfiles( appname, logname=None ):\n if logname is None:\n path = cfg.root_log_path\n logn = appname\n else:\n path = join( cfg.root_log_path, appname )\n logn = logname\n #for entry in os.scandir( path ): # scandir added in python 3.5\n for entry in os.listdir( path ): # тоже самое без scandir\n entry_name = join( path, entry )\n statinfo = os.stat( entry_name)\n if statinfo.st_mode & stat.S_IFREG:\n #if entry.is_file():\n #M = LOGFILE_MASK.search( entry.name ) # возвращается дескриптор сопоставления\n M = LOGFILE_MASK.search( entry )\n if M:\n #print( M.start(), M.end() )\n #print( M.group(0) ) # руппа в выражении RE под номером 0\n #print( M.groups() )\n if M.group(1) == logn:\n #yield join( path, entry.name )\n yield join( path, entry )","sub_path":"05_Project_Logs/packet_01_logs/logfiles.py","file_name":"logfiles.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581276968","text":"from .models import Post\nfrom django import forms\nimport datetime\nclass RawPostForm(forms.Form):\n title = forms.CharField(initial= 'Trung')\n slug = forms.SlugField()\n description = forms.CharField()\n content = forms.CharField()\n published = forms.BooleanField(required=False)\n created = forms.DateTimeField(initial=datetime.date.today)\n","sub_path":"Django/netmag/blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"996391","text":"from django.shortcuts import render\nfrom datetime import datetime\n\ndef index(request):\n #return HttpResponse(\"Hello, world. You're at the polls index.\")\n d = {\n 'hour': datetime.now().hour,\n 'message': 'Sample message',\n }\n \n return render(request, 'home/index.html')\n","sub_path":"g_django/g_django/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"454465739","text":"import boto3\nimport os\nfrom os import path\nfrom configparser import ConfigParser\nfrom botocore.exceptions import *\nimport sys\nimport os\nimport base64\nimport datetime\nimport hashlib\nimport hmac\nimport requests\nimport urllib\n\n\ndef list_instances(logger, tags, ** kwargs):\n ec2 = boto3.resource('ec2')\n\n ec2_filters = []\n for tag_key in tags.keys():\n ec2_filters.append(\n {'Name': 'tag:' + tag_key, 'Values': [tags[tag_key]]})\n instances = ec2.instances.filter(Filters=ec2_filters)\n logger.debug(instances)\n ec2_instances = []\n for instance in instances:\n # logger.debug(instance)\n instance_struct = {}\n instance_struct['Id'] = instance.id\n instance_struct['Name'] = ''\n instance_struct['State'] = instance.state['Name']\n logger.debug(instance.tags)\n if instance.tags != None:\n for tag in instance.tags:\n if tag['Key'] == 'Name':\n instance_struct['name'] = tag['Value']\n\n ec2_instances.append(instance_struct)\n logger.debug(ec2_instances)\n return ec2_instances\n\n\ndef stop_instances(ids):\n\n ec2 = boto3.resource('ec2')\n ec2.instances.filter(InstanceIds=ids).stop()\n\n\n# Key derivation functions. See:\n# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n\ndef list_instances_api(logger, tags, ** kwargs):\n\n # Read AWS access key from env. variables or configuration file. Best practice is NOT\n # to embed credentials in code.\n access_key = os.environ.get('AWS_ACCESS_KEY_ID')\n secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')\n if access_key is None or secret_key is None:\n config = ConfigParser()\n config.read([path.join(path.expanduser(\"~\"), '.aws/credentials')])\n try:\n access_key = config.get('default', 'aws_access_key_id')\n secret_key = config.get(\n 'default', 'aws_secret_access_key')\n except:\n raise Exception(\"No access and secret key is available.\")\n logger.debug(access_key)\n logger.debug(secret_key)\n\n method = 'GET'\n service = 'ec2'\n host = 'ec2.amazonaws.com'\n # region = 'us-east-1'\n region = 'us-west-2'\n endpoint = 'https://ec2.amazonaws.com'\n # request_parameters = 'Action=DescribeRegions&Version=2013-10-15'\n request_parameters = 'Action=DescribeInstances&Version=2013-10-15'\n\n ec2_filters = []\n for tag_key in tags.keys():\n ec2_filters.append(\n {'Name': 'tag:' + tag_key, 'Values': [tags[tag_key]]})\n\n # Create a date for headers and the credential string\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n logger.debug('amzdate=' + amzdate + '|')\n datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n # ************* TASK 1: CREATE A CANONICAL REQUEST *************\n # http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n\n # Step 1 is to define the verb (GET, POST, etc.)--already done.\n\n # Step 2: Create canonical URI--the part of the URI from domain to query\n # string (use '/' if no path)\n canonical_uri = '/'\n\n # Step 3: Create the canonical query string. In this example (a GET request),\n # request parameters are in the query string. Query string values must\n # be URL-encoded (space=%20). The parameters must be sorted by name.\n # For this example, the query string is pre-formatted in the request_parameters variable.\n canonical_querystring = request_parameters\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the\n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n signed_headers = 'host;x-amz-date'\n\n # Step 6: Create payload hash (hash of the request body content). For GET\n # requests, the payload is an empty string (\"\").\n payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + \\\n '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + \\\n '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + \\\n '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, (string_to_sign).encode(\n 'utf-8'), hashlib.sha256).hexdigest()\n\n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in\n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + \\\n credential_scope + ', ' + 'SignedHeaders=' + \\\n signed_headers + ', ' + 'Signature=' + signature\n\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\",\n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n headers = {'x-amz-date': amzdate, 'Authorization': authorization_header}\n logger.debug(headers)\n # ************* SEND THE REQUEST *************\n request_url = endpoint + '?' + canonical_querystring\n\n print('\\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')\n print('Request URL = ' + request_url)\n r = requests.get(request_url, headers=headers)\n\n print('\\nRESPONSE++++++++++++++++++++++++++++++++++++')\n print('Response code: %d\\n' % r.status_code)\n print(r.text)\n\n ec2_instances = []\n for instance in instances:\n\n instance_struct = {}\n instance_struct['Id'] = instance.id\n instance_struct['Name'] = ''\n instance_struct['State'] = instance.state['Name']\n for tag in instance.tags:\n if tag['Key'] == 'Name':\n instance_struct['name'] = tag['Value']\n\n ec2_instances.append(instance_struct)\n\n return ec2_instances\n","sub_path":"cloudctl/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7075035","text":"import sys, subprocess\n\ndef main():\n\twhile 1:\n\t\tcmdlist = [\"python\", \"-m\", \"execnet.script.socketserver\"]\n\t\tcmdlist.extend(sys.argv[1:])\n\t\ttext = \"starting subcommand: \" + \" \".join(cmdlist)\n\t\tprint(text)\n\t\tprocess = subprocess.Popen(cmdlist)\n\t\tprocess.wait()","sub_path":"Deployment/slave/UnityClusterSlave.py","file_name":"UnityClusterSlave.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"258864839","text":"'''Define functions for rotating density matrices in the QED simulation of a laser-atom system.\nAuthor: Manish Patel\nDate created: 12/05/2021\n'''\n\nfrom LASED.density_matrix import *\nimport numpy as np\nimport math\nimport copy\n\ndef wigner_D(J, alpha, beta, gamma):\n \"\"\"Calculates the Wigner D-matrix for rotation by Eueler angles (alpha, beta, gamma).\n \n Parameters:\n J (int): total angular momentum quantum number of the state which will be rotated with the \n resulting D-matrix.\n alpha (float): rotation around z-axis in radians.\n beta (float): rotation about the y'-axis in radians.\n gamma (float): rotation about the z''-axis in radians.\n \n Returns:\n ndarray: A square matrix of size 2J+1.\n \"\"\"\n size = 2*J+1 # Number of sub-states\n m = np.linspace(-J, J, size, dtype=int) # Projections of J\n D = np.zeros((size, size), dtype = complex) # Set up D-matrix\n for i, mp in enumerate(m):\n for j, mpp in enumerate(m):\n alpha_const = math.cos(-mp*alpha)+1.j*math.sin(-mp*alpha)\n gamma_const = math.cos(-mpp*gamma)+1.j*math.sin(-mpp*gamma)\n D[i, j] = alpha_const*small_Wigner_D(J, beta, mp, mpp)*gamma_const\n return D\n\ndef small_Wigner_D(J, beta, mp, m):\n \"\"\"Calculates the small Wigner D-matrix elements for rotation.\n \n Parameters:\n J (int): total angular momentum quantum number of the state which will be rotated with the resulting D-matrix.\n beta (float): rotation about the y'-axis in radians.\n mp (int): row number of element in the Wigner D-matrix\n m (int): column number oif element in the Wigner D-matrix\n \n Returns:\n float: The small Wigner D-matrix elements\n \"\"\"\n const = np.sqrt((math.factorial(J+mp))*math.factorial(J-mp)*math.factorial(J+m)*math.factorial(J-m))\n d_sum = 0\n # Define limits so sum does not contain negative factorials\n s_max = min(J+m, J-mp)\n s_min = max(0, m-mp)\n sum_index = np.linspace(s_min, s_max, )\n for s in range(s_min, s_max+1): # Have to go to s_max+1 or will miss out on the s_max value\n numerator = np.power(-1, mp - m + s)*np.power(math.cos(beta/2), 2*J+m-mp-2*s)*np.power(math.sin(beta/2), mp-m+2*s)\n denominator = math.factorial(J+m-s)*math.factorial(s)*math.factorial(mp-m+s)*math.factorial(J-mp-s)\n d_sum += numerator/denominator\n \n return const*d_sum\n\ndef rotation(rho, J, alpha, beta, gamma):\n \"\"\"Rotates a density matrix by the wigner D-matrix.\n \n The rotation is determined by Euler angles (alpha, beta, gamma). (rho_newframe) = (D)(rho)(D*).\n \n Parameters:\n J (int): total angular momentum quantum number of the state which will be rotated with the \n resulting D-matrix.\n alpha (float): rotation around z-axis in radians.\n beta (float): rotation about the y'-axis in radians.\n gamma (float): rotation about the z''-axis in radians.\n \n Returns:\n ndarray: The rotated density matrix.\n \"\"\"\n D_matrix = np.transpose(wigner_D(J, alpha, beta, gamma))\n D_conj = np.transpose(np.conj(D_matrix))\n return np.dot(D_matrix, np.dot(rho, D_conj))\n\ndef rotateInitialMatrix(flat_rho, n, E, G, alpha, beta, gamma):\n \"\"\"Rotate the excited and ground state populations by the Euler angles.\n \n Parameters:\n flat_rho (list): A flattened 2D density matrix\n n (int): Number of substates which compose the density matrix flat_rho\n E (list of States): list of excited State objects which compose flat_rho\n G (list of States): list of ground State objects which compose flat_rho\n alpha (float): rotation around z-axis in radians.\n beta (float): rotation about the y'-axis in radians.\n gamma (float): rotation about the z''-axis in radians.\n \n Returns:\n list of lists: A rotated flattened 2D density matrix\n \"\"\"\n # Make a copy to return\n rotated_rho = copy.deepcopy(flat_rho)\n # Rotate the excited state populations and atomic coherences\n J_E = JNumber(E)\n rotated_excited_rho = rotation(getSingleStateMatrix(rotated_rho, n, E), J_E, alpha, beta, gamma)\n appendDensityMatrixToFlatCoupledMatrix(rotated_rho, rotated_excited_rho, E, n)\n \n # Rotate the ground state populations and atomic coherences\n J_G = JNumber(G)\n rotated_ground_rho = rotation(getSingleStateMatrix(rotated_rho, n, G), J_G, alpha, beta, gamma)\n appendDensityMatrixToFlatCoupledMatrix(rotated_rho, rotated_ground_rho, G, n)\n \n return rotated_rho","sub_path":"base-LASED/LASED/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390659009","text":"#!/usr/bin/env python\n#-*-coding:utf-8-*-\n\n\nimport asyncio\nimport json\nimport logging\nimport re\nimport requests\nimport telepot\nimport telepot.aio\nfrom telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton\nfrom telepot.namedtuple import ReplyKeyboardRemove\nfrom datetime import datetime\n\n\nlogging.basicConfig(\n filename='logs',\n filemode='a',\n level=logging.DEBUG,\n format='%(asctime)s %(message)s'\n )\n\n\nAPI_URL = 'https://api.coinmarketcap.com/v1/ticker'\n\n\ndef comma_me(amount):\n orig = amount\n new = re.sub(\"^(-?\\d+)(\\d{3})\", '\\g<1>,\\g<2>', amount)\n if orig == new:\n return new\n else:\n return comma_me(new)\n\n\ndef get_from_api(url=API_URL, convert='EUR', limit=None):\n \"\"\"Getting infos from API using requests\"\"\"\n params = {'convert': convert}\n if limit:\n params['limit'] = limit\n response = requests.get(url, params=params)\n if response.status_code != 200:\n error_msg = \"Couldn't get infos from API\"\n raise ConnectionError(error_msg)\n else:\n result = response.json()\n return result\n\n\nclass Currency(object):\n \"\"\"Representation of a currency in CoinMarketCap API\"\"\"\n\n def __init__(self, symbol, id=None):\n self.symbol = symbol.upper()\n\n def __repr__(self):\n return ''.format(self.symbol)\n\n def get_infos(self, conversion=None):\n if not conversion:\n result = get_from_api('{url}/{id}'.format(url=API_URL, id=self.id))\n else:\n result = get_from_api(\n '{url}/{id}'.format(url=API_URL, id=self.id),\n convert=conversion\n )\n infos = result.pop()\n for key, value in infos.items():\n setattr(self, key, value) # each key is now an attr of class\n\n @staticmethod\n def all():\n \"\"\"Returns a dict where keys are currencies' symbols\n and values are names\"\"\"\n result = get_from_api(API_URL)\n response = []\n for infos in result:\n currency = Currency(infos['symbol'], infos['id'])\n for key, value in infos.items():\n if key not in ['symbol', 'id']:\n setattr(currency, key, value)\n response.append(currency)\n return response\n\n\nasync def on_chat_message(msg):\n global chat_id\n content_type, chat_type, chat_id = telepot.glance(msg)\n date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n username = msg['from']['username']\n text = msg['text']\n log = ('Chat: {content_type} '\n '{chat_type} {chat_id} '\n '{username} {text}').format(\n content_type=content_type,\n chat_type=chat_type,\n chat_id=chat_id,\n username=username,\n text=text\n )\n print(date, log)\n logging.info(log)\n\n if content_type != 'text':\n return\n\n if text == '/start':\n markup = ReplyKeyboardMarkup(\n keyboard=[\n KeyBoarButton(text='/{}'.format(currency))\n for currency in CURRENCIES\n ]\n )\n await bot.sendMessage(\n chat_id,\n 'Select currency to get information about.',\n reply_markup=markup\n )\n\n elif text in CURRENCIES:\n currency = CURRENCIES[text[1:]]\n currency = currency.get_infos('TRY')\n response = ('{name} @ {date}\\n'\n '1 {symbol} = {price_usd:.2f} USD\\n'\n '1 {symbol} = {price_eur:.2f} EUR\\n'\n '1 {symbol} = {price_try:.2f} TRY\\n'\n '{symbol}-USD Volume in 24h: {usd_volume} USD\\n'\n '{symbol} % Changed in 24h: {percent_change} %').format(\n name=currency.name,\n date=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n symbol=currency.symbol,\n price_usd=float(currency.price_usd),\n price_eur=float(currency.price_eur),\n price_try=float(currency.price_try),\n usd_volume=getattr(currency, '24h_volume_usd'),\n percentage_change=currency.percent_change_24h\n )\n await bot.sendMessage(chat_id, response)\n\n elif text == '/about':\n advice_msg = ('To advice us:\\n'\n 'https://github.com/omergulen/telegram-currency-bot\\n'\n 'or\\n'\n 'omrglen@gmail.com\\n'\n 'Thanks for support!')\n await bot.sendMessage(chat_id, advice_msg)\n await bot.sendMessage(chat_id, '/start to re-open keyboard')\n\n else:\n await bot.sendMessage(\n chat_id,\n ('/start to re-open keyboard\\n'\n '/about to advice us :)')\n )\n\n\nif __name__ == '__main__':\n TOKEN = \"**************************************\"\n\n CURRENCIES = {\n currency.symbol: currency\n for currency in Currency.all()\n }\n\n bot = telepot.aio.Bot(TOKEN)\n answerer = telepot.aio.helper.Answerer(bot)\n\n loop = asyncio.get_event_loop()\n loop.create_task(bot.message_loop({'chat': on_chat_message}))\n\n print('Listening ...')\n\n loop.run_forever()\n","sub_path":"v0.4.1.py","file_name":"v0.4.1.py","file_ext":"py","file_size_in_byte":5269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32826415","text":"from Songbird import *\n\ndonald = Songbird('Donald Duck','Quack-quack!')#Создаем экземпляр/переменную и присваиваем 2 атрибута('имя', 'песня')\nprint(donald.name,'ID: ',id(donald))#выводим ID выведенной памят для экземпляра/переменной donald\ndonald.sing()#Выводит Quack-quack!\ndel donald#В книге, это позволяет очистить память от экземпляра/переменной, но он это делает автоматически\npity = Songbird('Pity','Pity-pity!')\nprint(pity.name,'ID: ',id(pity))\npity.sing()\ndel pitty","sub_path":"SingBird/CheckIDAndDel.py","file_name":"CheckIDAndDel.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433019431","text":"class Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n open = '([{'\n mapping = {\n ')': '(',\n ']': '[',\n '}': '{'\n }\n for l in s:\n if l in open:\n stack.append(l)\n elif stack and stack[-1] == mapping[l]:\n stack.pop()\n else:\n return False\n return stack == []\n\n\nif __name__ == '__main__':\n solution = Solution()\n result = solution.isValid('(]')\n print(result)\n","sub_path":"0020_valid_parentheses.py","file_name":"0020_valid_parentheses.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276121434","text":"def get_end_state(self):\n ' Get end state '\n self.cli_get_netstream_config()\n if self.netstream_cfg:\n self.end_state['type'] = self.type\n self.end_state['record_name'] = self.record_name\n if self.description:\n tmp_value = re.findall('description (.*)', self.netstream_cfg)\n if tmp_value:\n self.end_state['description'] = tmp_value[0]\n if self.match:\n if (self.type == 'ip'):\n tmp_value = re.findall('match ip (.*)', self.netstream_cfg)\n else:\n tmp_value = re.findall('match inner-ip (.*)', self.netstream_cfg)\n if tmp_value:\n self.end_state['match'] = tmp_value\n if self.collect_counter:\n tmp_value = re.findall('collect counter (.*)', self.netstream_cfg)\n if tmp_value:\n self.end_state['collect_counter'] = tmp_value\n if self.collect_interface:\n tmp_value = re.findall('collect interface (.*)', self.netstream_cfg)\n if tmp_value:\n self.end_state['collect_interface'] = tmp_value\n if (self.end_state == self.existing):\n self.changed = False\n self.updates_cmd = list()","sub_path":"Data Set/bug-fixing-5/adfbd04b3ab611a9807a36c7d4ab648d53a811be--fix.py","file_name":"adfbd04b3ab611a9807a36c7d4ab648d53a811be--fix.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232610569","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\nimport os\n\nAUTHOR = u'Gustavo Sandoval'\nSITENAME = u'Almost Brooklyn'\nSITEURL = ''\n\nPATH = 'content'\n\n# Times and dates\nDEFAULT_DATE_FORMAT = '%b %d, %Y'\nTIMEZONE = 'America/Atikokan'\nDEFAULT_LANG = u'en'\n\n# Set the article URL\nARTICLE_URL = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/'\nARTICLE_SAVE_AS = 'blog/{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# # Blogroll\n# LINKS = (('Pelican', 'http://getpelican.com/'),\n# ('Python.org', 'http://python.org/'),\n# ('Jinja2', 'http://jinja.pocoo.org/'),\n# ('You can modify those links in your config file', '#'),)\n\n# # Social widget\n# SOCIAL = (('@gussand', 'http://www.twitter.com/gussand'),\n# ('github', 'http://www.github.com/gussand'),)\n\nDEFAULT_PAGINATION = 10\n\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\n\n# This requires Pelican 3.3+\nSTATIC_PATHS = ['images', 'figures', 'downloads', 'favicon.png']\nPAGE_PATHS = ['downloads']\n\nCODE_DIR = 'downloads/code'\nNOTEBOOK_DIR = 'downloads/notebooks'\n\n# Theme and plugins\nTHEME = 'pelican-octopress-theme/'\nPLUGIN_PATHS = ['pelican-plugins']\nPLUGINS = ['summary', 'liquid_tags.img', 'liquid_tags.video',\n 'liquid_tags.include_code', 'liquid_tags.notebook',\n 'liquid_tags.literal']\n\n# The theme file should be updated so that the base header contains the line:\n#\n# {% if EXTRA_HEADER %}\n# {{ EXTRA_HEADER }}\n# {% endif %}\n#\n# This header file is automatically generated by the notebook plugin\n# if not os.path.exists('_nb_header.html'):\n# import warnings\n# warnings.warn(\"_nb_header.html not found. \"\n# \"Rerun make html to finalize build.\")\n# else:\n# EXTRA_HEADER = open('_nb_header.html').read().decode('utf-8')\n\n\n# Sharing\nTWITTER_USER = 'gussand'\nFACEBOOK_LIKE = False\nTWITTER_TWEET_BUTTON = True\nTWITTER_LATEST_TWEETS = True\nTWITTER_FOLLOW_BUTTON = True\nTWITTER_TWEET_COUNT = 3\nTWITTER_SHOW_REPLIES = 'false'\nTWITTER_SHOW_FOLLOWER_COUNT = 'false'\n#GITHUB_USER = 'gussand'\n#GITHUB_SHOW_USER_LINK = 'true'\n\n# RSS/Atom feeds\nFEED_DOMAIN = SITEURL\nFEED_ATOM = 'atom.xml'\n\n# Search\nSEARCH_BOX = True\n\n# RSS/Atom feeds\nFEED_DOMAIN = SITEURL\nFEED_ATOM = 'atom.xml'\n\n# Search\nSEARCH_BOX = True\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317702965","text":"\nimport MySQLdb\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport datetime\n\n\nconn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"qolsys\", db=\"sunny\")\ncursor = conn.cursor()\n#cursor.execute(\"select insertedtime, count(*) as noofclientsinsertedatgiventime from leshanfinal where insertedtime > ('2018-01-22 20:51:00') and insertedtime < ('2018-01-22 21:7:12')\",);\n\ncursor.execute(\"select atatime, noofclientsconnected from clientsconnected\",);\n\ncolumns = cursor.fetchall()\n\n\n\nprint(columns)\n\n\nfor row in columns:\n\n\n # print(\"{:%m/%d/%Y}\".format(helo))\n\n final = \"{:%d/%H/%M/%S}\".format(row[0])\n\n print(\"value is : \")\n print(final)\n print(row[0],row[1])\n\n#df = pd.DataFrame( [[ij for ij in i] for i in columns] )\n\n#df1=df.rename(columns={'Date': row[0],'Client': row[1]}, inplace=True);\n\n df1 = pd.DataFrame({0:final, 1:[row[1]] })\n\n df1.sort_values(by=1, ascending=False)\n\n plt.scatter(df1[0],df1[1])\n plt.xlabel(final)\n print(final)\n\nplt.ylabel(\"No of Clients connectd at given time\")\nplt.show()\nplt.show()\n\nprint(\"lopp no\")\n\n\n\n\n'''\n\n\n\ndf = pd.DataFrame( [[ij for ij in i] for i in columns] )\n\nprint('hello')\n\n\n\ndf1=df.rename(columns={'Date': row[0],'Client': row[1]}, inplace=True);\n\n'''","sub_path":"codee/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73499475","text":"#\n# Copyright 2014 OpenStack Foundation\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_config import cfg\nfrom six.moves import http_client\nfrom six.moves.urllib import parse\nfrom swiftclient import client as swift_client\nfrom swiftclient import exceptions as swift_exceptions\nfrom swiftclient import utils as swift_utils\n\nfrom ironic.common import exception\nfrom ironic.common.i18n import _\nfrom ironic.common import keystone\n\nswift_opts = [\n cfg.IntOpt('swift_max_retries',\n default=2,\n help=_('Maximum number of times to retry a Swift request, '\n 'before failing.'))\n]\n\n\nCONF = cfg.CONF\nCONF.register_opts(swift_opts, group='swift')\n\nCONF.import_opt('admin_user', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('admin_tenant_name', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('admin_password', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('auth_uri', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('auth_version', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('insecure', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('cafile', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\nCONF.import_opt('region_name', 'keystonemiddleware.auth_token',\n group='keystone_authtoken')\n\n\nclass SwiftAPI(object):\n \"\"\"API for communicating with Swift.\"\"\"\n\n def __init__(self,\n user=None,\n tenant_name=None,\n key=None,\n auth_url=None,\n auth_version=None,\n region_name=None):\n \"\"\"Constructor for creating a SwiftAPI object.\n\n :param user: the name of the user for Swift account\n :param tenant_name: the name of the tenant for Swift account\n :param key: the 'password' or key to authenticate with\n :param auth_url: the url for authentication\n :param auth_version: the version of api to use for authentication\n :param region_name: the region used for getting endpoints of swift\n \"\"\"\n user = user or CONF.keystone_authtoken.admin_user\n tenant_name = tenant_name or CONF.keystone_authtoken.admin_tenant_name\n key = key or CONF.keystone_authtoken.admin_password\n auth_url = auth_url or CONF.keystone_authtoken.auth_uri\n auth_version = auth_version or CONF.keystone_authtoken.auth_version\n auth_url = keystone.get_keystone_url(auth_url, auth_version)\n params = {'retries': CONF.swift.swift_max_retries,\n 'insecure': CONF.keystone_authtoken.insecure,\n 'cacert': CONF.keystone_authtoken.cafile,\n 'user': user,\n 'tenant_name': tenant_name,\n 'key': key,\n 'authurl': auth_url,\n 'auth_version': auth_version}\n region_name = region_name or CONF.keystone_authtoken.region_name\n if region_name:\n params['os_options'] = {'region_name': region_name}\n\n self.connection = swift_client.Connection(**params)\n\n def create_object(self, container, object, filename,\n object_headers=None):\n \"\"\"Uploads a given file to Swift.\n\n :param container: The name of the container for the object.\n :param object: The name of the object in Swift\n :param filename: The file to upload, as the object data\n :param object_headers: the headers for the object to pass to Swift\n :returns: The Swift UUID of the object\n :raises: SwiftOperationError, if any operation with Swift fails.\n \"\"\"\n try:\n self.connection.put_container(container)\n except swift_exceptions.ClientException as e:\n operation = _(\"put container\")\n raise exception.SwiftOperationError(operation=operation, error=e)\n\n with open(filename, \"r\") as fileobj:\n\n try:\n obj_uuid = self.connection.put_object(container,\n object,\n fileobj,\n headers=object_headers)\n except swift_exceptions.ClientException as e:\n operation = _(\"put object\")\n raise exception.SwiftOperationError(operation=operation,\n error=e)\n\n return obj_uuid\n\n def get_temp_url(self, container, object, timeout):\n \"\"\"Returns the temp url for the given Swift object.\n\n :param container: The name of the container in which Swift object\n is placed.\n :param object: The name of the Swift object.\n :param timeout: The timeout in seconds after which the generated url\n should expire.\n :returns: The temp url for the object.\n :raises: SwiftOperationError, if any operation with Swift fails.\n \"\"\"\n try:\n account_info = self.connection.head_account()\n except swift_exceptions.ClientException as e:\n operation = _(\"head account\")\n raise exception.SwiftOperationError(operation=operation,\n error=e)\n\n storage_url, token = self.connection.get_auth()\n parse_result = parse.urlparse(storage_url)\n swift_object_path = '/'.join((parse_result.path, container, object))\n temp_url_key = account_info['x-account-meta-temp-url-key']\n url_path = swift_utils.generate_temp_url(swift_object_path, timeout,\n temp_url_key, 'GET')\n return parse.urlunparse((parse_result.scheme,\n parse_result.netloc,\n url_path,\n None,\n None,\n None))\n\n def delete_object(self, container, object):\n \"\"\"Deletes the given Swift object.\n\n :param container: The name of the container in which Swift object\n is placed.\n :param object: The name of the object in Swift to be deleted.\n :raises: SwiftObjectNotFoundError, if object is not found in Swift.\n :raises: SwiftOperationError, if operation with Swift fails.\n \"\"\"\n try:\n self.connection.delete_object(container, object)\n except swift_exceptions.ClientException as e:\n operation = _(\"delete object\")\n if e.http_status == http_client.NOT_FOUND:\n raise exception.SwiftObjectNotFoundError(object=object,\n container=container,\n operation=operation)\n\n raise exception.SwiftOperationError(operation=operation, error=e)\n\n def head_object(self, container, object):\n \"\"\"Retrieves the information about the given Swift object.\n\n :param container: The name of the container in which Swift object\n is placed.\n :param object: The name of the object in Swift\n :returns: The information about the object as returned by\n Swift client's head_object call.\n :raises: SwiftOperationError, if operation with Swift fails.\n \"\"\"\n try:\n return self.connection.head_object(container, object)\n except swift_exceptions.ClientException as e:\n operation = _(\"head object\")\n raise exception.SwiftOperationError(operation=operation, error=e)\n\n def update_object_meta(self, container, object, object_headers):\n \"\"\"Update the metadata of a given Swift object.\n\n :param container: The name of the container in which Swift object\n is placed.\n :param object: The name of the object in Swift\n :param object_headers: the headers for the object to pass to Swift\n :raises: SwiftOperationError, if operation with Swift fails.\n \"\"\"\n try:\n self.connection.post_object(container, object, object_headers)\n except swift_exceptions.ClientException as e:\n operation = _(\"post object\")\n raise exception.SwiftOperationError(operation=operation, error=e)\n","sub_path":"ironic/common/swift.py","file_name":"swift.py","file_ext":"py","file_size_in_byte":9060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638124216","text":"\"\"\"\nThermal classifier \n\"\"\"\n\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n\nimport os\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import roc_curve\nfrom sklearn.svm import SVC\nfrom sklearn.cross_validation import train_test_split, cross_val_score\n\nDATA_FOLDER = \"C:\\\\Users\\\\t-yeresh\\\\data\"\n\ndata = pd.DataFrame.from_csv(os.path.join(DATA_FOLDER, \"roi\", \"thermalClassifierData_1.csv\"), index_col=4, header=None)\n\nX = StandardScaler().fit_transform(data.values)\ny = data.index\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=.5)\n\n\nclf = SVC(class_weight={1: 100, 2: 100}, probability=True)\ny_score = clf.fit(x_train, y_train).decision_function(x_test)\nfpr, tpr, thr = roc_curve(y_test.ravel(), y_score.ravel(), pos_label=2)\n\n\ndef plot():\n # Plot of a ROC curve for a specific class\n plt.figure()\n plt.plot(fpr, tpr, label='ROC curve')\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n# Now run the classifier on the unlabeled data\n\nidx = np.where(fpr >= .05)[0][0]\ntheta = thr[idx]\nprint(\"Using theta=%f with %f FP and %f TP\" % (theta, fpr[idx], tpr[idx]))\n\nscaler = StandardScaler().fit(data.values)\nnewdata = pd.DataFrame.from_csv(os.path.join(DATA_FOLDER, \"roi\", \"thermal_ToClassify.csv\"), index_col=None, header=None)\n\nclf = SVC(class_weight={1: 100, 2: 100}, probability=True).fit(scaler.transform(data.values), y)\nout = clf.decision_function(scaler.fit_transform(newdata)) > theta\n\nnewdata['lbl'] = out.ravel().astype(int) + 1 # 1-> regular, 2->thermal\nnewdata.to_csv(os.path.join(DATA_FOLDER, \"roi\", \"thermal_ToClassify__out.csv\"), header=None, index=None,\n float_format=\"%.5f\")\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"acc_stuff/roi/thermal.py","file_name":"thermal.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373867028","text":"#!/usr/bin/env python3\nimport sys\nimport os\nfrom functools import wraps\nfrom oauth2client import file\nfrom apiclient.discovery import build\nfrom datetime import datetime\n\n\nOUTDIR = os.path.expanduser('~/Desktop/experiments (mirrored)')\n# hardcoded\nSTORE = file.Storage('/Users/sku/scripts/guava_data/creds.txt')\nLOG = '/Users/sku/scripts/logs/mirror_experiments.log'\n\n\ndef debug(func):\n\t@wraps(func)\n\tdef debug_wrapper(*args, **kwargs):\n\t\tprint(f'---------- debugging {func.__name__} ----------')\n\t\tprint(f'args: {args}')\n\t\tprint(f'kwargs: {kwargs}')\n\t\tdebug_wrapper.calls += 1\n\t\tprint(f'calls: {debug_wrapper.calls}')\n\t\tret = func(*args, **kwargs)\n\t\tprint(f'return: {ret}')\n\t\tprint(f'---------- end debugging {func.__name__} ----------')\n\t\treturn(ret)\n\tdebug_wrapper.calls = 0\n\treturn(debug_wrapper)\n\n\ndef get_service(store):\n\t'''Creates and returns Google API service object.'''\n\tservice = build('drive', 'v3', credentials=store.get())\n\treturn(service)\n\n\ndef get_remote_files(service):\n\t'''Retrieves Google Sheets files, returns list of File resources (response obj\n\tfrom Drive API).'''\n\tfiles = []\n\tpageToken = None\n\twhile 1:\n\t\t# hardcoded Experiments folder\n\t\tq = {\"q\":\"'1By0bvvHaZoNFfCI9mqAaj-ZqksJzWYKz' in parents and trashed=false\",\n\t\t\t\t \"pageToken\":pageToken}\n\t\tresponse = service.files().list(**q).execute()\n\t\tfor n in response['files']:\n\t\t\tif n['mimeType'] == 'application/vnd.google-apps.spreadsheet':\n\t\t\t\tfiles.append(n)\n\t\tif response.get('nextPageToken') is None:\n\t\t\tbreak\n\t\telse:\n\t\t\tpageToken = response['nextPageToken']\n\treturn(files)\n\n\ndef write_to_disk(file_res, service):\n\t'''Takes File Resource (response from drive list) and service object, then\n\twrites to disk file.'''\n\tdat = service.files().export(\n\t\tfileId=file_res['id'],\n\t\tmimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t).execute()\n\tnew = file_res['name'] + '.xlsx'\n\twith open(os.path.join(OUTDIR, new), 'wb') as f:\n\t\tf.write(dat)\n\n\nif __name__ == '__main__':\n\twith open(LOG, 'at') as log:\n\t\tprint(f'---------- {datetime.now()} ----------', file=log)\n\t\ttry:\n\t\t\tservice = get_service(STORE)\n\t\texcept:\n\t\t\ttraceback.print_exc(file=log)\n\t\t\tsys.exit()\n\t\tfiles = get_remote_files(service)\n\t\tprint(f'\\tfound {len(files)} file(s)', file=log)\n\t\tfor n in files:\n\t\t\tprint(f'\\twriting {n[\"name\"]}', file=log)\n\t\t\twrite_to_disk(n, service)\n\t\tprint('', file=log)\n","sub_path":"mirror_experiments.py","file_name":"mirror_experiments.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"217709638","text":"import os\nimport pickle\nimport subprocess\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\n\nfrom config import get_cfg_defaults\n\nfrom model import build_model, train, test\n\n\ndef load_data(cfg, envname):\n with open(os.path.join(cfg.DATASETS.DATA_DIR, '%s.pkl' % envname), 'rb') as f:\n data = pickle.load(f)\n return data\n\n\ndef split_data(cfg, data):\n actions = data['actions']\n actions = actions.reshape(actions.shape[0], actions.shape[2])\n observations = data['observations']\n\n X_train, X_test, y_train, y_test = train_test_split(observations, actions,\n test_size=cfg.DATASETS.RATIO, shuffle=cfg.DATASETS.SHUFFLE)\n\n return X_train, X_test, y_train, y_test\n\n\ndef get_model_file_path(cfg, method_type, envname):\n return os.path.join(cfg.MODEL.NN.OUTPUT_DIR, '%s_%s' % (method_type, envname))\n\n\ndef train_dagger(cfg, model, model_file_path, envname, X_train, y_train, num_rollouts):\n rewards_mean = []\n rewards_std = []\n for i in range(cfg.MODEL.NN.DAGGER_EPOCHES):\n print('Dagger epoch number %d' % (i + 1))\n train(cfg, model, model_file_path, X_train, y_train)\n\n subprocess.call(\n 'python run_expert.py experts/%s.pkl %s --num_rollouts %d --load_model %s' %\n (envname, envname, num_rollouts, model_file_path),\n shell=True)\n\n data = load_data(cfg, envname)\n\n returns = data['returns']\n rewards_mean.append(np.mean(returns))\n rewards_std.append(np.std(returns))\n\n new_X_train, X_test, new_y_train, y_test = split_data(cfg, data)\n X_train = np.concatenate((X_train, new_X_train))\n y_train = np.concatenate((y_train, new_y_train))\n\n return rewards_mean, rewards_std\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('envname', type=str)\n parser.add_argument('--dagger', action='store_true')\n parser.add_argument('--num_rollouts', type=int, default=20,\n help='Number of expert roll outs in dagger mode')\n\n args = parser.parse_args()\n\n # build the config\n cfg = get_cfg_defaults()\n cfg.freeze()\n\n data = load_data(cfg, args.envname)\n X_train, X_test, y_train, y_test = split_data(cfg, data)\n\n input_size = np.prod(X_train[0].shape)\n output_size = np.prod(y_train[0].shape)\n\n model = build_model(cfg, input_size, output_size)\n\n if args.dagger:\n model_file_path = get_model_file_path(cfg, cfg.MODEL.NN.DAGGER_FILE_NAME, args.envname)\n rewards_mean, rewards_std = train_dagger(cfg, model, model_file_path, args.envname, X_train, y_train, args.num_rollouts)\n print('mean of rewards per iterations is', rewards_mean)\n print('std of rewards per iterations is', rewards_std)\n\n else:\n model_file_path = get_model_file_path(cfg, cfg.MODEL.NN.BC_FILE_NAME, args.envname)\n train(cfg, model, model_file_path, X_train, y_train)\n\n test(model_file_path, X_test, y_test)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15317827","text":"# coding=utf-8\n# Copyright 2021 The HuggingFace Inc. team. All rights reserved.\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\"\"\" Testing suite for the PyTorch TrOCR model. \"\"\"\n\nimport unittest\n\nfrom transformers import TrOCRConfig\nfrom transformers.testing_utils import is_torch_available, require_torch, torch_device\n\nfrom ...generation.test_utils import GenerationTesterMixin\nfrom ...test_configuration_common import ConfigTester\nfrom ...test_modeling_common import ModelTesterMixin, ids_tensor\nfrom ...test_pipeline_mixin import PipelineTesterMixin\n\n\nif is_torch_available():\n import torch\n\n from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM\n\n\n@require_torch\nclass TrOCRStandaloneDecoderModelTester:\n def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n d_model=16,\n decoder_seq_length=7,\n is_training=True,\n is_decoder=True,\n use_attention_mask=True,\n use_cache=False,\n use_labels=True,\n decoder_start_token_id=2,\n decoder_ffn_dim=32,\n decoder_layers=2,\n decoder_attention_heads=4,\n max_position_embeddings=30,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.hidden_size = d_model\n self.num_hidden_layers = decoder_layers\n self.decoder_layers = decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.decoder_attention_heads = decoder_attention_heads\n self.num_attention_heads = decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.use_cache = use_cache\n self.max_position_embeddings = max_position_embeddings\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 2\n self.decoder_attention_idx = 1\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n attention_mask = None\n if self.use_attention_mask:\n attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)\n\n lm_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n config = TrOCRConfig(\n vocab_size=self.vocab_size,\n d_model=self.d_model,\n decoder_layers=self.decoder_layers,\n decoder_ffn_dim=self.decoder_ffn_dim,\n decoder_attention_heads=self.decoder_attention_heads,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n use_cache=self.use_cache,\n pad_token_id=self.pad_token_id,\n decoder_start_token_id=self.decoder_start_token_id,\n max_position_embeddings=self.max_position_embeddings,\n )\n\n return (config, input_ids, attention_mask, lm_labels)\n\n def create_and_check_decoder_model_past(\n self,\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ):\n config.use_cache = True\n model = TrOCRDecoder(config=config).to(torch_device).eval()\n input_ids = input_ids[:2]\n\n input_ids[input_ids == 0] += 1\n # first forward pass\n outputs = model(input_ids, use_cache=True)\n outputs_use_cache_conf = model(input_ids)\n outputs_no_past = model(input_ids, use_cache=False)\n\n self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))\n self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)\n\n past_key_values = outputs[\"past_key_values\"]\n\n # create hypothetical next token and extent to next_input_ids\n next_tokens = ids_tensor((2, 1), config.vocab_size - 1) + 1\n\n # append to next input_ids and\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n\n output_from_no_past = model(next_input_ids)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, past_key_values=past_key_values)[\"last_hidden_state\"]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()\n\n # test that outputs are equal for slice\n assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n config, input_ids, attention_mask, lm_labels = config_and_inputs\n\n inputs_dict = {\"input_ids\": input_ids, \"attention_mask\": attention_mask}\n return config, inputs_dict\n\n\n@require_torch\nclass TrOCRStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):\n all_model_classes = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()\n all_generative_model_classes = (TrOCRForCausalLM,) if is_torch_available() else ()\n pipeline_model_mapping = {\"text-generation\": TrOCRForCausalLM} if is_torch_available() else {}\n fx_compatible = True\n test_pruning = False\n\n def setUp(self):\n self.model_tester = TrOCRStandaloneDecoderModelTester(self, is_training=False)\n self.config_tester = ConfigTester(self, config_class=TrOCRConfig)\n\n # not implemented currently\n def test_inputs_embeds(self):\n pass\n\n # trocr has no base model\n def test_save_load_fast_init_from_base(self):\n pass\n\n # trocr has no base model\n def test_save_load_fast_init_to_base(self):\n pass\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_decoder_model_past(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)\n\n # decoder cannot keep gradients\n def test_retain_grad_hidden_states_attentions(self):\n return\n\n @unittest.skip(\"The model doesn't support left padding\") # and it's not used enough to be worth fixing :)\n def test_left_padding_compatibility(self):\n pass\n","sub_path":"tests/models/trocr/test_modeling_trocr.py","file_name":"test_modeling_trocr.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9861555","text":"# -*- coding:utf-8 -*-\n\n\n# ================================================================================\n# 加载模块\nimport time\nimport matplotlib.pyplot as plt\n# import pymysql\n# 使用query set\n\n# 加载自己模块\nfrom app.son_module import GlobalVar as gl\n\n# 加载数据库表\nfrom app.models import DataModel\n\n# ================================================================================\n# 子功能函数\n\n\n# ----------------------------------------\n# 图片保存到文件夹\ndef save_img(img, path):\n time_ = time.strftime(\"%Y-%m-%d==%H:%M:%S\", time.localtime())\n path = path + time_ +'.png'\n plt.imsave(path, img)\n return time_, path\n\n\n# ----------------------------------------\n# 保存图片中瓶子的数据到数据库中\ndef save_inf_database(time_, json, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b, remarks):\n # 使用原生sql\n \"\"\"\n # 打开数据库连接\n db = pymysql.connect(\"localhost\", \"root\", \"Qq1234!@#$\", \"img_to_3D\")\n # 使用cursor()方法获取操作游标\n cursor = db.cursor()\n # SQL 更新语句\n sql = INSERT INTO img_to_3D (time, json, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b)\n VALUES (datetime.now(), json, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b)\n try:\n # 执行SQL语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n except:\n # 发生错误时回滚\n db.rollback()\n # 关闭数据库连接\n db.close()\n return\n \"\"\"\n # 使用query set\n try:\n data = DataModel(time=time_,\n json=json,\n length_json=length_json,\n img_path=img_path,\n canny_path=canny_path,\n correct_path=correct_path,\n correct_high=correct_high,\n correct_width=correct_width,\n a=a,\n b=b,\n remarks=remarks)\n data.save()\n return None\n except Exception as err:\n return err\n\n\n# ----------------------------------------\n# 日志模块\ndef save_log(time, file_name, operate): # operate就是原图、canny图、修正图\n f = open(gl.log_path, 'a')\n inf = '# 其中操作1代表保存原图、2代表轮廓图、3代表修正后的图' + '\\n' + '日期' + '\\t' + '操作' + '\\t' + '路径' + '\\n'\n f.write(inf)\n f.close()\n log_inf = str(time) + '\\t' + str(file_name) + '\\t' + str(operate) + '\\n'\n f = open(gl.log_path, 'a')\n f.write(log_inf)\n f.close()\n return None\n\n\n# ================================================================================\n# 主调用模块\ndef save_log_img(flag, img, canny_img, correct_img, json_, length_json, correct_high, correct_width, a, b):\n # 日志和图片保存\n # 保存原图\n if flag is False:\n img_time, img_path = save_img(img, gl.false_img_path)\n # 保存日志\n save_log(img_time, str(img_time), 1)\n\n # 数据库保存\n # time_, json, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b, remarks\n save_inf_database(img_time, json_, length_json, img_path, None, None, correct_high, correct_width,\n a, b, None)\n else:\n img_time, img_path = save_img(img, gl.true_img_path)\n # 保存日志\n save_log(img_time, str(img_time), 1)\n\n # 保存边缘轮廓图\n canny_time, canny_path = save_img(canny_img, gl.canny_img_path)\n # 保存日志\n save_log(canny_time, str(canny_time), 2)\n\n # 保存修正后的图\n correct_time, correct_path = save_img(correct_img, img)\n # 保存日志\n save_log(canny_time, str(canny_time), 3)\n\n # 数据库保存\n # time_, json, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b, remarks\n save_inf_database(img_time, json_, length_json, img_path, canny_path, correct_path, correct_high, correct_width, a, b, None)\n\n\n# ================================================================================\n# 主函数\nclass SaveImgInformation:\n def main(flag, img, canny_img, correct_img, json_, length_json, correct_high, correct_width, a, b):\n try:\n save_log_img(flag, img, canny_img, correct_img, json_, length_json, correct_high, correct_width, a, b)\n return None\n except Exception as err:\n return err\n","sub_path":"实验/img_to_3d/app/son_module/save_img_information.py","file_name":"save_img_information.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"279882829","text":"#Importing libraries\nimport numpy as np\nfrom numpy import asarray\nfrom numpy import zeros\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding, LSTM\nfrom keras.layers.core import Activation\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers.core import Dense, SpatialDropout1D\nfrom keras.utils.np_utils import to_categorical\nimport re\nimport json\nimport pandas as pd\nfrom keras.callbacks import ModelCheckpoint\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\n\nnp.random.seed(42)\n\nINPUT_FILE = \"../Python_NLP_Movie_Sentiment/data/imdb-dataset-of-50k-movie-reviews/IMDB Dataset.csv\"\nGLOVE_MODEL = '../Python_NLP_Movie_Sentiment/data/glove6b100dtxt/glove.6B.100d.txt'\n\n\n\nNUM_WORDS = 6000\nMAXLEN=100 # max number of word per document. > is truncated\nembedding_dim = 100\nlstm_out = 128\nbatch_size= 128\n\n#\n#https://www.geeksforgeeks.org/removing-stop-words-nltk-python/\n\n#https://stackabuse.com/python-for-nlp-movie-sentiment-analysis-using-deep-learning-in-keras/\n\n#https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/\n\n#https://towardsdatascience.com/understanding-lstm-and-its-quick-implementation-in-keras-for-sentiment-analysis-af410fd85b47\n\n#https://github.com/keras-team/keras/blob/master/examples/pretrained_word_embeddings.py\n\n#Check-point: https://machinelearningmastery.com/check-point-deep-learning-models-keras/\n\n#Time Series Data with LSTMs (walk-forward validation)- NOT USE KFOLD: https://machinelearningmastery.com/backtest-machine-learning-models-time-series-forecasting/\n\n#https://towardsdatascience.com/sentiment-analysis-using-lstm-step-by-step-50d074f09948\n\n# EMOTION CLASIFICATION ALL TIPS IN ONE ARTICLE: https://medium.com/appening-io/emotion-classification-2d4ed93bf4e2\n\nTAG_RE = re.compile(r'<[^>]+>')\n\ndef remove_tags(text):\n return TAG_RE.sub('', text)\n\ndef preprocess_text(sen):\n # Removing html tags\n sentence = remove_tags(sen)\n\n # Remove punctuations and numbers\n sentence = re.sub('[^a-zA-Z]', ' ', sentence)\n\n # Single character removal\n sentence = re.sub(r\"\\s+[a-zA-Z]\\s+\", ' ', sentence)\n\n # Removing multiple spaces\n sentence = re.sub(r'\\s+', ' ', sentence)\n\n #stop_words = set(stopwords.words('english'))\n #word_tokens = word_tokenize(sentence)\n filtered_sentence = []\n #filtered_sentence = [w for w in word_tokens if not w in stop_words ]\n\n #for w in word_tokens:\n # if w not in stop_words:\n # filtered_sentence.append(w)\n\n #.join\n\n return sentence\n\ndef clean_text(sentences):\n X = []\n for sen in sentences:\n X.append(preprocess_text(sen))\n return X\n\n#Cargando data\ndata = pd.read_csv(INPUT_FILE)\nsentences = list(data['review'])\nprint('nb sequences:', len(sentences))\nX = clean_text(sentences)\n#y = pd.get_dummies(data['sentiment']).values\ny = data['sentiment']\ny = np.array(list(map(lambda x: 1 if x==\"positive\" else 0, y)))\nprint(y)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n\ntokenizer = Tokenizer(NUM_WORDS)\ntokenizer.fit_on_texts(X_train)\n#print(tokenizer.word_index) # To see the dicstionary\n\nvocab_size = len(tokenizer.word_index) + 1\n\n#encoded_docs\nX_train = tokenizer.texts_to_sequences(X_train)\nX_test = tokenizer.texts_to_sequences(X_test)\n\n# pad documents to a max length of words\n#padded_docs\nX_train = pad_sequences(X_train, padding='post', maxlen=MAXLEN)\nX_test = pad_sequences(X_test, padding='post', maxlen=MAXLEN)\n\n\n\n#----------------------------------------------------------------------------------------------------\n#--------------------GloVe word embedding------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------\n# load the entire GloVe word embedding file into memory as a dictionary of word to embedding array.\nembeddings_dictionary = dict()\nglove_file = open(GLOVE_MODEL, encoding=\"utf8\")\n\nfor line in glove_file:\n records = line.split()\n word = records[0]\n coefs = asarray(records[1:], dtype='float32')\n embeddings_dictionary [word] = coefs\nglove_file.close()\n\nembedding_matrix = zeros((vocab_size, 100))\nfor word, index in tokenizer.word_index.items():\n embedding_vector = embeddings_dictionary.get(word)\n if embedding_vector is not None:\n embedding_matrix[index] = embedding_vector\n#----------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------\n\n##Buidling the LSTM network\n#model = Sequential()\n#embedding_layer = Embedding(vocab_size, embedding_dim,weights=[embedding_matrix],input_length = MAXLEN,trainable=False)\n#model.add(embedding_layer)\n#model.add(LSTM(lstm_out, dropout_U = 0.2, dropout_W = 0.2))\n#model.add(Dense(2))\n#model.add(Activation(activation='softmax'))\n#model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])\n\n# create model\nmodel = Sequential()\nembedding_layer = Embedding(vocab_size, embedding_dim,weights=[embedding_matrix],input_length = MAXLEN,trainable=False)\nmodel.add(embedding_layer)\nmodel.add(LSTM(lstm_out))\nmodel.add(Dense(1))\nmodel.add(Activation(activation='sigmoid'))\n\n# Compile model\nmodel.compile(loss = 'binary_crossentropy', optimizer='adam',metrics = ['accuracy'])\n\n\n# checkpoint\nfilepath=\"checkpoint/weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ncallbacks_list = [checkpoint]\n\n\nprint(model.summary())\n\n# Fit the model\n\nhistory = model.fit(X_train, y_train, batch_size=batch_size, epochs=1, verbose=0,callbacks=callbacks_list, validation_split=0.2)\n\n# Measuring score and accuracy on validation set\n\nscore= model.evaluate(X_test, y_test, verbose = 2, batch_size = batch_size)\n\nprint(\"Logloss score: %.2f\" % (score[0]))\nprint(\"Validation set Accuracy: %.2f\" % (score[1]))\n\n\nprint(history.history)\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\n\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train','test'], loc='upper left')\nplt.show()\n\n","sub_path":"lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374664704","text":"import re\n\nimport open3d as o3d\nimport numpy as np\n\n# from motpy import Detection, MultiObjectTracker, NpImage, Box\n\nclass SimpleTracker:\n \"\"\"Handcrafted 3d tracker to track a object th at is held by hand.\"\"\"\n\n RED = np.array([1, 0, 0])\n GREEN = np.array([0, 1, 0])\n\n def __init__(self):\n self.previous_previous_bounding_box = None\n self.previous_bounding_box = None\n\n def get_tracked_onahole(self, closest_bounding_box: o3d.geometry.OrientedBoundingBox, made_from_2d_detection: bool):\n \"\"\"Track and returns most probable bounding box for single object held by hand.\n\n It is optimized to heuristically track hand holded object.\n For example, it uses heuristic of physical hand speed to eliminate wrong bounding box.\n \"\"\"\n # aaa = [pcd]\n\n if closest_bounding_box is not None:\n new_box = o3d.geometry.OrientedBoundingBox(closest_bounding_box)\n if made_from_2d_detection:\n new_box.color = self.RED\n else:\n if self.previous_bounding_box is not None:\n if self.previous_previous_bounding_box is not None:\n new_box.extent = self.previous_bounding_box.extent + (self.previous_bounding_box.extent - self.previous_previous_bounding_box.extent)\n new_box.center = self.previous_bounding_box.center + (self.previous_bounding_box.center - self.previous_previous_bounding_box.center)\n new_box.color = self.GREEN\n else:\n new_box.extent = self.previous_bounding_box.extent\n new_box.center = self.previous_bounding_box.center\n new_box.color = self.GREEN\n else:\n pass\n # import IPython; IPython.embed()\n\n # For trajectory visualization.\n # aaa.append(closest_bounding_box)\n # box = o3d.geometry.OrientedBoundingBox()\n # box.center = closest_bounding_box.center\n # box.extent = [0.05, 0.05, 0.05]\n\n # visualizer.vis.add_geometry(box)\n\n self.previous_previous_bounding_box = self.previous_bounding_box\n self.previous_bounding_box = o3d.geometry.OrientedBoundingBox(new_box)\n\n return new_box\n else:\n return None\n\nclass KalmanMultiTracker:\n def __init__(self):\n # model_spec = {'order_pos': 2, 'dim_pos': 3,\n # 'order_size': 0, 'dim_size': 3,\n # 'q_var_pos': 0.05, 'r_var_pos': 0.05}\n model_spec = {'order_pos': 0, 'dim_pos': 3,\n 'order_size': 0, 'dim_size': 3,\n 'q_var_pos': 0.01, 'r_var_pos': 0.01}\n dt = 1 / 30.0\n self._multi_tracker = MultiObjectTracker(\n dt=dt, model_spec=model_spec,\n active_tracks_kwargs={'min_steps_alive': 0, 'max_staleness': 12},\n tracker_kwargs={'max_staleness': 12}\n )\n \n def _get_longest_life_track(self):\n tracks = self._multi_tracker.active_tracks(min_steps_alive=3)\n\n longest_life_track = None\n longest_life_length = 0\n\n for track in tracks:\n if track.tracker.steps_positive > longest_life_length:\n longest_life_length = track.tracker.steps_positive\n longest_life_track = track\n\n if longest_life_track is not None:\n min_p = longest_life_track.box[:3]\n max_p = longest_life_track.box[3:]\n bounding_box = o3d.geometry.OrientedBoundingBox()\n extent = max_p - min_p\n bounding_box.extent = extent\n bounding_box.center = min_p + extent / 2.0\n\n return bounding_box\n else:\n return None\n\n def get_tracked_onahole(self, closest_bounding_box: o3d.geometry.OrientedBoundingBox, made_from_2d_detection: bool):\n if closest_bounding_box is not None:\n if made_from_2d_detection:\n half_size = closest_bounding_box.extent / 2.0\n min_p = closest_bounding_box.center - half_size\n max_p = closest_bounding_box.center + half_size\n\n self._multi_tracker.step(detections=[Detection(\n box = min_p.tolist() + max_p.tolist(),\n score = 1.0\n )])\n return self._get_longest_life_track()\n else:\n self._multi_tracker.step(detections=[])\n return self._get_longest_life_track()\n else:\n self._multi_tracker.step(detections=[])\n return self._get_longest_life_track()\n\ntrackers = {}\nfor tracker in [SimpleTracker, KalmanMultiTracker]:\n tracker_name = name = re.sub(r'(? 0:\r\n for category_ele in category_eles:\r\n url = self.wrapped_url(urlparse.urljoin(self.lr.current_url, category_ele.attrib['href']))\r\n text = category_ele.text.strip()\r\n\r\n key = '%s@@%s' % (url_obj[2], text)\r\n\r\n md5_key = hashlib.md5(key.encode('utf-8')).hexdigest()\r\n\r\n if md5_key not in self.key_set:\r\n logger.info('Add Category: %s' % url)\r\n self.url_info[md5_key] = [url, URL_TYPE.BEST_SELL_CATEGORY, key, False, md5_key]\r\n self.key_set.add(md5_key)\r\n\r\n self.url_info.sync()\r\n except:\r\n logger.error(traceback.format_exc())\r\n return wrapped\r\n\r\ndef next_page(method):\r\n def wrapped(self, **kwargs):\r\n\r\n try:\r\n method(self, **kwargs)\r\n\r\n urls = []\r\n\r\n for ele in self.lr.xpaths('//div[@id=\"zg_paginationWrapper\"]//a')[1:]:\r\n page_url = urlparse.urljoin(self.lr.current_url, ele.attrib['href'].strip())\r\n\r\n id = page_url.split('/ref', 1)[0].rsplit('/', 1)[-1]\r\n index = page_url.split('&pg=', 1)[-1]\r\n key = '%s_%s' % (id, index)\r\n md5_key = hashlib.md5(key).hexdigest()\r\n\r\n if md5_key not in self.key_set:\r\n logger.info('Add Category Page: %s' % page_url)\r\n self.url_info[md5_key] = [page_url, URL_TYPE.BEST_SELL_CATEGORY_NEXT, key, False, md5_key]\r\n self.key_set.add(md5_key)\r\n\r\n self.url_info.sync()\r\n except:\r\n logger.error(traceback.format_exc())\r\n\r\n\r\n return wrapped\r\n\r\ndef product_url(method):\r\n def wrapped(self, **kwargs):\r\n\r\n try:\r\n method(self, **kwargs)\r\n\r\n urls = []\r\n product_eles = self.lr.xpaths('//div[@class=\"zg_itemImageImmersion\"]/a')\r\n\r\n for ele in product_eles:\r\n product_url = urlparse.urljoin(self.lr.current_url, ele.attrib['href'].strip())\r\n asin = product_url.split('/dp/', 1)[1].split('/', 1)[0]\r\n\r\n md5_key = hashlib.md5(asin).hexdigest()\r\n\r\n if md5_key not in self.key_set:\r\n logger.info('Add Product: %s' % asin)\r\n self.url_info[md5_key] = [product_url, URL_TYPE.PRODUCT_URL, asin, False, md5_key]\r\n self.key_set.add(md5_key)\r\n\r\n self.url_info.sync()\r\n except:\r\n logger.error(traceback.format_exc())\r\n\r\n return wrapped\r\n\r\ndef url_over(method):\r\n def wrapped(self, **kwargs):\r\n\r\n method(self, **kwargs)\r\n\r\n url_obj = kwargs.get('url_obj')\r\n url_obj[3] = True\r\n\r\n self.url_info[url_obj[4]] = url_obj\r\n self.url_info.sync()\r\n\r\n return wrapped\r\n\r\nclass BestSell(AmazonBase):\r\n\r\n URL_INFO_ROOT = 'I:\\\\amazon_url_info'\r\n\r\n best_url = 'https://www.amazon.com/Best-Sellers/zgbs'\r\n\r\n def __init__(self, key_set, **kwargs):\r\n super(BestSell, self).__init__(**kwargs)\r\n\r\n self.URL_INFO_ROOT = kwargs.get('url_info_root', 'file:///I:\\\\amazon_url_info')\r\n\r\n self.url_info = Shove(self.URL_INFO_ROOT)\r\n\r\n self.key_set = key_set\r\n\r\n\r\n @category\r\n @next_page\r\n @product_url\r\n @url_over\r\n def categories(self, url_obj=None, **kwargs):\r\n self.load(url_obj[0].encode('utf-8'))\r\n\r\n\r\n\r\n @product_url\r\n @url_over\r\n def category_next(self, url_obj=None, **kwargs):\r\n self.load(url_obj[0].encode('utf-8'))\r\n\r\n @url_over\r\n def product(self, url_obj=None, **kwargs):\r\n\r\n md5 = hashlib.md5(url_obj[2])\r\n cache_name = '%s.gz' % md5.hexdigest()\r\n\r\n if self.load_cache(cache_name):\r\n logger.info('Product File Exists: %s' % url_obj[2])\r\n return\r\n\r\n super(BestSell, self).product(asin=url_obj[2], **kwargs)\r\n\r\n def categories_first(self, categories):\r\n self.load(self.best_url)\r\n\r\n category_eles = self.lr.xpaths('//ul[@id=\"zg_browseRoot\"]/ul/li/a')\r\n\r\n for category_ele in category_eles:\r\n if category_ele.text.strip() in categories:\r\n url = self.wrapped_url(urlparse.urljoin(self.best_url, category_ele.attrib['href']))\r\n\r\n key = category_ele.text.strip()\r\n md5_key = hashlib.md5(key.encode('utf-8')).hexdigest()\r\n\r\n if md5_key not in self.key_set:\r\n self.url_info[md5_key] = [url, URL_TYPE.BEST_SELL_CATEGORY, key, False, md5_key]\r\n self.key_set.add(md5_key)\r\n\r\n self.url_info.sync()\r\n","sub_path":"amazon/amazon_spider/x/spider1/best_sell2.py","file_name":"best_sell2.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281640876","text":"from django.conf import settings\nfrom django.conf.urls import url, include\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\n\nadmin.site.site_header = 'Panel de Control : Famisoft'\n\nadmin.site.site_title = 'Famisoft Software y Desarrollo a la Medida'\n\nurlpatterns = [\n url(r'^', include('web.urls', namespace=\"web\")),\n url(r'^summernote/', include('django_summernote.urls')),\n url(r'^jet/', include('jet.urls', 'jet')),\n url(r'^jet/dashboard/', include('jet.dashboard.urls', 'jet-dashboard')),\n url(r'^admin/', admin.site.urls),\n url(r'^articles/', include(\"articles.urls\", namespace=\"article\")),\n url(r'^products/', include(\"products.urls\", namespace=\"product\")),\n url(r'^categories/', include(\"products.urls_categories\", namespace=\"category\")),\n url(r'^newsletter/', include(\"newsletters.urls\", namespace=\"newsletter\")),\n url(r'^games/', include(\"games.urls\", namespace=\"game\")),\n]\n\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += [\n url(r'^__debug__/', include(debug_toolbar.urls)),\n ]\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"cms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405060261","text":"\"\"\"\nAuthor: Andrew Stocker\nDescription: scrapes and number of submissions in a given subreddit\nInput: arg1= subreddit id and arg2= # of submissions\nRun: python bulk_scrape arg1 arg2\n\"\"\"\nimport praw\nfrom scraper import get_reddit_client, pkl_thread\n\nfrom sys import argv\n\n\ndef bulk_scrape(submissions):\n for t in submissions:\n pkl_thread(t)\n\n\nif __name__==\"__main__\":\n R = get_reddit_client()\n \n subreddit_id = argv[1] #example: www.reddit.com/r/cars use \"cars\"\n limit = int(argv[2]) #number of submissions to scrape\n \n submissions = R.get_subreddit(subreddit_id).get_hot(limit=limit)\n \n bulk_scrape(submissions)\n \n","sub_path":"bulk_scrape.py","file_name":"bulk_scrape.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"635419355","text":"import numpy as np\nfrom .getTLE import getTLE\nimport datetime\n\n\ndef _read_tle_decimal(rep):\n \"\"\"Convert *rep* to decimal value.\"\"\"\n if rep[0] in [\"-\", \" \", \"+\"]:\n digits = rep[1:-2].strip()\n val = rep[0] + \".\" + digits + \"e\" + rep[-2:]\n else:\n digits = rep[:-2].strip()\n val = \".\" + digits + \"e\" + rep[-2:]\n\n return float(val)\n\n\ndef getPIE(satno, filename):\n Line1 = getTLE(satno, filename)[0]\n Line2 = getTLE(satno, filename)[1]\n\n CK2 = 5.413080e-4\n XKE = 0.743669161e-1\n XMNPDA = 1440.0\n\n # def __init__(self, tle):\n satnumber = Line1[2:7]\n excentricity = int(Line2[26:33]) * 10 ** -7\n mean_motion = float(Line2[52:63]) * (np.pi * 2 / XMNPDA)\n mean_motion_derivative = float(Line1[33:43]) * \\\n np.pi * 2 / XMNPDA ** 2\n mean_motion_sec_derivative = _read_tle_decimal(Line1[44:52]) * \\\n np.pi * 2 / XMNPDA ** 3\n n_0 = mean_motion\n k_e = XKE\n k_2 = CK2\n i_0 = np.deg2rad((float(Line2[8:16])))\n e_0 = excentricity\n\n a_1 = (k_e / n_0) ** (2.0 / 3)\n delta_1 = ((3 / 2.0) * (k_2 / a_1**2) * ((3 * np.cos(i_0)**2 - 1) /\n (1 - e_0**2)**(2.0 / 3)))\n\n a_0 = a_1 * (1 - delta_1 / 3 - delta_1**2 - (134.0 / 81) * delta_1**3)\n\n delta_0 = ((3 / 2.0) * (k_2 / a_0**2) * ((3 * np.cos(i_0)**2 - 1) /\n (1 - e_0**2)**(2.0 / 3)))\n\n # original mean motion\n n_0pp = n_0 / (1 + delta_0)\n original_mean_motion = n_0pp\n\n # semi major axis\n a_0pp = a_0 / (1 - delta_0)\n # semi_major_axis = a_0pp\n\n period = np.pi * 2 / n_0pp\n inclination = (float(Line2[8:16]))\n elset = int(Line2[63:68])\n epoch_year = str(Line1[18:20])\n epoch_day = float(Line1[20:32])\n epoch = np.datetime64(datetime.datetime.strptime(epoch_year, \"%y\") +\n datetime.timedelta(days=epoch_day - 1), 'us')\n # epoch = Line1[18:32]\n return period, inclination, elset, a_0pp, epoch\n\n\nif __name__ == '__main__':\n SCC = 25544\n Period = getPIE(SCC, 'tle.txt')[0]\n Inclination = getPIE(SCC, 'tle.txt')[1]\n Elset = getPIE(SCC, 'tle.txt')[2]\n SemiMA = getPIE(SCC, 'tle.txt')[3]\n Epoch = getPIE(SCC, 'tle.txt')[4]\n print(getPIE(SCC, 'tle.txt'))\n print(Period, Inclination, Elset, SemiMA, Epoch)\n","sub_path":"application/ceres/getpie.py","file_name":"getpie.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"438077083","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"Tools for analyzing and mitigating disparity in Machine Learning models.\"\"\"\n\nimport os\nimport sys\nfrom .show_versions import show_versions # noqa: F401\n\n\n# Finesse the version\n_FAIRLEARN_DEV_VERSION_ENV_VAR = \"FAIRLEARN_DEV_VERSION\"\n\n_base_version = \"0.4.5\"\n_dev_version = \"\"\n\nif _FAIRLEARN_DEV_VERSION_ENV_VAR in os.environ.keys():\n dev_version_string = os.environ[_FAIRLEARN_DEV_VERSION_ENV_VAR]\n try:\n dev_version_value = int(dev_version_string)\n if dev_version_value >= 0:\n _dev_version = \".dev{0}\".format(dev_version_value)\n else:\n msg = \"Value of {0} was not greater than or equal to zero. Ignoring\"\n print(msg.format(_FAIRLEARN_DEV_VERSION_ENV_VAR), file=sys.stderr)\n except ValueError:\n msg = \"Value of {0} in {1} did not parse to integer. Ignoring\"\n print(msg.format(dev_version_string, _FAIRLEARN_DEV_VERSION_ENV_VAR), file=sys.stderr)\n\n\n__name__ = \"fairlearn\"\n__version__ = \"{0}{1}\".format(_base_version, _dev_version)\n\n\n# Common strings\n_NO_PREDICT_BEFORE_FIT = \"Must call fit before attempting to make predictions\"\n\n\n# Setup logging infrastructure\nimport logging # noqa: E402\nimport atexit # noqa: E402\n# Only log to disk if environment variable FAIRLEARN_LOGS specified\nfairlearn_logs = os.environ.get('FAIRLEARN_LOGS')\nif fairlearn_logs is not None:\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n os.makedirs(os.path.dirname(fairlearn_logs), exist_ok=True)\n handler = logging.FileHandler(fairlearn_logs, mode='w')\n handler.setLevel(logging.INFO)\n logger.addHandler(handler)\n logger.info('Initializing logging file for fairlearn')\n\n def close_handler(): # noqa: D103\n handler.close()\n logger.removeHandler(handler)\n atexit.register(close_handler)\n","sub_path":"fairlearn/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80228001","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand, CommandError\nfrom channel.models import Channel\nfrom channel.fetcher import ChannelFetcher\n\n\nclass Command(BaseCommand):\n help = 'Runs channel fetch'\n\n def add_arguments(self, parser):\n parser.add_argument('channel_name', type=str)\n\n def handle(self, *args, **options):\n channel_name = options.get('channel_name')\n channel = Channel.objects.get(name=channel_name)\n ChannelFetcher(channel).fetch_channel()\n\n self.stdout.write(self.style.SUCCESS('Successfully fetched channel \"%s\"' % channel))\n","sub_path":"channel/management/commands/fetch_channel.py","file_name":"fetch_channel.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317203598","text":"import sys\nimport pprint\nsys.stdin = open('점심.txt','r')\n\nfrom collections import deque\ndef order(choice,k):\n global choices\n if k == len(p):\n choices.append(choice)\n return\n order(choice + [0],k+1)\n order(choice + [1],k+1)\n\nT = int(input())\nfor tc in range(1,T+1):\n N = int(input())\n m = [list(map(int,input().split())) for _ in range(N)]\n stair = []\n p = []\n start_point = []\n for y in range(N):\n for x in range(N):\n if m[y][x] > 1:\n q = deque([0]*m[y][x])\n stair.append(q)\n start_point.append((y,x))\n if m[y][x] == 1:\n p.append((y,x))\n choices = []\n order([],0)\n\n people = []\n for choice in choices:\n r = []\n for i in range(len(p)):\n y,x = p[i]\n s = choice[i]\n ey,ex = start_point[s]\n d = abs(y-ey) + abs(x-ex)\n r.append((s,d))\n people.append(r)\n\n\n Min = 0xfffffffffff\n for num in people:\n Q = deque(num)\n L = [[0,0],[0,0]]\n cnt = 0\n while Q or sum(stair[0]) + sum(stair[1]) != 0 or sum(L[0]) + sum(L[1]) != 0:\n L[0][0] = sum(L[0])\n L[1][0] = sum(L[1])\n L[0][1] = L[1][1] = 0\n for j in range(2):\n if stair[-1] != 1:\n X = 3 - sum(stair[j])\n if L[j][0] > X : \n stair[j].popleft()\n stair[j].append(X)\n L[j][0] -= X\n else:\n stair[j].popleft()\n stair[j].append(L[j][0])\n L[j][0] = 0\n else:\n stair[j].popleft()\n stair[j].append(0)\n if Q:\n for i in range(len(Q)):\n S,D = Q.popleft()\n if D-1 == 0:\n L[S][1] += 1\n else:\n Q.append((S,D-1))\n for t in range(2):\n T = 3 - sum(stair[t])\n if T > 0 and L[t][0] >= T : \n stair[t].pop()\n stair[t].append(T)\n L[t][0] -= T\n print(Q)\n print(L)\n print(stair)\n cnt += 1\n Min = min(cnt,Min)\n print('#{} {}'.format(tc,Min))\n","sub_path":"1112/점심 copy.py","file_name":"점심 copy.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"373390561","text":"# -*- coding:utf-8 -*-\r\nimport urllib2\r\nimport cookielib\r\nfrom bs4 import BeautifulSoup\r\nimport sys \r\nreload(sys)\r\nsys.setdefaultencoding('utf-8') \r\n\r\ndef _get_new_data(page_url, soup):\r\n res_data = {}\r\n res_data['url'] = page_url\r\n res_data['description'] = soup.get_text(strip=True)\r\n return res_data\r\n\r\n\r\nif __name__=='__main__':\r\n hdr = {'User-Agent':'Mozilla/5.0'}\r\n root_url = 'https://github.com/d3/d3-shape/blob/master/README.md#areas'\r\n req = urllib2.Request(root_url,headers=hdr)\r\n response = urllib2.urlopen(req)\r\n html_content = response.read()\r\n soup = BeautifulSoup(html_content, 'lxml', from_encoding='utf-8')\r\n data = _get_new_data(root_url, soup)\r\n\r\n x = open('asd.txt', 'w')\r\n x.writelines(str(data['description']))\r\n","sub_path":"browerdata/x.py","file_name":"x.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"632228136","text":"import abjad\n\n\ndef configure_score(section, score):\n abjad.setting(score).accidental_style = \"forget\"\n abjad.Tuplet.set_denominator_of_tuplets_to_at_least(score, 8)\n for leaf in abjad.iterate(score).leaves():\n abjad.detach(abjad.Tie)\n abjad.detach(abjad.RepeatTie)\n if section.name_string == \"A1\":\n first_leaf = score[:].get(abjad.Leaf, 0)\n first_leaf.override.score.metronome_mark.extra_offset = (0, 6)\n if section.is_final:\n score.add_double_bar()\n if section.colophon is not None:\n markup, extra_offset = section.colophon\n score.add_final_markup(markup, extra_offset=extra_offset)\n","sub_path":"archipel/etc/implementation/score/configure_score.py","file_name":"configure_score.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"252105492","text":"import pandas as pd\nfrom configparser import ConfigParser\nimport tableauserverclient as TSC\nfrom pandas.util.testing import assert_frame_equal\nfrom parameterized import parameterized\nimport unittest\n\n\nclass SimpleTest(unittest.TestCase):\n\n @parameterized.expand([\n [1],\n [2],\n [3],\n ])\n def test_validation(self, key):\n self.assertTrue(True)\n\n def test_frame(self):\n df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})\n df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]})\n assert_frame_equal(df1, df2, check_dtype=False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253496997","text":"import web3\nimport requests\nimport json\nimport time\n\n# Define starting time\nstart_time = time.time()\n\n# Define Etherscan API Key\ninfura_key = open(\"infura_key.txt\", \"r\").readlines()[0].rstrip()\n\n# Define Etherscan API Key\netherscan_key = open(\"etherscan_key.txt\", \"r\").readlines()[0].rstrip()\n\n# Define Sender Address\nsender_address = '0x267be1c1d684f78cb4f6a176c4911b741e4ffdc0' #(Kraken_4)\n\n# Blocknummer von Startblock\nstartblock = 5263000\n\n#Blocknummer von Endblock\nendblock = 5264264\n\n#Balance Minimum\neth_min = 0.1\n\n#Check Balance at which block\nblockNumber = 5264265\n\n# Checken, welche Wallets etwas von Kraken_4 erhalten haben\nrecipients = requests.get(f'http://api.etherscan.io/api?module=account&action=txlist&address={sender_address}&startblock={startblock}&endblock={endblock}&sort=asc&apikey={etherscan_key}')\nprint('--- Request: DONE ---')\nprint('--- Request time: %s seconds ---\\n' % (time.time() - start_time))\n# Resultat in JSON Format umwandeln\nrecipients = recipients.json()\n# Anzahl tx in Resultat zählen\nresult_count = len(recipients['result'])\nprint(f'{result_count} tx found from block {startblock} to {endblock}\\n')\n\ntest_addresses = []\nok_addresses = []\n\nfor x in recipients['result']:\n value = float(x['value'])/10**18\n if x['isError']=='0' and x['to'] not in test_addresses:\n test_addresses.append(x[\"to\"])\n\nfrom web3 import Web3, HTTPProvider\nw3 = Web3(HTTPProvider(f\"https://mainnet.infura.io/{infura_key}\"))\n\ntxtfile = open(\"ok_addresses.txt\", \"w\")\n\nfor address in test_addresses:\n address = w3.toChecksumAddress(address)\n if w3.fromWei(w3.eth.getBalance(address,blockNumber),\"ether\") >= eth_min:\n ok_addresses.append(address)\n txtfile.write(\"%s\\n\" % address) \n\nprint(len(ok_addresses), \"unique addresses found with over\", eth_min, \"ETH at block\", blockNumber)\n\nprint(\"Success rate =\", \"{:.1%}\".format(len(ok_addresses)/len(test_addresses)))\n\nprint(\"Address dump:\", ok_addresses)\n","sub_path":"TESTS/account_list.py","file_name":"account_list.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168396597","text":"import re\nimport codecs\n\n\nwith codecs.open('charges.log', \"r\", \"utf_8_sig\") as f:\n row_data = [row for row in f]\n\n\ndef parse(rows):\n result = []\n for i in range(len(rows)):\n element = re.findall('\\w+.\\w+', rows[i])\n result.append(element)\n result = list(filter(None, result))\n return result\n\nres = parse(row_data)\n\nwith open('result.txt', \"w\") as f:\n for i in range(len(res)):\n f.write('%s' % res[i] + '\\n')\n","sub_path":"parser/log_parser.py","file_name":"log_parser.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219915230","text":"import torch.nn as nn\nimport math\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, inplanes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n return out\n\n\nclass ResNet18_224(nn.Module):\n\n def __init__(self, num_classes=10):\n self.inplanes = 64\n super(ResNet18_224, self).__init__()\n\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.downsample1 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(64))\n self.downsample2 = nn.Sequential(\n nn.Conv2d(128, 128, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(128))\n self.downsample3 = nn.Sequential(\n nn.Conv2d(256, 256, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(256))\n self.downsample4 = nn.Sequential(\n nn.Conv2d(512, 512, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(512))\n\n self.bn1 = nn.BatchNorm2d(64)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding =1)\n self.block11 = BasicBlock(64, 64, stride=1) \n self.block12 = BasicBlock(64, 64, stride=1) \n self.block21 = BasicBlock(64, 128, stride=2) \n self.block22 = BasicBlock(128, 128, stride=1) \n self.block31 = BasicBlock(128, 256, stride=2) \n self.block32 = BasicBlock(256, 256, stride=1) \n self.block41 = BasicBlock(256, 512, stride=2) \n self.block42 = BasicBlock(512, 512, stride=1) \n\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(512, num_classes)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = F.relu(x)\n x = self.maxpool(x)\n\n x = self.block11(x)\n x = x + self.downsample1(x)\n x = F.relu(x)\n x = self.block12(x)\n x = x + self.downsample1(x)\n x = F.relu(x)\n x = self.block21(x)\n x = F.relu(x)\n x = self.block22(x)\n x = x + self.downsample2(x)\n x = F.relu(x)\n x = self.block31(x)\n x = F.relu(x)\n x = self.block32(x)\n x = x + self.downsample3(x)\n x = F.relu(x)\n x = self.block41(x)\n x = F.relu(x)\n x = self.block42(x)\n x = x + self.downsample4(x)\n x = F.relu(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n","sub_path":"models/resnet_224.py","file_name":"resnet_224.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"445592814","text":"wordsfile = open(r\"C:\\Users\\Joel\\Documents\\GitHub\\mansion-of-murders\\words.txt\")\nwords = wordsfile.read()\nlines = words.split(sep=\"\\n\")\n\nverbs = [lines[i].split()[1] for i in range (len(lines))]\n\nprintout = \"\"\nfor item in verbs:\n\tprintout += \"INSERT INTO all_verbs VALUES ('{0}');\\n\".format(item)\nprint(printout)\ninput()","sub_path":"verbs_tool.py","file_name":"verbs_tool.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578188026","text":"# coding=utf-8\nfrom management import BaseCommand\nfrom static_tester.android.android_tester import AndroidAnalyzer\nfrom static_tester.ios.ios_tester import IosAnalyzer\nfrom utils import einfo\n\nandroid_tester = ['get_base_info', 'static_start']\nios_tester = ['get_base_info', 'static_start']\n\n\nclass Command(BaseCommand):\n def __init__(self):\n super(Command, self).__init__()\n self.help = \"静态检测.\"\n\n def handle(self):\n file_type = self.get_file_type()\n if file_type == 'APK':\n app = AndroidAnalyzer(self.file_name)\n app.get_base_info()\n elif file_type == 'IOS':\n app = IosAnalyzer(self.file_name)\n else:\n einfo('未知文件类型')\n return\n app.start()\n","sub_path":"management/commands/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72212723","text":"class DisjointSet:\n \"\"\"\n Class for DisjointSet data structure.\n \"\"\"\n\n def __init__(self):\n self.root = {}\n self.size = {}\n\n def union(self, a, b):\n \"\"\"\n Combines sets of a and b. Makes new set for them if both are not present in any set.\n :param a: String or other object.\n :param b: String or other object.\n :return: None\n \"\"\"\n if a not in self.root and b not in self.root:\n self.root[a] = self.root[b] = a\n self.size[a] = 2\n elif a not in self.root:\n root_b = self.get_root(b)\n self.root[a] = root_b\n self.size[root_b] += 1\n elif b not in self.root:\n root_a = self.get_root(a)\n self.root[b] = root_a\n self.size[root_a] += 1\n else:\n root_a = self.get_root(a)\n root_b = self.get_root(b)\n if root_a != root_b:\n if self.size[root_a] < self.size[root_b]:\n self.root[root_a] = root_b\n self.size[root_a] = self.size[root_a] + self.size[root_b]\n else:\n self.root[root_b] = root_a\n self.size[root_b] = self.size[root_b] + self.size[root_a]\n\n def same_set(self, a, b):\n \"\"\"\n Checks if a and b belong to same set.\n :param a: String or other object.\n :param b: String or other object.\n :raises KeyError: if a or b are not in any set.\n :return: True if a and b are in same set, False otherwise.\n \"\"\"\n return self.get_root(a) == self.get_root(b)\n\n def get_root(self, a):\n \"\"\"\n Checks if a and b belong to same set.\n :param a: String or other object.\n :raises KeyError: if a is not in any set.\n :return: True if a and b are in same set, False otherwise.\n \"\"\"\n while self.root[a] != a:\n a = self.root[a]\n return a\n\n def disjoint_sets(self):\n \"\"\"\n Constructs all the sets.\n :return: A list of all sets.\n \"\"\"\n set_dict = {}\n for node in self.root:\n node_root = self.get_root(node)\n if node_root not in set_dict:\n set_dict[node_root] = set()\n set_dict[node_root].add(node)\n return list(set_dict.values())\n\n\nif __name__ == '__main__':\n ds = DisjointSet()\n n = int(input(\"Enter number of connections: \"))\n print(\"Enter {} connections:\".format(n))\n for _ in range(n):\n a, b = input().split()\n ds.union(a, b)\n groups = ds.disjoint_sets()\n print(\"There are a total of {} groups. They are:\".format(len(groups)))\n for s in groups:\n print(s)\n n = int(input(\"Enter number of pairs to be tested: \"))\n print(\"Enter {} pairs:\".format(n))\n for _ in range(n):\n a, b = input().split()\n if ds.same_set(a, b):\n print(\"{} and {} are connected to each other\".format(a, b))\n else:\n print(\"{} and {} are not connected to each other\".format(a, b))\n\n\"\"\"\nSample output:\n\nEnter number of connections: 5\nEnter 5 connections:\nPradnya Anisha\nAustin Pradnya\nAustin Melburne\nVishal Akash\nRahul Pavan\nThere are a total of 3 groups. They are:\n{'Anisha', 'Austin', 'Pradnya', 'Melburne'}\n{'Akash', 'Vishal'}\n{'Rahul', 'Pavan'}\nEnter number of pairs to be tested: 2\nEnter 2 pairs:\nPradnya Melburne\nPradnya and Melburne are connected to each other\nPavan Vishal\nPavan and Vishal are not connected to each other\n\"\"\"\n","sub_path":"assessment4.py","file_name":"assessment4.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412322621","text":"from smartcard.CardType import AnyCardType\r\nfrom smartcard.CardRequest import CardRequest\r\nfrom smartcard.util import toHexString\r\nCOMMAND = [0xFF, 0xCA, 0x00, 0x00, 0x00] #handshake cmd needed to initiate data transfer\r\nLOAD_AUTH_KEY=[0xFF,0x82,0x00,0x00,0x06,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]#Load authentication key\r\nAUTHENTICATE_COMMAND=[0xFF, 0x88, 0x00, 0x04, 0x60, 0x00]#authenticate\r\n\r\ncardtype=AnyCardType()\r\ncardreq=CardRequest(timeout=100, cardType=cardtype)\r\ncardservice=cardreq.waitforcard()\r\ncardservice.connection.connect()\r\nprint(toHexString(cardservice.connection.getATR()))\r\nprint(cardservice.connection.transmit(LOAD_AUTH_KEY))\r\nprint(cardservice.connection.transmit(AUTHENTICATE_COMMAND))\r\nprint(cardservice.connection.transmit([0xFF, 0xB0, 0x00, 0x04, 0x3]))\r\n","sub_path":"serial_com.py","file_name":"serial_com.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"86534058","text":"# 张三给李四通过网银转账 100 极客币,现有数据库中三张表:\n# 一张为用户表,包含用户 ID 和用户名字,另一张为用户资产表,包含用户 ID 用户总资产,\n# 第三张表为审计用表,记录了转账时间,转账 id,被转账 id,转账金额。\n# 请合理设计三张表的字段类型和表结构;\n# 请实现转账 100 极客币的 SQL(可以使用 pymysql 或 sqlalchemy-orm 实现),张三余额不足,转账过程中数据库 crash 等情况需保证数据一致性。\n\nimport pymysql\nfrom dbconfig import read_db_conf\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, desc, DateTime, DECIMAL\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom datetime import datetime\n\n# 读取数据库配置\ndbserver = read_db_conf()\nhost = dbserver[\"host\"]\ndatabase = dbserver[\"database\"]\nuser = dbserver[\"user\"]\npassword = dbserver[\"password\"]\n\nBase = declarative_base()\n\nclass user_table(Base):\n __tablename__ = 'user'\n id = Column(Integer(), primary_key=True)\n name = Column(String(15), unique=True)\n create_time = Column(DateTime, default=datetime.now)\n update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)\n\n def __repr__(self):\n result = '{\"user_id\":%s, \"user_name\":%s}' % (self.id, self.name)\n return result\n\nclass account_table(Base):\n __tablename__ = \"account\"\n id = Column(Integer(), primary_key=True)\n user_id = Column(Integer())\n user_asset = Column(DECIMAL(10, 2))\n created_time = Column(DateTime, default=datetime.now)\n update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)\n\n def __repr__(self):\n result = '{\"user_id\":%s, \"user_asset\":%s}' % (self.user_id, self.user_asset)\n\nclass accountflow_table(Base):\n __tablename__ = \"account_flow\"\n id = Column(Integer(), primary_key=True)\n from_id = Column(Integer())\n to_id = Column(Integer())\n deal_money = Column(DECIMAL(10,2))\n ceated_time = Column(DateTime, default=datetime.now)\n update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)\n\n def __repr__(self):\n result = '{\"from_id\":%s, \"to_id\":%s, \"deal_money\":%s}' % (self.from_id, self.to_id, self.deal_money)\n return result\n\ndburl = \"mysql+pymysql://%s:%s:3306/%s?charset=utf8mb4\" %(user, password, host, database)\nengine = create_engine(dburl, echo=True, encoding=\"utf-8\")\n\nBase.metadata.create_all(engine)\n\nsessionclass = sessionmaker(bind=engine)\nsession = sessionclass()\nuser_obj = [user(name=\"zhangsan\"), user(name=\"lisi\")]\nsession.add_all(user_obj)\naccount_obj = [account_table(user_id=1,user_asset=150), account_table(user_id=2, user_asset=200)]\nsession.add_all(account_obj)\nsession.commit()\n\nwith engine.begin() as conn:\n zhangsan_count = session.query(account_table).outjoin(user_table, account_table.user_id==user_table.id).filter(user_table.name == \"zhangsan\").first()\n lisi_count = session.query(account_table).outjoin(user_table, account_table.user_id==user_table.id).filter(user_table.name == \"lisi\").first()\n\n if float(zhangsan_count.user_asset) >= 100:\n sql = \"UPDATE account SET user_asset=%s, update_time=%s WHERE user_id=%s\"\n zs_value = (float(zhangsan_count.user_asset)-100, str(datetime.now()), int(zhangsan_count.user_id))\n conn.execute(sql, zs_value)\n\n ls_value = (float(lisi_count.user_asset)+100, str(datetime.now()), int(lisi_count.user_id))\n conn.execute(sql, ls_value)\n\n sql = \"INSERT INTO account_flow(from_id, to_id, deal_money, created_time, update_time) VALUES(%s,%s,%s,%s,%s)\"\n value = (int(zhangsan_count.user_id),int(lisi_count.user_id),100,str(datetime.now()),str(datetime.now()))\n conn.execute(sql, value)\n else:\n print(\"交易失败\")\n conn.execute(\"UPDATE account SET user_asset=%s WHERE user_id=%s\" %(float(zhangsan_count.user_asset)+200, int(zhangsan_count.user_id)))","sub_path":"week03/week03_work06.py","file_name":"week03_work06.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361382740","text":"from __future__ import print_function\r\n\r\nimport io\r\nimport os\r\nfrom datetime import datetime\r\nfrom itertools import permutations\r\nfrom sys import stderr\r\n\r\nfrom typing import Dict, Union, Iterable, Iterator, List, Tuple, IO, Set\r\n\r\nfrom storytelling_db import StoryTellingDatabase, User, Story, Edit, StoryTellingException, \\\r\n hash_password\r\n\r\n\r\ndef utf8(s):\r\n # type: (str) -> unicode\r\n return unicode(s, encoding='utf-8', errors='replace')\r\n\r\n\r\nclass PrivilegedStoryTellingDatabase(StoryTellingDatabase):\r\n def __init__(self, path='data/storytelling.db'):\r\n super(PrivilegedStoryTellingDatabase, self).__init__(path)\r\n self._num_users = -1 # type: int\r\n self._last_committed_uid = 0 # type: int\r\n self._usernames = None # type: Set[unicode]\r\n self._users = None # type: Dict[int, User]\r\n self._stories = None # type: Dict[int, Story]\r\n self._edits = None # type: Dict[int, Dict[int, Edit]]\r\n\r\n @property\r\n def num_users(self):\r\n # type: () -> int\r\n if self._num_users == -1:\r\n self.db.cursor.execute('SELECT COUNT(*) FROM users')\r\n self._num_users = self.db.cursor.fetchone()[0]\r\n self._last_committed_uid = self._num_users\r\n return self._num_users\r\n\r\n @property\r\n def uids(self):\r\n # type: () -> Iterable[int]\r\n for uid in self.db.cursor.execute('SELECT id FROM users'):\r\n yield uid[0]\r\n\r\n @property\r\n def usernames(self):\r\n # type: () -> Set[str]\r\n if self._usernames is not None:\r\n return self._usernames\r\n self._usernames = {username[0] for username in self.db.cursor.execute(\r\n 'SELECT username FROM users')}\r\n return self._usernames\r\n\r\n @property\r\n def users(self):\r\n # type: () -> Dict[int, User]\r\n if self._users is not None:\r\n return self._users\r\n self._users = {id: User(id, username)\r\n for id, username in self.db.cursor.execute(\r\n 'SELECT id, username FROM users')}\r\n self._usernames = {user.username for user in self._users.viewvalues()}\r\n return self._users\r\n\r\n @property\r\n def stories(self):\r\n # type: () -> Dict[int, Story]\r\n if self._stories is not None:\r\n return self._stories\r\n self._stories = {id: Story(id, storyname)\r\n for id, storyname in self.db.cursor.execute(\r\n 'SELECT id, storyname FROM stories')}\r\n return self._stories\r\n\r\n @property\r\n def edits(self):\r\n # type: () -> Dict[int, Dict[int, Edit]]\r\n if self._edits is not None:\r\n return self._edits\r\n self._edits = {\r\n story.id: {edit.user.id: edit for edit in self.get_edits(story)}\r\n for story in self.stories.viewvalues()\r\n }\r\n return self._edits\r\n\r\n def invalidate(self):\r\n self._users = None\r\n self._stories = None\r\n self._edits = None\r\n\r\n def add_user(self, username, password):\r\n if username in self.usernames:\r\n raise StoryTellingException('username already in use')\r\n uid = self._num_users + 1\r\n self._num_users = uid\r\n self._usernames.add(username)\r\n self._users[uid] = User(uid, username)\r\n\r\n def _yield_new_users(self):\r\n # type: () -> Iterable[Tuple[int, unicode, unicode, str]]\r\n start = self._last_committed_uid + 1\r\n end = self._num_users\r\n for uid in xrange(start, end + 1):\r\n if uid % 100 == 0:\r\n print('adding user #{} out of {}'.format(uid, end))\r\n username = self._users[uid].username\r\n yield uid, username, hash_password(username), datetime.now().isoformat()\r\n\r\n def commit_added_users(self):\r\n if self._last_committed_uid == self._num_users:\r\n return\r\n self.db.cursor.executemany('INSERT INTO users VALUES (?, ?, ?, ?)', self._yield_new_users())\r\n self._last_committed_uid = self._num_users\r\n\r\n def add_story(self, storyname, user, text):\r\n # type: (unicode, User, unicode) -> Tuple[Story, Edit]\r\n story, edit = super(PrivilegedStoryTellingDatabase, self).add_story(storyname, user, text)\r\n self.stories[story.id] = story\r\n self.edits[story.id] = {user.id: edit}\r\n return story, edit\r\n\r\n def _yield_edit_values(self, story, uids, texts):\r\n # type: (Story, Iterator[int], Iterator[unicode]) -> Iterable[Tuple[int, int, unicode, str]]\r\n story_id = story.id\r\n edits = self.edits[story_id]\r\n for text in texts:\r\n uid = uids.next()\r\n time = datetime.now()\r\n edits[uid] = Edit(story, User(uid, None), text, time)\r\n yield story_id, uids.next(), text, time.isoformat()\r\n\r\n def edit_story_many_times(self, story, uids, texts):\r\n # type: (Story, Iterator[int], Iterator[unicode]) -> None\r\n self.db.conn.cursor().executemany('INSERT INTO edits VALUES (?, ?, ?, ?)',\r\n self._yield_edit_values(story, uids, texts))\r\n self.commit()\r\n\r\n def commit(self):\r\n self.commit_added_users()\r\n super(PrivilegedStoryTellingDatabase, self).commit()\r\n\r\n\r\nclass BadGutenbergStoryHeaderException(Exception):\r\n pass\r\n\r\n\r\nNumber = Union[int, float]\r\n\r\n\r\ndef list_dir_txts(dir_path, max_files=float('inf')):\r\n # type: (str, Number) -> Iterable[str]\r\n i = 1\r\n for filename in os.listdir(dir_path):\r\n if not filename.endswith('.txt'):\r\n continue\r\n filename = dir_path + '/' + filename\r\n yield filename\r\n i += 1\r\n if i > max_files:\r\n break\r\n\r\n\r\nclass StoryBuilder(object):\r\n DEFAULT_AUTHORS_PATH = 'data/authors.txt'\r\n\r\n @staticmethod\r\n def find_author_title(f):\r\n # type: (IO) -> Tuple[unicode, unicode]\r\n lines = [] # type: List[str]\r\n while True:\r\n line = f.readline().strip() # type: str\r\n if len(line) == 0:\r\n if len(lines) == 0:\r\n continue\r\n break\r\n lines.append(line)\r\n header = ' '.join(lines).lstrip('The Project Gutenberg Etext of ') # type: str\r\n # print(header)\r\n\r\n splitters = (', by ', ' by ', ' Translated by ', ', Edited by ')\r\n for splitter in splitters:\r\n if splitter in header:\r\n header_parts = header.split(splitter, 2) # type: List[str]\r\n if len(header_parts) == 2:\r\n title, author = header_parts\r\n return utf8(title.strip()), utf8(author.strip())\r\n\r\n raise BadGutenbergStoryHeaderException('bad file: {}, header: {}'.format(f.name, header))\r\n\r\n @staticmethod\r\n def find_authors(dir, max_authors=float('inf')):\r\n # type: (str, Number) -> Iterable[unicode]\r\n i = 1\r\n for filename in list_dir_txts(dir, max_authors):\r\n with open(filename) as f:\r\n try:\r\n title, author = StoryBuilder.find_author_title(f)\r\n print('found author #{} in {}'.format(i, filename))\r\n yield author\r\n i += 1\r\n except BadGutenbergStoryHeaderException as e:\r\n print(e, file=stderr)\r\n\r\n @staticmethod\r\n def find_unique_authors(dir, max_authors=float('inf')):\r\n # type: (str, Number) -> Set[unicode]\r\n return {author for author in StoryBuilder.find_authors(dir, max_authors)}\r\n\r\n @staticmethod\r\n def save_authors(dir, out_filename=DEFAULT_AUTHORS_PATH, max_authors=float('inf')):\r\n if os.path.exists(out_filename):\r\n with io.open(out_filename, encoding='utf-8') as f:\r\n authors = {line.strip() for line in f}\r\n else:\r\n authors = {}\r\n with io.open(out_filename, 'w', encoding='utf-8') as f:\r\n authors.update(StoryBuilder.find_unique_authors(dir, max_authors))\r\n for author in sorted(authors):\r\n f.write(author)\r\n f.write(u'\\n')\r\n\r\n def __init__(self, db, authors_filename=DEFAULT_AUTHORS_PATH, tmp_dir='data'):\r\n # type: (PrivilegedStoryTellingDatabase, str, str) -> None\r\n self._db = db # type: PrivilegedStoryTellingDatabase\r\n self._authors_filename = authors_filename # type: str\r\n self.tmp_dir = tmp_dir # type: str\r\n self._new_usernames = self._generate_usernames() # type: Iterator[unicode]\r\n self._new_uids = self._generate_uids() # type: Iterator[int]\r\n _ = self._db.users\r\n self.num_stories_added = 0 # type: int\r\n\r\n def _generate_usernames(self):\r\n # type: () -> Iterable[unicode]\r\n \"\"\"Generate infinite permutations of usernames.\"\"\"\r\n i = 1\r\n while True:\r\n simple_usernames = [utf8(line.strip()) for line in open(self._authors_filename)]\r\n # map(print, simple_usernames)\r\n for username_parts in permutations(simple_usernames, i):\r\n # print(username)\r\n # noinspection PyCompatibility\r\n yield ', '.join(username_parts)\r\n i += 1\r\n\r\n def _generate_uids(self):\r\n # type: () -> Iterable[int]\r\n for username in self._generate_usernames():\r\n try:\r\n user = self._db.add_user(username, username)\r\n yield user.id\r\n except StoryTellingException:\r\n pass\r\n\r\n def add_lines(self, title, author, lines):\r\n # type: (unicode, unicode, Iterator[unicode]) -> None\r\n story, edit = self._db.add_story(title, User(author, ''), 'Title: ' + title)\r\n self._db.edit_story_many_times(story, xrange(1, self._db.num_users + 1).__iter__(), lines)\r\n\r\n def _buffer_story(self, story_filename):\r\n # type: (str) -> Tuple[str, int, unicode, unicode]\r\n with open(story_filename) as f:\r\n title, author = self.find_author_title(f)\r\n\r\n while f.readline()[:3] != '***':\r\n pass\r\n\r\n tmp = self.tmp_dir + '/' + os.path.basename(story_filename)\r\n num_lines = 0\r\n try:\r\n with io.open(tmp, 'w', encoding='utf-8') as buf:\r\n for line in f:\r\n line = line.strip()\r\n if len(line) == 0:\r\n continue\r\n buf.write(utf8(line))\r\n buf.write(u'\\n')\r\n num_lines += 1\r\n except:\r\n os.remove(tmp)\r\n return tmp, num_lines, title, author\r\n\r\n def add_gutenberg_story(self, story_filename):\r\n self.num_stories_added += 1\r\n tmp, num_lines, title, author = self._buffer_story(story_filename)\r\n try:\r\n print(u'adding story #{} {} by {} ({})'.format(self.num_stories_added, title, author,\r\n utf8(story_filename)))\r\n num_new_uids = num_lines - self._db.num_users\r\n add_user = self._db.add_user\r\n new_usernames = self._new_usernames\r\n for i in xrange(num_new_uids):\r\n add_user(new_usernames.next(), '')\r\n self._db.commit_added_users()\r\n\r\n with io.open(tmp, encoding='utf-8') as buf:\r\n self.add_lines(title, author, (line.strip() for line in buf))\r\n\r\n finally:\r\n os.remove(tmp)\r\n\r\n def add_gutenberg_stories(self, dir='data/stories/', max_stories=float('inf')):\r\n # type: (str, Number) -> Iterable[str]\r\n i = 1\r\n for filename in list_dir_txts(dir):\r\n try:\r\n self.add_gutenberg_story(filename)\r\n yield filename\r\n i += 1\r\n if i > max_stories:\r\n break\r\n except (BadGutenbergStoryHeaderException, StoryTellingException, Exception) as e:\r\n print(e, file=stderr)\r\n self.num_stories_added -= 1\r\n\r\n\r\nif __name__ == '__main__':\r\n db = PrivilegedStoryTellingDatabase(path='data/storytelling - GutenbergCopy.db')\r\n\r\n # StoryBuilder.save_authors('D:/gutenberg/flattened', max_authors=10000)\r\n story_builder = StoryBuilder(db)\r\n\r\n print('ARTIFICIALLY BUILDING STORIES:\\n')\r\n # noinspection PyTypeChecker\r\n list(story_builder.add_gutenberg_stories(dir='D:/gutenberg/flattened', max_stories=100))\r\n","sub_path":"StoryTellingGame/story_builder.py","file_name":"story_builder.py","file_ext":"py","file_size_in_byte":12480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"245022980","text":"#!/usr/bin/env python\n\nimport test_cli.osn_unittest as test\nimport framework.osn_api as osn_api\n\n\nclass GetAndListCommandsBasics(test.OsnTestCase):\n \"\"\"OsnTestCase class to test all '...-list' commands with zero required arguments\n and the corresponding '...-get' commands that require a single argument.\"\"\"\n\n def setUp(self):\n \"\"\"Activate a system before running 'ListCommandsBasics.test_...'.\"\"\"\n _ = self.activate()\n\n # create and initialize api variables\n self.api_version, self.api = osn_api.api_from('qs', self.server())\n\n def tearDown(self):\n \"\"\"Deactivate the system after running 'ListCommandsBasics.test_...()'.\"\"\"\n self.deactivate() # deactivate all systems\n\n def test_get_and_list_commands(self):\n \"\"\"Test basic functionality of all '...-list' commands that require zero arguments,\n and test all related '...-get' commands that require a single argument using the result from '...-list'.\"\"\"\n\n required = 'is_required'\n actions = {}\n command_set = {}\n\n get_commands = {name[: name.rfind('-get')]: name for name in self.api.iterkeys() if name.endswith('-get')}\n list_commands = {name[: name.rfind('-list')]: name for name in self.api.iterkeys() if name.endswith('-list')}\n total_get_commands = len(get_commands)\n total_list_commands = len(list_commands)\n\n # todo: Has QSTOR-2900 been resolved? This test is expected to fail\n self.assertRaises(test.env.EmptyQuantaStorCommandOutputOsnError, self.path_list)\n # Remove 'path-list' from the '-list' command set until above bug identified in above referenced JIRA ticket\n command_popped = list_commands.pop('path')\n self.assertEqual(command_popped, 'path-list', \"Expected to remove 'path-list' command\")\n\n # identify '...-list' commands that have no required arguments\n num_list_commands = 0\n for command_root, command_name in list_commands.iteritems():\n command = self.api[command_name] # a dict\n\n # create a list of required arguments\n keywords = command['kwargs'] # a list of dict\n required_arguments = [key['name'] for key in keywords if key[required]]\n if len(required_arguments) == 0:\n try:\n _ = command_set[command_root] # test for command_root in command_set\n except KeyError: # first time using the value of command_root as a key\n command_set[command_root] = {}\n finally:\n command_set[command_root]['list'] = command_name\n num_list_commands += 1\n\n # identify '...-get' commands that have only one required argument\n num_get_commands = 0\n for command_root, command_name in get_commands.iteritems():\n command = self.api[command_name] # a dict\n\n # create a list of required arguments\n keywords = command['kwargs'] # a list of dict\n required_arguments = [key['name'] for key in keywords if key[required]]\n if len(required_arguments) == 1:\n try:\n _ = command_set[command_root] # test for command_root in command_set\n except KeyError: # first time using the value of command_root as a key\n command_set[command_root] = {}\n finally:\n command_set[command_root]['get'] = command_name\n command_set[command_root]['arg'] = required_arguments[0]\n num_get_commands += 1\n\n exceptional_results = {}\n for command_root, get_and_list_commands in command_set.iteritems():\n try: # determine whether the '...-list' command for this command_root has zero required arguments\n command_name = get_and_list_commands['list']\n except KeyError: # the '...-list' command requires at least one argument\n continue\n\n # execute the '...-list' commands with zero arguments\n item_ids = []\n try:\n result = self.qs_output({'qs': command_name})\n except (test.env.EmptyQuantaStorCommandOutputOsnError, test.env.CommandFailedQSError) as err:\n exceptional_results[command_name] = str(err)\n except Exception as err:\n exceptional_results[command_name] = str(err)\n else:\n if result.tag != test.env.xml.OSN_OBJECT_LIST:\n exceptional_results[command_name] = \"Actual: %s, Expected: %s\" % \\\n (result.tag, test.env.xml.OSN_OBJECT_LIST)\n else: # good result\n xpath = \"%s%s\" % (test.env.xml.Xpath.RELATIVE, test.env.xml.OSN_OBJECT)\n items = result.findall(xpath)\n # select all non-None ID's\n item_ids = [item.findtext(test.env.xml.ID) for item in items\n if item.findtext(test.env.xml.ID) is not None and len(item.findtext(test.env.xml.ID)) != 0]\n # print \"Command '%s' results\\n%s\" % (command_name, item_ids)\n\n # execute the '...-get' command for each item_id returned from the '...-list' command\n # assume the required argument takes an 'id' value\n try: # determine whether the '...-get' command for this command_root has one required argument\n command_name = get_and_list_commands['get']\n arg_name = get_and_list_commands['arg']\n except KeyError: # the '...-get' command requires at least two arguments\n continue\n\n if len(item_ids) > 0:\n for item_id in item_ids:\n # execute the '...-get' commands with zero arguments\n qs_command = dict([('qs', command_name), (str(arg_name), item_id)])\n try:\n result = self.qs_output(qs_command)\n except (test.env.EmptyQuantaStorCommandOutputOsnError, test.env.CommandFailedQSError) as err:\n exceptional_results[command_name] = \"'%s' raised an exception\\n%s\" % (qs_command, str(err))\n except Exception as err:\n exceptional_results[command_name] = \"'%s' raised an exception\\n%s\" % (qs_command, str(err))\n else: # '...-get returned a valid result\n if result.tag != test.env.xml.OSN_OBJECT:\n exceptional_results[command_name] = \"'%s' result.tag '%s' (expected '%s')\" % \\\n (qs_command, result.tag, test.env.xml.OSN_OBJECT)\n\n # check for exceptional results\n num_exceptional_cases = len(exceptional_results)\n exceptions = [\"%s:\\n %s\" % (key, value) for key, value in exceptional_results.iteritems()]\n error_msg = \"Tested %d of %d '...-list' and %d of %d '...-get' commands, yielding %d exceptional cases\\n%s\" % \\\n (num_list_commands, total_list_commands, num_get_commands, total_get_commands,\n num_exceptional_cases, '\\n'.join(exceptions))\n self.assertEqual(num_exceptional_cases, 0, error_msg)\n\n\ndef main():\n test.unittest.main()\n\nif __name__ == '__main__':\n main()\n","sub_path":"test/osnpy/test_cli/qs_test_cases/test_get_and_list_commands_basic.py","file_name":"test_get_and_list_commands_basic.py","file_ext":"py","file_size_in_byte":7389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"25111120","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 22 10:09:21 2015\n\n@author: jordan\n\"\"\"\nfrom Serre2 import *\nfrom scipy import *\nimport csv\nimport os\nfrom numpy.linalg import norm \nfrom matplotlib.pyplot import plot,ylim\nfrom scipy.special import ellipj,ellipk,ellipe\n\nfrom scipy.optimize import bisect\n\n#gives exact up to linears, so is second order accurate huzzah \n \ndef copyarraytoC(a):\n n = len(a)\n b = mallocPy(n)\n for i in range(n):\n writetomem(b,i,a[i])\n return b\n \ndef copywritearraytoC(a,b):\n n = len(a)\n for i in range(n):\n writetomem(b,i,a[i])\n \ndef copyarrayfromC(a,n):\n b = [0]*n\n for i in range(n):\n b[i] = readfrommem(a,i)\n \n return b\n \ndef makeX(sx,ex,dx): \n x = arange(sx, ex, dx)\n return x \n\ndef ForcedbedM(x,t,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,g,dx):\n n = len(x)\n h = zeros(n)\n w = zeros(n)\n b= zeros(n)\n u = zeros(n)\n G = zeros(n)\n \n for i in range(n):\n phi = x[i] - a2*t \n \n \n \n h[i] = a0 + a1*exp(-(phi - a3)**2/(2*a4))*exp(a5*t)\n u[i] = a6*exp(-(phi - a3)**2/(2*a4))*exp(a7*t)\n b[i] = a8*sin(a9*x[i])\n w[i] = h[i] + b[i]\n \n hxi = -a1/a4*(phi - a3)*exp(-(phi - a3)**2/(2*a4))*exp(a5*t)\n uxi = -a6/a4*(phi - a3)*exp(-(phi - a3)**2/(2*a4))*exp(a7*t)\n\n uxxi = -a6/(a4**2)*exp(-(phi - a3)**2/(2*a4))*(a4 - ((phi) - a3)**2)*exp(a7*t)\n \n bxi = a8*a9*cos(a9*x[i]) \n bxxi = -a8*a9**2*sin(a9*x[i])\n \n \n G[i] = u[i]*h[i]*(1 + hxi*bxi + 0.5*h[i]*bxxi + bxi*bxi) - h[i]*h[i]*hxi*uxi - h[i]*h[i]*h[i]/3.0*uxxi\n \n return h,u,G,b,w\n\ndef close(t,ts,dt):\n n = len(ts)\n var = False\n for i in range(n):\n if abs(ts[i] - t) < dt:\n var = True\n \n return var\n\n\nwdir = \"../../../../../../../data/2018/raw/Thesis/ForcedFin/Dry/usolve/FDVM2/\"\nif not os.path.exists(wdir):\n os.makedirs(wdir)\n\nfor ki in range(3,16):\n \n wdirji = wdir + str(ki) + \"/\"\n if not os.path.exists(wdirji):\n os.makedirs(wdirji)\n \n a8 = 1.0\n a9 = 2*pi/50.0\n \n width = 2*(2*pi/a9)\n \n a0 = 0.0\n a1 = 0.5\n a2 = ((2*pi) / a9)/10.0\n a3 = -pi/2.0/a9 -width/4.0\n a4 = width/2**6\n a5 = 0.0\n a6 = a1\n a7 = 0.0\n\n \n g = 9.81\n \n startx = -pi/2.0/a9 -width\n sx= startx\n endx = -pi/2.0/a9 +width\n ex = endx\n startt = 0.0\n st = startt\n endt = 0\n et = endt\n \n dx = width / (2.0)**(ki)\n l = 0.5 / (a6*exp(a7*endt) + sqrt(g*(a0 + a1*exp(a5*endt))))\n dt = l*dx\n\n theta = 1.2\n \n nMBC = 3\n nEBC = 3\n nCBC = 1\n \n x = makeX(sx,ex + 0.1*dx,dx)\n n= len(x)\n xMbeg = array([x[0] - 1.5*dx, x[0] - dx, x[0] - 0.5*dx])\n xMend = array([x[-1] + 0.5*dx, x[-1] + dx, x[-1] + 1.5*dx])\n xCbc = concatenate(([x[0] - dx], x, [x[-1] + dx]))\n \n nMbc = 3*n + 2*nMBC\n nEbc = 2*n - 1 + 2*nEBC\n nCbc = n + 2*nCBC\n \n \n h,u,G,b,w = ForcedbedM(x,st,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,g,dx)\n \n hMbeg = a0*ones(nMBC)\n GMbeg = zeros(nMBC)\n bMbeg = a8*sin(a9*xMbeg)\n wMbeg = hMbeg + bMbeg\n \n uEbeg = zeros(nEBC)\n duEbeg = zeros(nEBC)\n \n ddbCbeg =[ -a9*a9*a8*sin(a9*(x[0] - dx))]\n \n hMend = a0*ones(nMBC)\n GMend = zeros(nMBC)\n bMend = a8*sin(a9*xMend)\n wMend = hMend + bMend\n \n uEend = zeros(nEBC)\n duEend = zeros(nEBC)\n \n ddbCend = [ -a9*a9*a8*sin(a9*(x[-1] + dx))] \n \n niBC = 4\n xbegC = arange(sx - niBC*dx,sx,dx)\n xendC = arange(ex + dx,ex + (niBC+1)*dx,dx) \n \n b0C = a8*sin(a9*xbegC)\n b1C = a8*sin(a9*xendC)\n \n xbcC = concatenate([xbegC,x,xendC])\n bbcC = concatenate([b0C,b,b1C])\n xbcC_c = copyarraytoC(xbcC)\n bbcC_c = copyarraytoC(bbcC)\n \n u0C = u[0]*ones(niBC)\n u1C = u[-1]*ones(niBC) \n h0C = h[0]*ones(niBC)\n h1C = h[-1]*ones(niBC)\n G0C = G[0]*ones(niBC)\n G1C = G[-1]*ones(niBC)\n \n hbcC = concatenate([h0C,h,h1C])\n ubcC = concatenate([u0C,u,u1C])\n GbcC = concatenate([G0C,G,G1C])\n \n hbcC_c = copyarraytoC(hbcC)\n ubcC_c = copyarraytoC(ubcC)\n GbcC_c = copyarraytoC(GbcC)\n \n Eni = HankEnergyall(xbcC_c,hbcC_c,ubcC_c,bbcC_c,g,n + 2*niBC,niBC,dx)\n Pni = uhall(xbcC_c,hbcC_c,ubcC_c,n + 2*niBC,niBC,dx)\n Mni = hall(xbcC_c,hbcC_c,n + 2*niBC,niBC,dx)\n Gni = Gall(xbcC_c,GbcC_c,n + 2*niBC,niBC,dx)\n \n deallocPy(hbcC_c)\n deallocPy(ubcC_c)\n deallocPy(GbcC_c)\n \n \n\n h_c = copyarraytoC(h)\n G_c = copyarraytoC(G)\n x_c = copyarraytoC(x)\n b_c = copyarraytoC(b)\n \n hMbeg_c = copyarraytoC(hMbeg)\n hMend_c = copyarraytoC(hMend)\n GMbeg_c = copyarraytoC(GMbeg)\n GMend_c = copyarraytoC(GMend)\n wMbeg_c = copyarraytoC(wMbeg)\n wMend_c = copyarraytoC(wMend)\n bMbeg_c = copyarraytoC(bMbeg)\n bMend_c = copyarraytoC(bMend)\n uEbeg_c = copyarraytoC(uEbeg)\n uEend_c = copyarraytoC(uEend)\n duEbeg_c = copyarraytoC(duEbeg)\n duEend_c = copyarraytoC(duEend)\n ddbCbeg_c = copyarraytoC(ddbCbeg)\n ddbCend_c = copyarraytoC(ddbCend)\n \n hMbc_c = mallocPy(nMbc)\n GMbc_c = mallocPy(nMbc)\n wMbc_c = mallocPy(nMbc)\n bMbc_c = mallocPy(nMbc)\n \n duEbc_c = mallocPy(nEbc)\n uEbc_c = mallocPy(nEbc)\n \n ddbCbc_c = mallocPy(nCbc)\n \n wt = [0,et/4.0,et/2.0,3*et/4.0,et]\n t = 0.0\n #Just an FEM solve here\n while t < et: \n \n if close(t,wt,dt):\n hiC = copyarrayfromC(h_c,n)\n GiC = copyarrayfromC(G_c,n) \n \n edgevaluesSplit(h_c,G_c,b_c, hMbeg_c,GMbeg_c,wMbeg_c,bMbeg_c,duEbeg_c,uEbeg_c,ddbCbeg_c,hMend_c,GMend_c,wMend_c,bMend_c,duEend_c,uEend_c, ddbCend_c,nMBC,nEBC,nCBC,n,nMbc,nEbc,nCbc, hMbc_c,GMbc_c,wMbc_c,bMbc_c,duEbc_c,uEbc_c, ddbCbc_c, dx, theta)\n\n uEbcC = copyarrayfromC(uEbc_c,nEbc)\n uiC = uEbcC[nEBC:-nEBC:2]\n wiC = hiC + b\n \n u0C = uiC[0]*ones(niBC)\n u1C = uiC[-1]*ones(niBC) \n h0C = hiC[0]*ones(niBC)\n h1C = hiC[-1]*ones(niBC)\n G0C = GiC[0]*ones(niBC)\n G1C = GiC[-1]*ones(niBC)\n \n hbcC1 = concatenate([h0C,hiC,h1C])\n ubcC1 = concatenate([u0C,uiC,u1C])\n GbcC1 = concatenate([G0C,GiC,G1C])\n \n hbcC_c = copyarraytoC(hbcC1)\n ubcC_c = copyarraytoC(ubcC1)\n GbcC_c = copyarraytoC(GbcC1)\n \n En = HankEnergyall(xbcC_c,hbcC_c,ubcC_c,bbcC_c,g,n + 2*niBC,niBC,dx)\n Pn = uhall(xbcC_c,hbcC_c,ubcC_c,n + 2*niBC,niBC,dx)\n Mn = hall(xbcC_c,hbcC_c,n + 2*niBC,niBC,dx)\n Gn = Gall(xbcC_c,GbcC_c,n + 2*niBC,niBC,dx)\n \n deallocPy(hbcC_c)\n deallocPy(ubcC_c)\n deallocPy(GbcC_c)\n \n s = wdirji + \"outList\" + str(t)+\"s.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow([\"cell midpoint\" ,'h', 'G' , 'u(m/s)','bed','w' ]) \n \n for j in range(n):\n writefile2.writerow([str(x[j]), str(hiC[j]) , str(GiC[j]) , str(uiC[j]),str(b[j]),str(wiC[j])])\n \n s = wdirji + \"outSing\" + str(t)+\"s.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow(['dx' ,'dt','time',\"Energy\", \"Mass\", \"Momentum\", \"G\" ,\"EnergyI\", \"MassI\", \"MomentumI\", \"GI\" ]) \n writefile2.writerow([str(dx),str(dt),str(t),str(En),str(Mn),str(Pn),str(Gn),str(Eni),str(Mni),str(Pni),str(Gni)]) \n \n \n evolvewrapBC(h_c,G_c,b_c,hMbeg_c,GMbeg_c,wMbeg_c,bMbeg_c,duEbeg_c,uEbeg_c,ddbCbeg_c,hMend_c,GMend_c,wMend_c,bMend_c,duEend_c,uEend_c,ddbCend_c,hMbeg_c,GMbeg_c,wMbeg_c,duEbeg_c,uEbeg_c,hMend_c,GMend_c,wMend_c,duEend_c,uEend_c,nMBC,nEBC,nCBC,n,nMbc,nEbc,nCbc,dx,dt,g,theta,x_c,t,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9)\n t = t + dt\n print(t)\n \n hiC = copyarrayfromC(h_c,n)\n GiC = copyarrayfromC(G_c,n) \n \n edgevaluesSplit(h_c,G_c,b_c, hMbeg_c,GMbeg_c,wMbeg_c,bMbeg_c,duEbeg_c,uEbeg_c,ddbCbeg_c,hMend_c,GMend_c,wMend_c,bMend_c,duEend_c,uEend_c, ddbCend_c,nMBC,nEBC,nCBC,n,nMbc,nEbc,nCbc, hMbc_c,GMbc_c,wMbc_c,bMbc_c,duEbc_c,uEbc_c, ddbCbc_c, dx, theta)\n\n wMbcC = copyarrayfromC(wMbc_c,nMbc) \n hMbcC = copyarrayfromC(hMbc_c,nMbc) \n GMbcC = copyarrayfromC(GMbc_c,nMbc) \n bMbcC = copyarrayfromC(bMbc_c,nMbc) \n \n uEbcC = copyarrayfromC(uEbc_c,nEbc)\n uiC = uEbcC[nEBC:-nEBC:2]\n wiC = hiC + b\n \n u0C = uiC[0]*ones(niBC)\n u1C = uiC[-1]*ones(niBC) \n h0C = hiC[0]*ones(niBC)\n h1C = hiC[-1]*ones(niBC)\n G0C = GiC[0]*ones(niBC)\n G1C = GiC[-1]*ones(niBC)\n \n hbcC1 = concatenate([h0C,hiC,h1C])\n ubcC1 = concatenate([u0C,uiC,u1C])\n GbcC1 = concatenate([G0C,GiC,G1C])\n \n hbcC_c = copyarraytoC(hbcC1)\n ubcC_c = copyarraytoC(ubcC1)\n GbcC_c = copyarraytoC(GbcC1)\n \n En = HankEnergyall(xbcC_c,hbcC_c,ubcC_c,bbcC_c,g,n + 2*niBC,niBC,dx)\n Pn = uhall(xbcC_c,hbcC_c,ubcC_c,n + 2*niBC,niBC,dx)\n Mn = hall(xbcC_c,hbcC_c,n + 2*niBC,niBC,dx)\n Gn = Gall(xbcC_c,GbcC_c,n + 2*niBC,niBC,dx)\n \n deallocPy(hbcC_c)\n deallocPy(ubcC_c)\n deallocPy(GbcC_c)\n \n s = wdirji + \"outList\" + str(t)+\"s.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow([\"cell midpoint\" ,'h', 'G' , 'u(m/s)','bed','w' ]) \n \n for j in range(n):\n writefile2.writerow([str(x[j]), str(hiC[j]) , str(GiC[j]) , str(uiC[j]),str(b[j]),str(wiC[j])])\n \n s = wdirji + \"outSing\" + str(t)+\"s.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow(['dx' ,'dt','time',\"Energy\", \"Mass\", \"Momentum\", \"G\" ,\"EnergyI\", \"MassI\", \"MomentumI\", \"GI\" ]) \n writefile2.writerow([str(dx),str(dt),str(t),str(En),str(Mn),str(Pn),str(Gn),str(Eni),str(Mni),str(Pni),str(Gni)]) \n \n \n xG = concatenate(([x[0] - dx],x,[x[-1]+ dx]))\n \n xubc = []\n xhbc = []\n for i in range(len(xG)):\n if i == 0:\n xubc.append(xG[i] - 0.5*dx)\n xubc.append(xG[i])\n xubc.append(xG[i] + 0.5*dx)\n else:\n \n xubc.append(xG[i])\n xubc.append(xG[i] + 0.5*dx)\n \n xhbc.append(xG[i] - 0.5*dx)\n xhbc.append(xG[i])\n xhbc.append(xG[i] + 0.5*dx)\n \n hAbc,uta,GAbc,bAbc,wta= ForcedbedM(xhbc,t,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,g,dx)\n uhAbc = uta*hAbc\n \n hta,uAbc,Gta,bta,wta= ForcedbedM(xubc,t,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,g,dx)\n \n hA,uA,GA,bA,wta = ForcedbedM(x,t,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,g,dx)\n \n uhbcC = []\n for i in range(len(xG)):\n uhbcC.append(uEbcC[2*i] * hMbcC[3*i])\n uhbcC.append(uEbcC[2*i +1] * hMbcC[3*i + 1])\n uhbcC.append(uEbcC[2*i +2] * hMbcC[3*i + 2])\n \n\n uhA = hA *uA\n uhiC = array(uiC)*array(hiC) \n \n hL1 = norm(hMbcC -hAbc, ord=1)/ norm(hAbc, ord=1)\n bL1 = norm(bMbcC -bAbc, ord=1)/ norm(bAbc, ord=1)\n GL1 = norm(GMbcC -GAbc, ord=1)/ norm(GAbc, ord=1)\n uL1 = norm(uEbcC -uAbc, ord=1)/ norm(uAbc, ord=1)\n uhL1 = norm(uhbcC -uhAbc, ord=1)/ norm(uhAbc, ord=1) \n \n \n hC1v = (Mn - Mni)/ Mni\n uhC1v = (Pn - Pni)/Pni\n GC1v = (Gn - Gni)/Gni\n EC1v = (En - Eni)/Eni \n \n deallocPy(hMbc_c)\n deallocPy(GMbc_c)\n deallocPy(wMbc_c)\n deallocPy(bMbc_c)\n deallocPy(duEbc_c)\n deallocPy(uEbc_c)\n deallocPy(ddbCbc_c)\n \n deallocPy(h_c)\n deallocPy(G_c)\n deallocPy(b_c)\n \n deallocPy(hMbeg_c)\n deallocPy(hMend_c)\n deallocPy(wMbeg_c)\n deallocPy(wMend_c)\n deallocPy(GMbeg_c)\n deallocPy(GMend_c)\n deallocPy(bMbeg_c)\n deallocPy(bMend_c)\n deallocPy(uEbeg_c)\n deallocPy(uEend_c)\n deallocPy(duEbeg_c)\n deallocPy(duEend_c)\n deallocPy(ddbCbeg_c)\n deallocPy(ddbCend_c)\n\n s = wdir + \"hL1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",hL1)\n file1.write(s)\n\n s = wdir + \"GL1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",GL1)\n file1.write(s)\n\n s = wdir + \"uhL1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",uhL1)\n file1.write(s)\n\n s = wdir + \"uL1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",uL1)\n file1.write(s)\n \n s = wdir + \"bL1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",bL1)\n file1.write(s)\n \n s = wdir + \"hC1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",hC1v)\n file1.write(s)\n \n s = wdir + \"uhC1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",uhC1v)\n file1.write(s) \n \n\n s = wdir + \"GC1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",GC1v)\n file1.write(s) \n\n s = wdir + \"HC1.dat\"\n with open(s,'a') as file1:\n s =\"%3.8f%5s%1.20f\\n\" %(dx,\" \",EC1v)\n file1.write(s) ","sub_path":"CODE/experimentcode/Thesis/Forced/GrowingGaussianBumpoverPeriodicBed/FDVMMods/usolve2/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":13487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417586170","text":"# vietoj pasikliovimo dictionary formatu, naudosime normalų objektą.\n# id yra pitono raktodis todėl naudojame _id.\n\nimport sqlite3\nfrom flask_restful import Resource, reqparse\nfrom code1.Models.user import UserModel\n\nclass UserRegister(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument('username',\n type=str,\n required=True,\n help = \"This feald cannot be blank.\"\n )\n\n parser.add_argument('password',\n type=str,\n required=True,\n help = \"This feald cannot be blank.\"\n )\n\n\n def post(self):\n\n data = UserRegister.parser.parse_args()\n\n # šita eilutė išgelbėja mus nuo to pačio userio sukūrimo net kelis kartus.\n\n if UserModel.find_by_username(data['username']): # not none\n return {\"message\": \"A user with that username already exists\"}, 400\n\n\n user = UserModel(**data) # išpakuoja duomenis iš data išparsintos info.\n user.save_to_db()\n\n # # print(data)\n # connection = sqlite3.connect('data.db')\n # cursor = connection.cursor()\n #\n # # apie query. Id autoincrimentinasi todėl insertiname null\n # query = \"INSERT INTO users VALUES (NULL, ?, ?)\"\n # cursor.execute(query, (data['username'], data['password'])) # username ir pw turi būti tuple objekte\n #\n # connection.commit()\n # connection.close()\n\n return {\"message\": \"User created successfully.\"}, 201\n\n\n","sub_path":"Recources/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102738628","text":"# -*- coding: utf-8 -*-\nfrom collections import defaultdict\n\nimport numpy as np\nimport six\nimport tensorflow as tf\n\nfrom tfsnippet.utils import (humanize_duration,\n StatisticsCollector,\n get_default_session_or_error,\n DocInherit)\n\n__all__ = [\n 'MetricFormatter',\n 'DefaultMetricFormatter',\n 'MetricLogger',\n 'summarize_variables',\n]\n\n\n@DocInherit\nclass MetricFormatter(object):\n \"\"\"\n Base class for a training metrics formatter.\n\n A training metric formatter determines the order of metrics, and the way\n to display the values of these metrics, in :class:`MetricLogger`.\n \"\"\"\n\n def sort_metrics(self, names):\n \"\"\"\n Sort the names of metrics.\n\n Args:\n names: Iterable metric names.\n\n Returns:\n list[str]: Sorted metric names.\n \"\"\"\n raise NotImplementedError()\n\n def format_metric(self, name, value):\n \"\"\"\n Format the value of specified metric.\n\n Args:\n name: Name of the metric.\n value: Value of the metric.\n\n Returns:\n str: Human readable string representation of the metric value.\n \"\"\"\n raise NotImplementedError()\n\n\nclass DefaultMetricFormatter(MetricFormatter):\n \"\"\"\n Default training metric formatter.\n\n This class sorts the metrics as follows:\n\n 1. The metrics are first divided into groups according to the suffices\n of their names as follows:\n\n 1. names ending with \"time\" or \"timer\" should come first\n 2. names ending with \"loss\" should come the second\n 3. names ending with \"acc\" or \"accuracy\" should come the third\n 4. other names should all come afterwards\n\n 2. The metrics are then sorted according to their names, within each group.\n\n The values of the metrics would be formatted into 6-digit real numbers,\n except for metrics with \"time\" or \"timer\" as suffices in their names,\n which would be formatted using :func:`~tfsnippet.utils.humanize_duration`.\n \"\"\"\n\n def sort_metrics(self, names):\n def sort_key(name):\n if name.endswith('time') or name.endswith('timer'):\n return -3, name\n elif name.endswith('loss'):\n return -2, name\n elif name.endswith('acc') or name.endswith('accuracy'):\n return -1, name\n return 0, name\n\n return sorted(names, key=sort_key)\n\n def format_metric(self, name, value):\n if name.endswith('time') or name.endswith('timer'):\n return humanize_duration(float(value))\n else:\n return '{:.6g}'.format(float(value))\n\n\nclass MetricLogger(object):\n \"\"\"\n Logger for the training metrics.\n\n This class provides convenient methods for logging training metrics,\n and for writing metrics onto disk via TensorFlow summary writer.\n The statistics of the metrics could be formatted into human readable\n strings via :meth:`format_logs`.\n\n An example of using this logger is:\n\n .. code-block:: python\n\n logger = MetricLogger(tf.summary.FileWriter(log_dir))\n global_step = 1\n\n for epoch in range(1, max_epoch+1):\n for batch in DataFlow.arrays(...):\n loss, _ = session.run([loss, train_op], ...)\n logger.collect_metrics({'loss': loss}, global_step)\n global_step += 1\n\n valid_loss = session.run([loss], ...)\n logger.collect_metrics({'valid_loss': valid_loss}, global_step)\n print('Epoch {}, step {}: {}'.format(\n epoch, global_step, logger.format_logs()))\n logger.clear()\n \"\"\"\n\n def __init__(self, summary_writer=None, formatter=None):\n \"\"\"\n Construct the :class:`MetricLogger`.\n\n Args:\n summary_writer: TensorFlow summary writer.\n formatter (MetricFormatter): Metric formatter for this logger.\n If not specified, will use an instance of\n :class:`DefaultMetricFormatter`.\n \"\"\"\n if formatter is None:\n formatter = DefaultMetricFormatter()\n self._formatter = formatter\n self._summary_writer = summary_writer\n\n # accumulators for various metrics\n self._metrics = defaultdict(StatisticsCollector)\n\n def clear(self):\n \"\"\"Clear all the metric statistics.\"\"\"\n # Instead of calling ``self._metrics.clear()``, we reset every\n # collector object (so that they can be reused).\n # This may help reduce the time cost on GC.\n for k, v in six.iteritems(self._metrics):\n v.reset()\n\n def collect_metrics(self, metrics, global_step=None):\n \"\"\"\n Collect the statistics of metrics.\n\n Args:\n metrics (dict[str, float or np.ndarray or DynamicValue]):\n Dict from metrics names to their values.\n For :meth:`format_logs`, there is no difference between\n calling :meth:`collect_metrics` only once, with an array\n of metric values; or calling :meth:`collect_metrics` multiple\n times, with one value at each time.\n However, for the TensorFlow summary writer, only the mean of\n the metric values would be recorded, if calling\n :meth:`collect_metrics` with an array.\n global_step (int or tf.Variable or tf.Tensor): The global step\n counter. (optional)\n \"\"\"\n from tfsnippet.trainer import DynamicValue\n tf_summary_values = []\n for k, v in six.iteritems(metrics):\n if isinstance(v, DynamicValue):\n v = v.get()\n v = np.asarray(v)\n self._metrics[k].collect(v)\n\n if self._summary_writer is not None:\n mean_value = v.mean()\n tf_summary_values.append(\n tf.summary.Summary.Value(tag=k, simple_value=mean_value))\n\n if tf_summary_values:\n summary = tf.summary.Summary(value=tf_summary_values)\n if global_step is not None and \\\n isinstance(global_step, (tf.Variable, tf.Tensor)):\n global_step = get_default_session_or_error().run(global_step)\n self._summary_writer.add_summary(summary, global_step=global_step)\n\n def format_logs(self):\n \"\"\"\n Format the metric statistics as human readable strings.\n\n Returns:\n str: The formatted metric statistics.\n \"\"\"\n buf = []\n for key in self._formatter.sort_metrics(six.iterkeys(self._metrics)):\n metric = self._metrics[key]\n if metric.has_value:\n name = key.replace('_', ' ')\n val = self._formatter.format_metric(key, metric.mean)\n if metric.counter > 1:\n std = ' (±{})'.format(\n self._formatter.format_metric(key, metric.stddev))\n else:\n std = ''\n buf.append('{}: {}{}'.format(name, val, std))\n return '; '.join(buf)\n\n\ndef summarize_variables(variables, title='Variables Summary'):\n \"\"\"\n Get a formatted summary about the variables.\n\n Args:\n variables (list[tf.Variable] or dict[str, tf.Variable]): List or\n dict of variables to be summarized.\n title (str): Optional title of this summary.\n\n Returns:\n str: Formatted summary about the variables.\n \"\"\"\n if isinstance(variables, dict):\n var_name, var_shape = list(zip(*sorted(six.iteritems(variables))))\n var_shape = [s.get_shape() for s in var_shape]\n else:\n variables = sorted(variables, key=lambda v: v.name)\n var_name = [v.name.rsplit(':', 1)[0] for v in variables]\n var_shape = [v.get_shape() for v in variables]\n\n var_count = [int(np.prod(s.as_list(), dtype=np.int32)) for s in var_shape]\n var_count_total = sum(var_count)\n var_shape = [str(s) for s in var_shape]\n var_count = [str(s) for s in var_count]\n\n buf = []\n if len(var_count) > 0:\n var_title = '{} ({:d} in total)'.format(title, var_count_total)\n\n var_name_len = max(map(len, var_name))\n var_shape_len = max(map(len, var_shape))\n var_count_len = max(map(len, var_count))\n var_table = []\n\n for name, shape, count in zip(var_name, var_shape, var_count):\n var_table.append(\n '{name:<{namelen}} {shape:<{shapelen}} '\n '{count}'.format(\n name=name, shape=shape, count=count,\n namelen=var_name_len, shapelen=var_shape_len,\n countlen=var_count_len\n )\n )\n\n max_line_length = max(\n var_name_len + var_shape_len + var_count_len + 4,\n len(var_title)\n )\n buf.append(var_title)\n buf.append('-' * max_line_length)\n buf.extend(var_table)\n\n return '\\n'.join(buf)\n","sub_path":"tfsnippet/scaffold/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":9032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"239886156","text":"__author__ = 'jmh081701'\nfrom database import *\ndb=DataBase(ip=\"127.0.0.1\")\n#db.delete(cond={})\n#db.data_clean()\n#db.data_augmentation()\ndataset=db.get_dataset()\nprint(len(dataset))\n#print(dataset)\n\n","sub_path":"tool/dbmanager.py","file_name":"dbmanager.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397247007","text":"#!/usr/bin/env python3\n\n#\n#Copyright (c) 2016-2021, NVIDIA CORPORATION.\n#SPDX-License-Identifier: Apache-2.0\n\n# Install every component other than libec, swiftclient, and swift\n# If a workspace is found, first we'll try to find an install command. If there\n# isn't one, let's try to find a script named install.sh in the root of the\n# component.\n#\n# If we're not using a manifest, stick to the old behavior: try to find a\n# script named install.sh at the root of each top-level dir in the workspace.\n#\n# If any way to install is found, execute it inside the container.\n\n\nimport os\nimport sys\nimport subprocess\n\nfrom libs import colorprint\nfrom libs import workspaces\nfrom libs.cli import run_command\nfrom libs.manifest import Manifest\n\n\nSCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))\nINSTALL_LOG_FILE_NAME = \"install.log\"\n\n\ndef exit_with_error(error_text, logfile_path):\n colorprint.error(error_text, logfile_path)\n sys.exit(1)\n\n\ndef get_manifest(workspace_name, logfile_path):\n if workspace_name is None:\n workspace_name = workspaces.get_last_workspace_name()\n if workspace_name is None:\n exit_with_error(\"No workspace found.\", logfile_path)\n workspace_path = workspaces.get_workspace_path(workspace_name)\n manifest_path = workspaces.get_manifest_path(workspace_name)\n if not os.path.isfile(manifest_path):\n colorprint.warning(\"Error: could not find manifest at {}. While it's \"\n \"not mandatory, it's highly recommended to use one.\"\n \" Read 'README_MANIFEST.md' for more \"\n \"information.\".format(manifest_path), logfile_path)\n return None\n else:\n try:\n return Manifest(manifest_path, workspace_path)\n except Exception as e:\n exit_with_error(e.message, logfile_path)\n\n\ndef get_install_commands(manifest, workspace_path, logfile_path):\n commands = []\n excluded_components = ['swift', 'python-swiftclient', 'liberasurecode']\n if manifest is not None:\n for component in manifest.get_components():\n if component not in excluded_components:\n dest_path = manifest.get_relative_dest_path_for_section(\n component)\n install_cmd = manifest.get_component_option(component,\n \"install\")\n if install_cmd is not None:\n # We add the component to the excluded list to NOT check\n # for the install.sh script in the next step.\n excluded_components.append(component)\n commands.append(os.path.join(dest_path, install_cmd))\n else:\n install_sh_path = os.path.join(workspace_path, dest_path,\n \"install.sh\")\n if os.path.isfile(install_sh_path):\n commands.append(os.path.join(dest_path, \"install.sh\"))\n\n else:\n for entry in os.scandir(workspace_path):\n if entry.is_dir() and entry.name not in excluded_components and \\\n os.path.isfile('{}/{}/install.sh'.format(workspace_path,\n entry.name)):\n commands.append(os.path.join(entry.name, \"install.sh\"))\n return commands\n\n\nif __name__ == \"__main__\":\n container_name = sys.argv[1]\n if len(sys.argv) > 2:\n workspace_name = sys.argv[2]\n else:\n workspace_name = container_name\n workspace_path = workspaces.get_workspace_path(workspace_name)\n logfile_path = os.path.abspath(os.path.join(workspace_path,\n INSTALL_LOG_FILE_NAME))\n manifest = get_manifest(workspace_name, logfile_path)\n\n install_commands = get_install_commands(manifest, workspace_path,\n logfile_path)\n\n for install_command in install_commands:\n cmd = 'lxc exec {} -- /bin/bash /home/swift/code/{}'.format(\n container_name, install_command)\n try:\n run_command(cmd, logfile_path=logfile_path)\n except Exception as e:\n colorprint.error(str(e), logfile_path)\n sys.exit(1)\n","sub_path":"generic_installer.py","file_name":"generic_installer.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"130599064","text":"\"\"\" Zip scaled datasets\n\nThe paths and all other constants are set to run on CMP grid for ANHIR dataset\nzip only images mentioned in cover file and landmarks from source\n\n>> python bm_ANHIR/zip_dataset_by_cover.py \\\n -i /datagrid/Medical/dataset_ANHIR/images_private \\\n -l /datagrid/Medical/dataset_ANHIR/landmarks \\\n -la /datagrid/Medical/dataset_ANHIR/landmarks_all \\\n -csv /datagrid/Medical/dataset_ANHIR/images/dataset_medium.csv\n\nCopyright (C) 2016-2019 Jiri Borovec \n\"\"\"\n\nimport os\nimport sys\nimport logging\nimport argparse\nimport subprocess\n\nimport pandas as pd\n\nsys.path += [os.path.abspath('.'), os.path.abspath('..')] # Add path to root\nfrom benchmark.cls_benchmark import COL_IMAGE_REF, COL_IMAGE_MOVE, COL_POINTS_MOVE\n\nZIP_COMMAND = 'cd %s && zip --split-size 1g %s.zip -r %s'\n\n\ndef arg_parse_params():\n \"\"\" parse the input parameters\n\n :return dict: {str: str}\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--path_dataset', type=str,\n help='path to the input image', required=True)\n parser.add_argument('-l', '--path_landmarks', type=str,\n help='path to the input landmarks', required=True)\n parser.add_argument('-la', '--path_landmarks_all', type=str,\n help='path to the all landmarks', required=True)\n parser.add_argument('-csv', '--path_csv', type=str, required=True,\n help='path to coordinate csv file')\n args = vars(parser.parse_args())\n return args\n\n\ndef main(path_dataset, path_landmarks, path_landmarks_all, path_csv):\n name_csv = os.path.splitext(os.path.basename(path_csv))[0]\n df_cover = pd.read_csv(path_csv)\n\n images = df_cover[COL_IMAGE_REF].tolist() + df_cover[COL_IMAGE_MOVE].tolist()\n folders = set(os.path.dirname(p) for p in images\n if os.path.isdir(os.path.join(path_dataset, os.path.dirname(p))))\n # Remove previous compressed images\n cmd = 'rm %s' % os.path.join(path_dataset, name_csv + '.z*')\n logging.info(cmd)\n subprocess.call(cmd, shell=True)\n # compress the images\n cmd = ZIP_COMMAND % (path_dataset, name_csv, ' '.join(folders))\n logging.info(cmd)\n subprocess.call(cmd, shell=True)\n\n landmarks = set(df_cover[COL_POINTS_MOVE].tolist())\n landmarks = [p for p in landmarks\n if os.path.isfile(os.path.join(path_landmarks_all, p))]\n # compress the landmarks\n cmd = ZIP_COMMAND % (path_landmarks_all, name_csv, ' '.join(landmarks))\n logging.info(cmd)\n subprocess.call(cmd, shell=True)\n # Move the compressed landmarks\n cmd = 'mv %s %s' % (os.path.join(path_landmarks_all, name_csv + '.zip'),\n os.path.join(path_landmarks, name_csv + '.zip'))\n logging.info(cmd)\n subprocess.call(cmd, shell=True)\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n arg_params = arg_parse_params()\n main(**arg_params)\n","sub_path":"bm_ANHIR/zip_dataset_by_cover.py","file_name":"zip_dataset_by_cover.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579828415","text":"# Test program for IRQ based access to MPU9250\n# Note there will be small differences between the lines because\n# of drift or movement occurring between the readings\nfrom imu.mpu9250 import MPU9250\n\nimu = MPU9250(bus=1, device_addr=0x68)\n\nfor count in range(10):\n scale = 6.6666 # Correction factors involve floating point\n mag = list(map(lambda x, y : x*y/scale, imu.mag.ixyz, imu.mag_correction))\n print(\"Interrupt:\", [x/16384 for x in imu.accel.ixyz], [x/131 for x in imu.gyro.ixyz], mag)\n print(\"Normal: \", imu.accel.xyz, imu.gyro.xyz, imu.mag.xyz)\n print()\n","sub_path":"MPU9250_tests/irqtest.py","file_name":"irqtest.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264636214","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# %%\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.colors as colors\n\nmpl.rc('text', usetex=True)\nmpl.rc('font', family='serif')\nmpl.rc('font', size=10)\n\n# %%\n# file with data from the experiment\n# Note: header=6 is for NetLogo data\n\nexp_desc = 'exp2-indirect_vs_patch_prob'\n\ndata = pd.read_csv(exp_desc + '.csv', header=6)\n\n# %%\n# select variables for the analysis \n# this depends on the experiment\n\n# variables\n# 1st is different for each plot\n# 2nd and 3rd vars provide axes for plots\n# 4th variable is visualized\n# variant 1\n# v = ['mobility-prob', 'patch-infection-weight', 'patch-contamination-prob','mean-infected']\n# variant 2\nv = ['indirect-infection-prob', 'patch-infection-prob', 'mobility-prob', 'patch-contamination-prob', 'mean-infected']\nvl = [r'$\\nu_{2}$', r'$\\nu_{3}$', 'mobility', 'patch contamination probability']\n\n# selection for plotting\n\n# vars 0 and 1 are used to index plots\nvar0s = [0.3, 0.6, 0.9]\nvar1s = [0.3, 0.6, 0.9]\n\n# variable 2nd and 3rd are used to inded plot data\nvar2s = data[v[2]].unique()\nvar3s = data[v[3]].unique()\n\ndf = pd.DataFrame(columns=v)\n\n# %%\n# calculate mean for the presented variable\n\nfor v0 in var0s:\n for v1 in var1s:\n for v2 in var2s:\n for v3 in var3s:\n df.loc[len(df.index)] = [\n v0,\n v1,\n v2,\n v3,\n data[(data[v[0]] == v0) & (data[v[1]] == v1) & (data[v[2]] == v2) & (data[v[3]] == v3) ]['%infected'].mean()\n ]\n\n# %%\n\nfig = mpl.figure.Figure(figsize=(6, 5.5))\nlevels = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90]\n\nfor i, v0 in enumerate(var0s):\n \n for j, v1 in enumerate(var1s):\n axs = fig.add_subplot(331 + i + 3*j);\n plot_data = df[ (df[v[0]] == v0) & (df[v[1]] == v1) ][[v[2], v[3], v[4]]].to_numpy()\n\n\n # first two elements of plot_data correspond to the values of 2nd and 3rd variable\n axs.contour(\n plot_data.T[0].reshape(len(var2s), len(var2s)), \n plot_data.T[1].reshape(len(var3s), len(var3s)),\n plot_data.T[2].reshape(21, 21),\n levels=levels,\n colors='k', linestyles='dotted', linewidths=0.5\n )\n\n im = axs.contourf(\n plot_data.T[0].reshape(len(var2s), len(var2s)),\n plot_data.T[1].reshape(len(var3s), len(var3s)),\n plot_data.T[2].reshape(21, 21),\n levels=levels,\n cmap = 'hot_r',\n norm = colors.Normalize(vmin=0, vmax=levels[-1]),\n )\n\n axs.set_title('abcdefghi'[i+3*j] + ') ' + vl[0] + '=' + str(v0) +', ' + vl[1] + '=' + str(v1))\n axs.set_xticks(np.arange(0, 1.01, 0.2))\n\n axs.grid(True, linestyle=':', linewidth=0.5, c='k')\n\n if j not in [2]:\n axs.set_xticklabels([])\n\n if i not in [0]:\n axs.set_yticklabels([])\n\n if i == 1 and j == 2:\n axs.set_xlabel(vl[2])\n if i == 0 and j == 1:\n axs.set_ylabel(vl[3])\n\ncbar_ax = fig.add_axes([0.125, 1.02, 0.8, 0.02])\ncbar = fig.colorbar(im, cax=cbar_ax, orientation=\"horizontal\")\ncbar.set_ticklabels([str(l) + \"\\%\" for l in levels])\n\nfig.tight_layout()\ndisplay(fig)\n\n\n# %%\nfName = \"plot_\" + exp_desc + \"_all.pdf\"\nprint(\"INFO] Saving \" + fName)\nfig.savefig('plots/'+fName, format=\"pdf\", bbox_inches='tight')\n","sub_path":"exp2-indirect_vs_patch_prob.py","file_name":"exp2-indirect_vs_patch_prob.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"273029439","text":"\"\"\"this py file has all the functions to extract cloud details\"\"\"\r\n\r\n\r\n\r\nimport db_conn\r\n\r\n\r\n\r\n \r\n \r\n\r\ndef verify_admin(admn_id , pswd,cursor):\r\n \"\"\"\r\n error codes:\r\n 1 : others\r\n 2 : id incorrect\r\n 3 : password incorrect\r\n\r\n 0 : login successful\r\n \"\"\"\r\n ad_l = []\r\n \r\n try:\r\n q_str = 'select * from admin_login_details where userid = ' + '\"'+str(admn_id)+'\"'\r\n rows_cnt = cursor.execute(q_str)\r\n a = cursor.fetchall()\r\n x = get_admin_detail(admn_id,cursor)\r\n \r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n \r\n if fetch == 's':\r\n if rows_cnt > 0:\r\n aid = 'c'\r\n \r\n if a[0]['password'] == pswd:\r\n ap = 'c'\r\n ad_l.append(0)\r\n if x[0] == 0:\r\n ad_l.append(x[1])\r\n return ad_l\r\n else:\r\n ap = 'i'\r\n ad_l.append(3)\r\n return ad_l\r\n else:\r\n aid = 'i'\r\n ad_l.append(2)\r\n return ad_l\r\n else:\r\n ad_l.append(1)\r\n return ad_l\r\n \r\ndef verify_client(clnt_id , pswd,cursor):\r\n \"\"\"\r\n error codes:\r\n 1 : others\r\n 2 : id incorrect\r\n 3 : password incorrect\r\n\r\n 0 : login successful\r\n \"\"\"\r\n\r\n cd_l = []\r\n try:\r\n q_str = 'select * from client_login_details where userid = ' + '\"'+str(clnt_id)+'\"'\r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n x = get_client_detail(clnt_id,cursor)\r\n \r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n \r\n if fetch == 's':\r\n if rows_cnt > 0:\r\n cid = 'c'\r\n \r\n if c[0]['password'] == pswd:\r\n ap = 'c'\r\n cd_l.append(0)\r\n if x[0] == 0:\r\n cd_l.append(x[1])\r\n return cd_l\r\n else:\r\n cp = 'i'\r\n cd_l.append(3)\r\n return cd_l\r\n else:\r\n cid = 'i'\r\n cd_l.append(2)\r\n return cd_l\r\n else:\r\n cd_l.append(1)\r\n return cd_l\r\n \r\n\r\n\r\ndef get_admin_detail(admn_id,cursor):\r\n apd_l = []\r\n try:\r\n q_str = 'select * from admin_personal_details where userid = ' + '\"'+str(admn_id)+'\"'\r\n rows_cnt = cursor.execute(q_str)\r\n a = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n if fetch == 's':\r\n apd_l.append(0)\r\n apd_l.append(a)\r\n return apd_l\r\n else:\r\n apd_l.append(1)\r\n return apd_l\r\n \r\n\r\ndef get_client_detail(clnt_id,cursor):\r\n cpd_l = []\r\n try:\r\n q_str = 'select * from client_personal_details where userid = ' + '\"'+str(clnt_id)+'\"'\r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n if fetch == 's':\r\n cpd_l.append(0)\r\n cpd_l.append(c)\r\n return cpd_l\r\n else:\r\n cpd_l.append(1)\r\n return cpd_l \r\n\r\n\r\ndef get_student_list(cursor,f = 0 , search_string = '' , sbi = 0 , sbn = 0):\r\n\r\n cl_l = []\r\n q_str = 'select * from client_personal_details'\r\n\r\n if(search_string == '' or f ==0):\r\n pass\r\n else:\r\n if(sbi == 0 and sbn == 0):\r\n sbn = 1\r\n if(sbn == 1):\r\n q_str = q_str + (' where name like \"{}%\"').format(search_string)\r\n elif(sbi == 1):\r\n q_str = q_str + (' where userid = \"{}\"').format(search_string)\r\n try:\r\n \r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n if fetch == 's':\r\n cl_l.append(0)\r\n cl_l.append(c)\r\n return cl_l\r\n else:\r\n cl_l.append(1)\r\n return cl_l \r\n \r\ndef get_transactions(cursor,bf = 0 ,sf = 0 ,dft =0, sbs = 0 , stid = '' ,sba = 0, admn_id = '', df = '',dt ='',status = ''):\r\n tl_l = []\r\n q_str = 'select * from transactions'\r\n cf = 0\r\n if bf==1 and sbs==1 and stid!='':\r\n q_str = q_str + (' where client_id = \"{}\"').format(stid)\r\n cf=1\r\n if bf==1 and sba == 1 and admn_id !='':\r\n if cf==1:\r\n q_str = q_str + (' and approver = \"{}\"').format(admn_id)\r\n\r\n else:\r\n q_str = q_str + (' where approver = \"{}\"').format(admn_id)\r\n cf=1\r\n if sf==1 and status!='':\r\n if cf==1:\r\n q_str = q_str + (' and approved = \"{}\"').format(status)\r\n else:\r\n q_str = q_str + (' where approved = \"{}\"').format(status)\r\n cf =1 \r\n\r\n if dft == 1 and df != '':\r\n if dt == '':\r\n if cf == 1:\r\n q_str = q_str + (' and date_time >= \"{}\"').format(df)\r\n else:\r\n q_str = q_str + (' where date_time >= \"{}\"').format(df)\r\n cf=1\r\n else:\r\n if cf == 1:\r\n q_str = q_str + (' and date_time >= \"{}\" or date_time <= \"{}\"').format(df,dt)\r\n else:\r\n q_str = q_str + (' where date_time >= \"{}\" or date_time <= \"{}\"').format(df,dt)\r\n cf=1\r\n \r\n \r\n \r\n\r\n try:\r\n print(q_str)\r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n \r\n fetch = 'f'\r\n if fetch == 's':\r\n tl_l.append(0)\r\n tl_l.append(c)\r\n return tl_l\r\n else:\r\n tl_l.append(1)\r\n return tl_l \r\n \r\n\r\n\r\ndef get_approvals(cursor,bf=0,sf = 0,tf=0,dft=0,sbs=0,clnt_id = '', sba = 0 , admin_id='',status = '',tid = '',df='',dt=''):\r\n al_l = []\r\n q_str = 'select * from approvals'\r\n\r\n if ((clnt_id == '' and admn_id == '' and df == '' )or bf ==0) and ( sf == 0 or status == '') and ( tf == 0 or tid =='') and (df == 0 or df ==''):\r\n pass\r\n else:\r\n cf = 0\r\n if(sbs == 0 and sba == 0 and bf ==1):\r\n sbs = 1\r\n if(sbs == 1 and bf==1 and clnt_id != ''):\r\n q_str = q_str + (' where requester_id = \"{}\"').format(clnt_id)\r\n cf = 1\r\n if(sba == 1 and bf ==1 and admin_id !=''):\r\n if cf ==1:\r\n q_str = q_str + (' and approver_id = \"{}\"').format(admn_id)\r\n cf = 1\r\n else:\r\n q_str = q_str + (' where approver_id = \"{}\"').format(admn_id)\r\n cf = 1\r\n if(sf ==1 and status !=''):\r\n if cf ==1:\r\n q_str = q_str + (' and approved = \"{}\"').format(status)\r\n cf = 1\r\n else:\r\n q_str = q_str + (' where approved = \"{}\"').format(status)\r\n cf = 1\r\n if(tf ==1 and tid !=''):\r\n if cf ==1:\r\n q_str = q_str + (' and tid = \"{}\"').format(tid)\r\n cf = 1\r\n else:\r\n q_str = q_str + (' where tid = \"{}\"').format(tid)\r\n cf = 1\r\n\r\n if(dft ==1 and df !=''):\r\n if cf ==1:\r\n if dt == '':\r\n q_str = q_str + (' and posted_on >= \"{}\"').format(df)\r\n cf=1\r\n else:\r\n q_str = q_str + (' and posted_on >= \"{}\" and posted_on <= \"{}\"').format(df,dt)\r\n cf = 1\r\n else:\r\n if dt == '':\r\n q_str = q_str + (' where posted_on >= \"{}\" ').format(df,dt)\r\n cf=1\r\n else:\r\n q_str = q_str + (' where posted_on >= \"{}\" and posted_on <= \"{}\"').format(df,dt)\r\n cf = 1\r\n \r\n try:\r\n \r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n if fetch == 's':\r\n al_l.append(0)\r\n al_l.append(c)\r\n return al_l\r\n else:\r\n al_l.append(1)\r\n return al_l \r\n\r\n#try catch run query block\r\n\r\ndef run_query(cursor,q_str):\r\n ql_l = []\r\n try:\r\n \r\n rows_cnt = cursor.execute(q_str)\r\n c = cursor.fetchall()\r\n fetch = 's'\r\n except:\r\n fetch = 'f'\r\n if fetch == 's':\r\n ql_l.append(0)\r\n ql_l.append(c)\r\n return ql_l\r\n else:\r\n ql_l.append(1)\r\n return ql_l \r\n\r\n#admin_login_details\r\n\r\ndef fecth_admin_login_detail(cursor,userid=''):\r\n q_str = 'select * from admin_login_details'\r\n \r\n if userid != '' :\r\n q_str = q_str +( ' where userid = \"{}\"').format(userid)\r\n return run_query(cursor,q_str)\r\n\r\n#admin_login_details_update\r\ndef admin_login_details_update(cursor,userid='',aid=''):\r\n q_str = 'select * from admin_login_details_update'\r\n cf=0\r\n if userid != '' :\r\n q_str = q_str +( ' where userid = \"{}\"').format(userid)\r\n cf=1\r\n if aid != '':\r\n if cf == 1 :\r\n q_str = q_str +( ' and aid = \"{}\"').format(aid)\r\n else:\r\n q_str = q_str +( ' where aid = \"{}\"').format(aid)\r\n print(q_str)\r\n return run_query(cursor,q_str)\r\n\r\n#admin_personal_details_update\r\n\r\ndef admin_personal_details_update(cursor,userid='',aid=''):\r\n q_str = 'select * from admin_personal_details_update'\r\n cf=0\r\n if userid != '' :\r\n q_str = q_str +( ' where userid = \"{}\"').format(userid)\r\n cf=1\r\n if aid != '':\r\n if cf == 1 :\r\n q_str = q_str +( ' and aid = \"{}\"').format(aid)\r\n else:\r\n q_str = q_str +( ' where aid = \"{}\"').format(aid)\r\n print(q_str)\r\n return run_query(cursor,q_str)\r\n#client_login_details\r\ndef fecth_client_login_detail(cursor,userid=''):\r\n q_str = 'select * from client_login_details'\r\n \r\n if userid != '' :\r\n q_str = q_str +( ' where userid = \"{}\"').format(userid)\r\n return run_query(cursor,q_str)\r\n#client_login_details_update\r\ndef client_login_details_update(cursor,userid='',aid=''):\r\n q_str = 'select * from client_login_details_update'\r\n cf=0\r\n if userid != '' :\r\n q_str = q_str +( ' where userid = \"{}\"').format(userid)\r\n cf=1\r\n if aid != '':\r\n if cf == 1 :\r\n q_str = q_str +( ' and aid = \"{}\"').format(aid)\r\n else:\r\n q_str = q_str +( ' where aid = \"{}\"').format(aid)\r\n print(q_str)\r\n return run_query(cursor,q_str)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n","sub_path":"database_ops.py","file_name":"database_ops.py","file_ext":"py","file_size_in_byte":10318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244872715","text":"from typing import List\nfrom typing import Union\nfrom typing import Iterable\n\n\nfrom click import Group\nfrom click import Context\nfrom click import Command\n\nfrom .db import is_admin\nfrom .exceptions import PermissionDenied\n\n\ndef _get_main_help_msg(cmd_grps: dict):\n \"\"\"\n Main help message when user types `help`.\n List of available commands registered in `cmd_grps`.\n \"\"\"\n msg_cmds = \"\\n\".join(f\"{cmd}\" for cmd in cmd_grps.keys())\n msg = \"Following is a list of commands currently available.\\n\"\n msg += f\"```{msg_cmds}```\"\n msg += \"\\nType `help ` for more information about the `command`\"\n return msg\n\n\ndef _get_nested_command(grp: Group, names: Iterable[str]) -> Union[Group, Command]:\n \"\"\"Recursively find nested command and get it's help.\"\"\"\n if len(names) == 1:\n return grp.get_command(Context(grp, info_name=grp.name), names[0])\n else:\n child_grp = grp.get_command(Context(grp, info_name=grp.name), names[0])\n return _get_nested_command(child_grp, names[1:])\n\n\ndef get_help_msg(cmd: str, cmd_grps: dict) -> str:\n \"\"\"Returns main or nested help message.\"\"\"\n cmds = cmd.split()\n assert cmds[0] == \"help\"\n if len(cmds) == 1:\n return _get_main_help_msg(cmd_grps)\n else:\n root_grp_or_cmd = cmd_grps[cmds[1]]\n nested_grp_or_cmd = (\n root_grp_or_cmd\n if len(cmds) == 2\n else _get_nested_command(root_grp_or_cmd, cmds[2:])\n )\n ctx = Context(nested_grp_or_cmd, info_name=\" \".join(cmds[1:]))\n return f\"```{nested_grp_or_cmd.get_help(ctx)}```\"\n\n\ndef admin_check(user_id: str) -> str:\n if is_admin(user_id):\n return\n raise PermissionDenied(\n \"You do not seem to have the necessary permissions to perform this action.\"\n )\n","sub_path":"common/CloudBotWorkersCommon/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"248656778","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.interpolate\n\n\nL = pd.read_csv('csv_activation_CorJo.csv')\nx = L.iloc[1:2480, 0].values\ny = L.iloc[1:2480, 1].values\n\n\ndef f(z):\n f = scipy.interpolate.interp1d(x,y,kind='nearest',fill_value=\"extrapolate\")\n return f(z)\n\n\ndef activationNMOS(x):\n return(np.vectorize(f)(x))\n\n\nx_ = np.linspace(0, 5, 100)\ny_ = activationNMOS(x_)\n\n\ndef test():\n plt.title(\"Activation function of Coco&Jo\")\n plt.plot(x_, y_, 'r.-')\n plt.plot(x, y, 'g--')\n plt.grid()\n plt.legend(['polynomial approximation', 'ground truth'])\n plt.show()\n \n#test()\n\n\n\n","sub_path":"ActivationFunction/activationNmos.py","file_name":"activationNmos.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"472209235","text":"#!/usr/bin/env python\nfrom enum import Enum\nfrom queue import PriorityQueue\nimport numpy as np\nimport math\nfrom bresenham import bresenham\n\ndef create_grid(data, drone_altitude, safety_distance):\n \"\"\"\n Returns a grid representation of a 2D configuration space\n based on given obstacle data, drone altitude and safety distance\n arguments.\n \"\"\"\n\n # minimum and maximum north coordinates\n # TODO: DIMENSION OF OUR GAZEBO WORLD\n # north_min = np.floor(np.min(data[:, 0] - data[:, 3]))\n # north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))\n north_min = 0\n north_max = 340\n print(north_min,north_max)\n\n # minimum and maximum east coordinates\n # east_min = np.floor(np.min(data[:, 1] - data[:, 4]))\n # east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))\n east_min = 0\n east_max = 150\n print(east_min,east_max)\n\n # given the minimum and maximum coordinates we can\n # calculate the size of the grid.\n north_size = int(np.ceil((north_max - north_min + 1)))\n east_size = int(np.ceil((east_max - east_min + 1)))\n print(north_size,east_size)\n\n\n # Initialize an empty grid\n grid = np.zeros((north_size, east_size))\n\n # Populate the grid with obstacles\n for i in range(data.shape[0]):\n north, east, alt, d_north, d_east, d_alt = data[i, :]\n if alt + d_alt + safety_distance > drone_altitude:\n obstacle = [\n int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)),\n int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)),\n int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)),\n int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)),\n ]\n grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1\n\n\n return grid, int(north_min), int(east_min)\n\ndef createGazeboGrid():\n north_min = 0\n north_max = 34\n east_min = 0\n east_max = 15\n\n north_size = int(np.ceil((north_max - north_min)))\n east_size = int(np.ceil((east_max - east_min)))\n print(north_size,east_size)\n\n # Initialize an empty grid\n grid = np.zeros((east_size,north_size))\n print('size of grid')\n print(np.shape(grid))\n grid_2 = np.zeros((5,10))\n for i in range(0,np.shape(grid)[0]):\n grid[i,0] =1\n grid[i,-1]= 1\n for j in range(0,np.shape(grid)[1]):\n grid[0,j] = 1\n grid[-1,j]= 1\n print(grid[0:10,0:10])\n\n return grid\n\n\n\n# Assume all actions cost the same.\nclass Action(Enum):\n \"\"\"\n An action is represented by a 3 element tuple.\n The first 2 values are the delta of the action relative\n to the current grid position. The third and final value\n is the cost of performing the action.\n \"\"\"\n\n WEST = (0, -1, 1)\n EAST = (0, 1, 1)\n NORTH = (-1, 0, 1)\n SOUTH = (1, 0, 1)\n \n NORTH_WEST = (-1, -1, math.sqrt(2))\n NORTH_EAST = (-1, 1, math.sqrt(2))\n SOUTH_WEST = (1, -1, math.sqrt(2))\n SOUTH_EAST = (1, 1, math.sqrt(2))\n\n @property\n def cost(self):\n return self.value[2]\n\n @property\n def delta(self):\n return (self.value[0], self.value[1])\n\n\ndef valid_actions(grid, current_node):\n \"\"\"\n Returns a list of valid actions given a grid and current node.\n \"\"\"\n valid_actions = list(Action)\n n, m = grid.shape[0] - 1, grid.shape[1] - 1\n x, y = current_node\n\n # check if the node is off the grid or\n # it's an obstacle\n\n if x - 1 < 0 or grid[x - 1, y] == 1:\n valid_actions.remove(Action.NORTH)\n if x + 1 > n or grid[x + 1, y] == 1:\n valid_actions.remove(Action.SOUTH)\n if y - 1 < 0 or grid[x, y - 1] == 1:\n valid_actions.remove(Action.WEST)\n if y + 1 > m or grid[x, y + 1] == 1:\n valid_actions.remove(Action.EAST)\n \n if (x-1 < 0) or (y-1 < 0) or grid[x-1, y-1] == 1:\n valid_actions.remove(Action.NORTH_WEST)\n if (x-1 < 0) or (y+1 > m) or grid[x-1, y+1] == 1:\n valid_actions.remove(Action.NORTH_EAST)\n if (x+1 > n) or (y+1 > m) or grid[x+1, y+1] == 1:\n valid_actions.remove(Action.SOUTH_EAST)\n if (x+1 > n) or (y-1 < 0) or grid[x+1, y-1] == 1:\n valid_actions.remove(Action.SOUTH_WEST)\n\n return valid_actions\n\n\ndef a_star(grid, h, start, goal):\n \"\"\"\n Given a grid and heuristic function returns\n the lowest cost path from start to goal.\n \"\"\"\n\n path = []\n path_cost = 0\n queue = PriorityQueue()\n queue.put((0, start))\n visited = set(start)\n\n branch = {}\n found = False\n\n while not queue.empty():\n item = queue.get()\n current_cost = item[0]\n current_node = item[1]\n\n if current_node == goal:\n print('Found a path.')\n found = True\n break\n else:\n # Get the new vertexes connected to the current vertex\n for a in valid_actions(grid, current_node):\n next_node = (current_node[0] + a.delta[0], current_node[1] + a.delta[1])\n new_cost = current_cost + a.cost + h(next_node, goal)\n\n if next_node not in visited:\n visited.add(next_node)\n queue.put((new_cost, next_node))\n\n branch[next_node] = (new_cost, current_node, a)\n\n if found:\n # retrace steps\n n = goal\n path_cost = branch[n][0]\n path.append(goal)\n while branch[n][1] != start:\n path.append(branch[n][1])\n n = branch[n][1]\n path.append(branch[n][1])\n else:\n print('**********************')\n print('Failed to find a path!')\n print('**********************') \n return path[::-1], path_cost\n\ndef heuristic(position, goal_position):\n return np.linalg.norm(np.array(position) - np.array(goal_position))\n\ndef point(p):\n return np.array([p[0], p[1], 1.]).reshape(1, -1)\n\ndef collinearity_check(p1, p2, p3, grid, epsilon=1e-6):\n m = np.concatenate((p1, p2, p3), 0)\n det = np.linalg.det(m)\n return abs(det) < epsilon\n\ndef prune_path(path, grid):\n pruned_path = [p for p in path]\n \n i = 0\n while i < (len(pruned_path) - 2):\n p1 = point(pruned_path[i])\n p2 = point(pruned_path[i+1])\n p3 = point(pruned_path[i+2])\n \n if collinearity_check(p1, p2, p3, grid):\n pruned_path.remove(pruned_path[i+1])\n else:\n i +=1\n return pruned_path\n\n\nif __name__ == \"__main__\":\n\n TARGET_ALTITUDE = 5\n SAFETY_DISTANCE = 5 # safety distance from obstacles\n grid = createGazeboGrid()\n\n # Read in obstacle map TODO: WE HAVE TO CONVERT OUR OBSTACLES SOME HOW INTO CSV File *****\n #data = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=3)\n # grid, north_offset, east_offset = create_grid(data, TARGET_ALTITUDE, SAFETY_DISTANCE)\n\n # print(np.shape(grid))\n # print(grid[0:,0:20])\n # # Starting poistion\n # current_local_pos = global_to_local(self.global_position, self.global_home)\n # grid_start = (int(current_local_pos[0] - north_offset), int(current_local_pos[1] - east_offset))\n #\n #\n # # Take GPS co-ordinates as Grid goal -Me\n # grid_goal = (-122.396582, 37.795714, 0)\n # grid_goal = global_to_local(grid_goal, self.global_home)\n # grid_goal = (int(grid_goal[0] - north_offset), int(grid_goal[1] - east_offset))\n #\n #\n # # Run A* to find a path from start to goal\n # # TODO: add diagonal motions with a cost of sqrt(2) to your A* implementation\n # # or move to a different search space such as a graph (not done here)\n # print('Local Start and Goal: ', grid_start, grid_goal)\n # path, _ = a_star(grid, heuristic, grid_start, grid_goal)\n #\n # # TODO: prune path to minimize number of waypoints\n # # TODO (if you're feeling ambitious): Try a different approach altogether!\n # path = prune_path(path, grid)\n #\n # # Convert path to waypoints\n # waypoints = [[p[0] + north_offset, p[1] + east_offset, TARGET_ALTITUDE, 0] for p in path]\n # # Set self.waypoints\n","sub_path":"src/path_planning/nodes/2D_planning_temp.py","file_name":"2D_planning_temp.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}